Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

feat: improve Download Manager accessibility and fix text extraction (#1195)

LearningCircuit4b6b5fbd8ac8
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.py
index 2a7796ac61..5db9facbbb 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -172,13 +172,6 @@ def get_rag_service(collection_id: Optional[str] = None) -> LibraryRAGService:
# Page Routes
-@rag_bp.route("/rag-manager")
-@login_required
-def rag_manager_page():
- """Render the RAG Manager page."""
- return render_template("pages/rag_manager.html")
-
-
@rag_bp.route("/embedding-settings")
@login_required
def embedding_settings_page():
diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.py
index fa4a0f2a32..67cca93fa2 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -8,6 +8,7 @@ Handles downloading PDFs from various academic sources with:
- File organization and storage
"""
+import hashlib
import re
import time
import uuid
@@ -28,12 +29,14 @@ from ...database.models.download_tracker import (
)
from ...security import redact_data
from ...database.models.library import (
+ Collection,
Document as Document,
DocumentStatus,
DownloadQueue as LibraryDownloadQueue,
DocumentCollection,
)
from ...database.models.research import ResearchResource
+from ...database.library_init import get_source_type_id, get_default_library_id
from ...database.session_context import get_user_db_session
from ...utilities.db_utils import get_settings_manager
from ...security.path_validator import PathValidator
@@ -574,11 +577,6 @@ class DownloadService:
existing_doc.processed_at = datetime.now(UTC)
else:
# Get source type ID for research downloads
- from ...database.library_init import (
- get_source_type_id,
- get_default_library_id,
- )
-
try:
source_type_id = get_source_type_id(
self.username, "research_download"
@@ -741,8 +739,6 @@ class DownloadService:
True,
"library PDF storage",
mode="wb",
- username=self.username,
- settings_manager=self.settings,
)
return str(validated_path)
@@ -1432,7 +1428,7 @@ class DownloadService:
)
if doc:
- # Update document with extracted text
+ # Update existing document with extracted text
doc.text_content = text
doc.character_count = character_count
doc.word_count = word_count
@@ -1454,9 +1450,67 @@ class DownloadService:
f"Updated document {doc.id} with extracted text ({word_count} words)"
)
else:
- logger.warning(
- f"No document found to store text for resource {resource.id}. "
- "Text content will not be saved to database."
+ # Create a new Document for text-only extraction
+ # Generate hash from text content
+ text_hash = hashlib.sha256(text.encode()).hexdigest()
+
+ # Get source type for research downloads
+ try:
+ source_type_id = get_source_type_id(
+ self.username, "research_download"
+ )
+ except Exception:
+ logger.exception(
+ "Failed to get source type for text document"
+ )
+ raise
+
+ # Create new document
+ doc_id = str(uuid.uuid4())
+ doc = Document(
+ id=doc_id,
+ source_type_id=source_type_id,
+ resource_id=resource.id,
+ research_id=resource.research_id,
+ document_hash=text_hash,
+ original_url=resource.url,
+ file_path="text_only_not_stored",
+ file_size=character_count, # Use character count as file size for text-only
+ file_type="text",
+ mime_type="text/plain",
+ title=resource.title,
+ text_content=text,
+ character_count=character_count,
+ word_count=word_count,
+ extraction_method=extraction_method,
+ extraction_source=extraction_source,
+ extraction_quality="high"
+ if extraction_method == "native_api"
+ else "medium",
+ status=DocumentStatus.COMPLETED,
+ processed_at=datetime.now(UTC),
+ )
+ session.add(doc)
+
+ # Link to default Library collection
+ library_collection = (
+ session.query(Collection).filter_by(name="Library").first()
+ )
+ if library_collection:
+ doc_collection = DocumentCollection(
+ document_id=doc_id,
+ collection_id=library_collection.id,
+ indexed=False,
+ chunk_count=0,
+ )
+ session.add(doc_collection)
+ else:
+ logger.warning(
+ f"Library collection not found - document {doc_id} will not be linked to default collection"
+ )
+
+ logger.info(
+ f"Created new document {doc_id} for text-only extraction ({word_count} words)"
)
logger.info(
diff --git a/src/local_deep_research/web/static/js/rag_manager.js b/src/local_deep_research/web/static/js/rag_manager.js
deleted file mode 100644
index abfc13fdb5..0000000000
--- a/src/local_deep_research/web/static/js/rag_manager.js
+++ /dev/null
@@ -1,1083 +0,0 @@
-/**
- * RAG Manager JavaScript
- * Handles the RAG Manager UI interactions and API calls
- */
-
-// Available providers and models loaded from API
-let providerOptions = [];
-let availableModels = {};
-let currentIndexInfo = null; // Store current index info for comparison
-
-/**
- * Safe fetch wrapper with URL validation
- */
-async function safeFetch(url, options = {}) {
- // Internal URLs starting with '/' are safe
- if (!url.startsWith('/')) {
- if (!URLValidator.isSafeUrl(url)) {
- throw new Error(`Blocked unsafe URL: ${url}`);
- }
- }
- return fetch(url, options);
-}
-
-// Store all documents for filtering
-let allDocuments = [];
-let currentFilter = 'all';
-let currentPage = 1;
-let totalPages = 1;
-const perPage = 50;
-let currentCollectionId = null; // Currently selected collection
-
-/**
- * Initialize the page
- */
-document.addEventListener('DOMContentLoaded', function() {
- // Load collections first, then everything else
- loadCollections().then(() => {
- // After collection is selected, load the rest
- loadAvailableModels().then(() => {
- loadCurrentSettings();
- });
- loadCurrentIndexInfo();
- loadStats();
- loadDocuments();
- });
-
- // Setup collection selector change handler
- document.getElementById('collection-selector').addEventListener('change', function() {
- currentCollectionId = this.value;
- // Reload everything when collection changes
- loadCurrentIndexInfo();
- loadStats();
- loadDocuments();
- });
-
- // Setup provider change handler
- document.getElementById('embedding-provider').addEventListener('change', function() {
- updateModelOptions();
- toggleOllamaUrlField();
- checkSettingsMismatch();
- });
-
- // Setup model change handler
- document.getElementById('embedding-model').addEventListener('change', checkSettingsMismatch);
-
- // Setup Ollama URL change handler
- document.getElementById('ollama-url').addEventListener('input', checkSettingsMismatch);
-
- // Setup chunk size/overlap change handlers
- document.getElementById('chunk-size').addEventListener('input', checkSettingsMismatch);
- document.getElementById('chunk-overlap').addEventListener('input', checkSettingsMismatch);
-
- // Setup config form submission
- document.getElementById('rag-config-form').addEventListener('submit', handleConfigSubmit);
-});
-
-/**
- * Load available collections
- */
-async function loadCollections() {
- try {
- const response = await safeFetch('/library/api/collections');
- const data = await response.json();
-
- if (data.success && data.collections) {
- const selector = document.getElementById('collection-selector');
- selector.innerHTML = '';
-
- data.collections.forEach(collection => {
- const option = document.createElement('option');
- option.value = collection.id;
- option.textContent = collection.name;
- if (collection.is_default) {
- option.selected = true;
- currentCollectionId = collection.id;
- }
- selector.appendChild(option);
- });
- }
- } catch (error) {
- console.error('Error loading collections:', error);
- showError('Failed to load collections');
- }
-}
-
-/**
- * Load available embedding providers and models
- */
-async function loadAvailableModels() {
- try {
- const response = await safeFetch('/library/api/rag/models');
- const data = await response.json();
-
- if (data.success) {
- providerOptions = data.provider_options || [];
- availableModels = data.providers || {};
-
- // Populate provider dropdown
- populateProviders();
-
- // Update models for current provider (don't select yet, wait for settings)
- updateModelOptions();
- } else {
- showError('Failed to load available models: ' + data.error);
- }
- } catch (error) {
- console.error('Error loading models:', error);
- showError('Failed to load available models');
- }
-}
-
-/**
- * Load current RAG settings from database
- */
-async function loadCurrentSettings() {
- try {
- const response = await safeFetch('/library/api/rag/settings');
- const data = await response.json();
-
- if (data.success && data.settings) {
- const settings = data.settings;
-
- // Set provider
- const providerSelect = document.getElementById('embedding-provider');
- if (settings.embedding_provider) {
- providerSelect.value = settings.embedding_provider;
- }
-
- // Update models for this provider
- updateModelOptions();
-
- // Set model
- const modelSelect = document.getElementById('embedding-model');
- if (settings.embedding_model) {
- modelSelect.value = settings.embedding_model;
- updateModelDescription();
- }
-
- // Set chunk size and overlap
- if (settings.chunk_size) {
- document.getElementById('chunk-size').value = settings.chunk_size;
- }
- if (settings.chunk_overlap) {
- document.getElementById('chunk-overlap').value = settings.chunk_overlap;
- }
-
- // Load Ollama URL from global settings
- loadOllamaUrl();
-
- // Show/hide Ollama URL field based on provider
- toggleOllamaUrlField();
- }
- } catch (error) {
- console.error('Error loading current settings:', error);
- // Don't show error to user - just use defaults
- }
-}
-
-/**
- * Populate provider dropdown
- */
-function populateProviders() {
- const providerSelect = document.getElementById('embedding-provider');
- const currentValue = providerSelect.value;
-
- // Clear existing options
- providerSelect.innerHTML = '';
-
- // Add provider options
- providerOptions.forEach(provider => {
- const option = document.createElement('option');
- option.value = provider.value;
- option.textContent = provider.label;
- providerSelect.appendChild(option);
- });
-
- // Restore previous value if it exists
- if (currentValue && Array.from(providerSelect.options).some(opt => opt.value === currentValue)) {
- providerSelect.value = currentValue;
- } else if (providerSelect.options.length > 0) {
- providerSelect.value = providerSelect.options[0].value;
- }
-}
-
-/**
- * Update model dropdown based on selected provider
- */
-function updateModelOptions() {
- const provider = document.getElementById('embedding-provider').value;
- const modelSelect = document.getElementById('embedding-model');
- const descriptionSpan = document.getElementById('model-description');
-
- // Clear existing options
- modelSelect.innerHTML = '';
-
- // Add models for selected provider
- const models = availableModels[provider] || [];
- models.forEach(modelData => {
- const option = document.createElement('option');
- option.value = modelData.value;
- option.textContent = modelData.label;
- modelSelect.appendChild(option);
- });
-
- // Update description for first model
- updateModelDescription();
-
- // Add change handler for model selection (remove old handler first)
- modelSelect.removeEventListener('change', updateModelDescription);
- modelSelect.addEventListener('change', updateModelDescription);
-}
-
-/**
- * Update model description text
- */
-function updateModelDescription() {
- const provider = document.getElementById('embedding-provider').value;
- const modelSelect = document.getElementById('embedding-model');
- const descriptionSpan = document.getElementById('model-description');
-
- // Get selected model's label which contains the description
- const selectedOption = modelSelect.options[modelSelect.selectedIndex];
- if (selectedOption) {
- // Extract description from label (after the dash)
- const label = selectedOption.textContent;
- const parts = label.split(' - ');
- if (parts.length > 1) {
- descriptionSpan.textContent = parts.slice(1).join(' - ');
- } else {
- descriptionSpan.textContent = '';
- }
- } else {
- descriptionSpan.textContent = '';
- }
-}
-
-/**
- * Load current index information
- */
-async function loadCurrentIndexInfo() {
- const infoContainer = document.getElementById('current-index-info');
-
- if (!currentCollectionId) return;
-
- try {
- const response = await safeFetch(`/library/api/rag/info?collection_id=${currentCollectionId}`);
- const data = await response.json();
-
- if (data.success) {
- if (data.info) {
- renderIndexInfo(data.info);
- } else {
- infoContainer.innerHTML = `
- <div class="ldr-alert ldr-alert-info">
- <i class="fas fa-info-circle"></i> No RAG index exists yet. Configure settings and index documents to get started.
- </div>
- `;
- }
- } else {
- infoContainer.innerHTML = `
- <div class="ldr-alert ldr-alert-danger">
- Error loading index info: ${data.error}
- </div>
- `;
- }
- } catch (error) {
- console.error('Error loading index info:', error);
- infoContainer.innerHTML = `
- <div class="ldr-alert ldr-alert-danger">
- Failed to load index information
- </div>
- `;
- }
-}
-
-/**
- * Render index information
- */
-function renderIndexInfo(info) {
- const infoContainer = document.getElementById('current-index-info');
-
- // Store index info for comparison
- currentIndexInfo = info;
-
- infoContainer.innerHTML = `
- <div class="ldr-info-item">
- <span class="ldr-info-label">Embedding Model:</span>
- <span class="ldr-info-value">${info.embedding_model}</span>
- </div>
- <div class="ldr-info-item">
- <span class="ldr-info-label">Provider:</span>
- <span class="ldr-info-value">${info.embedding_model_type}</span>
- </div>
- <div class="ldr-info-item">
- <span class="ldr-info-label">Vector Dimension:</span>
- <span class="ldr-info-value">${info.embedding_dimension}</span>
- </div>
- <div class="ldr-info-item">
- <span class="ldr-info-label">Chunk Size:</span>
- <span class="ldr-info-value">${info.chunk_size} characters</span>
- </div>
- <div class="ldr-info-item">
- <span class="ldr-info-label">Chunk Overlap:</span>
- <span class="ldr-info-value">${info.chunk_overlap} characters</span>
- </div>
- <div class="ldr-info-item">
- <span class="ldr-info-label">Total Chunks:</span>
- <span class="ldr-info-value">${info.chunk_count}</span>
- </div>
- <div class="ldr-info-item">
- <span class="ldr-info-label">Documents:</span>
- <span class="ldr-info-value">${info.total_documents}</span>
- </div>
- <div class="ldr-info-item">
- <span class="ldr-info-label">Last Updated:</span>
- <span class="ldr-info-value">${new Date(info.last_updated_at).toLocaleString()}</span>
- </div>
- `;
-
- // Check if current form settings match the index
- checkSettingsMismatch();
-}
-
-/**
- * Check if current form settings match the indexed settings
- */
-function checkSettingsMismatch() {
- // Only check if we have index info
- if (!currentIndexInfo) {
- return;
- }
-
- const provider = document.getElementById('embedding-provider').value;
- const model = document.getElementById('embedding-model').value;
- const chunkSize = parseInt(document.getElementById('chunk-size').value);
- const chunkOverlap = parseInt(document.getElementById('chunk-overlap').value);
-
- // Check for mismatches
- const providerMismatch = provider !== currentIndexInfo.embedding_model_type;
- const modelMismatch = model !== currentIndexInfo.embedding_model;
- const chunkSizeMismatch = chunkSize !== currentIndexInfo.chunk_size;
- const chunkOverlapMismatch = chunkOverlap !== currentIndexInfo.chunk_overlap;
-
- const hasMismatch = providerMismatch || modelMismatch || chunkSizeMismatch || chunkOverlapMismatch;
-
- // Get or create warning container
- let warningContainer = document.getElementById('embedding-warning');
- if (!warningContainer) {
- warningContainer = document.createElement('div');
- warningContainer.id = 'embedding-warning';
- warningContainer.style.marginTop = '15px';
- const configSection = document.querySelector('.ldr-config-section:nth-child(2)');
- if (configSection) {
- configSection.appendChild(warningContainer);
- }
- }
-
- if (hasMismatch) {
- const changes = [];
- if (providerMismatch) changes.push(`Provider: ${currentIndexInfo.embedding_model_type} → ${provider}`);
- if (modelMismatch) changes.push(`Model: ${currentIndexInfo.embedding_model} → ${model}`);
- if (chunkSizeMismatch) changes.push(`Chunk Size: ${currentIndexInfo.chunk_size} → ${chunkSize}`);
- if (chunkOverlapMismatch) changes.push(`Chunk Overlap: ${currentIndexInfo.chunk_overlap} → ${chunkOverlap}`);
-
- warningContainer.innerHTML = `
- <div class="ldr-alert ldr-alert-warning" style="margin-top: 10px;">
- <i class="fas fa-exclamation-triangle"></i>
- <strong>Settings Changed!</strong><br>
- <small>${changes.map(c => escapeHtml(c)).join(', ')}</small><br>
- <small style="display: block; margin-top: 8px;">
- ⚠️ <strong>You'll need to re-index all documents</strong> for these changes to take effect.
- The current index was created with different settings and won't work properly with the new configuration.
- </small>
- </div>
- `;
- warningContainer.style.display = 'block';
- } else {
- warningContainer.style.display = 'none';
- }
-}
-
-/**
- * Load RAG statistics
- */
-async function loadStats() {
- if (!currentCollectionId) return;
-
- const statsContainer = document.getElementById('rag-stats');
-
- try {
- const response = await safeFetch(`/library/api/rag/stats?collection_id=${currentCollectionId}`);
- const data = await response.json();
-
- if (data.success) {
- renderStats(data.stats);
- } else {
- statsContainer.innerHTML = `
- <div class="ldr-alert ldr-alert-danger">
- Error loading statistics: ${data.error}
- </div>
- `;
- }
- } catch (error) {
- console.error('Error loading stats:', error);
- statsContainer.innerHTML = `
- <div class="ldr-alert ldr-alert-danger">
- Failed to load statistics
- </div>
- `;
- }
-}
-
-/**
- * Render statistics
- */
-function renderStats(stats) {
- const statsContainer = document.getElementById('rag-stats');
-
- statsContainer.innerHTML = `
- <div class="ldr-stat-card">
- <span class="ldr-stat-value">${stats.total_documents}</span>
- <span class="ldr-stat-label">Total Text Documents</span>
- </div>
- <div class="ldr-stat-card">
- <span class="ldr-stat-value">${stats.indexed_documents}</span>
- <span class="ldr-stat-label">Indexed</span>
- </div>
- <div class="ldr-stat-card ldr-warning">
- <span class="ldr-stat-value">${stats.unindexed_documents}</span>
- <span class="ldr-stat-label">Not Indexed</span>
- </div>
- <div class="ldr-stat-card">
- <span class="ldr-stat-value">${stats.total_chunks}</span>
- <span class="ldr-stat-label">Total Chunks</span>
- </div>
- `;
-}
-
-/**
- * Handle configuration form submission
- */
-async function handleConfigSubmit(event) {
- event.preventDefault();
-
- // Validate that a collection is selected
- if (!currentCollectionId) {
- showError('Please select a collection first');
- return;
- }
-
- // Save Ollama URL first if provider is ollama
- const provider = document.getElementById('embedding-provider').value;
- if (provider === 'ollama') {
- const ollamaUrlSaved = await saveOllamaUrl();
- if (!ollamaUrlSaved) {
- showError('Failed to save Ollama URL');
- return;
- }
- }
-
- const formData = {
- embedding_provider: provider,
- embedding_model: document.getElementById('embedding-model').value,
- chunk_size: parseInt(document.getElementById('chunk-size').value),
- chunk_overlap: parseInt(document.getElementById('chunk-overlap').value),
- collection_id: currentCollectionId
- };
-
- try {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
-
- const response = await safeFetch('/library/api/rag/configure', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': csrfToken
- },
- body: JSON.stringify(formData)
- });
-
- // Log response for debugging
- console.log('Response status:', response.status);
- const responseText = await response.text();
- console.log('Response text:', responseText);
-
- let data;
- try {
- data = JSON.parse(responseText);
- } catch (parseError) {
- console.error('Failed to parse JSON:', parseError);
- console.error('Response was:', responseText);
- showError('Server returned invalid response. Check console for details.');
- return;
- }
-
- if (data.success) {
- showSuccess('Configuration updated successfully! You can now index documents with the new settings.');
- loadCurrentIndexInfo();
- } else {
- showError('Failed to update configuration: ' + data.error);
- }
- } catch (error) {
- console.error('Error updating configuration:', error);
- showError('Failed to update configuration: ' + error.message);
- }
-}
-
-/**
- * Index all documents
- */
-async function indexAllDocuments(forceReindex) {
- if (!currentCollectionId) {
- showError('Please select a collection first');
- return;
- }
-
- const progressContainer = document.getElementById('progress-container');
- const progressBar = document.getElementById('progress-bar');
- const progressLog = document.getElementById('progress-log');
-
- // Show progress container
- progressContainer.style.display = 'block';
- progressBar.style.width = '0%';
- progressBar.textContent = '0%';
- progressLog.innerHTML = '';
-
- // Add initial log entry
- addLogEntry('Starting indexing process...', 'info');
-
- let eventSource = null;
- let reconnectAttempts = 0;
- const maxReconnectAttempts = 3;
- const reconnectDelay = 2000; // 2 seconds
-
- function createEventSource() {
- try {
- eventSource = new EventSource(`/library/api/rag/index-all?force_reindex=${forceReindex}&collection_id=${currentCollectionId}`);
-
- eventSource.onmessage = function(event) {
- // Reset reconnect attempts on successful message
- reconnectAttempts = 0;
-
- try {
- const data = JSON.parse(event.data);
-
- if (data.type === 'start') {
- addLogEntry(data.message, 'info');
- progressBar.style.width = '10%';
- progressBar.textContent = '10%';
- } else if (data.type === 'progress') {
- // Update progress bar
- progressBar.style.width = `${data.percent}%`;
- progressBar.textContent = `${data.percent}%`;
-
- // Add log entry for current document
- addLogEntry(`[${data.current}/${data.total}] Indexing: ${data.title}`, 'info');
- } else if (data.type === 'complete') {
- const results = data.results;
- addLogEntry(`Indexing complete!`, 'success');
- addLogEntry(`✓ Successfully indexed: ${results.successful}`, 'success');
- if (results.skipped > 0) {
- addLogEntry(`⊘ Skipped (already indexed): ${results.skipped}`, 'info');
- }
- if (results.failed > 0) {
- addLogEntry(`✗ Failed: ${results.failed}`, 'error');
- results.errors.forEach(err => {
- addLogEntry(` - ${err.title}: ${err.error}`, 'error');
- });
- }
-
- progressBar.style.width = '100%';
- progressBar.textContent = '100%';
- progressBar.classList.remove('ldr-progress-bar-animated');
-
- // Refresh stats and document list
- setTimeout(() => {
- refreshStats();
- loadDocuments();
- }, 1000);
-
- closeEventSource();
- } else if (data.type === 'error') {
- addLogEntry(`Server error: ${data.error}`, 'error');
- progressBar.classList.remove('ldr-progress-bar-animated');
- progressBar.classList.add('ldr-bg-danger');
- closeEventSource();
- }
- } catch (parseError) {
- console.error('Failed to parse SSE message:', parseError, 'Raw data:', event.data);
- addLogEntry('Received invalid data from server', 'error');
- }
- };
-
- eventSource.onerror = function(error) {
- console.error('EventSource error:', error);
-
- // Check if we should attempt reconnection
- if (eventSource.readyState === EventSource.CLOSED) {
- // Connection permanently closed
- addLogEntry('Connection closed by server', 'error');
- closeEventSource();
- } else if (eventSource.readyState === EventSource.CONNECTING) {
- // Attempting to reconnect automatically
- if (reconnectAttempts < maxReconnectAttempts) {
- reconnectAttempts++;
- addLogEntry(`Connection lost. Reconnecting... (${reconnectAttempts}/${maxReconnectAttempts})`, 'warn');
-
- // EventSource will automatically try to reconnect
- // We just need to handle the case where it fails repeatedly
- setTimeout(() => {
- if (eventSource && eventSource.readyState === EventSource.CONNECTING) {
- addLogEntry('Reconnection taking longer than expected...', 'warn');
- }
- }, reconnectDelay);
- } else {
- // Max reconnect attempts reached
- addLogEntry('Unable to reconnect after multiple attempts. Please refresh the page and try again.', 'error');
- progressBar.classList.remove('ldr-progress-bar-animated');
- progressBar.classList.add('ldr-bg-danger');
- closeEventSource();
- }
- } else {
- // Unknown error state
- addLogEntry('Connection error occurred. Check your network connection.', 'error');
- progressBar.classList.remove('ldr-progress-bar-animated');
- progressBar.classList.add('ldr-bg-danger');
- closeEventSource();
- }
- };
-
- eventSource.onopen = function() {
- if (reconnectAttempts > 0) {
- addLogEntry('Connection restored! Continuing...', 'success');
- }
- };
-
- } catch (error) {
- console.error('Error creating EventSource:', error);
- addLogEntry(`Failed to start indexing: ${error.message}`, 'error');
- progressBar.classList.add('ldr-bg-danger');
- }
- }
-
- function closeEventSource() {
- if (eventSource) {
- eventSource.close();
- eventSource = null;
- }
- }
-
- // Create the EventSource connection
- createEventSource();
-}
-
-/**
- * Add log entry to progress log
- */
-function addLogEntry(message, type = 'info') {
- const progressLog = document.getElementById('progress-log');
- const entry = document.createElement('div');
- entry.className = `ldr-log-entry ldr-${type}`;
- entry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
- progressLog.appendChild(entry);
- progressLog.scrollTop = progressLog.scrollHeight;
-}
-
-/**
- * Refresh statistics
- */
-function refreshStats() {
- loadStats();
- loadCurrentIndexInfo();
- loadDocuments();
-}
-
-/**
- * Show success message
- */
-function showSuccess(message) {
- alert('Success: ' + message);
-}
-
-/**
- * Show error message
- */
-function showError(message) {
- alert('Error: ' + message);
-}
-
-/**
- * Load documents list with pagination
- */
-async function loadDocuments(page = 1) {
- if (!currentCollectionId) return;
-
- const documentsContainer = document.getElementById('documents-list');
-
- try {
- const response = await safeFetch(
- `/library/api/rag/documents?page=${page}&per_page=${perPage}&filter=${currentFilter}&collection_id=${currentCollectionId}`
- );
- const data = await response.json();
-
- if (data.success) {
- allDocuments = data.documents;
- currentPage = data.pagination.page;
- totalPages = data.pagination.pages;
- renderDocuments();
- renderPagination(data.pagination);
- } else {
- documentsContainer.innerHTML = `
- <div class="ldr-alert ldr-alert-danger">
- Error loading documents: ${data.error}
- </div>
- `;
- }
- } catch (error) {
- console.error('Error loading documents:', error);
- documentsContainer.innerHTML = `
- <div class="ldr-alert ldr-alert-danger">
- Failed to load documents
- </div>
- `;
- }
-}
-
-/**
- * Render pagination controls
- */
-function renderPagination(pagination) {
- let paginationContainer = document.getElementById('pagination-container');
-
- // Create container if it doesn't exist
- if (!paginationContainer) {
- paginationContainer = document.createElement('div');
- paginationContainer.id = 'pagination-container';
- paginationContainer.style.marginTop = '20px';
- paginationContainer.style.textAlign = 'center';
-
- const documentsSection = document.querySelector('.ldr-documents-section');
- if (documentsSection) {
- documentsSection.appendChild(paginationContainer);
- }
- }
-
- if (pagination.pages <= 1) {
- paginationContainer.innerHTML = '';
- return;
- }
-
- const { page, pages, total } = pagination;
-
- let paginationHTML = '<div class="ldr-pagination">';
-
- // Previous button
- paginationHTML += `
- <button class="ldr-btn ldr-btn-sm"
- onclick="loadDocuments(${page - 1})"
- ${page <= 1 ? 'disabled' : ''}>
- &laquo; Previous
- </button>
- `;
-
- // Page numbers
- const maxPageButtons = 5;
- let startPage = Math.max(1, page - Math.floor(maxPageButtons / 2));
- let endPage = Math.min(pages, startPage + maxPageButtons - 1);
-
- if (endPage - startPage < maxPageButtons - 1) {
- startPage = Math.max(1, endPage - maxPageButtons + 1);
- }
-
- if (startPage > 1) {
- paginationHTML += `
- <button class="ldr-btn ldr-btn-sm" onclick="loadDocuments(1)">1</button>
- `;
- if (startPage > 2) {
- paginationHTML += '<span style="padding: 0 10px;">...</span>';
- }
- }
-
- for (let i = startPage; i <= endPage; i++) {
- paginationHTML += `
- <button class="ldr-btn ldr-btn-sm ${i === page ? 'ldr-active' : ''}"
- onclick="loadDocuments(${i})">
- ${i}
- </button>
- `;
- }
-
- if (endPage < pages) {
- if (endPage < pages - 1) {
- paginationHTML += '<span style="padding: 0 10px;">...</span>';
- }
- paginationHTML += `
- <button class="ldr-btn ldr-btn-sm" onclick="loadDocuments(${pages})">${pages}</button>
- `;
- }
-
- // Next button
- paginationHTML += `
- <button class="ldr-btn ldr-btn-sm"
- onclick="loadDocuments(${page + 1})"
- ${page >= pages ? 'disabled' : ''}>
- Next &raquo;
- </button>
- `;
-
- paginationHTML += `</div>`;
- paginationHTML += `<div style="margin-top: 10px; color: #666;">Showing ${allDocuments.length} of ${total} documents</div>`;
-
- paginationContainer.innerHTML = paginationHTML;
-}
-
-/**
- * Render documents based on current filter
- */
-function renderDocuments() {
- const documentsContainer = document.getElementById('documents-list');
-
- // Documents are already filtered by backend
- if (allDocuments.length === 0) {
- documentsContainer.innerHTML = `
- <div class="ldr-alert ldr-alert-info">
- No documents found for this filter.
- </div>
- `;
- return;
- }
-
- // Render documents
- documentsContainer.innerHTML = allDocuments.map(doc => `
- <div class="ldr-document-item">
- <div class="ldr-document-info">
- <div class="ldr-document-title">${escapeHtml(doc.title)}</div>
- <div class="ldr-document-meta">
- ${doc.rag_indexed
- ? `<span class="ldr-badge-indexed"><i class="fas fa-check"></i> Indexed (${doc.chunk_count} chunks)</span>`
- : `<span class="ldr-badge-unindexed"><i class="fas fa-times"></i> Not Indexed</span>`
- }
- ${doc.original_url ? ` • Source: ${escapeHtml(doc.original_url.substring(0, 50))}${doc.original_url.length > 50 ? '...' : ''}` : ''}
- </div>
- </div>
- <div class="ldr-document-actions">
- ${doc.rag_indexed
- ? `<button class="ldr-btn ldr-btn-sm ldr-btn-warning" onclick="reindexDocument(${doc.id}, '${escapeHtml(doc.title)}')">
- <i class="fas fa-redo"></i> Re-index
- </button>
- <button class="ldr-btn ldr-btn-sm ldr-btn-danger" onclick="removeDocument(${doc.id}, '${escapeHtml(doc.title)}')">
- <i class="fas fa-trash"></i> Remove
- </button>`
- : `<button class="ldr-btn ldr-btn-sm ldr-btn-success" onclick="indexDocument(${doc.id}, '${escapeHtml(doc.title)}')">
- <i class="fas fa-plus"></i> Index
- </button>`
- }
- </div>
- </div>
- `).join('');
-}
-
-/**
- * Filter documents list
- */
-function filterDocuments(filter) {
- currentFilter = filter;
-
- // Update button states
- document.querySelectorAll('.ldr-filter-controls .ldr-btn').forEach(btn => {
- btn.classList.remove('ldr-active');
- });
- event.target.classList.add('ldr-active');
-
- // Reload documents from page 1 with new filter
- loadDocuments(1);
-}
-
-/**
- * Index a single document
- */
-async function indexDocument(docId, title) {
- if (!currentCollectionId) {
- showError('Please select a collection first');
- return;
- }
-
- try {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
- const response = await safeFetch('/library/api/rag/index-document', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': csrfToken
- },
- body: JSON.stringify({
- text_doc_id: docId,
- collection_id: currentCollectionId,
- force_reindex: false
- })
- });
-
- const data = await response.json();
- if (data.success) {
- showSuccess(`Successfully indexed: ${title}`);
- loadDocuments();
- refreshStats();
- } else {
- showError(`Failed to index ${title}: ${data.error}`);
- }
- } catch (error) {
- console.error('Error indexing document:', error);
- showError(`Error indexing ${title}: ${error.message}`);
- }
-}
-
-/**
- * Re-index a document
- */
-async function reindexDocument(docId, title) {
- if (!currentCollectionId) {
- showError('Please select a collection first');
- return;
- }
-
- try {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
- const response = await safeFetch('/library/api/rag/index-document', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': csrfToken
- },
- body: JSON.stringify({
- text_doc_id: docId,
- collection_id: currentCollectionId,
- force_reindex: true
- })
- });
-
- const data = await response.json();
- if (data.success) {
- showSuccess(`Successfully re-indexed: ${title}`);
- loadDocuments();
- refreshStats();
- } else {
- showError(`Failed to re-index ${title}: ${data.error}`);
- }
- } catch (error) {
- console.error('Error re-indexing document:', error);
- showError(`Error re-indexing ${title}: ${error.message}`);
- }
-}
-
-/**
- * Remove a document from RAG
- */
-async function removeDocument(docId, title) {
- if (!currentCollectionId) {
- showError('Please select a collection first');
- return;
- }
-
- if (!confirm(`Are you sure you want to remove "${title}" from the RAG index?`)) {
- return;
- }
-
- try {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
- const response = await safeFetch('/library/api/rag/remove-document', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': csrfToken
- },
- body: JSON.stringify({
- text_doc_id: docId,
- collection_id: currentCollectionId
- })
- });
-
- const data = await response.json();
- if (data.success) {
- showSuccess(`Successfully removed: ${title}`);
- loadDocuments();
- refreshStats();
- } else {
- showError(`Failed to remove ${title}: ${data.error}`);
- }
- } catch (error) {
- console.error('Error removing document:', error);
- showError(`Error removing ${title}: ${error.message}`);
- }
-}
-
-/**
- * Escape HTML to prevent XSS
- */
-function escapeHtml(text) {
- const div = document.createElement('div');
- div.textContent = text;
- return div.innerHTML;
-}
-
-/**
- * Toggle Ollama URL field visibility based on selected provider
- */
-function toggleOllamaUrlField() {
- const provider = document.getElementById('embedding-provider').value;
- const ollamaUrlGroup = document.getElementById('ollama-url-group');
-
- if (provider === 'ollama') {
- ollamaUrlGroup.style.display = 'block';
- } else {
- ollamaUrlGroup.style.display = 'none';
- }
-}
-
-/**
- * Load Ollama URL from settings
- */
-async function loadOllamaUrl() {
- try {
- const response = await safeFetch('/settings/api/embeddings.ollama.url');
- const data = await response.json();
-
- if (data && data.value) {
- document.getElementById('ollama-url').value = data.value;
- }
- } catch (error) {
- console.error('Error loading Ollama URL:', error);
- }
-}
-
-/**
- * Save Ollama URL to settings
- */
-async function saveOllamaUrl() {
- const ollamaUrl = document.getElementById('ollama-url').value.trim();
-
- try {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
-
- const response = await safeFetch('/settings/api/embeddings.ollama.url', {
- method: 'PUT',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': csrfToken
- },
- body: JSON.stringify({
- value: ollamaUrl
- })
- });
-
- const data = await response.json();
- if (data.error) {
- console.error('Failed to save Ollama URL:', data.error);
- return false;
- }
- return true;
- } catch (error) {
- console.error('Error saving Ollama URL:', error);
- return false;
- }
-}
diff --git a/src/local_deep_research/web/templates/components/sidebar.html b/src/local_deep_research/web/templates/components/sidebar.html
index febb79a376..a139637719 100644
--- a/src/local_deep_research/web/templates/components/sidebar.html
+++ b/src/local_deep_research/web/templates/components/sidebar.html
@@ -38,6 +38,12 @@
<span class="ldr-nav-text">Collections</span>
</a>
</li>
+ <li {% if active_page == 'download-manager' %}class="active ldr-sidebar-item--nested"{% else %}class="ldr-sidebar-item--nested"{% endif %} data-page="download-manager">
+ <a href="{{ url_for('library.download_manager_page') }}" title="Download Manager">
+ <i class="fas fa-download"></i>
+ <span class="ldr-nav-text">Downloads</span>
+ </a>
+ </li>
</ul>
</div>
diff --git a/src/local_deep_research/web/templates/pages/download_manager.html b/src/local_deep_research/web/templates/pages/download_manager.html
index 616fc6c241..cc182473c7 100644
--- a/src/local_deep_research/web/templates/pages/download_manager.html
+++ b/src/local_deep_research/web/templates/pages/download_manager.html
@@ -7,6 +7,21 @@
<div class="ldr-manager-header">
<h1>Download Manager</h1>
<div class="ldr-header-actions">
+ <div class="ldr-btn-group" style="margin-right: 15px;">
+ <button class="btn btn-success" onclick="downloadAllNew()"
+ {% if not enable_pdf_storage %}
+ disabled
+ title="PDF downloads are disabled. Enable PDF storage in Settings → Research Library"
+ {% else %}
+ title="Download ALL available PDF files to disk"
+ {% endif %}>
+ <i class="fas fa-file-pdf"></i> Download ALL PDFs
+ </button>
+ <button class="btn btn-info" onclick="downloadAllAsText()"
+ title="Extract ALL text to encrypted database">
+ <i class="fas fa-database"></i> Extract ALL Text
+ </button>
+ </div>
<button class="btn btn-secondary" onclick="window.location.href='/library'">
<i class="fas fa-book"></i> Back to Library
</button>
@@ -1323,6 +1338,208 @@ function cancelDownloads() {
}
}
+// Download ALL PDFs function
+async function downloadAllNew() {
+ const btn = event.target.closest('button');
+ const originalContent = btn.innerHTML;
+ btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Preparing...';
+ btn.disabled = true;
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
+
+ // First, queue all undownloaded articles
+ const queueResponse = await fetch('/library/api/queue-all-undownloaded', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ }
+ });
+
+ if (!queueResponse.ok) {
+ throw new Error(`HTTP error! status: ${queueResponse.status}`);
+ }
+
+ const queueResult = await queueResponse.json();
+
+ if (queueResult.queued === 0) {
+ alert('No new articles to download. All available articles have already been downloaded.');
+ btn.innerHTML = originalContent;
+ btn.disabled = false;
+ return;
+ }
+
+ // Show progress modal
+ document.getElementById('download-progress-modal').style.display = 'block';
+ document.querySelector('#download-progress-modal h2').textContent = 'Downloading ALL PDFs';
+
+ // Reset progress
+ document.getElementById('overall-progress').style.width = '0%';
+ document.getElementById('current-count').textContent = '0';
+ document.getElementById('total-count').textContent = queueResult.queued;
+ document.getElementById('download-log').innerHTML = '';
+
+ btn.innerHTML = originalContent;
+ btn.disabled = false;
+
+ // Create abort controller
+ currentDownloadController = new AbortController();
+
+ // Start streaming download
+ const downloadResponse = await fetch('/library/api/download-bulk', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({research_ids: queueResult.research_ids || []}),
+ signal: currentDownloadController.signal
+ });
+
+ const reader = downloadResponse.body.getReader();
+ const decoder = new TextDecoder();
+
+ while (true) {
+ const {done, value} = await reader.read();
+ if (done) break;
+
+ const chunk = decoder.decode(value);
+ const lines = chunk.split('\n');
+
+ for (const line of lines) {
+ if (line.startsWith('data: ')) {
+ const data = JSON.parse(line.slice(6));
+ updateProgress(data);
+
+ if (data.complete) {
+ currentDownloadController = null;
+ setTimeout(() => {
+ closeProgressModal();
+ location.reload();
+ }, 2000);
+ }
+ }
+ }
+ }
+
+ } catch (error) {
+ if (error.name === 'AbortError') {
+ console.log('Download cancelled by user');
+ } else {
+ console.error('Failed to start downloads:', error);
+ alert('Failed to start downloads. Please try again.');
+ }
+ btn.innerHTML = originalContent;
+ btn.disabled = false;
+ } finally {
+ currentDownloadController = null;
+ }
+}
+
+// Extract ALL Text function
+async function downloadAllAsText() {
+ const btn = event.target.closest('button');
+ const originalContent = btn.innerHTML;
+ btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Extracting...';
+ btn.disabled = true;
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
+
+ // Show progress modal
+ document.getElementById('download-progress-modal').style.display = 'block';
+ document.querySelector('#download-progress-modal h2').textContent = 'Text Extraction to Database';
+
+ // Reset progress
+ document.getElementById('overall-progress').style.width = '0%';
+ document.getElementById('current-count').textContent = '0';
+ document.getElementById('total-count').textContent = '0';
+ document.getElementById('download-log').innerHTML = '';
+
+ currentDownloadController = new AbortController();
+
+ const response = await fetch('/library/api/download-all-text', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({}),
+ signal: currentDownloadController.signal
+ });
+
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+
+ while (true) {
+ const {done, value} = await reader.read();
+ if (done) break;
+
+ const chunk = decoder.decode(value);
+ const lines = chunk.split('\n');
+
+ for (const line of lines) {
+ if (line.startsWith('data: ')) {
+ const data = JSON.parse(line.slice(6));
+ updateTextExtractionProgress(data);
+
+ if (data.complete) {
+ currentDownloadController = null;
+ setTimeout(() => {
+ closeProgressModal();
+ alert(`Text extraction complete! Extracted ${data.total} documents to encrypted database.`);
+ }, 2000);
+ }
+ }
+ }
+ }
+
+ } catch (error) {
+ if (error.name === 'AbortError') {
+ console.log('Text extraction cancelled by user');
+ } else {
+ console.error('Failed to start text extraction:', error);
+ alert('Failed to start text extraction. Please try again.');
+ }
+ } finally {
+ btn.innerHTML = originalContent;
+ btn.disabled = false;
+ currentDownloadController = null;
+ }
+}
+
+// Update text extraction progress
+function updateTextExtractionProgress(data) {
+ const progressBar = document.getElementById('overall-progress');
+ const currentCount = document.getElementById('current-count');
+ const totalCount = document.getElementById('total-count');
+ const log = document.getElementById('download-log');
+
+ progressBar.style.width = `${data.progress}%`;
+ currentCount.textContent = data.current;
+ totalCount.textContent = data.total;
+
+ if (data.file) {
+ const entry = document.createElement('div');
+ entry.className = `ldr-download-entry ${data.status}`;
+
+ let statusIcon = data.status === 'success' ? '✓' : '✗';
+ let statusText = data.status === 'success' ? 'Text extracted' : (data.error || 'Extraction failed');
+
+ entry.innerHTML = `
+ <span class="ldr-status-icon">${statusIcon}</span>
+ <div class="ldr-entry-details">
+ <strong>${data.file}</strong>
+ <span class="ldr-status-text">${statusText}</span>
+ </div>
+ `;
+
+ log.appendChild(entry);
+ log.scrollTop = log.scrollHeight;
+ }
+}
+
// Format dates and durations on page load
document.addEventListener('DOMContentLoaded', function() {
// Format dates
diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.html
index 17b30e7674..903c0d0f98 100644
--- a/src/local_deep_research/web/templates/pages/library.html
+++ b/src/local_deep_research/web/templates/pages/library.html
@@ -31,8 +31,8 @@
<button class="btn btn-primary" onclick="window.location.href='/library/download-manager'">
<i class="fas fa-download"></i> Download Manager
</button>
- <button class="btn btn-info" onclick="window.location.href='/library/rag-manager'">
- <i class="fas fa-brain"></i> RAG Manager
+ <button class="btn btn-info" onclick="window.location.href='/library/collections'">
+ <i class="fas fa-folder-open"></i> Collections
</button>
<div class="library-stats">
<span class="stat-item">
diff --git a/src/local_deep_research/web/templates/pages/rag_manager.html b/src/local_deep_research/web/templates/pages/rag_manager.html
deleted file mode 100644
index 3009107b64..0000000000
--- a/src/local_deep_research/web/templates/pages/rag_manager.html
+++ /dev/null
@@ -1,527 +0,0 @@
-{% extends "base.html" %}
-
-{% block title %}RAG Manager{% endblock %}
-
-{% block content %}
-<div class="ldr-library-container">
- <div class="ldr-library-header">
- <h1>RAG Manager</h1>
- <p class="ldr-subtitle">Manage semantic search indexing for your library documents</p>
- </div>
-
- <!-- Collection Selector -->
- <div class="ldr-rag-collection-selector ldr-mb-4">
- <div class="ldr-form-group">
- <label for="collection-selector"><i class="fas fa-folder"></i> Select Collection</label>
- <select id="collection-selector" class="ldr-form-control ldr-form-control-lg">
- <option value="">Loading collections...</option>
- </select>
- </div>
- </div>
-
- <!-- Configuration Panel -->
- <div class="ldr-rag-config-panel">
- <h2><i class="fas fa-cog"></i> Configuration</h2>
-
- <div class="ldr-config-grid">
- <!-- Current Index Info -->
- <div class="ldr-config-section">
- <h3>Current Index</h3>
- <div id="current-index-info" class="ldr-info-box">
- <div class="ldr-loading-spinner">
- <i class="fas fa-spinner fa-spin"></i> Loading...
- </div>
- </div>
- </div>
-
- <!-- Embedding Model Selection -->
- <div class="ldr-config-section">
- <h3>Embedding Configuration</h3>
- <form id="rag-config-form">
- <div class="ldr-form-group">
- <label for="embedding-provider">Provider</label>
- <select id="embedding-provider" class="ldr-form-control">
- <option value="">Loading providers...</option>
- </select>
- </div>
-
- <div class="ldr-form-group" id="ollama-url-group" style="display: none;">
- <label for="ollama-url">Ollama URL</label>
- <input type="text" id="ollama-url" class="ldr-form-control" placeholder="http://localhost:11434">
- <small class="ldr-form-text ldr-text-muted">
- URL of the Ollama server for embedding models. Leave empty to use the default LLM Ollama URL.
- </small>
- </div>
-
- <div class="ldr-form-group">
- <label for="embedding-model">Model</label>
- <select id="embedding-model" class="ldr-form-control">
- <!-- Options loaded dynamically -->
- </select>
- <small class="ldr-form-text ldr-text-muted">
- <span id="model-description"></span>
- </small>
- </div>
-
- <div class="ldr-form-row">
- <div class="ldr-form-group ldr-col-md-6">
- <label for="chunk-size">Chunk Size</label>
- <input type="number" id="chunk-size" class="ldr-form-control" value="1000" min="100" max="5000" step="100">
- <small class="ldr-form-text ldr-text-muted">Characters per chunk</small>
- </div>
- <div class="ldr-form-group ldr-col-md-6">
- <label for="chunk-overlap">Chunk Overlap</label>
- <input type="number" id="chunk-overlap" class="ldr-form-control" value="200" min="0" max="1000" step="50">
- <small class="ldr-form-text ldr-text-muted">Overlap between chunks</small>
- </div>
- </div>
-
- <button type="submit" class="ldr-btn ldr-btn-primary">
- <i class="fas fa-save"></i> Apply Configuration
- </button>
- <small class="ldr-form-text ldr-text-muted ldr-mt-2">
- Note: Changing configuration will create a new index. Existing indexed documents will need to be re-indexed.
- </small>
- </form>
- </div>
- </div>
- </div>
-
- <!-- Statistics Panel -->
- <div class="ldr-rag-stats-panel">
- <h2><i class="fas fa-chart-bar"></i> Statistics</h2>
- <div id="rag-stats" class="ldr-stats-grid">
- <div class="ldr-loading-spinner">
- <i class="fas fa-spinner fa-spin"></i> Loading statistics...
- </div>
- </div>
- </div>
-
- <!-- Bulk Operations Panel -->
- <div class="ldr-rag-operations-panel">
- <h2><i class="fas fa-tasks"></i> Bulk Operations</h2>
-
- <div class="ldr-operations-grid">
- <button class="ldr-btn ldr-btn-success ldr-btn-lg" onclick="indexAllDocuments(false)">
- <i class="fas fa-play"></i> Index Unindexed Documents
- </button>
- <button class="ldr-btn ldr-btn-warning ldr-btn-lg" onclick="indexAllDocuments(true)">
- <i class="fas fa-redo"></i> Re-Index All Documents
- </button>
- <button class="ldr-btn ldr-btn-info ldr-btn-lg" onclick="refreshStats()">
- <i class="fas fa-sync"></i> Refresh Statistics
- </button>
- </div>
-
-
- <!-- Progress Display -->
- <div id="progress-container" class="ldr-mt-4" style="display: none;">
- <h3>Indexing Progress</h3>
- <div class="ldr-progress">
- <div id="progress-bar" class="ldr-progress-bar ldr-progress-bar-striped ldr-progress-bar-animated" role="progressbar" style="width: 0%">
- 0%
- </div>
- </div>
- <div id="progress-log" class="ldr-log-container ldr-mt-3"></div>
- </div>
- </div>
-
- <!-- Document List -->
- <div class="ldr-rag-documents-panel">
- <h2><i class="fas fa-list"></i> Library Documents</h2>
-
- <div class="ldr-filter-controls ldr-mb-3">
- <div class="ldr-btn-group" role="group">
- <button type="button" class="ldr-btn ldr-btn-outline-primary ldr-active" onclick="filterDocuments('all')">
- All Documents
- </button>
- <button type="button" class="ldr-btn ldr-btn-outline-success" onclick="filterDocuments('indexed')">
- Indexed
- </button>
- <button type="button" class="ldr-btn ldr-btn-outline-warning" onclick="filterDocuments('unindexed')">
- Not Indexed
- </button>
- </div>
- </div>
-
- <div id="documents-list" class="ldr-documents-list">
- <div class="ldr-loading-spinner">
- <i class="fas fa-spinner fa-spin"></i> Loading documents...
- </div>
- </div>
- </div>
-</div>
-
-
-<style>
-.ldr-library-container {
- padding: 20px;
- max-width: 1400px;
- margin: 0 auto;
- background: var(--bg-primary, #1a1a1a);
- min-height: 100vh;
-}
-
-.ldr-library-header {
- margin-bottom: 30px;
-}
-
-.ldr-library-header h1 {
- color: var(--text-primary, #e4e4e4);
- font-size: 2em;
- margin: 0 0 10px 0;
-}
-
-.ldr-library-header .ldr-subtitle {
- color: var(--text-secondary, #999);
- font-size: 1.1em;
- margin-top: 10px;
-}
-
-.ldr-rag-config-panel,
-.ldr-rag-stats-panel,
-.ldr-rag-operations-panel,
-.ldr-rag-documents-panel {
- background: var(--card-bg, #2a2a2a);
- border-radius: 8px;
- padding: 25px;
- margin-bottom: 25px;
- box-shadow: 0 2px 4px var(--shadow-color, rgba(0,0,0,0.3));
- border: 1px solid var(--border-color, #333);
-}
-
-.ldr-rag-config-panel h2,
-.ldr-rag-stats-panel h2,
-.ldr-rag-operations-panel h2,
-.ldr-rag-documents-panel h2 {
- margin-bottom: 20px;
- color: var(--text-primary, #e4e4e4);
- font-size: 1.5em;
-}
-
-.ldr-config-grid {
- display: grid;
- grid-template-columns: 1fr 1fr;
- gap: 30px;
-}
-
-@media (max-width: 992px) {
- .ldr-config-grid {
- grid-template-columns: 1fr;
- }
-}
-
-.ldr-config-section {
- background: var(--input-bg, #1a1a1a);
- padding: 20px;
- border-radius: 6px;
- border: 1px solid var(--border-color, #444);
-}
-
-.ldr-config-section h3 {
- margin-bottom: 15px;
- font-size: 1.2em;
- color: var(--text-primary, #e4e4e4);
-}
-
-.ldr-info-box {
- background: var(--card-bg, #2a2a2a);
- padding: 15px;
- border-radius: 4px;
- border-left: 4px solid var(--primary-color, #007bff);
-}
-
-.ldr-info-box .ldr-alert {
- margin: 0;
- padding: 12px;
-}
-
-.ldr-info-box:has(.ldr-alert) {
- background: transparent;
- padding: 0;
- border: none;
-}
-
-.ldr-info-box .ldr-info-item {
- display: flex;
- justify-content: space-between;
- padding: 8px 0;
- border-bottom: 1px solid var(--border-color, #444);
-}
-
-.ldr-info-box .ldr-info-item:last-child {
- border-bottom: none;
-}
-
-.ldr-info-box .ldr-info-label {
- font-weight: 600;
- color: var(--text-secondary, #999);
-}
-
-.ldr-info-box .ldr-info-value {
- color: var(--text-primary, #e4e4e4);
-}
-
-.ldr-stats-grid {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
- gap: 20px;
-}
-
-.ldr-stat-card {
- background: var(--input-bg, #1a1a1a);
- padding: 20px;
- border-radius: 6px;
- text-align: center;
- border-left: 4px solid var(--success-color, #28a745);
- border: 1px solid var(--border-color, #444);
-}
-
-.ldr-stat-card.ldr-warning {
- border-left-color: var(--warning-color, #ffc107);
-}
-
-.ldr-stat-card .ldr-stat-value {
- font-size: 2.5em;
- font-weight: bold;
- color: var(--text-primary, #e4e4e4);
- display: block;
-}
-
-.ldr-stat-card .ldr-stat-label {
- color: var(--text-secondary, #999);
- margin-top: 10px;
- font-size: 0.9em;
-}
-
-.ldr-operations-grid {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
- gap: 20px;
-}
-
-
-/* Modal Styles */
-.ldr-modal {
- position: fixed;
- z-index: 1000;
- left: 0;
- top: 0;
- width: 100%;
- height: 100%;
- background-color: rgba(0, 0, 0, 0.7);
- display: flex;
- align-items: center;
- justify-content: center;
-}
-
-.ldr-modal-content {
- background: var(--card-bg, #2a2a2a);
- border-radius: 8px;
- width: 90%;
- max-width: 500px;
- max-height: 90vh;
- overflow-y: auto;
-}
-
-.ldr-modal-large {
- max-width: 800px;
-}
-
-.ldr-modal-header {
- padding: 20px;
- border-bottom: 1px solid var(--border-color, #444);
- display: flex;
- justify-content: space-between;
- align-items: center;
-}
-
-.ldr-modal-close {
- font-size: 28px;
- font-weight: bold;
- color: var(--text-secondary, #999);
- cursor: pointer;
-}
-
-.ldr-modal-close:hover {
- color: var(--text-primary, #e4e4e4);
-}
-
-.ldr-modal-body {
- padding: 20px;
-}
-
-.ldr-modal-footer {
- padding: 15px 20px;
- border-top: 1px solid var(--border-color, #444);
- display: flex;
- justify-content: flex-end;
- gap: 10px;
-}
-
-
-.ldr-mb-2 {
- margin-bottom: 10px;
-}
-
-.ldr-mt-2 {
- margin-top: 10px;
-}
-
-.ldr-mt-3 {
- margin-top: 15px;
-}
-
-.ldr-form-row {
- display: flex;
- gap: 20px;
- margin-bottom: 15px;
-}
-
-.ldr-col-md-6 {
- flex: 1;
-}
-
-.ldr-mt-4 {
- margin-top: 20px;
-}
-
-.ldr-loading-spinner {
- text-align: center;
- padding: 40px;
- color: var(--text-secondary, #999);
- font-size: 1.2em;
-}
-
-.ldr-log-container {
- max-height: 300px;
- overflow-y: auto;
- background: var(--input-bg, #1a1a1a);
- padding: 15px;
- border-radius: 4px;
- font-family: monospace;
- font-size: 0.9em;
- border: 1px solid var(--border-color, #444);
-}
-
-.ldr-log-entry {
- padding: 5px 0;
- border-bottom: 1px solid var(--border-color, #444);
-}
-
-.ldr-log-entry:last-child {
- border-bottom: none;
-}
-
-.ldr-log-entry.ldr-success {
- color: var(--success-color, #28a745);
-}
-
-.ldr-log-entry.ldr-error {
- color: var(--danger-color, #dc3545);
-}
-
-.ldr-log-entry.ldr-info {
- color: var(--info-color, #17a2b8);
-}
-
-.ldr-documents-list {
- margin-top: 20px;
-}
-
-.ldr-filter-controls {
- display: flex;
- justify-content: space-between;
- align-items: center;
-}
-
-.ldr-document-item {
- background: var(--input-bg, #1a1a1a);
- padding: 15px;
- margin-bottom: 10px;
- border-radius: 6px;
- display: flex;
- justify-content: space-between;
- align-items: center;
- border: 1px solid var(--border-color, #444);
-}
-
-.ldr-document-info {
- flex: 1;
-}
-
-.ldr-document-title {
- font-weight: 600;
- color: var(--text-primary, #e4e4e4);
- margin-bottom: 5px;
-}
-
-.ldr-document-meta {
- font-size: 0.9em;
- color: var(--text-secondary, #999);
-}
-
-.ldr-document-actions {
- display: flex;
- gap: 10px;
-}
-
-.ldr-badge-indexed {
- background: var(--success-color, #28a745);
- color: white;
- padding: 4px 8px;
- border-radius: 4px;
- font-size: 0.85em;
-}
-
-.ldr-badge-unindexed {
- background: var(--secondary-color, #6c757d);
- color: white;
- padding: 4px 8px;
- border-radius: 4px;
- font-size: 0.85em;
-}
-
-.ldr-alert {
- padding: 12px 16px;
- margin-bottom: 10px;
- border-radius: 4px;
- border: 1px solid transparent;
-}
-
-.ldr-alert-info {
- color: #0c5460;
- background-color: #d1ecf1;
- border-color: #bee5eb;
-}
-
-.ldr-alert-danger {
- color: #721c24;
- background-color: #f8d7da;
- border-color: #f5c6cb;
-}
-
-.ldr-alert-success {
- color: #155724;
- background-color: #d4edda;
- border-color: #c3e6cb;
-}
-
-.ldr-alert-warning {
- color: #856404;
- background-color: #fff3cd;
- border-color: #ffeaa7;
-}
-
-.ldr-alert i {
- margin-right: 8px;
-}
-
-.ldr-btn-sm {
- padding: 4px 10px;
- font-size: 0.85em;
-}
-</style>
-
-<script src="/static/js/rag_manager.js"></script>
-{% endblock %}