stability and settings

This commit is contained in:
2025-09-17 12:36:24 +00:00
parent 4d586a46e9
commit 2115238217
9 changed files with 1271 additions and 265 deletions

View File

@@ -1,21 +1,35 @@
// static/js/script.js
document.addEventListener('DOMContentLoaded', () => {
// --- Element Selectors ---
const jobListBody = document.getElementById('job-list-body');
const pdfForm = document.getElementById('pdf-form');
const pdfFileInput = document.getElementById('pdf-file-input');
const pdfFileName = document.getElementById('pdf-file-name');
const audioForm = document.getElementById('audio-form');
const audioFileInput = document.getElementById('audio-file-input');
const audioFileName = document.getElementById('audio-file-name');
const conversionForm = document.getElementById('conversion-form');
const conversionFileInput = document.getElementById('conversion-file-input');
const conversionFileName = document.getElementById('conversion-file-name');
const outputFormatSelect = document.getElementById('output-format-select');
// MODIFICATION: Store the Choices.js instance in a variable
let conversionChoices = null;
const activePolls = new Map();
// --- Main Event Listeners ---
pdfFileInput.addEventListener('change', () => updateFileName(pdfFileInput, pdfFileName));
audioFileInput.addEventListener('change', () => updateFileName(audioFileInput, audioFileName));
pdfForm.addEventListener('submit', (e) => handleFormSubmit(e, '/ocr-pdf', pdfForm, pdfFileInput, pdfFileName));
audioForm.addEventListener('submit', (e) => handleFormSubmit(e, '/transcribe-audio', audioForm, audioFileInput, audioFileName));
conversionFileInput.addEventListener('change', () => updateFileName(conversionFileInput, conversionFileName));
pdfForm.addEventListener('submit', (e) => handleFormSubmit(e, '/ocr-pdf', pdfForm));
audioForm.addEventListener('submit', (e) => handleFormSubmit(e, '/transcribe-audio', audioForm));
conversionForm.addEventListener('submit', (e) => handleFormSubmit(e, '/convert-file', conversionForm));
jobListBody.addEventListener('click', (event) => {
if (event.target.classList.contains('cancel-button')) {
@@ -24,19 +38,55 @@ document.addEventListener('DOMContentLoaded', () => {
}
});
function initializeConversionSelector() {
// MODIFICATION: Destroy the old instance if it exists before creating a new one
if (conversionChoices) {
conversionChoices.destroy();
}
conversionChoices = new Choices(outputFormatSelect, {
searchEnabled: true,
itemSelectText: 'Select',
shouldSort: false,
placeholder: true,
placeholderValue: 'Select a format...',
});
const tools = window.APP_CONFIG.conversionTools || {};
const choicesArray = [];
for (const toolKey in tools) {
const tool = tools[toolKey];
const group = {
label: tool.name,
id: toolKey,
disabled: false,
choices: []
};
for (const formatKey in tool.formats) {
group.choices.push({
value: `${toolKey}_${formatKey}`,
label: `${formatKey.toUpperCase()} - ${tool.formats[formatKey]}`
});
}
choicesArray.push(group);
}
conversionChoices.setChoices(choicesArray, 'value', 'label', true);
}
// --- Helper Functions ---
function updateFileName(input, nameDisplay) {
nameDisplay.textContent = input.files.length > 0 ? input.files[0].name : 'No file chosen';
nameDisplay.title = nameDisplay.textContent; // Add a tooltip for the full name
const fileName = input.files.length > 0 ? input.files[0].name : 'No file chosen';
nameDisplay.textContent = fileName;
nameDisplay.title = fileName;
}
async function handleFormSubmit(event, endpoint, form, fileInput, fileNameDisplay) {
async function handleFormSubmit(event, endpoint, form) {
event.preventDefault();
const fileInput = form.querySelector('input[type="file"]');
const fileNameDisplay = form.querySelector('.file-name');
if (!fileInput.files[0]) return;
// MODIFICATION: Use new FormData(form) to capture all form fields,
// including the new model size dropdown for the audio form.
const formData = new FormData(form);
const submitButton = form.querySelector('button[type="submit"]');
submitButton.disabled = true;
@@ -47,54 +97,49 @@ document.addEventListener('DOMContentLoaded', () => {
throw new Error(errorData.detail || `HTTP error! Status: ${response.status}`);
}
const result = await response.json();
// To provide immediate feedback, create a placeholder job object
const preliminaryJob = {
id: result.job_id,
status: 'pending',
progress: 0,
original_filename: fileInput.files[0].name,
task_type: endpoint.includes('ocr') ? 'ocr' : 'transcription',
created_at: new Date().toISOString(),
processed_filepath: null,
error_message: null
task_type: endpoint.includes('ocr') ? 'ocr' : (endpoint.includes('transcribe') ? 'transcription' : 'conversion'),
created_at: new Date().toISOString()
};
renderJobRow(preliminaryJob); // Render immediately
startPolling(result.job_id); // Start polling for updates
renderJobRow(preliminaryJob);
startPolling(result.job_id);
} catch (error) {
console.error('Error submitting job:', error);
alert(`Submission failed: ${error.message}`);
} finally {
form.reset();
fileNameDisplay.textContent = 'No file chosen';
fileNameDisplay.title = '';
if (fileNameDisplay) fileNameDisplay.textContent = 'No file chosen';
// MODIFICATION: Use the stored instance to correctly reset the dropdown
// without causing an error.
if (form.id === 'conversion-form' && conversionChoices) {
conversionChoices.clearInput();
conversionChoices.setValue([]); // Clears the selected value
}
submitButton.disabled = false;
}
}
async function handleCancelJob(jobId) {
if (!confirm('Are you sure you want to cancel this job?')) return;
try {
const response = await fetch(`/job/${jobId}/cancel`, { method: 'POST' });
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || 'Failed to cancel job.');
}
// The polling mechanism will update the UI to "cancelled" automatically.
// We can stop polling immediately to be more efficient.
stopPolling(jobId);
// Optionally, force an immediate UI update
const row = document.getElementById(`job-${jobId}`);
if (row) {
const statusCell = row.querySelector('td[data-label="Status"] .cell-value');
const actionCell = row.querySelector('td[data-label="Action"] .cell-value');
if (statusCell) {
statusCell.innerHTML = `<span class="job-status-badge status-cancelled">cancelled</span>`;
}
if (actionCell) {
actionCell.innerHTML = `<span>-</span>`;
}
if (statusCell) statusCell.innerHTML = `<span class="job-status-badge status-cancelled">Cancelled</span>`;
if (actionCell) actionCell.innerHTML = `<span>-</span>`;
}
} catch (error) {
console.error('Error cancelling job:', error);
@@ -107,7 +152,7 @@ document.addEventListener('DOMContentLoaded', () => {
const response = await fetch('/jobs');
if (!response.ok) throw new Error('Failed to fetch jobs.');
const jobs = await response.json();
jobListBody.innerHTML = ''; // Clear existing
jobListBody.innerHTML = '';
for (const job of jobs.reverse()) {
renderJobRow(job);
if (['pending', 'processing'].includes(job.status)) {
@@ -126,10 +171,7 @@ document.addEventListener('DOMContentLoaded', () => {
try {
const response = await fetch(`/job/${jobId}`);
if (!response.ok) {
if (response.status === 404) {
console.warn(`Job ${jobId} not found. Stopping poll.`);
stopPolling(jobId);
}
if (response.status === 404) stopPolling(jobId);
return;
}
const job = await response.json();
@@ -139,9 +181,9 @@ document.addEventListener('DOMContentLoaded', () => {
}
} catch (error) {
console.error(`Error polling for job ${jobId}:`, error);
stopPolling(jobId); // Stop polling on network or other errors
stopPolling(jobId);
}
}, 2500); // Poll every 2.5 seconds
}, 2500);
activePolls.set(jobId, intervalId);
}
@@ -159,21 +201,28 @@ document.addEventListener('DOMContentLoaded', () => {
row.id = `job-${job.id}`;
jobListBody.prepend(row);
}
const taskTypeLabel = job.task_type.includes('ocr') ? 'PDF/Image OCR' : 'Transcription';
const formattedDate = new Date(job.created_at).toLocaleString();
let statusHtml = `<span class="job-status-badge status-${job.status}">${job.status}</span>`;
let actionHtml = `<span>-</span>`;
if (job.status === 'processing') {
// Show real progress for transcription, but an indeterminate one for OCR tasks
const progressClass = job.task_type === 'transcription' ? '' : 'indeterminate';
const progressWidth = job.task_type === 'transcription' ? job.progress : 100;
const progressBarHtml = `<div class="progress-bar-container"><div class="progress-bar ${progressClass}" style="width: ${progressWidth}%"></div></div>`;
statusHtml += progressBarHtml;
let taskTypeLabel = 'Unknown';
if (job.task_type === 'ocr' || job.task_type === 'ocr-image') {
taskTypeLabel = 'OCR';
} else if (job.task_type === 'transcription') {
taskTypeLabel = 'Transcription';
} else if (job.task_type === 'conversion' && job.processed_filepath) {
const extension = job.processed_filepath.split('.').pop();
taskTypeLabel = `Convert to ${extension.toUpperCase()}`;
} else if (job.task_type === 'conversion') {
taskTypeLabel = 'Conversion';
}
const formattedDate = new Date(job.created_at).toLocaleString();
let statusHtml = `<span class="job-status-badge status-${job.status}">${job.status}</span>`;
if (job.status === 'processing') {
const progressClass = (job.task_type === 'transcription' && job.progress > 0) ? '' : 'indeterminate';
const progressWidth = job.task_type === 'transcription' ? job.progress : 100;
statusHtml += `<div class="progress-bar-container"><div class="progress-bar ${progressClass}" style="width: ${progressWidth}%"></div></div>`;
}
let actionHtml = `<span>-</span>`;
if (job.status === 'pending' || job.status === 'processing') {
actionHtml = `<button class="cancel-button" data-job-id="${job.id}">Cancel</button>`;
} else if (job.status === 'completed' && job.processed_filepath) {
@@ -184,12 +233,10 @@ document.addEventListener('DOMContentLoaded', () => {
actionHtml = `<span class="error-text"${errorTitle}>Failed</span>`;
}
// Use textContent for filename to prevent XSS and add a title for overflow
const escapedFilename = job.original_filename.replace(/</g, "&lt;").replace(/>/g, "&gt;");
const escapedFilename = job.original_filename ? job.original_filename.replace(/</g, "&lt;").replace(/>/g, "&gt;") : "No filename";
row.innerHTML = `
<td data-label="File"><span class="cell-value" title="${escapedFilename}">${escapedFilename}</span></td>
<td data-label="Type"><span class="cell-value">${taskTypeLabel}</span></td>
<td data-label="Task"><span class="cell-value">${taskTypeLabel}</span></td>
<td data-label="Submitted"><span class="cell-value">${formattedDate}</span></td>
<td data-label="Status"><span class="cell-value">${statusHtml}</span></td>
<td data-label="Action" class="action-col"><span class="cell-value">${actionHtml}</span></td>
@@ -197,5 +244,6 @@ document.addEventListener('DOMContentLoaded', () => {
}
// --- Initial Load ---
initializeConversionSelector();
loadInitialJobs();
});

108
static/js/settings.js Normal file
View File

@@ -0,0 +1,108 @@
// static/js/settings.js
document.addEventListener('DOMContentLoaded', () => {
const settingsForm = document.getElementById('settings-form');
const saveStatus = document.getElementById('save-status');
const clearHistoryBtn = document.getElementById('clear-history-btn');
const deleteFilesBtn = document.getElementById('delete-files-btn');
// --- Save Settings ---
settingsForm.addEventListener('submit', async (event) => {
event.preventDefault();
saveStatus.textContent = 'Saving...';
saveStatus.classList.remove('success', 'error');
const formData = new FormData(settingsForm);
const settingsObject = {};
// Convert FormData to a nested object
formData.forEach((value, key) => {
// Handle checkboxes that might not be submitted if unchecked
if (key.includes('ocr_settings')) {
const checkbox = document.querySelector(`[name="${key}"]`);
if (checkbox && checkbox.type === 'checkbox') {
value = checkbox.checked;
}
}
const keys = key.split('.');
let current = settingsObject;
keys.forEach((k, index) => {
if (index === keys.length - 1) {
current[k] = value;
} else {
current[k] = current[k] || {};
current = current[k];
}
});
});
// Ensure unchecked OCR boxes are sent as false
const ocrCheckboxes = settingsForm.querySelectorAll('input[type="checkbox"][name^="ocr_settings"]');
ocrCheckboxes.forEach(cb => {
const keys = cb.name.split('.');
if (!formData.has(cb.name)) {
// this is a bit of a hack but gets the job done for this specific form
settingsObject[keys[0]][keys[1]][keys[2]] = false;
}
});
try {
const response = await fetch('/settings/save', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(settingsObject)
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || 'Failed to save settings.');
}
saveStatus.textContent = 'Settings saved successfully!';
saveStatus.classList.add('success');
} catch (error) {
saveStatus.textContent = `Error: ${error.message}`;
saveStatus.classList.add('error');
console.error('Error saving settings:', error);
} finally {
setTimeout(() => {
saveStatus.textContent = '';
saveStatus.classList.remove('success', 'error');
}, 5000);
}
});
// --- Clear History ---
clearHistoryBtn.addEventListener('click', async () => {
if (!confirm('ARE YOU SURE?\n\nThis will permanently delete all job history records from the database.')) {
return;
}
try {
const response = await fetch('/settings/clear-history', { method: 'POST' });
if (!response.ok) throw new Error('Server responded with an error.');
const result = await response.json();
alert(`Success: ${result.deleted_count} job records have been deleted.`);
} catch (error) {
alert('An error occurred while clearing history.');
console.error(error);
}
});
// --- Delete Files ---
deleteFilesBtn.addEventListener('click', async () => {
if (!confirm('ARE YOU SURE?\n\nThis will permanently delete all files in the "processed" folder.')) {
return;
}
try {
const response = await fetch('/settings/delete-files', { method: 'POST' });
if (!response.ok) throw new Error('Server responded with an error.');
const result = await response.json();
alert(`Success: ${result.deleted_count} files have been deleted.`);
} catch (error) {
alert('An error occurred while deleting files.');
console.error(error);
}
});
});