students: modal for student face refs and found/similar photos
Кнопка "Лица" в строке ученика открывает #studentFacesModal: эталонные фото, фото, где лицо ученика уже найдено, и похожие непривязанные лица. Эталоны переехали из #profileDataModal — id элементов должны быть в документе ровно один раз. Поиск похожих личностей переведён с перебора эмбеддингов на хранение кандидата в БД: photo_faces.best_student_id + best_score заполняются при скане и при пересчёте, у привязанных лиц обнуляются. Частичный индекс WHERE student_id IS NULL - без него запрос поднимал бы все эмбеддинги. Также: - пересчёт по всем фото теперь запускается и при удалении эталона, иначе кандидаты устаревают - иконки в панели действий карточки фото и в бейдже лиц - lucide - бейдж лиц прижат вправо, панель действий прижата к низу карточки
This commit is contained in:
@@ -236,14 +236,16 @@ This document defines how AI agents should work with the WhatIDo codebase. Follo
|
||||
- **`face_scanned_at`** в `group_photos` и `entry_photos` — единственный признак «несканировано». Кнопка «Найти лица» и `POST /api/faces/scan-unscanned` берут `WHERE face_scanned_at IS NULL`; `rescan: true` в теле проходит все фото заново
|
||||
- **Скан при загрузке** — `scanFacesBackground()` через `setImmediate` **после** `res.json(...)`: в группе после `INSERT ... RETURNING`, в записи журнала после `COMMIT` (там фото в транзакции, поэтому id `entry_photos` дотягиваются отдельным SELECT). Роут не блокируется
|
||||
- **Эмбеддинги не переиспользуются между фото**: при каждом скане фото refs перечитываются целиком (`loadFaceRefs`) — объём маленький (десятки строк), кэш дал бы риск устаревшей привязки
|
||||
- **Пересчёт привязок по всем фото** — `rematchFaces()`: идёт по `photo_faces` **с `student_id IS NULL`**, батчами по 1000 (пагинация по `id > lastId`, не по `LIMIT` — молча терять хвост нельзя), и каждому лицу пересчитывает косинус к эталонам. Детект не повторяется: эмбеддинги уже в БД, `face-id` не нужен. Автозапуск — `rematchFacesBackground()` из `POST /api/students/:id/face-refs` (через `setImmediate` **после** `res.status(201)`, под `face_id_enabled = 'true'`); ручной запуск — `POST /api/faces/rematch` под `requireAuth, requireAdmin`, кнопка `#faceRematchBtn` в `#sec-faces`. Смысл: фото, просканированные до появления эталона, получили `student_id = NULL` навсегда — без пересчёта они так и остались бы нераспознанными
|
||||
- **Пересчёт привязок по всем фото** — `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`. Уже привязанные лица пересчёт **не трогает**: ручная привязка имеет приоритет, а ошибочный авто-матч остаётся — чинить его можно только вручную
|
||||
- **Три состояния рамки** в `#faceViewerModal` (классы `.face-box--matched` / `--candidate` / `--unassigned`): привязано автоматически → `Имя · NN%`; привязано вручную → `Имя · вручную`; не привязано, но лучший кандидат ≥ `FACE_CANDIDATE_MIN` (0.5, константа в `groups.js`) → `Похож: Имя · NN%`; иначе `Не опознано`. Кандидат считается на лету в `GET /api/photos/:sourceType/:sourceId/faces` через `bestFaceCandidate()` (`matchFaceToStudent` с порогом `Infinity`), поэтому подпись актуальна и для фото, просканированных до добавления эталонов. Клик по рамке с кандидатом сразу открывает `#faceAssignModal` и подставляет имя кандидата в `#faceAssignSearch` — привязка в один клик, поле очищается вручную
|
||||
- **Кандидат хранится в БД, а не считается на лету**: `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` — по нему ищутся «похожие», без него запрос поднимал бы все эмбеддинги
|
||||
- **Три состояния рамки** в `#faceViewerModal` (классы `.face-box--matched` / `--candidate` / `--unassigned`): привязано автоматически → `Имя · NN%`; привязано вручную → `Имя · вручную`; не привязано, но `best_score` ≥ `candidate_min` → `Похож: Имя · NN%`; иначе `Не опознано`. Клик по рамке с кандидатом открывает `#faceAssignModal` и подставляет имя кандидата в `#faceAssignSearch` — привязка в один клик
|
||||
- **Ручная привязка всегда доступна**: `PUT /api/photo-faces/:faceId/assign` ставит `confidence = 1`, `student_id: 0`/отсутствие снимает привязку. Автопорог — `face_id_threshold` (валидация в `PUT /api/settings`: 0.3..0.99), «неопознано» ≠ ошибка
|
||||
- **Доступ**: `studentProfileAccess()` для эталонов, `groupBelongsToBranches()` для лиц фото — не-admin не видит и не привязывает лица чужих филиалов. `POST /api/faces/scan-unscanned` под `requireAdmin`
|
||||
- **Фильтры** — и в галерее группы, и в глобальном `/api/photos`: `student_id` и `unassigned_faces=1` через `EXISTS` по `photo_faces`. В `/api/photos` матчинг идёт **по `pf.photo_path = t.path`, а не по id**: в этом агрегаторе `source_id` для `group_photo` — это `group_id`, а для `entry` — `id` записи, так что сопоставление с `photo_faces.source_id` (там id фото) даёт ложные совпадения и молча теряет результат. Путь фото — единственный общий ключ. В галерее группы (`GET /api/groups/:id/photos`) матчинг по `pf.source_id = gp.id` корректен
|
||||
- **Бэкап и sweep**: `student_face_refs` + `photo_faces` в `BACKUP_TABLES` и `BACKUP_SEQUENCE_TABLES`, в `normalizeRestoreData` и restore-INSERT (с проверкой FK: фото → `group_photos`/`entry_photos`, `student_id` → `students`). `student_face_refs.photo_path` **обязан** быть в `sweepOrphanedUploads`, иначе файлы эталонов снесутся как сироты сразу после restore
|
||||
- **Фронт**: `students.html`/`students.js` — «Библиотека лиц» + «Фото с учеником» в `#profileDataModal`; `groups.html`/`groups.js` — оверлей `.face-box` (`.face-box--matched` / `.face-box--unassigned`) в модалке `#faceViewerModal`, привязка в `#faceAssignModal`, селект-фильтр и кнопка «Найти лица»; `photos.html`/`photos.js` — фильтр «По лицам»; настройки — карточка `#sec-faces`. CSS в `public/admin.css`, блок `/* --- Библиотека лиц --- */`
|
||||
- **Фронт**: `students.html`/`students.js` — «Библиотека лиц» + «Фото с учеником» в `#profileDataModal`; `groups.html`/`groups.js` — оверлей `.face-box` (`.face-box--matched` / `.face-box--candidate` / `.face-box--unassigned`) в модалке `#faceViewerModal`, привязка в `#faceAssignModal`, селект-фильтр и кнопка «Найти лица»; `photos.html`/`photos.js` — фильтр «По лицам»; настройки — карточка `#sec-faces`. CSS в `public/admin.css`, блок `/* --- Библиотека лиц --- */`
|
||||
- **Отдельная модалка лица ученика** — `#studentFacesModal` в `students.html`, кнопка «Лица» в строке ученика (`data-faces-student` + `data-faces-name`, делегирование в `students.js` рядом с `[data-profile-data]`) и `#pfFacesBtn` из окна профиля. Показывает эталоны, найденные фото и похожие непривязанные (`similar` из `GET /api/students/:id/face-photos`, счётчики в `#faceFoundCount`/`#faceSimilarCount`). Эталоны живут **здесь**, а не в `#profileDataModal` — не дублируйте `faceRefsList`/`facePhotosList` между двумя модалками, id должны быть в документе ровно один раз. В `#pfFacesBtn` id ученика читается **до** `closeProfileData()`: та обнуляет `profileDataId`, и передача после неё отправила бы запросы на `/api/students/null/...`
|
||||
- **Список учеников для привязки — по всем группам, не по текущей**: на фото может быть ученик из другой группы, поэтому `#faceAssignSearch` ищет по `allStudents` (`GET /api/students`, уже ограниченный филиалами на сервере) по имени **и по названию группы**, сортировка — сначала ученики текущей группы, в строке видно `.attach-sub` с группой. Не сужайте список до `currentGroupId`. Селект-фильтр `#faceStudentFilter` в тулбаре, наоборот, остаётся по текущей группе и пересобирается в `renderFaceStudentFilter()` при каждом `openPhotos()` — данные учеников грузятся один раз (`allStudentsLoaded`) и не должны перечитываться под текущую группу
|
||||
- **Новую `FACE_ID_*` документируют в трёх местах**: `.env.example`, `README.md` (раздел «Библиотека лиц») и здесь
|
||||
|
||||
|
||||
@@ -609,6 +609,8 @@ function normalizeRestoreData(data) {
|
||||
det_score: optFloat(x.det_score, 0, 1),
|
||||
student_id: x.student_id == null ? null : reqInt(x.student_id),
|
||||
confidence: optFloat(x.confidence, 0, 1),
|
||||
best_student_id: x.best_student_id == null ? null : reqInt(x.best_student_id),
|
||||
best_score: optFloat(x.best_score, 0, 1),
|
||||
created_at: optTs(x.created_at),
|
||||
updated_at: optTs(x.updated_at),
|
||||
})).filter(x => x.source_id && x.photo_path);
|
||||
|
||||
@@ -600,12 +600,15 @@ CREATE TABLE IF NOT EXISTS photo_faces (
|
||||
det_score REAL DEFAULT 0,
|
||||
student_id INT REFERENCES students(id) ON DELETE SET NULL,
|
||||
confidence REAL DEFAULT 0,
|
||||
best_student_id INT REFERENCES students(id) ON DELETE SET NULL,
|
||||
best_score REAL NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_photo_faces_source ON photo_faces(source_type, source_id);
|
||||
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;
|
||||
|
||||
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;
|
||||
|
||||
@@ -756,12 +756,18 @@ CREATE TABLE IF NOT EXISTS photo_faces (
|
||||
det_score REAL DEFAULT 0,
|
||||
student_id INT REFERENCES students(id) ON DELETE SET NULL,
|
||||
confidence REAL DEFAULT 0,
|
||||
best_student_id INT REFERENCES students(id) ON DELETE SET NULL,
|
||||
best_score REAL NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
ALTER TABLE photo_faces ADD COLUMN IF NOT EXISTS best_student_id INT REFERENCES students(id) ON DELETE SET NULL;
|
||||
ALTER TABLE photo_faces ADD COLUMN IF NOT EXISTS best_score REAL NOT NULL DEFAULT 0;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_photo_faces_source ON photo_faces(source_type, source_id);
|
||||
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;
|
||||
|
||||
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;
|
||||
|
||||
+11
-3
@@ -272,6 +272,10 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b
|
||||
.face-shot{position:relative;width:104px;height:78px;border-radius:8px;overflow:hidden;border:1px solid var(--border);flex:0 0 auto}
|
||||
.face-shot img{width:100%;height:100%;object-fit:cover;display:block;cursor:zoom-in}
|
||||
.face-shot a.face-src{position:absolute;left:4px;bottom:4px;background:rgba(0,0,0,.6);color:#fff;font-size:.6rem;font-weight:600;padding:1px 5px;border-radius:5px;text-decoration:none}
|
||||
.face-shot.is-similar a.face-src{background:rgba(180,83,9,.92)}
|
||||
.face-shot .face-score{position:absolute;right:4px;top:4px;background:rgba(15,23,42,.78);color:#e2e8f0;font-size:.62rem;font-weight:700;padding:1px 5px;border-radius:5px}
|
||||
.face-shot .face-score.auto{background:rgba(37,99,235,.9);color:#fff}
|
||||
.face-shot .face-score.manual{background:rgba(71,85,105,.9);color:#fff}
|
||||
.face-box{position:absolute;border:2px solid rgba(148,163,184,.9);border-radius:4px;cursor:pointer;box-sizing:border-box}
|
||||
.face-box:hover{border-color:#fff}
|
||||
.face-box--unassigned{background:rgba(148,163,184,.18);border-style:dashed}
|
||||
@@ -286,7 +290,8 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b
|
||||
.face-stage .face-box{pointer-events:auto}
|
||||
.face-empty{color:var(--muted);font-size:.78rem}
|
||||
.btn-primary.ghost.spinning svg{animation:spin 1s linear infinite}
|
||||
.p-faces{position:absolute;left:8px;top:8px;background:rgba(15,23,42,.72);color:#e2e8f0;font-size:.68rem;font-weight:700;padding:2px 7px;border-radius:999px;pointer-events:none}
|
||||
.p-faces{position:absolute;right:8px;top:8px;background:rgba(15,23,42,.72);color:#e2e8f0;font-size:.68rem;font-weight:700;padding:2px 7px;border-radius:999px;pointer-events:none;display:inline-flex;align-items:center;gap:4px}
|
||||
.p-faces svg{width:12px;height:12px}
|
||||
.p-faces.unassigned{background:#b45309;color:#fff}
|
||||
.p-faces-btn{background:none;border:none;color:var(--accent);cursor:pointer;font-size:.9rem;padding:2px 4px}
|
||||
.attach-item{display:flex;align-items:center;gap:8px;width:100%;text-align:left;background:var(--bg);border:1px solid var(--border);border-radius:8px;padding:8px 10px;cursor:pointer}
|
||||
@@ -318,9 +323,12 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b
|
||||
.photo-item .drag-hint{position:absolute;top:6px;left:6px;z-index:2;background:rgba(0,0,0,.55);color:#fff;border-radius:6px;padding:2px 7px;font-size:.85rem;line-height:1.2;cursor:grab;user-select:none;pointer-events:none}
|
||||
.photo-item .p-cap{padding:8px 10px;font-size:.78rem;color:var(--text);min-height:1.2em;white-space:pre-wrap;word-break:break-word}
|
||||
.photo-item .p-date{font-size:.72rem;color:var(--muted);padding:0 10px 6px}
|
||||
.photo-item .p-actions{display:flex;justify-content:flex-end;gap:4px;padding:6px 8px;border-top:1px solid var(--border)}
|
||||
.photo-item .p-actions button{background:none;border:none;cursor:pointer;font-size:1rem;color:var(--muted);padding:4px}
|
||||
.photo-item .p-actions{display:flex;justify-content:flex-end;gap:4px;padding:6px 8px;border-top:1px solid var(--border);margin-top:auto}
|
||||
.photo-item .p-actions button{background:none;border:none;cursor:pointer;font-size:1rem;color:var(--muted);padding:4px;display:inline-flex;align-items:center;justify-content:center}
|
||||
.photo-item .p-actions button svg{width:16px;height:16px}
|
||||
.photo-item .p-actions .p-edit:hover{color:var(--accent)}
|
||||
.photo-item .p-actions .p-enhance:hover{color:#eab308}
|
||||
.photo-item .p-actions .p-faces-btn:hover{color:var(--accent)}
|
||||
.photo-item .p-actions .p-del:hover{color:#ef4444}
|
||||
.photo-item .p-actions .p-cover:hover{color:#8b5cf6}
|
||||
.photo-item .p-actions .p-cover.active{color:#8b5cf6}
|
||||
|
||||
+15
-13
@@ -1,4 +1,7 @@
|
||||
const DAYS = ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'];
|
||||
const FACE_CANDIDATE_MIN = 0.5;
|
||||
const facePct = v => Math.round((Number(v) || 0) * 100) + '%';
|
||||
const faceCandidateMin = () => (Number(faceViewer.candidateMin) > 0 ? Number(faceViewer.candidateMin) : FACE_CANDIDATE_MIN);
|
||||
let branchesCache = [];
|
||||
let tutorsCache = [];
|
||||
let allGroups = [];
|
||||
@@ -163,6 +166,7 @@ async function loadGroupPhotos() {
|
||||
document.getElementById('photoGrid').innerHTML = photos.length
|
||||
? photos.map(photoHTML).join('')
|
||||
: '<div class="empty" style="grid-column:1/-1">Фото пока нет. Загрузите первое фото.</div>';
|
||||
renderIcons();
|
||||
renderPager(document.getElementById('photosPager'), photoPage, Math.max(1, Math.ceil(totalPhotos / PHOTO_PAGE_SIZE)), goPhotoPage);
|
||||
}
|
||||
|
||||
@@ -170,7 +174,7 @@ function goPhotoPage(p) { photoPage = p; loadGroupPhotos(); }
|
||||
|
||||
let allStudents = [];
|
||||
let allStudentsLoaded = false;
|
||||
let faceViewer = { photoId: null, faces: [], sourceType: 'group', layout: null };
|
||||
let faceViewer = { photoId: null, faces: [], sourceType: 'group', layout: null, candidateMin: FACE_CANDIDATE_MIN };
|
||||
let faceAssignFaceId = null;
|
||||
|
||||
async function loadAllStudents() {
|
||||
@@ -222,15 +226,13 @@ async function openFaceViewer(photoId) {
|
||||
}
|
||||
const data = await res.json();
|
||||
faceViewer.faces = data.faces || [];
|
||||
faceViewer.candidateMin = Number(data.candidate_min) > 0 ? Number(data.candidate_min) : FACE_CANDIDATE_MIN;
|
||||
renderFaceViewer(photo.photo_path);
|
||||
} catch {
|
||||
body.innerHTML = '<div class="empty">Не удалось загрузить лица</div>';
|
||||
}
|
||||
}
|
||||
|
||||
const FACE_CANDIDATE_MIN = 0.5;
|
||||
const facePct = v => Math.round((Number(v) || 0) * 100) + '%';
|
||||
|
||||
function faceBoxesHTML(nw, nh) {
|
||||
if (!nw || !nh) return '';
|
||||
return faceViewer.faces.map(f => {
|
||||
@@ -241,7 +243,7 @@ function faceBoxesHTML(nw, nh) {
|
||||
cls = 'face-box face-box--matched';
|
||||
const name = f.student_name || 'Ученик';
|
||||
label = f.manual ? name + ' · вручную' : name + ' · ' + facePct(f.confidence);
|
||||
} else if (f.best_student_id && f.best_score >= FACE_CANDIDATE_MIN) {
|
||||
} else if (f.best_student_id && f.best_score >= faceCandidateMin()) {
|
||||
cls = 'face-box face-box--candidate';
|
||||
label = 'Похож: ' + (f.best_student_name || 'ученик') + ' · ' + facePct(f.best_score);
|
||||
}
|
||||
@@ -284,7 +286,7 @@ function renderFaceViewer(photoPath) {
|
||||
function closeFaceViewer() {
|
||||
if (faceViewer.layout) window.removeEventListener('resize', faceViewer.layout);
|
||||
document.getElementById('faceViewerModal').classList.remove('open');
|
||||
faceViewer = { photoId: null, faces: [], sourceType: 'group', layout: null };
|
||||
faceViewer = { photoId: null, faces: [], sourceType: 'group', layout: null, candidateMin: FACE_CANDIDATE_MIN };
|
||||
}
|
||||
|
||||
async function openFaceAssign(faceId) {
|
||||
@@ -292,7 +294,7 @@ async function openFaceAssign(faceId) {
|
||||
faceAssignFaceId = faceId;
|
||||
const face = faceViewer.faces.find(f => String(f.id) === String(faceId));
|
||||
const inp = document.getElementById('faceAssignSearch');
|
||||
inp.value = face && !face.student_id && face.best_student_id && face.best_score >= FACE_CANDIDATE_MIN
|
||||
inp.value = face && !face.student_id && face.best_student_id && face.best_score >= faceCandidateMin()
|
||||
? (face.best_student_name || '')
|
||||
: '';
|
||||
renderFaceAssignList(inp.value);
|
||||
@@ -388,7 +390,7 @@ function photoHTML(p) {
|
||||
const faces = p.face_count || 0;
|
||||
const unassigned = p.face_unassigned || 0;
|
||||
const faceBadge = faces
|
||||
? `<span class="p-faces${unassigned ? ' unassigned' : ''}" data-faces-photo="${p.id}" title="Распознанных лиц: ${faces}${unassigned ? `, не опознано: ${unassigned}` : ''}">👤 ${faces}${unassigned ? ` (${unassigned})` : ''}</span>`
|
||||
? `<span class="p-faces${unassigned ? ' unassigned' : ''}" data-faces-photo="${p.id}" title="Распознанных лиц: ${faces}${unassigned ? `, не опознано: ${unassigned}` : ''}"><i data-lucide="scan-face"></i> ${faces}${unassigned ? ` (${unassigned})` : ''}</span>`
|
||||
: '';
|
||||
return `
|
||||
<div class="photo-item" data-photo-id="${p.id}" data-photo-path="${esc(p.photo_path)}" draggable="true">
|
||||
@@ -398,11 +400,11 @@ function photoHTML(p) {
|
||||
<div class="p-cap">${esc(p.caption || '')}</div>
|
||||
<div class="p-date">${taken ? taken + ' · ' : ''}${uploaded}</div>
|
||||
<div class="p-actions">
|
||||
<button class="p-cover${isCover ? ' active' : ''}" data-photo-id="${p.id}" data-photo-path="${esc(p.photo_path)}" title="${isCover ? 'Текущая обложка' : 'Сделать обложкой'}" ${isCover ? 'disabled' : ''}>🖼️</button>
|
||||
<button class="p-edit" data-edit-photo="${p.id}" title="Редактировать">✎</button>
|
||||
<button class="p-faces-btn" data-faces-photo="${p.id}" title="Лица на фото">👤</button>
|
||||
<button class="p-enhance" data-enhance-photo="${p.id}" title="Улучшить фото">✨</button>
|
||||
<button class="p-del" data-del-photo="${p.id}" title="Удалить">×</button>
|
||||
<button class="p-cover${isCover ? ' active' : ''}" data-photo-id="${p.id}" data-photo-path="${esc(p.photo_path)}" title="${isCover ? 'Текущая обложка' : 'Сделать обложкой'}" ${isCover ? 'disabled' : ''}><i data-lucide="image"></i></button>
|
||||
<button class="p-edit" data-edit-photo="${p.id}" title="Редактировать"><i data-lucide="pencil"></i></button>
|
||||
<button class="p-faces-btn" data-faces-photo="${p.id}" title="Лица на фото"><i data-lucide="scan-face"></i></button>
|
||||
<button class="p-enhance" data-enhance-photo="${p.id}" title="Улучшить фото"><i data-lucide="sparkles"></i></button>
|
||||
<button class="p-del" data-del-photo="${p.id}" title="Удалить"><i data-lucide="trash-2"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
+82
-13
@@ -8,6 +8,7 @@ let aSearchTimer = null;
|
||||
let attachGroupLoaded = false;
|
||||
let faceRefs = [];
|
||||
let facePhotos = [];
|
||||
let faceSimilar = [];
|
||||
|
||||
async function loadGroupOptions(sel, selected) {
|
||||
if (!groupOptionsLoaded) {
|
||||
@@ -101,6 +102,7 @@ function renderStudents() {
|
||||
<button class="btn-save" data-save-student="${s.id}">Сохранить</button>
|
||||
<button class="btn-link" data-profile-student="${s.id}" title="Скачать профиль ученика (ZIP: фото и работы)">Профиль</button>
|
||||
<button class="btn-link" data-profile-data="${s.id}" title="Данные профиля: заполняют разделы страницы профиля в архиве">Данные</button>
|
||||
<button class="btn-link" data-faces-student="${s.id}" data-faces-name="${esc(s.name)}" title="Эталоны лиц и фото, где ученик распознан">Лица</button>
|
||||
<button class="btn-link" data-export-student="${esc(s.name)}" title="Сформировать ZIP-отчёт: фотографии и файлы">Отчёт</button>
|
||||
<button class="btn-link" data-copy-student="${esc(s.name)}" title="Скопировать ссылку с подстановкой имени">Ссылка</button>
|
||||
<button class="btn-del" data-del-student="${s.id}" title="Удалить">×</button>
|
||||
@@ -247,8 +249,6 @@ function openProfileData(id) {
|
||||
profileDataId = id;
|
||||
loadGroupOptions();
|
||||
loadStudentPhotos(id);
|
||||
loadFaceRefs(id);
|
||||
loadFacePhotos(id);
|
||||
fetch(`${API}/api/students/${id}/profile`, { headers: hdr() })
|
||||
.then(r => (r.ok ? r.json() : Promise.reject(new Error('load'))))
|
||||
.then(data => fillProfileForm(data.profile, data.name, data.photo_path))
|
||||
@@ -259,8 +259,27 @@ function openProfileData(id) {
|
||||
function closeProfileData() {
|
||||
document.getElementById('profileDataModal').classList.remove('open');
|
||||
profileDataId = null;
|
||||
}
|
||||
|
||||
async function openStudentFaces(id, name) {
|
||||
profileDataId = id;
|
||||
faceRefs = [];
|
||||
facePhotos = [];
|
||||
faceSimilar = [];
|
||||
document.getElementById('studentFacesName').textContent = name || '';
|
||||
renderFaceRefs();
|
||||
renderFacePhotos();
|
||||
renderFaceSimilar();
|
||||
document.getElementById('studentFacesModal').classList.add('open');
|
||||
await Promise.all([loadFaceRefs(id), loadFacePhotos(id)]);
|
||||
}
|
||||
|
||||
function closeStudentFaces() {
|
||||
document.getElementById('studentFacesModal').classList.remove('open');
|
||||
profileDataId = null;
|
||||
faceRefs = [];
|
||||
facePhotos = [];
|
||||
faceSimilar = [];
|
||||
}
|
||||
|
||||
async function loadFaceRefs(id) {
|
||||
@@ -294,6 +313,14 @@ function renderFaceRefs() {
|
||||
`).join('');
|
||||
}
|
||||
|
||||
function refreshFacesAfterRefChange() {
|
||||
const id = profileDataId;
|
||||
if (!id) return;
|
||||
setTimeout(() => {
|
||||
if (profileDataId === id) loadFacePhotos(id);
|
||||
}, 2500);
|
||||
}
|
||||
|
||||
async function addFaceRef(file) {
|
||||
if (!profileDataId || !file) return;
|
||||
if (!file.type.startsWith('image/')) {
|
||||
@@ -312,7 +339,8 @@ async function addFaceRef(file) {
|
||||
}
|
||||
faceRefs.push(data);
|
||||
renderFaceRefs();
|
||||
showToast('Эталон добавлен');
|
||||
showToast('Эталон добавлен, пересчитываем лица на всех фото...');
|
||||
refreshFacesAfterRefChange();
|
||||
} catch {
|
||||
showToast('Не удалось добавить эталон');
|
||||
}
|
||||
@@ -327,6 +355,8 @@ async function delFaceRef(refId) {
|
||||
}
|
||||
faceRefs = faceRefs.filter(r => r.id !== refId);
|
||||
renderFaceRefs();
|
||||
showToast('Эталон удалён, пересчитываем лица...');
|
||||
refreshFacesAfterRefChange();
|
||||
} catch {
|
||||
showToast('Не удалось удалить эталон');
|
||||
}
|
||||
@@ -341,10 +371,14 @@ async function loadFacePhotos(id) {
|
||||
}
|
||||
const data = await res.json();
|
||||
facePhotos = data.photos || [];
|
||||
faceSimilar = data.similar || [];
|
||||
renderFacePhotos();
|
||||
renderFaceSimilar();
|
||||
} catch {
|
||||
facePhotos = [];
|
||||
faceSimilar = [];
|
||||
renderFacePhotos();
|
||||
renderFaceSimilar();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -353,19 +387,42 @@ function facePhotoHref(p) {
|
||||
return 'photos.html';
|
||||
}
|
||||
|
||||
const facePctOf = v => Math.round((Number(v) || 0) * 100) + '%';
|
||||
|
||||
function faceShotHTML(p, i, opts) {
|
||||
const score = opts.manual ? 'вручную' : facePctOf(p.confidence);
|
||||
const cls = opts.similar ? 'face-score' : 'face-score ' + (opts.manual ? 'manual' : 'auto');
|
||||
return `
|
||||
<div class="face-shot${opts.similar ? ' is-similar' : ''}">
|
||||
<img src="${esc(thumbSrc(p.path))}" data-face-shot="${i}" alt="" loading="lazy">
|
||||
<span class="${cls}">${esc(score)}</span>
|
||||
<a class="face-src" href="${facePhotoHref(p)}">${esc(p.group_name || (p.source_type === 'entry' ? 'Запись' : 'Группа'))}</a>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderFacePhotos() {
|
||||
const wrap = document.getElementById('facePhotosList');
|
||||
if (!wrap) return;
|
||||
const cnt = document.getElementById('faceFoundCount');
|
||||
if (cnt) cnt.textContent = facePhotos.length ? `— ${facePhotos.length}` : '';
|
||||
if (!facePhotos.length) {
|
||||
wrap.innerHTML = '<span class="face-empty">Пока нет фото, где распознан этот ученик</span>';
|
||||
wrap.innerHTML = '<span class="face-empty">Пока нет фото, где лицо ученика привязано</span>';
|
||||
return;
|
||||
}
|
||||
wrap.innerHTML = facePhotos.map((p, i) => `
|
||||
<div class="face-shot">
|
||||
<img src="${esc(thumbSrc(p.path))}" data-face-shot="${i}" alt="" loading="lazy">
|
||||
<a class="face-src" href="${facePhotoHref(p)}">${p.source_type === 'entry' ? 'Запись' : 'Группа'}</a>
|
||||
</div>
|
||||
`).join('');
|
||||
wrap.innerHTML = facePhotos.map((p, i) => faceShotHTML(p, i, { manual: p.manual, similar: false })).join('');
|
||||
}
|
||||
|
||||
function renderFaceSimilar() {
|
||||
const wrap = document.getElementById('faceSimilarList');
|
||||
if (!wrap) return;
|
||||
const cnt = document.getElementById('faceSimilarCount');
|
||||
if (cnt) cnt.textContent = faceSimilar.length ? `— ${faceSimilar.length}` : '';
|
||||
if (!faceSimilar.length) {
|
||||
wrap.innerHTML = '<span class="face-empty">Похожих непривязанных лиц не найдено</span>';
|
||||
return;
|
||||
}
|
||||
wrap.innerHTML = faceSimilar.map((p, i) => faceShotHTML(p, i, { manual: false, similar: true })).join('');
|
||||
}
|
||||
|
||||
async function loadStudentPhotos(id) {
|
||||
@@ -715,6 +772,8 @@ document.getElementById('studentList').addEventListener('click', e => {
|
||||
if (pf) { exportStudentProfile(parseInt(pf.dataset.profileStudent, 10)); return; }
|
||||
const pd = e.target.closest('[data-profile-data]');
|
||||
if (pd) { openProfileData(parseInt(pd.dataset.profileData, 10)); return; }
|
||||
const fc = e.target.closest('[data-faces-student]');
|
||||
if (fc) { openStudentFaces(parseInt(fc.dataset.facesStudent, 10), fc.dataset.facesName || ''); return; }
|
||||
const dl = e.target.closest('[data-del-student]');
|
||||
if (dl) { delStudent(parseInt(dl.dataset.delStudent, 10)); }
|
||||
});
|
||||
@@ -751,6 +810,14 @@ document.addEventListener('paste', e => {
|
||||
});
|
||||
document.getElementById('profileDataModal').addEventListener('click', e => { if (e.target === e.currentTarget) closeProfileData(); });
|
||||
|
||||
document.getElementById('pfFacesBtn').addEventListener('click', () => {
|
||||
const pid = profileDataId;
|
||||
const name = document.getElementById('profileDataTitle').textContent;
|
||||
closeProfileData();
|
||||
openStudentFaces(pid, name);
|
||||
});
|
||||
document.getElementById('studentFacesCloseBtn').addEventListener('click', closeStudentFaces);
|
||||
document.getElementById('studentFacesModal').addEventListener('click', e => { if (e.target === e.currentTarget) closeStudentFaces(); });
|
||||
document.getElementById('faceRefAddBtn').addEventListener('click', () => document.getElementById('faceRefFile').click());
|
||||
document.getElementById('faceRefFile').addEventListener('change', e => {
|
||||
const f = e.target.files[0];
|
||||
@@ -762,17 +829,19 @@ document.getElementById('faceRefsList').addEventListener('click', e => {
|
||||
if (!btn) return;
|
||||
delFaceRef(parseInt(btn.dataset.faceRefDel, 10));
|
||||
});
|
||||
document.getElementById('facePhotosList').addEventListener('click', e => {
|
||||
function openFaceShot(list, e) {
|
||||
const img = e.target.closest('[data-face-shot]');
|
||||
if (!img) return;
|
||||
const p = facePhotos[parseInt(img.dataset.faceShot, 10)];
|
||||
const p = list[parseInt(img.dataset.faceShot, 10)];
|
||||
if (!p) return;
|
||||
const m = document.getElementById('imgModal');
|
||||
const s = document.getElementById('imgModalSrc');
|
||||
if (!m || !s) return;
|
||||
s.src = `${API}${p.path}`;
|
||||
m.classList.add('open');
|
||||
});
|
||||
}
|
||||
document.getElementById('facePhotosList').addEventListener('click', e => openFaceShot(facePhotos, e));
|
||||
document.getElementById('faceSimilarList').addEventListener('click', e => openFaceShot(faceSimilar, e));
|
||||
|
||||
(async () => {
|
||||
if (await checkAuth()) {
|
||||
|
||||
+34
-10
@@ -208,18 +208,12 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-field" style="grid-column:1/-1">
|
||||
<label>Библиотека лиц — эталонные фото для распознавания</label>
|
||||
<div class="face-refs" id="faceRefsList"></div>
|
||||
<div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-top:6px">
|
||||
<input type="file" id="faceRefFile" accept="image/*" hidden>
|
||||
<button type="button" class="btn-primary ghost" id="faceRefAddBtn">Добавить эталон</button>
|
||||
<span class="hint">1–2 фото анфас при хорошем свете. Лицо на фото ищет сервис face-id.</span>
|
||||
<label>Распознавание лиц</label>
|
||||
<div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap">
|
||||
<button type="button" class="btn-primary ghost" id="pfFacesBtn">Эталоны и фото с учеником</button>
|
||||
<span class="hint">Задать эталонные фото для распознавания и посмотреть, где ученик уже найден на фото.</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-field" style="grid-column:1/-1">
|
||||
<label>Фото с учеником (по распознаванию лиц)</label>
|
||||
<div class="face-refs" id="facePhotosList"></div>
|
||||
</div>
|
||||
<div style="grid-column:1/-1;display:flex;justify-content:flex-end;gap:8px">
|
||||
<button type="button" class="btn-primary ghost" id="profileDataCancelBtn">Отмена</button>
|
||||
<button type="submit" class="btn-primary">Сохранить</button>
|
||||
@@ -228,6 +222,36 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="studentFacesModal">
|
||||
<div class="edit-modal" style="max-width:900px;width:96%;max-height:92dvh;overflow-y:auto">
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:12px">
|
||||
<h3 style="font-size:1.05rem;font-weight:600">Лица: <span id="studentFacesName"></span></h3>
|
||||
<button type="button" class="btn-primary ghost" id="studentFacesCloseBtn">Закрыть</button>
|
||||
</div>
|
||||
|
||||
<div class="settings-field">
|
||||
<label>Эталоны лиц</label>
|
||||
<div class="face-refs" id="faceRefsList"></div>
|
||||
<div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-top:6px">
|
||||
<input type="file" id="faceRefFile" accept="image/*" hidden>
|
||||
<button type="button" class="btn-primary ghost" id="faceRefAddBtn">Добавить эталон</button>
|
||||
<span class="hint">1–2 фото анфас при хорошем свете. После добавления система пересчитает лица на всех фото.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-field">
|
||||
<label>Фото, где лицо ученика найдено <span id="faceFoundCount" class="hint"></span></label>
|
||||
<div class="face-refs" id="facePhotosList"></div>
|
||||
</div>
|
||||
|
||||
<div class="settings-field">
|
||||
<label>Похожие лица — ещё не привязаны <span id="faceSimilarCount" class="hint"></span></label>
|
||||
<div class="face-refs" id="faceSimilarList"></div>
|
||||
<span class="hint">Фото, где есть лицо, похожее на этого ученика, но сходство ниже порога автопривязки. Привязку ставит тьютор в просмотрщике фото на странице группы.</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="imgModal">
|
||||
<img id="imgModalSrc" alt="">
|
||||
</div>
|
||||
|
||||
@@ -1720,12 +1720,17 @@ async function ensureFaceTables() {
|
||||
det_score REAL DEFAULT 0,
|
||||
student_id INT REFERENCES students(id) ON DELETE SET NULL,
|
||||
confidence REAL DEFAULT 0,
|
||||
best_student_id INT REFERENCES students(id) ON DELETE SET NULL,
|
||||
best_score REAL NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ DEFAULT now()
|
||||
)`);
|
||||
await pool.query('ALTER TABLE photo_faces ADD COLUMN IF NOT EXISTS best_student_id INT REFERENCES students(id) ON DELETE SET NULL');
|
||||
await pool.query('ALTER TABLE photo_faces ADD COLUMN IF NOT EXISTS best_score REAL NOT NULL DEFAULT 0');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_photo_faces_source ON photo_faces(source_type, source_id)');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_photo_faces_student ON photo_faces(student_id)');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_photo_faces_source_student ON photo_faces(source_type, source_id, student_id)');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_photo_faces_best ON photo_faces(best_student_id) WHERE student_id IS NULL');
|
||||
await pool.query('ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS face_scanned_at TIMESTAMPTZ');
|
||||
await pool.query('ALTER TABLE entry_photos ADD COLUMN IF NOT EXISTS face_scanned_at TIMESTAMPTZ');
|
||||
}
|
||||
@@ -1777,6 +1782,8 @@ function faceThreshold(v) {
|
||||
return Math.min(0.99, Math.max(0.3, n));
|
||||
}
|
||||
|
||||
const FACE_CANDIDATE_MIN = 0.5;
|
||||
|
||||
function safeId(v) {
|
||||
const n = parseInt(v, 10);
|
||||
return Number.isFinite(n) && n > 0 ? n : 0;
|
||||
@@ -1815,11 +1822,6 @@ function matchFaceToStudent(embedding, refs, threshold) {
|
||||
return { student_id: studentId, confidence: best, best_id: bestId, best_name: bestName };
|
||||
}
|
||||
|
||||
function bestFaceCandidate(embedding, refs) {
|
||||
const m = matchFaceToStudent(embedding, refs, Infinity);
|
||||
return { score: m.confidence, student_id: m.best_id, name: m.best_name };
|
||||
}
|
||||
|
||||
async function photoFaceGroupId(sourceType, sourceId) {
|
||||
if (sourceType === 'entry') {
|
||||
const { rows } = await pool.query('SELECT e.group_id FROM entry_photos ep JOIN entries e ON e.id = ep.entry_id WHERE ep.id = $1', [sourceId]);
|
||||
@@ -1849,9 +1851,15 @@ async function rematchFaces(opts = {}) {
|
||||
scanned += rows.length;
|
||||
for (const r of rows) {
|
||||
const m = matchFaceToStudent(r.embedding, refs, threshold);
|
||||
if (!m.student_id) continue;
|
||||
if (!m.student_id) {
|
||||
await client.query(
|
||||
'UPDATE photo_faces SET student_id = $1, confidence = $2, updated_at = now() WHERE id = $3',
|
||||
'UPDATE photo_faces SET best_student_id = $1, best_score = $2, updated_at = now() WHERE id = $3',
|
||||
[m.best_id || null, Number(m.confidence) || 0, r.id]
|
||||
);
|
||||
continue;
|
||||
}
|
||||
await client.query(
|
||||
'UPDATE photo_faces SET student_id = $1, confidence = $2, best_student_id = NULL, best_score = 0, updated_at = now() WHERE id = $3',
|
||||
[m.student_id, m.confidence, r.id]
|
||||
);
|
||||
matched++;
|
||||
@@ -1892,10 +1900,11 @@ async function scanFacesForPhoto(sourceType, sourceId, photoPath, opts = {}) {
|
||||
const m = matchFaceToStudent(f.embedding, refs, threshold);
|
||||
const b = Array.isArray(f.bbox) ? f.bbox : [];
|
||||
await client.query(
|
||||
`INSERT INTO photo_faces (source_type, source_id, photo_path, bbox, embedding, det_score, student_id, confidence)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
|
||||
`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)`,
|
||||
[sourceType, sourceId, photoPath, JSON.stringify({ x: b[0] || 0, y: b[1] || 0, w: b[2] || 0, h: b[3] || 0 }),
|
||||
JSON.stringify(f.embedding), Number(f.det_score) || 0, m.student_id, m.confidence]
|
||||
JSON.stringify(f.embedding), Number(f.det_score) || 0, m.student_id, m.confidence,
|
||||
m.student_id ? null : (m.best_id || null), m.student_id ? 0 : (Number(m.confidence) || 0)]
|
||||
);
|
||||
}
|
||||
await client.query(
|
||||
@@ -5271,11 +5280,16 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
|
||||
const st = await client.query('SELECT 1 FROM students WHERE id = $1', [x.student_id]);
|
||||
if (!st.rowCount) continue;
|
||||
}
|
||||
if (x.best_student_id != null) {
|
||||
const bs = await client.query('SELECT 1 FROM students WHERE id = $1', [x.best_student_id]);
|
||||
if (!bs.rowCount) continue;
|
||||
}
|
||||
await client.query(
|
||||
`INSERT INTO photo_faces (id, source_type, source_id, photo_path, bbox, embedding, det_score, student_id, confidence, created_at, updated_at)
|
||||
VALUES ($1,$2,$3,$4,$5::jsonb,$6::jsonb,$7,$8,$9,$10,$11)`,
|
||||
`INSERT INTO photo_faces (id, source_type, source_id, photo_path, bbox, embedding, det_score, student_id, confidence, best_student_id, best_score, created_at, updated_at)
|
||||
VALUES ($1,$2,$3,$4,$5::jsonb,$6::jsonb,$7,$8,$9,$10,$11,$12,$13)`,
|
||||
[x.id, x.source_type, x.source_id, x.photo_path, JSON.stringify(x.bbox || {}), JSON.stringify(x.embedding || []),
|
||||
x.det_score || 0, x.student_id, x.confidence || 0, x.created_at || null, x.updated_at || null]
|
||||
x.det_score || 0, x.student_id, x.confidence || 0, x.best_student_id || null, x.best_score || 0,
|
||||
x.created_at || null, x.updated_at || null]
|
||||
);
|
||||
}
|
||||
for (const x of ndata.student_photos) {
|
||||
@@ -8481,6 +8495,7 @@ app.delete('/api/students/:id/face-refs/:refId', requireAuth, async (req, res) =
|
||||
safeUnlink(rows[0].photo_path.replace(/^\/?uploads\//, 'uploads/'));
|
||||
await logAudit(req, 'student.face_ref.delete', { student_id: id, ref_id: refId });
|
||||
res.json({ ok: true });
|
||||
rematchFacesBackground();
|
||||
});
|
||||
|
||||
|
||||
@@ -8506,20 +8521,18 @@ app.get('/api/photos/:sourceType/:sourceId/faces', requireAuth, async (req, res)
|
||||
return res.status(403).json({ error: 'Нет доступа' });
|
||||
}
|
||||
const { rows } = await pool.query(
|
||||
`SELECT pf.id, pf.bbox, pf.student_id, pf.confidence, pf.det_score, pf.embedding, s.name AS student_name
|
||||
`SELECT pf.id, pf.bbox, pf.student_id, pf.confidence, pf.det_score,
|
||||
pf.best_student_id, pf.best_score, s.name AS student_name, bs.name AS best_student_name
|
||||
FROM photo_faces pf
|
||||
LEFT JOIN students s ON s.id = pf.student_id
|
||||
LEFT JOIN students bs ON bs.id = pf.best_student_id
|
||||
WHERE pf.source_type = $1 AND pf.source_id = $2
|
||||
ORDER BY (pf.bbox->>'y')::int ASC, (pf.bbox->>'x')::int ASC`,
|
||||
[sourceType, sourceId]
|
||||
);
|
||||
const refs = await loadFaceRefs();
|
||||
res.json({
|
||||
faces: rows.map(r => {
|
||||
const best = r.student_id
|
||||
? { score: Number(r.confidence) || 0, student_id: r.student_id, name: r.student_name }
|
||||
: bestFaceCandidate(r.embedding, refs);
|
||||
return {
|
||||
candidate_min: FACE_CANDIDATE_MIN,
|
||||
faces: rows.map(r => ({
|
||||
id: r.id,
|
||||
x: r.bbox.x || 0, y: r.bbox.y || 0, w: r.bbox.w || 0, h: r.bbox.h || 0,
|
||||
student_id: r.student_id,
|
||||
@@ -8527,11 +8540,10 @@ app.get('/api/photos/:sourceType/:sourceId/faces', requireAuth, async (req, res)
|
||||
confidence: Number(r.confidence) || 0,
|
||||
det_score: r.det_score,
|
||||
manual: r.student_id ? Number(r.confidence) >= 1 : false,
|
||||
best_score: best.score || 0,
|
||||
best_student_id: best.student_id || null,
|
||||
best_student_name: best.name || null,
|
||||
};
|
||||
}),
|
||||
best_score: Number(r.best_score) || 0,
|
||||
best_student_id: r.best_student_id,
|
||||
best_student_name: r.best_student_name,
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8564,7 +8576,10 @@ app.put('/api/photo-faces/:faceId/assign', requireAuth, async (req, res) => {
|
||||
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, faceGroupId))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этому фото' });
|
||||
}
|
||||
await pool.query('UPDATE photo_faces SET student_id = $1, confidence = 1, updated_at = now() WHERE id = $2', [studentId || null, faceId]);
|
||||
await pool.query(
|
||||
'UPDATE photo_faces SET student_id = $1, confidence = 1, best_student_id = NULL, best_score = 0, updated_at = now() WHERE id = $2',
|
||||
[studentId || null, faceId]
|
||||
);
|
||||
await logAudit(req, 'photo_face.assign', { face_id: faceId, student_id: studentId || null, was: chk[0].student_id });
|
||||
res.json({ ok: true, student_id: studentId || null });
|
||||
});
|
||||
@@ -8578,6 +8593,9 @@ app.get('/api/students/:id/face-photos', requireAuth, async (req, res) => {
|
||||
}
|
||||
const acc = await studentProfileAccess(req.user, id);
|
||||
if (!acc.found) return res.status(acc.forbidden ? 403 : 404).json({ error: 'Ученик не найден' });
|
||||
const params = [];
|
||||
const gscope = apiBranchClause(req.user, 'g.branch_id', params);
|
||||
params.push(id);
|
||||
const { rows } = await pool.query(
|
||||
`SELECT DISTINCT ON (pf.source_type, pf.source_id) pf.source_type, pf.source_id, pf.photo_path,
|
||||
gp.group_id, e.id AS entry_ref, g.name AS group_name,
|
||||
@@ -8587,9 +8605,26 @@ app.get('/api/students/:id/face-photos', requireAuth, async (req, res) => {
|
||||
LEFT JOIN entry_photos ep ON ep.id = pf.source_id AND pf.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 pf.student_id = $1
|
||||
WHERE pf.student_id = $${params.length}${gscope}
|
||||
ORDER BY pf.source_type, pf.source_id, COALESCE(gp.created_at, ep.created_at) DESC`,
|
||||
[id]
|
||||
params
|
||||
);
|
||||
const sparams = [];
|
||||
const sscope = apiBranchClause(req.user, 'g.branch_id', sparams);
|
||||
sparams.push(id);
|
||||
const { rows: srows } = await pool.query(
|
||||
`SELECT DISTINCT ON (pf.source_type, pf.source_id) pf.source_type, pf.source_id, pf.photo_path,
|
||||
gp.group_id, e.id AS entry_ref, g.name AS group_name,
|
||||
COALESCE(gp.created_at, ep.created_at) AS created_at, pf.best_score
|
||||
FROM photo_faces pf
|
||||
LEFT JOIN group_photos gp ON gp.id = pf.source_id AND pf.source_type = 'group'
|
||||
LEFT JOIN entry_photos ep ON ep.id = pf.source_id AND pf.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 pf.student_id IS NULL AND pf.best_student_id = $${sparams.length}
|
||||
AND pf.best_score >= $${sparams.length + 1}${sscope}
|
||||
ORDER BY pf.source_type, pf.source_id, pf.best_score DESC`,
|
||||
sparams.concat([FACE_CANDIDATE_MIN])
|
||||
);
|
||||
res.json({
|
||||
photos: rows.map(r => ({
|
||||
@@ -8599,8 +8634,18 @@ app.get('/api/students/:id/face-photos', requireAuth, async (req, res) => {
|
||||
group_name: r.group_name,
|
||||
created_at: r.created_at,
|
||||
confidence: r.confidence,
|
||||
manual: Number(r.confidence) >= 1,
|
||||
})),
|
||||
similar: srows.map(r => ({
|
||||
source_type: r.source_type,
|
||||
source_id: r.source_type === 'group' ? r.group_id : (r.entry_ref || r.source_id),
|
||||
path: r.photo_path,
|
||||
group_name: r.group_name,
|
||||
created_at: r.created_at,
|
||||
score: Number(r.best_score) || 0,
|
||||
})),
|
||||
total: rows.length,
|
||||
similar_total: srows.length,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user