Implement photo-related enhancements and chat updates
This commit is contained in:
@@ -7,6 +7,13 @@ let studentsLoaded = false;
|
||||
let sourcesLoaded = false;
|
||||
let searchTimer = null;
|
||||
|
||||
const FACE_CANDIDATE_MIN = 0.5;
|
||||
let faceViewer = { sourceType: 'group', photoId: null, photoPath: '', faces: [], layout: null, candidateMin: FACE_CANDIDATE_MIN };
|
||||
let faceAssignFaceId = null;
|
||||
let allStudents = [];
|
||||
let allStudentsLoaded = false;
|
||||
let faceScanLiveSource = null;
|
||||
|
||||
function humanSize(b) {
|
||||
if (!b) return '';
|
||||
if (b < 1024) return b + ' Б';
|
||||
@@ -36,9 +43,11 @@ function photoCardHTML(p) {
|
||||
if (p.group_name) meta.push(esc(p.group_name));
|
||||
const link = photoLink(p);
|
||||
const canFix = isAdmin() && p.photo_key && p.photo_id != null;
|
||||
const canFaces = !!(p.face_source_type && p.face_photo_id != null);
|
||||
return `
|
||||
<div class="ph-card">
|
||||
<img src="${esc(photoThumb(url))}" data-img="${esc(url)}" loading="lazy" decoding="async" alt="" onerror="photoImgError(this)">
|
||||
${canFaces ? `<button type="button" class="btn-link ph-faces-btn" data-fv-source="${esc(p.face_source_type)}" data-fv-id="${esc(p.face_photo_id)}" data-fv-path="${esc(url)}" title="Распознанные лица"><i data-lucide="scan-face"></i></button>` : ''}
|
||||
<div class="ph-body">
|
||||
<span class="ph-badge">${esc(p.source_label)}</span>
|
||||
<div class="ph-title">${esc(p.title || 'Без описания')}</div>
|
||||
@@ -140,6 +149,7 @@ async function loadPhotos() {
|
||||
totalPhotos = srcFilter ? currentPhotos.length : data.total;
|
||||
fillSourceOptions();
|
||||
renderGrid();
|
||||
if (typeof renderIcons === 'function') renderIcons();
|
||||
renderPager(document.getElementById('pager'), page, Math.max(1, Math.ceil(totalPhotos / PAGE_SIZE)), goPage);
|
||||
}
|
||||
|
||||
@@ -148,6 +158,210 @@ function goPage(p) {
|
||||
loadPhotos();
|
||||
}
|
||||
|
||||
const faceCandidateMin = () => (Number(faceViewer.candidateMin) > 0 ? Number(faceViewer.candidateMin) : FACE_CANDIDATE_MIN);
|
||||
|
||||
async function loadFaceViewerFaces(sourceType, photoId) {
|
||||
const res = await fetch(`${API}/api/photos/${sourceType}/${photoId}/faces`, { headers: hdr() });
|
||||
if (!res.ok) throw new Error('faces');
|
||||
const data = await res.json();
|
||||
faceViewer.faces = data.faces || [];
|
||||
faceViewer.candidateMin = Number(data.candidate_min) > 0 ? Number(data.candidate_min) : FACE_CANDIDATE_MIN;
|
||||
faceViewer.imgWidth = Number(data.img_width) || 0;
|
||||
faceViewer.imgHeight = Number(data.img_height) || 0;
|
||||
faceViewer.scanned = Boolean(data.scanned);
|
||||
return faceViewer;
|
||||
}
|
||||
|
||||
function faceViewerWarn(msg) {
|
||||
const el = document.getElementById('faceViewerWarn');
|
||||
if (!el) return;
|
||||
if (msg) { el.textContent = msg; el.hidden = false; }
|
||||
else { el.textContent = ''; el.hidden = true; }
|
||||
}
|
||||
|
||||
function checkFaceViewerSync(nw, nh) {
|
||||
if (!faceViewer.imgWidth || !faceViewer.imgHeight) return;
|
||||
if (faceViewer.imgWidth === nw && faceViewer.imgHeight === nh) { faceViewerWarn(''); return; }
|
||||
faceViewerWarn(`Рамки рассчитаны для ${faceViewer.imgWidth}×${faceViewer.imgHeight}px, а текущее фото ${nw}×${nh}px. Нажмите «Переиндексировать», чтобы пересчитать.`);
|
||||
}
|
||||
|
||||
function faceBoxesHTML(nw, nh) {
|
||||
return faceViewer.faces.map(f => {
|
||||
const left = (f.x / nw) * 100;
|
||||
const top = (f.y / nh) * 100;
|
||||
const width = (f.w / nw) * 100;
|
||||
const height = (f.h / nh) * 100;
|
||||
let cls = 'face-box--unassigned';
|
||||
let label = 'Не опознано';
|
||||
if (f.student_id) {
|
||||
cls = 'face-box--matched';
|
||||
label = f.manual ? `${esc(f.student_name || '')} · вручную` : `${esc(f.student_name || '')} · ${Math.round((f.confidence || 0) * 100)}%`;
|
||||
} else if (f.best_student_id && f.best_score >= faceCandidateMin()) {
|
||||
cls = 'face-box--candidate';
|
||||
label = `Похож: ${esc(f.best_student_name || '')} · ${Math.round((f.best_score || 0) * 100)}%`;
|
||||
}
|
||||
return `<button type="button" class="face-box ${cls}" data-face-box="${f.id}" style="left:${left}%;top:${top}%;width:${width}%;height:${height}%" title="${esc(label)}"><span class="face-box-label">${label}</span></button>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderFaceViewer(photoPath) {
|
||||
if (faceViewer.layout) window.removeEventListener('resize', faceViewer.layout);
|
||||
const body = document.getElementById('faceViewerBody');
|
||||
if (!body) return;
|
||||
body.innerHTML = `<div class="face-stage"><img id="faceStageImg" src="${esc(API + photoPath)}" data-img="${esc(photoPath)}" alt=""><div class="face-overlay" id="faceOverlay"></div></div>`;
|
||||
const img = document.getElementById('faceStageImg');
|
||||
const overlay = document.getElementById('faceOverlay');
|
||||
const stage = img.parentElement;
|
||||
const layout = () => {
|
||||
const nw = img.naturalWidth || 0;
|
||||
const nh = img.naturalHeight || 0;
|
||||
if (!nw || !nh) return;
|
||||
overlay.style.width = img.clientWidth + 'px';
|
||||
overlay.style.height = img.clientHeight + 'px';
|
||||
overlay.innerHTML = faceViewer.faces.length ? faceBoxesHTML(nw, nh) : '<div class="empty">Лиц не найдено</div>';
|
||||
checkFaceViewerSync(nw, nh);
|
||||
if (typeof renderIcons === 'function') renderIcons();
|
||||
};
|
||||
faceViewer.layout = layout;
|
||||
window.addEventListener('resize', layout);
|
||||
img.addEventListener('load', layout);
|
||||
if (img.complete) layout();
|
||||
}
|
||||
|
||||
async function refreshOpenFaceViewer() {
|
||||
const photoId = faceViewer.photoId;
|
||||
if (!photoId) return;
|
||||
try {
|
||||
await loadFaceViewerFaces(faceViewer.sourceType, photoId);
|
||||
renderFaceViewer(faceViewer.photoPath);
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
function closeFaceViewer() {
|
||||
if (faceViewer.layout) window.removeEventListener('resize', faceViewer.layout);
|
||||
faceViewer.layout = null;
|
||||
faceViewer.photoId = null;
|
||||
faceViewer.photoPath = '';
|
||||
const m = document.getElementById('faceViewerModal');
|
||||
if (m) m.classList.remove('open');
|
||||
}
|
||||
|
||||
async function openFaceViewer(sourceType, photoId, photoPath) {
|
||||
if (faceViewer.layout) window.removeEventListener('resize', faceViewer.layout);
|
||||
faceViewer = { sourceType, photoId, photoPath, faces: [], layout: null, candidateMin: FACE_CANDIDATE_MIN };
|
||||
const body = document.getElementById('faceViewerBody');
|
||||
if (body) body.innerHTML = '<div class="empty">Загрузка...</div>';
|
||||
faceViewerWarn('');
|
||||
document.getElementById('faceViewerModal').classList.add('open');
|
||||
try {
|
||||
await loadFaceViewerFaces(sourceType, photoId);
|
||||
renderFaceViewer(photoPath);
|
||||
} catch (e) {
|
||||
if (body) body.innerHTML = `<div class="empty">${e.status === 404 ? 'Фото не найдено' : 'Не удалось загрузить лица'}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAllStudents() {
|
||||
if (allStudentsLoaded) return;
|
||||
try {
|
||||
const res = await fetch(`${API}/api/students?limit=10000`, { headers: hdr() });
|
||||
const data = res.ok ? await res.json() : [];
|
||||
const list = Array.isArray(data) ? data : (data && data.students) || [];
|
||||
allStudents = list.filter(s => !s.deleted_at).map(s => ({ id: s.id, name: s.name, group_id: s.group_id, group_name: s.group_name || s.group }));
|
||||
allStudentsLoaded = true;
|
||||
} catch { allStudents = []; }
|
||||
}
|
||||
|
||||
function renderFaceAssignList(q) {
|
||||
const list = document.getElementById('faceAssignList');
|
||||
if (!list) return;
|
||||
const query = (q || '').trim().toLowerCase();
|
||||
const filtered = allStudents.filter(s => {
|
||||
if (!query) return true;
|
||||
return (s.name || '').toLowerCase().includes(query) || (s.group_name || '').toLowerCase().includes(query);
|
||||
}).sort((a, b) => {
|
||||
// photos page has no "current group" concept; keep id order
|
||||
return String(a.name).localeCompare(String(b.name), 'ru');
|
||||
});
|
||||
list.innerHTML = filtered.map(s => `
|
||||
<button type="button" class="attach-item" data-face-pick="${s.id}">
|
||||
<span class="attach-name">${esc(s.name)}</span>
|
||||
<span class="attach-sub">${esc(s.group_name || '')}</span>
|
||||
</button>
|
||||
`).join('');
|
||||
if (typeof renderIcons === 'function') renderIcons();
|
||||
}
|
||||
|
||||
function openFaceAssign(faceId) {
|
||||
faceAssignFaceId = faceId;
|
||||
const face = faceViewer.faces.find(f => String(f.id) === String(faceId));
|
||||
const inp = document.getElementById('faceAssignSearch');
|
||||
if (inp) inp.value = (face && !face.student_id && face.best_student_id && face.best_score >= faceCandidateMin()) ? (face.best_student_name || '') : '';
|
||||
loadAllStudents().then(() => renderFaceAssignList(inp ? inp.value : ''));
|
||||
document.getElementById('faceAssignModal').classList.add('open');
|
||||
}
|
||||
|
||||
async function assignFace(studentId) {
|
||||
if (!faceAssignFaceId) return;
|
||||
try {
|
||||
const res = await fetch(`${API}/api/photo-faces/${faceAssignFaceId}/assign`, {
|
||||
method: 'PUT',
|
||||
headers: { ...hdr(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ student_id: studentId || 0 })
|
||||
});
|
||||
if (!res.ok) throw new Error('assign');
|
||||
document.getElementById('faceAssignModal').classList.remove('open');
|
||||
faceAssignFaceId = null;
|
||||
await refreshOpenFaceViewer();
|
||||
loadPhotos();
|
||||
} catch { showToast('Не удалось привязать лицо'); }
|
||||
}
|
||||
|
||||
async function rescanFaceViewerPhoto() {
|
||||
const photoId = faceViewer.photoId;
|
||||
const sourceType = faceViewer.sourceType;
|
||||
if (!photoId || !sourceType) return;
|
||||
const btn = document.getElementById('faceViewerRescanBtn');
|
||||
if (btn) { btn.disabled = true; btn.textContent = 'В очередь...'; }
|
||||
try {
|
||||
const res = await fetch(`${API}/api/photos/${sourceType}/${photoId}/faces/rescan`, {
|
||||
method: 'POST',
|
||||
headers: { ...hdr(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({})
|
||||
});
|
||||
if (!res.ok) throw new Error('rescan');
|
||||
showToast('Фото поставлено в очередь проверки — рамки обновятся автоматически');
|
||||
loadPhotos();
|
||||
} catch { showToast('Не удалось поставить в очередь'); }
|
||||
finally {
|
||||
if (btn) { btn.disabled = false; btn.textContent = 'Переиндексировать'; }
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
loadPhotos();
|
||||
}
|
||||
});
|
||||
faceScanLiveSource.onerror = () => {
|
||||
if (faceScanLiveSource) { faceScanLiveSource.close(); faceScanLiveSource = null; }
|
||||
setTimeout(connect, 5000);
|
||||
};
|
||||
};
|
||||
connect();
|
||||
window.addEventListener('beforeunload', () => { if (faceScanLiveSource) faceScanLiveSource.close(); });
|
||||
}
|
||||
|
||||
document.getElementById('studentFilter').addEventListener('change', () => { page = 1; loadPhotos(); });
|
||||
document.getElementById('groupFilter').addEventListener('change', () => { page = 1; loadPhotos(); });
|
||||
document.getElementById('sourceFilter').addEventListener('change', () => { page = 1; loadPhotos(); });
|
||||
@@ -161,7 +375,28 @@ document.getElementById('searchInput').addEventListener('input', () => {
|
||||
|
||||
document.getElementById('imgModal').addEventListener('click', e => e.currentTarget.classList.remove('open'));
|
||||
|
||||
document.getElementById('faceViewerCloseBtn')?.addEventListener('click', closeFaceViewer);
|
||||
document.getElementById('faceViewerRescanBtn')?.addEventListener('click', rescanFaceViewerPhoto);
|
||||
document.getElementById('faceViewerModal')?.addEventListener('click', e => { if (e.target === e.currentTarget) closeFaceViewer(); });
|
||||
document.getElementById('faceViewerBody')?.addEventListener('click', e => {
|
||||
const box = e.target.closest('[data-face-box]');
|
||||
if (box) openFaceAssign(box.dataset.faceBox);
|
||||
});
|
||||
document.getElementById('faceAssignCancelBtn')?.addEventListener('click', () => document.getElementById('faceAssignModal').classList.remove('open'));
|
||||
document.getElementById('faceAssignModal')?.addEventListener('click', e => { if (e.target === e.currentTarget) e.currentTarget.classList.remove('open'); });
|
||||
document.getElementById('faceAssignList')?.addEventListener('click', e => {
|
||||
const pick = e.target.closest('[data-face-pick]');
|
||||
if (pick) assignFace(parseInt(pick.dataset.facePick, 10));
|
||||
});
|
||||
document.getElementById('faceUnassignBtn')?.addEventListener('click', () => assignFace(0));
|
||||
document.getElementById('faceAssignSearch')?.addEventListener('input', e => renderFaceAssignList(e.target.value));
|
||||
|
||||
document.getElementById('grid').addEventListener('click', async e => {
|
||||
const facesBtn = e.target.closest('[data-fv-source]');
|
||||
if (facesBtn) {
|
||||
openFaceViewer(facesBtn.dataset.fvSource, parseInt(facesBtn.dataset.fvId, 10), facesBtn.dataset.fvPath);
|
||||
return;
|
||||
}
|
||||
const btn = e.target.closest('[data-quarantine]');
|
||||
if (!btn) return;
|
||||
if (await quarantineBrokenPhoto(btn.dataset.quarantine, btn.dataset.quarantineId)) loadPhotos();
|
||||
@@ -173,5 +408,6 @@ document.getElementById('grid').addEventListener('click', async e => {
|
||||
await loadGroupOptions();
|
||||
await loadStudentOptions();
|
||||
loadPhotos();
|
||||
connectFaceScanLive();
|
||||
}
|
||||
})();
|
||||
|
||||
Reference in New Issue
Block a user