Spaces:
Sleeping
Sleeping
File size: 17,427 Bytes
443e99e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 |
// Application State
const AppState = {
currentPdf: null,
pdfs: [],
deviceInfo: null,
};
// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
initializeTheme();
loadDeviceInfo();
initializeEventListeners();
loadPdfList();
});
// Theme Toggle
function initializeTheme() {
const savedTheme = localStorage.getItem('theme') || 'light';
document.body.setAttribute('data-theme', savedTheme);
updateThemeIcon(savedTheme);
document.getElementById('themeToggle').addEventListener('click', function() {
const currentTheme = document.body.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
document.body.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
updateThemeIcon(newTheme);
});
}
function updateThemeIcon(theme) {
const icon = document.getElementById('themeIcon');
if (icon) {
icon.className = theme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
}
}
// Load Device Info
async function loadDeviceInfo() {
try {
const response = await fetch('/api/device-info');
const data = await response.json();
AppState.deviceInfo = data;
updateDeviceStatus(data);
} catch (error) {
console.error('Error loading device info:', error);
updateDeviceStatus({ device: 'unknown', cuda_available: false });
}
}
function updateDeviceStatus(info) {
const badge = document.getElementById('deviceBadge');
const deviceName = document.getElementById('deviceName');
if (info.cuda_available) {
badge.textContent = 'GPU';
badge.className = 'badge bg-success';
deviceName.textContent = info.device_name || 'CUDA Device';
} else {
badge.textContent = 'CPU';
badge.className = 'badge bg-secondary';
deviceName.textContent = 'CPU Processing';
}
}
// Event Listeners
function initializeEventListeners() {
const uploadForm = document.getElementById('uploadForm');
uploadForm.addEventListener('submit', handleUpload);
}
// Handle File Upload
async function handleUpload(e) {
e.preventDefault();
const fileInput = document.getElementById('fileInput');
const files = fileInput.files;
if (files.length === 0) {
alert('Please select at least one PDF file');
return;
}
const extractionMode = document.querySelector('input[name="extractionMode"]:checked').value;
// Show processing section
document.getElementById('processingSection').style.display = 'block';
document.getElementById('resultsSection').style.display = 'none';
document.getElementById('emptyState').style.display = 'none';
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
formData.append('files[]', files[i]);
}
formData.append('extraction_mode', extractionMode);
try {
const response = await fetch('/api/upload', {
method: 'POST',
body: formData
});
const data = await response.json();
if (data.error) {
throw new Error(data.error);
}
// Hide processing section
document.getElementById('processingSection').style.display = 'none';
// Reload PDF list and show results
await loadPdfList();
// Show first PDF details if available
if (data.results && data.results.length > 0) {
const firstPdf = data.results[0];
if (!firstPdf.error) {
showPdfDetails(firstPdf.stem);
}
}
// Reset form
fileInput.value = '';
} catch (error) {
console.error('Upload error:', error);
alert('Error processing files: ' + error.message);
document.getElementById('processingSection').style.display = 'none';
}
}
// Load PDF List
async function loadPdfList() {
try {
const response = await fetch('/api/pdf-list');
const data = await response.json();
AppState.pdfs = data.pdfs || [];
renderPdfList();
if (AppState.pdfs.length > 0) {
document.getElementById('resultsSection').style.display = 'block';
document.getElementById('emptyState').style.display = 'none';
} else {
document.getElementById('resultsSection').style.display = 'none';
document.getElementById('emptyState').style.display = 'block';
}
} catch (error) {
console.error('Error loading PDF list:', error);
}
}
// Render PDF List
function renderPdfList() {
const pdfList = document.getElementById('pdfList');
pdfList.innerHTML = '';
if (AppState.pdfs.length === 0) {
pdfList.innerHTML = '<div class="text-center text-muted p-3">No PDFs processed yet</div>';
return;
}
AppState.pdfs.forEach((pdf, index) => {
const item = document.createElement('div');
item.className = `list-group-item d-flex align-items-center justify-content-between ${index === 0 && !AppState.currentPdf ? 'active' : ''} ${AppState.currentPdf === pdf.stem ? 'active' : ''}`;
const left = document.createElement('a');
left.href = '#';
left.className = 'flex-grow-1 text-decoration-none text-reset';
left.innerHTML = `
<div class="d-flex w-100 justify-content-between">
<h6 class="mb-0">
<i class="fas fa-file-pdf me-2"></i>
${pdf.stem}
</h6>
</div>
`;
left.addEventListener('click', function(e) {
e.preventDefault();
// Update active state
document.querySelectorAll('#pdfList .list-group-item').forEach(i => i.classList.remove('active'));
item.classList.add('active');
showPdfDetails(pdf.stem);
});
const delBtn = document.createElement('button');
delBtn.className = 'btn btn-sm btn-outline-danger ms-3';
delBtn.innerHTML = '<i class="fas fa-trash-alt"></i>';
delBtn.title = `Delete "${pdf.stem}"`;
delBtn.addEventListener('click', async (e) => {
e.preventDefault();
e.stopPropagation();
const confirmed = confirm(`Delete processed outputs for "${pdf.stem}"? This cannot be undone.`);
if (!confirmed) return;
try {
// Use form-encoded POST to the body endpoint for widest compatibility
const resp = await fetch('/api/delete', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
body: new URLSearchParams({ stem: pdf.stem }).toString()
});
const raw = await resp.text();
let res;
try { res = JSON.parse(raw); } catch (_) { res = null; }
if (!resp.ok || (res && res?.error)) {
throw new Error((res && res?.error) || raw || 'Delete failed');
}
// Refresh list and clear details if we deleted the active item
if (AppState.currentPdf === pdf.stem) {
AppState.currentPdf = null;
const details = document.getElementById('pdfDetails');
if (details) {
details.innerHTML = `
<div class="alert alert-success">
<i class="fas fa-check-circle me-2"></i>
Deleted "${pdf.stem}" successfully.
</div>
`;
}
}
await loadPdfList();
} catch (err) {
console.error('Delete error:', err);
alert('Failed to delete: ' + (err?.message || err));
}
});
item.appendChild(left);
item.appendChild(delBtn);
pdfList.appendChild(item);
});
}
// Show PDF Details
async function showPdfDetails(pdfStem) {
AppState.currentPdf = pdfStem;
// Update active state in list
document.querySelectorAll('#pdfList .list-group-item').forEach((item, index) => {
item.classList.remove('active');
const pdfStemFromItem = AppState.pdfs[index]?.stem;
if (pdfStemFromItem === pdfStem) {
item.classList.add('active');
}
});
try {
const response = await fetch(`/api/pdf-details/${encodeURIComponent(pdfStem)}`);
const data = await response.json();
if (data.error) {
throw new Error(data.error);
}
renderPdfDetails(data);
} catch (error) {
console.error('Error loading PDF details:', error);
document.getElementById('pdfDetails').innerHTML = `
<div class="alert alert-danger">
<i class="fas fa-exclamation-circle me-2"></i>
Error loading PDF details: ${error.message}
</div>
`;
}
}
// Render PDF Details
function renderPdfDetails(data) {
const container = document.getElementById('pdfDetails');
let html = `
<div class="card shadow-sm mb-4">
<div class="card-header bg-primary-custom text-white">
<h5 class="mb-0">
<i class="fas fa-file-pdf me-2"></i>
${data.stem}
</h5>
<button class="btn btn-sm btn-danger float-end" id="deletePdfBtn" title="Delete this processed PDF">
<i class="fas fa-trash-alt me-1"></i> Delete
</button>
</div>
<div class="card-body">
<div class="row mb-4">
<div class="col-md-3">
<div class="stat-card">
<i class="fas fa-images fa-2x text-primary mb-2"></i>
<div class="stat-value">${data.figures_count || 0}</div>
<div class="stat-label">Figures</div>
</div>
</div>
<div class="col-md-3">
<div class="stat-card">
<i class="fas fa-table fa-2x text-primary mb-2"></i>
<div class="stat-value">${data.tables_count || 0}</div>
<div class="stat-label">Tables</div>
</div>
</div>
<div class="col-md-3">
<div class="stat-card">
<i class="fas fa-list fa-2x text-primary mb-2"></i>
<div class="stat-value">${data.elements_count || 0}</div>
<div class="stat-label">Total Elements</div>
</div>
</div>
<div class="col-md-3">
<div class="stat-card">
<i class="fas fa-microchip fa-2x text-primary mb-2"></i>
<div class="stat-value">${AppState.deviceInfo?.device === 'cuda' ? 'GPU' : 'CPU'}</div>
<div class="stat-label">Device</div>
</div>
</div>
</div>
<div class="download-btn-group">
`;
if (data.annotated_pdf) {
html += `
<a href="/output/${data.annotated_pdf}" class="btn btn-primary" download>
<i class="fas fa-download me-2"></i>
Download Annotated PDF
</a>
`;
}
if (data.markdown_path) {
html += `
<a href="/output/${data.markdown_path}" class="btn btn-outline-primary" download>
<i class="fas fa-download me-2"></i>
Download Markdown
</a>
`;
}
html += `
</div>
</div>
</div>
`;
// Figures Section
if (data.figure_images && data.figure_images.length > 0) {
html += `
<div class="card shadow-sm mb-4">
<div class="card-header">
<h5 class="mb-0">
<i class="fas fa-images me-2"></i>
Figures (${data.figure_images.length})
</h5>
</div>
<div class="card-body">
<div class="image-gallery">
`;
data.figure_images.forEach((imgPath, index) => {
const figure = data.figures[index] || {};
html += `
<div class="image-item">
<img src="/output/${imgPath}" alt="Figure ${index + 1}" loading="lazy">
<div class="image-caption">
<strong>Figure ${index + 1}</strong>
${figure.page ? `<br><small class="text-muted">Page ${figure.page}</small>` : ''}
</div>
</div>
`;
});
html += `
</div>
</div>
</div>
`;
}
// Tables Section
if (data.table_images && data.table_images.length > 0) {
html += `
<div class="card shadow-sm mb-4">
<div class="card-header">
<h5 class="mb-0">
<i class="fas fa-table me-2"></i>
Tables (${data.table_images.length})
</h5>
</div>
<div class="card-body">
<div class="image-gallery">
`;
data.table_images.forEach((imgPath, index) => {
const table = data.tables[index] || {};
html += `
<div class="image-item">
<img src="/output/${imgPath}" alt="Table ${index + 1}" loading="lazy">
<div class="image-caption">
<strong>Table ${index + 1}</strong>
${table.page ? `<br><small class="text-muted">Page ${table.page}</small>` : ''}
</div>
</div>
`;
});
html += `
</div>
</div>
</div>
`;
}
// Markdown Preview
if (data.markdown_path) {
html += `
<div class="card shadow-sm">
<div class="card-header">
<h5 class="mb-0">
<i class="fas fa-file-code me-2"></i>
Markdown Preview
</h5>
</div>
<div class="card-body">
<div class="markdown-preview" id="markdownPreview">
Loading markdown...
</div>
</div>
</div>
`;
}
container.innerHTML = html;
// Load markdown preview if available
if (data.markdown_path) {
loadMarkdownPreview(data.markdown_path);
}
// Wire delete button
const deleteBtn = document.getElementById('deletePdfBtn');
if (deleteBtn) {
deleteBtn.addEventListener('click', async () => {
const confirmed = confirm(`Delete processed outputs for "${data.stem}"? This cannot be undone.`);
if (!confirmed) return;
try {
// Use form-encoded POST to the body endpoint for widest compatibility
const resp = await fetch('/api/delete', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
body: new URLSearchParams({ stem: data.stem }).toString()
});
const raw = await resp.text();
let res;
try { res = JSON.parse(raw); } catch (_) { res = null; }
if (!resp.ok || (res && res.error)) {
throw new Error((res && res.error) || raw || 'Delete failed');
}
// Refresh list and clear details
await loadPdfList();
document.getElementById('pdfDetails').innerHTML = `
<div class="alert alert-success">
<i class="fas fa-check-circle me-2"></i>
Deleted "${data.stem}" successfully.
</div>
`;
AppState.currentPdf = null;
} catch (err) {
console.error('Delete error:', err);
alert('Failed to delete: ' + (err?.message || err));
}
});
}
}
// Load Markdown Preview
async function loadMarkdownPreview(markdownPath) {
try {
const response = await fetch(`/output/${markdownPath}`);
const text = await response.text();
document.getElementById('markdownPreview').textContent = text;
} catch (error) {
console.error('Error loading markdown:', error);
document.getElementById('markdownPreview').textContent = 'Error loading markdown content';
}
}
|