Add transcription library and Llama GPU management

This commit is contained in:
2026-11-22 23:14:14 +03:00
parent 85929c9054
commit 5c5827d241
3 changed files with 1331 additions and 65 deletions
+666 -27
View File
@@ -25,10 +25,10 @@
<label for="audio-file" class="upload-area d-flex flex-column align-items-center justify-content-center text-center p-5 mb-3">
<i class="bi bi-cloud-arrow-up display-4 text-info mb-3"></i>
<span class="fw-semibold">Выберите аудиофайл или перетащите его сюда</span>
<span class="text-secondary small mt-2">WAV, MP3, M4A, OGG, FLAC, WEBM · до 500 МБ</span>
<span class="text-secondary small mt-2">WAV, MP3, M4A, AAC, OGG, OPUS, FLAC, WEBM · до 500 МБ</span>
<span id="file-name" class="small text-info mt-3">Файл не выбран</span>
</label>
<input class="visually-hidden" type="file" id="audio-file" name="file" accept="audio/*,.mp4,.mpeg,.mpga,.webm" required>
<input class="visually-hidden" type="file" id="audio-file" name="file" accept="audio/*,.aac,.mp4,.mpeg,.mpga,.webm,.opus" multiple required>
<div class="row g-3 align-items-end">
<div class="col-12 col-md-5">
<label for="language" class="form-label">Язык записи</label>
@@ -51,6 +51,82 @@
</div>
</section>
<section class="card border-secondary-subtle bg-dark-subtle mb-4">
<div class="card-body p-4">
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
<h2 class="h5 mb-0"><i class="bi bi-collection me-2"></i>Библиотека расшифровок</h2>
<span class="badge text-bg-secondary" id="queue-count">0</span>
</div>
<div class="btn-group mb-3" role="group" aria-label="Фильтр записей">
<button class="btn btn-outline-light active" data-filter="all">Все</button>
<button class="btn btn-outline-light" data-filter="queue">Очередь</button>
<button class="btn btn-outline-light" data-filter="history">История</button>
</div>
<div class="row g-2 mb-3">
<div class="col">
<input type="search" class="form-control" id="library-search"
placeholder="Поиск по названию, файлу, описанию и тегам">
</div>
<div class="col-auto">
<button class="btn btn-outline-light" id="search-button">
<i class="bi bi-search"></i>
</button>
</div>
</div>
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-2">
<div class="small text-secondary" id="library-info">Загрузка...</div>
<button class="btn btn-outline-danger btn-sm d-none" id="bulk-delete-button">
<i class="bi bi-trash me-1"></i>Удалить выбранные
(<span id="selected-count">0</span>)
</button>
</div>
<div id="queue-list">
<div class="text-secondary small">Загрузка записей...</div>
</div>
<div class="d-flex justify-content-between align-items-center mt-3">
<button class="btn btn-outline-light btn-sm" id="page-prev" disabled>
<i class="bi bi-chevron-left me-1"></i>Назад
</button>
<span class="small text-secondary" id="page-info">Страница 1</span>
<button class="btn btn-outline-light btn-sm" id="page-next" disabled>
Далее<i class="bi bi-chevron-right ms-1"></i>
</button>
</div>
</div>
</section>
<dialog id="metadata-dialog" class="bg-dark text-light border border-secondary rounded-3 p-0"
style="width:min(560px, calc(100% - 24px));">
<div class="p-4">
<h2 class="h5 mb-3">Свойства записи</h2>
<input type="hidden" id="metadata-job-id">
<div class="mb-3">
<label for="metadata-title" class="form-label">Название</label>
<input type="text" class="form-control" id="metadata-title" maxlength="200" required>
</div>
<div class="mb-3">
<label for="metadata-description" class="form-label">Описание</label>
<textarea class="form-control" id="metadata-description" rows="3" maxlength="2000"></textarea>
</div>
<div class="mb-3">
<label for="metadata-tags" class="form-label">Теги</label>
<input type="text" class="form-control" id="metadata-tags"
placeholder="Например: совещание, клиент, проект">
<div class="form-text">Разделяйте теги запятыми. Не более 20 тегов.</div>
</div>
<div class="d-flex justify-content-end gap-2">
<button class="btn btn-outline-light" id="metadata-cancel">Отмена</button>
<button class="btn btn-primary" id="metadata-save">Сохранить</button>
</div>
</div>
</dialog>
<section id="result-section" class="card border-secondary-subtle bg-dark-subtle d-none">
<div class="card-body p-4">
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
@@ -82,41 +158,604 @@ const resultSection = document.getElementById('result-section');
const transcript = document.getElementById('transcript');
let lastSegments = [];
fileInput.addEventListener('change', () => { fileName.textContent = fileInput.files[0]?.name || 'Файл не выбран'; });
function updateFileName() {
const files = Array.from(fileInput.files || []);
if (!files.length) {
fileName.textContent = 'Файл не выбран';
} else if (files.length === 1) {
fileName.textContent = files[0].name;
} else {
fileName.textContent = `Выбрано файлов: ${files.length}`;
}
}
fileInput.addEventListener('change', updateFileName);
const uploadArea = document.querySelector('.upload-area');
uploadArea.addEventListener('dragover', e => { e.preventDefault(); uploadArea.classList.add('drag-over'); });
uploadArea.addEventListener('dragleave', () => uploadArea.classList.remove('drag-over'));
uploadArea.addEventListener('drop', e => { e.preventDefault(); uploadArea.classList.remove('drag-over'); if (e.dataTransfer.files.length) { fileInput.files = e.dataTransfer.files; fileName.textContent = fileInput.files[0].name; } });
uploadArea.addEventListener('drop', e => {
e.preventDefault();
uploadArea.classList.remove('drag-over');
if (e.dataTransfer.files.length) {
fileInput.files = e.dataTransfer.files;
updateFileName();
}
});
let activeJobId = null;
let loadedJobId = null;
let currentPage = 1;
let currentFilter = 'all';
let currentQuery = '';
let totalPages = 1;
let selectedIds = new Set();
const statusLabels = {
queued: 'В очереди',
processing: 'Распознаётся',
completed: 'Готово',
failed: 'Ошибка'
};
const list = document.getElementById('queue-list');
const count = document.getElementById('queue-count');
const searchInput = document.getElementById('library-search');
const dialog = document.getElementById('metadata-dialog');
function updateSelectionUI() {
const button = document.getElementById('bulk-delete-button');
document.getElementById('selected-count').textContent = selectedIds.size;
button.classList.toggle('d-none', selectedIds.size === 0);
}
function renderQueue(jobs) {
list.replaceChildren();
count.textContent = document.getElementById('library-info').dataset.total || '0';
if (!jobs.length) {
const empty = document.createElement('div');
empty.className = 'text-secondary small py-3';
empty.textContent = 'Записей не найдено';
list.append(empty);
updateSelectionUI();
return;
}
jobs.forEach(job => {
const item = document.createElement('div');
item.className = 'd-flex flex-wrap align-items-center gap-3 py-3 border-bottom border-secondary-subtle';
if (job.status !== 'processing') {
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.className = 'form-check-input mt-0';
checkbox.checked = selectedIds.has(job.id);
checkbox.addEventListener('change', () => {
if (checkbox.checked) selectedIds.add(job.id);
else selectedIds.delete(job.id);
updateSelectionUI();
});
item.append(checkbox);
} else {
const spacer = document.createElement('span');
spacer.style.width = '16px';
item.append(spacer);
}
const info = document.createElement('div');
info.className = 'me-auto';
info.style.minWidth = '180px';
const name = document.createElement('div');
name.className = 'fw-semibold';
name.textContent = job.title || job.filename;
const details = document.createElement('div');
details.className = 'small text-secondary';
const date = new Date(job.created_at).toLocaleString();
const detailsParts = [
statusLabels[job.status] || job.status,
date,
job.filename
];
if (Number.isFinite(job.duration)) {
detailsParts.push(`${Math.round(job.duration)} сек.`);
}
if (job.detected_language) {
detailsParts.push(job.detected_language);
}
details.textContent = detailsParts.join(' · ');
info.append(name, details);
if (job.description) {
const description = document.createElement('div');
description.className = 'small text-secondary mt-1';
description.textContent = job.description;
info.append(description);
}
if (job.tags?.length) {
const tags = document.createElement('div');
tags.className = 'd-flex flex-wrap gap-1 mt-2';
job.tags.forEach(tag => {
const badge = document.createElement('span');
badge.className = 'badge text-bg-secondary';
badge.textContent = tag;
tags.append(badge);
});
info.append(tags);
}
if (job.error) {
const error = document.createElement('div');
error.className = 'small text-danger mt-1';
error.textContent = job.error;
info.append(error);
}
const actions = document.createElement('div');
actions.className = 'd-flex flex-wrap gap-2';
if (job.status === 'completed') {
const openButton = document.createElement('button');
openButton.className = 'btn btn-outline-info btn-sm';
openButton.textContent = 'Открыть';
openButton.addEventListener('click', () => openJob(job.id));
actions.append(openButton);
}
if (job.status !== 'processing') {
const editButton = document.createElement('button');
editButton.className = 'btn btn-outline-light btn-sm';
editButton.textContent = 'Изменить';
editButton.addEventListener('click', () => editMetadata(job));
actions.append(editButton);
const deleteButton = document.createElement('button');
deleteButton.className = 'btn btn-outline-danger btn-sm';
deleteButton.textContent = 'Удалить';
deleteButton.addEventListener('click', () => deleteJob(job.id));
actions.append(deleteButton);
}
item.append(info, actions);
list.append(item);
});
updateSelectionUI();
}
async function refreshQueue() {
try {
const params = new URLSearchParams({
page: String(currentPage),
per_page: '20'
});
if (currentFilter !== 'all') params.set('status', currentFilter);
if (currentQuery) params.set('q', currentQuery);
const response = await fetch(`/api/transcriptions?${params}`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
totalPages = Math.max(1, data.pages || 1);
if (currentPage > totalPages) {
currentPage = totalPages;
return refreshQueue();
}
document.getElementById('library-info').textContent =
`Найдено записей: ${data.total}`;
document.getElementById('library-info').dataset.total = data.total;
count.textContent = data.total;
document.getElementById('page-info').textContent =
`Страница ${data.page} из ${totalPages}`;
document.getElementById('page-prev').disabled = currentPage <= 1;
document.getElementById('page-next').disabled = currentPage >= totalPages;
renderQueue(data.jobs || []);
if (activeJobId) {
const active = data.jobs?.find(job => job.id === activeJobId);
if (active?.status === 'processing') {
document.getElementById('progress-label').textContent = 'Идёт распознавание...';
progress.classList.remove('d-none');
} else if (active?.status === 'queued') {
document.getElementById('progress-label').textContent = 'Задание ожидает своей очереди...';
progress.classList.remove('d-none');
} else if (active?.status === 'completed' && loadedJobId !== activeJobId) {
loadedJobId = activeJobId;
const completedId = activeJobId;
activeJobId = null;
progress.classList.add('d-none');
await openJob(completedId);
} else if (active?.status === 'failed') {
showError(active.error || 'Ошибка распознавания');
activeJobId = null;
progress.classList.add('d-none');
}
}
} catch (err) {
console.error('Не удалось обновить библиотеку:', err);
}
}
async function openJob(jobId) {
try {
const response = await fetch(`/api/transcriptions/${encodeURIComponent(jobId)}`);
const data = await response.json();
if (!response.ok) {
throw new Error(data.detail || `Ошибка HTTP ${response.status}`);
}
if (data.status !== 'completed' || !data.result) {
throw new Error('Результат задания пока недоступен');
}
const result = data.result;
transcript.value = result.text || '';
lastSegments = result.segments || [];
const meta = [];
if (result.language) meta.push(`Язык: ${result.language}`);
if (Number.isFinite(result.duration)) {
meta.push(`Длительность: ${Math.round(result.duration)} сек.`);
}
meta.push(`Название: ${data.title || data.filename}`);
meta.push(`Файл: ${data.filename}`);
document.getElementById('result-meta').textContent = meta.join(' · ');
resultSection.classList.remove('d-none');
resultSection.scrollIntoView({behavior: 'smooth', block: 'start'});
errorBox.classList.add('d-none');
} catch (err) {
showError(err.message);
}
}
function editMetadata(job) {
document.getElementById('metadata-job-id').value = job.id;
document.getElementById('metadata-title').value = job.title || job.filename;
document.getElementById('metadata-description').value = job.description || '';
document.getElementById('metadata-tags').value = (job.tags || []).join(', ');
dialog.showModal();
}
document.getElementById('metadata-cancel').addEventListener('click', () => dialog.close());
document.getElementById('metadata-save').addEventListener('click', async () => {
const id = document.getElementById('metadata-job-id').value;
const button = document.getElementById('metadata-save');
button.disabled = true;
try {
const response = await fetch(`/api/transcriptions/${encodeURIComponent(id)}`, {
method: 'PATCH',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
title: document.getElementById('metadata-title').value,
description: document.getElementById('metadata-description').value,
tags: document.getElementById('metadata-tags').value
.split(',').map(tag => tag.trim()).filter(Boolean)
})
});
const data = await response.json();
if (!response.ok) throw new Error(data.detail || `HTTP ${response.status}`);
dialog.close();
selectedIds.delete(id);
await refreshQueue();
} catch (err) {
showError(err.message);
} finally {
button.disabled = false;
}
});
async function deleteJob(jobId) {
if (!confirm('Удалить запись и связанные с ней файлы?')) return;
try {
const response = await fetch(`/api/transcriptions/${encodeURIComponent(jobId)}`, {
method: 'DELETE'
});
const data = await response.json();
if (!response.ok) throw new Error(data.detail || `HTTP ${response.status}`);
selectedIds.delete(jobId);
await refreshQueue();
} catch (err) {
showError(err.message);
}
}
document.getElementById('bulk-delete-button').addEventListener('click', async () => {
if (!selectedIds.size) return;
if (!confirm(`Удалить выбранные записи (${selectedIds.size}) и связанные файлы?`)) return;
const button = document.getElementById('bulk-delete-button');
button.disabled = true;
try {
const response = await fetch('/api/transcriptions/bulk', {
method: 'DELETE',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ids: Array.from(selectedIds)})
});
const data = await response.json();
if (!response.ok) throw new Error(data.detail || `HTTP ${response.status}`);
selectedIds.clear();
await refreshQueue();
if (data.skipped_processing) {
showError(`Удалено: ${data.deleted}. Пропущено (идёт обработка): ${data.skipped_processing}.`);
}
} catch (err) {
showError(err.message);
} finally {
button.disabled = false;
}
});
document.querySelectorAll('[data-filter]').forEach(button => {
button.addEventListener('click', () => {
currentFilter = button.dataset.filter;
currentPage = 1;
selectedIds.clear();
document.querySelectorAll('[data-filter]').forEach(item =>
item.classList.toggle('active', item === button)
);
refreshQueue();
});
});
function applySearch() {
currentQuery = searchInput.value.trim();
currentPage = 1;
selectedIds.clear();
refreshQueue();
}
document.getElementById('search-button').addEventListener('click', applySearch);
searchInput.addEventListener('keydown', event => {
if (event.key === 'Enter') applySearch();
});
document.getElementById('page-prev').addEventListener('click', () => {
if (currentPage > 1) {
currentPage--;
refreshQueue();
}
});
document.getElementById('page-next').addEventListener('click', () => {
if (currentPage < totalPages) {
currentPage++;
refreshQueue();
}
});
form.addEventListener('submit', async e => {
e.preventDefault();
if (!fileInput.files.length) return;
errorBox.classList.add('d-none'); resultSection.classList.add('d-none'); progress.classList.remove('d-none');
const files = Array.from(fileInput.files || []);
if (!files.length || submitButton.disabled) return;
const confirmed = confirm(
'Для транскрибации Portal выгрузит все загруженные модели Llama.cpp с GPU.\n\n' +
'Активные LLM-сессии могут быть прерваны. После транскрибации модели ' +
'автоматически не восстановятся.\n\nПродолжить?'
);
if (!confirmed) return;
errorBox.classList.add('d-none');
submitButton.disabled = true;
document.getElementById('progress-label').textContent = 'Файл отправлен. Выполняется распознавание...';
const body = new FormData(); body.append('file', fileInput.files[0]); body.append('language', document.getElementById('language').value);
progress.classList.remove('d-none');
const language = document.getElementById('language').value;
let submitted = 0;
try {
const response = await fetch('/api/transcribe', {method:'POST', body});
const data = await response.json();
if (!response.ok) throw new Error(data.detail || `Ошибка HTTP ${response.status}`);
transcript.value = data.text || '';
lastSegments = data.segments || [];
const meta = [];
if (data.language) meta.push(`Язык: ${data.language}`);
if (Number.isFinite(data.duration)) meta.push(`Длительность: ${Math.round(data.duration)} сек.`);
document.getElementById('result-meta').textContent = meta.join(' · ');
resultSection.classList.remove('d-none');
resultSection.scrollIntoView({behavior:'smooth', block:'start'});
} catch (err) { errorBox.textContent = err.message; errorBox.classList.remove('d-none'); }
finally { progress.classList.add('d-none'); submitButton.disabled = false; }
for (let i = 0; i < files.length; i++) {
document.getElementById('progress-label').textContent =
`Загружаем файл ${i + 1} из ${files.length}: ${files[i].name}`;
const body = new FormData();
body.append('file', files[i]);
body.append('language', language);
const response = await fetch('/api/transcribe', {
method: 'POST',
body
});
const data = await response.json();
if (!response.ok) {
throw new Error(
`${files[i].name}: ${data.detail || `Ошибка HTTP ${response.status}`}`
);
}
activeJobId = data.job_id;
loadedJobId = null;
currentFilter = 'all';
currentQuery = '';
currentPage = 1;
searchInput.value = '';
document.querySelectorAll('[data-filter]').forEach(item =>
item.classList.toggle('active', item.dataset.filter === 'all')
);
submitted++;
}
fileInput.value = '';
updateFileName();
document.getElementById('progress-label').textContent =
`В очередь добавлено файлов: ${submitted}`;
await refreshQueue();
} catch (err) {
const prefix = submitted
? `Успешно добавлено ${submitted} из ${files.length}. `
: '';
showError(prefix + err.message);
if (submitted) {
await refreshQueue();
} else {
progress.classList.add('d-none');
}
} finally {
submitButton.disabled = false;
}
});
async function pollQueue() {
await refreshQueue();
setTimeout(pollQueue, 2500);
}
pollQueue();
function showError(message) {
errorBox.textContent = message;
errorBox.classList.remove('d-none');
}
function requireText() {
if (!transcript.value.trim()) {
showError('Сначала выполните распознавание или введите текст.');
return false;
}
return true;
}
async function copyText(text) {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
return;
}
const area = document.createElement('textarea');
area.value = text;
area.style.position = 'fixed';
area.style.opacity = '0';
document.body.appendChild(area);
area.select();
const copied = document.execCommand('copy');
area.remove();
if (!copied) throw new Error('Браузер не разрешил копирование.');
}
document.getElementById('copy-button').addEventListener('click', async () => {
if (!requireText()) return;
try {
await copyText(transcript.value);
errorBox.textContent = 'Текст скопирован.';
errorBox.classList.remove('d-none');
} catch (err) {
showError(`Не удалось скопировать текст: ${err.message}`);
}
});
function download(name, content, type) {
if (!content) {
showError('Нет данных для экспорта.');
return;
}
const blob = new Blob([content], {type});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
document.getElementById('txt-button').addEventListener('click', () => {
if (requireText()) download('transcript.txt', transcript.value, 'text/plain;charset=utf-8');
});
function stamp(seconds) {
const ms = Math.round(seconds * 1000);
const h = String(Math.floor(ms / 3600000)).padStart(2, '0');
const m = String(Math.floor(ms % 3600000 / 60000)).padStart(2, '0');
const sec = String(Math.floor(ms % 60000 / 1000)).padStart(2, '0');
const milli = String(ms % 1000).padStart(3, '0');
return `${h}:${m}:${sec},${milli}`;
}
document.getElementById('srt-button').addEventListener('click', () => {
if (!requireText()) return;
const srt = lastSegments.map((x, i) =>
`${i + 1}\n${stamp(x.start || 0)} --> ${stamp(x.end || x.start || 0)}\n${x.text || ''}`
).join('\n\n');
if (!srt) {
showError('Speaches не вернул сегменты с таймкодами. Доступен экспорт TXT и DOCX.');
return;
}
download('transcript.srt', srt, 'text/plain;charset=utf-8');
});
document.getElementById('docx-button').addEventListener('click', async () => {
if (!requireText()) return;
const button = document.getElementById('docx-button');
button.disabled = true;
try {
const response = await fetch('/api/export/docx', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({text: transcript.value})
});
if (!response.ok) {
let message = 'Ошибка экспорта DOCX';
try {
const data = await response.json();
message = data.detail || message;
} catch {}
throw new Error(message);
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'transcript.docx';
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
} catch (err) {
showError(err.message);
} finally {
button.disabled = false;
}
});
document.getElementById('copy-button').addEventListener('click', async () => { await navigator.clipboard.writeText(transcript.value); });
function download(name, content, type) { const blob = new Blob([content], {type}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download=name; a.click(); URL.revokeObjectURL(url); }
document.getElementById('txt-button').addEventListener('click', () => download('transcript.txt', transcript.value, 'text/plain;charset=utf-8'));
function stamp(seconds) { const ms=Math.round(seconds*1000); const h=String(Math.floor(ms/3600000)).padStart(2,'0'); const m=String(Math.floor(ms%3600000/60000)).padStart(2,'0'); const s=String(Math.floor(ms%60000/1000)).padStart(2,'0'); const milli=String(ms%1000).padStart(3,'0'); return `${h}:${m}:${s},${milli}`; }
document.getElementById('srt-button').addEventListener('click', () => { const srt=lastSegments.map((x,i)=>`${i+1}\n${stamp(x.start||0)} --> ${stamp(x.end||x.start||0)}\n${x.text||''}`).join('\n\n'); if (!srt) { errorBox.textContent='Speaches не вернул сегменты с таймкодами. Доступен экспорт TXT и DOCX.'; errorBox.classList.remove('d-none'); return; } download('transcript.srt', srt, 'text/plain;charset=utf-8'); });
document.getElementById('docx-button').addEventListener('click', async () => { try { const response = await fetch('/api/export/docx', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({text:transcript.value})}); if (!response.ok) { const data=await response.json(); throw new Error(data.detail || 'Ошибка экспорта DOCX'); } const blob=await response.blob(); const url=URL.createObjectURL(blob); const a=document.createElement('a'); a.href=url; a.download='transcript.docx'; a.click(); URL.revokeObjectURL(url); } catch(err) { errorBox.textContent=err.message; errorBox.classList.remove('d-none'); } });
</script>
</body>
</html>