~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
feat: integrate document loaders with collection upload UI
LearningCircuite9f09a0a9611
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.pyindex 93fcd6e1bb..e656d0c756 100644--- a/src/local_deep_research/research_library/routes/rag_routes.py+++ b/src/local_deep_research/research_library/routes/rag_routes.py@@ -219,6 +219,33 @@ def get_rag_service(collection_id: Optional[str] = None) -> LibraryRAGService:)+# Config API Routes+++@rag_bp.route("/api/config/supported-formats", methods=["GET"])+@login_required+def get_supported_formats():+ """Return list of supported file formats for upload.++ This endpoint provides the single source of truth for supported file+ extensions, pulling from the document_loaders registry. The UI can+ use this to dynamically update the file input accept attribute.+ """+ from ...document_loaders import get_supported_extensions++ extensions = get_supported_extensions()+ # Sort extensions for consistent display+ extensions = sorted(extensions)++ return jsonify(+ {+ "extensions": extensions,+ "accept_string": ",".join(extensions),+ "count": len(extensions),+ }+ )++# Page Routes@@ -1349,50 +1376,6 @@ def delete_collection(collection_id):return handle_api_error("deleting collection", e)-def extract_text_from_file(- file_content: bytes, file_type: str, filename: str-) -> Optional[str]:- """- Extract text from uploaded file content.-- Uses the centralized document_loaders module which supports 35+ file formats.-- Args:- file_content: Raw file content as bytes- file_type: Type of file (pdf, txt, markdown, html, docx, csv, etc.)- filename: Original filename for logging-- Returns:- Extracted text as string, or None if extraction failed- """- from ...document_loaders import (- extract_text_from_bytes,- is_extension_supported,- )-- # Map file_type to extension (handle both "pdf" and ".pdf" formats)- extension = file_type if file_type.startswith(".") else f".{file_type}"-- # Check if the extension is supported- if not is_extension_supported(extension):- logger.warning(- f"Unsupported file type for text extraction: {file_type} ({filename})"- )- return None-- # Use the document_loaders module to extract text- text = extract_text_from_bytes(file_content, extension, filename)-- if text:- logger.info(- f"Successfully extracted text from {filename} ({file_type})"- )- else:- logger.warning(f"Could not extract text from {filename} ({file_type})")-- return text--@rag_bp.route("/api/collections/<string:collection_id>/upload", methods=["POST"])@@ -1535,20 +1518,34 @@ def upload_to_collection(collection_id):)else:# Create new document- filename = secure_filename(file.filename)+ from ...document_loaders import (+ extract_text_from_bytes,+ is_extension_supported,+ )- # Use the file extension directly as the file_type- # extract_text_from_file validates against the loader registry+ filename = secure_filename(file.filename)file_extension = Path(filename).suffix.lower()++ # Validate extension is supported before extraction+ if not is_extension_supported(file_extension):+ errors.append(+ {+ "filename": filename,+ "error": f"Unsupported format: {file_extension}",+ }+ )+ continue++ # Use file_type without leading dot for storagefile_type = (file_extension[1:]if file_extension.startswith(".")else file_extension)- # Extract text from the file- extracted_text = extract_text_from_file(- file_content, file_type, filename+ # Extract text using document_loaders module+ extracted_text = extract_text_from_bytes(+ file_content, file_extension, filename)# Clean the extracted text to remove surrogate charactersdiff --git a/src/local_deep_research/web/static/js/collection_upload.js b/src/local_deep_research/web/static/js/collection_upload.jsindex 7430807ca9..209d9df27a 100644--- a/src/local_deep_research/web/static/js/collection_upload.js+++ b/src/local_deep_research/web/static/js/collection_upload.js@@ -31,10 +31,70 @@ function escapeHtml(text) {// Store selected files globally to avoid losing themlet selectedFiles = [];+// Store supported formats (fetched from backend)+let supportedFormats = {+ extensions: [],+ accept_string: ''+};++/**+ * Fetch supported file formats from backend+ * Updates the file input accept attribute and help text+ */+async function fetchSupportedFormats() {+ try {+ const response = await safeFetch(URLS.LIBRARY_API.SUPPORTED_FORMATS);+ if (!response.ok) {+ throw new Error(`HTTP ${response.status}`);+ }+ const data = await response.json();++ supportedFormats = data;++ // Update file input accept attribute+ const fileInput = document.getElementById('files-input');+ if (fileInput && data.accept_string) {+ fileInput.accept = data.accept_string;+ }++ // Update help text with format details+ const formatDetails = document.getElementById('format-details');+ if (formatDetails && data.count) {+ formatDetails.textContent = `(${data.count} formats supported)`;+ }++ // Update the full format list in the instructions+ const fullFormatList = document.getElementById('full-format-list');+ if (fullFormatList && data.extensions) {+ // Format as comma-separated uppercase list+ const formatList = data.extensions+ .map(ext => ext.replace('.', '').toUpperCase())+ .join(', ');+ fullFormatList.textContent = `All supported: ${formatList}`;+ }++ SafeLogger.log(`📄 Loaded ${data.count} supported formats`);+ } catch (error) {+ SafeLogger.warn('Could not fetch supported formats, file picker will accept all files:', error);+ // Update UI to indicate formats could not be loaded+ const formatDetails = document.getElementById('format-details');+ if (formatDetails) {+ formatDetails.textContent = '';+ }+ const fullFormatList = document.getElementById('full-format-list');+ if (fullFormatList) {+ fullFormatList.textContent = 'Could not load format list';+ }+ }+}+/*** Initialize the upload page*/document.addEventListener('DOMContentLoaded', function() {+ // Fetch supported formats from backend+ fetchSupportedFormats();+// Setup form submissiondocument.getElementById('upload-files-form').addEventListener('submit', function(e) {SafeLogger.log('📋 Form submit event triggered');diff --git a/src/local_deep_research/web/static/js/config/urls.js b/src/local_deep_research/web/static/js/config/urls.jsindex 08d4911a91..96f81dd556 100644--- a/src/local_deep_research/web/static/js/config/urls.js+++ b/src/local_deep_research/web/static/js/config/urls.js@@ -111,7 +111,10 @@ if (typeof URLS !== 'undefined') {RAG_CONFIG: '/library/api/rag/config',RAG_STATUS: '/library/api/rag/status',RAG_INDEX_ALL: '/library/api/rag/index-all',- RAG_DOCUMENTS: '/library/api/rag/documents'+ RAG_DOCUMENTS: '/library/api/rag/documents',++ // Config+ SUPPORTED_FORMATS: '/library/api/config/supported-formats'}};diff --git a/src/local_deep_research/web/templates/pages/collection_upload.html b/src/local_deep_research/web/templates/pages/collection_upload.htmlindex 8af892f78c..172718d87b 100644--- a/src/local_deep_research/web/templates/pages/collection_upload.html+++ b/src/local_deep_research/web/templates/pages/collection_upload.html@@ -136,7 +136,7 @@<button type="button" class="ldr-btn-collections ldr-btn-collections-primary" onclick="document.getElementById('files-input').click()"><i class="fas fa-folder-open"></i> Browse Files</button>- <input type="file" id="files-input" name="files" multiple accept=".pdf,.txt,.md,.html,.htm" style="display: none;">+ <input type="file" id="files-input" name="files" multiple style="display: none;"></div><!-- Selected files preview -->@@ -145,7 +145,7 @@<ul id="file-list"></ul></div>- <p class="ldr-form-help">💡 Accepted formats: PDF, TXT, MD, HTML. Text will be extracted and stored securely.</p>+ <p class="ldr-form-help" id="format-help">💡 Supports many formats including PDF, Word, Excel, JSON, YAML, and more. <span id="format-details"></span></p></div><!-- PDF Storage Mode Selection -->@@ -218,12 +218,9 @@<div style="padding: 1rem;"><h3>📋 Supported File Types</h3>- <ul>- <li><strong>PDF</strong> - Documents and reports</li>- <li><strong>TXT</strong> - Plain text files</li>- <li><strong>MD</strong> - Markdown documents</li>- <li><strong>HTML</strong> - Web pages and HTML documents</li>- </ul>+ <p>Documents (PDF, DOCX, TXT, MD, RTF), Spreadsheets (CSV, XLSX, XLS),+ Data (JSON, YAML, XML, TOML), Presentations (PPT, PPTX), and more.</p>+ <p><small id="full-format-list">Loading supported formats...</small></p><h3>💡 Tips</h3><ul>diff --git a/tests/research_library/routes/test_rag_routes.py b/tests/research_library/routes/test_rag_routes.pyindex 1654897c00..75bc23f086 100644--- a/tests/research_library/routes/test_rag_routes.py+++ b/tests/research_library/routes/test_rag_routes.py@@ -460,6 +460,22 @@ class TestRagApiRoutes:response = client.get("/library/api/rag/stats")assert response.status_code in [200, 302, 401, 403, 500]+ def test_get_supported_formats_route(self):+ """Test /api/config/supported-formats GET endpoint exists."""+ from flask import Flask+ from local_deep_research.research_library.routes.rag_routes import (+ rag_bp,+ )++ app = Flask(__name__)+ app.config["SECRET_KEY"] = "test-secret"+ app.register_blueprint(rag_bp)++ with app.test_client() as client:+ response = client.get("/library/api/config/supported-formats")+ # 500 is acceptable in isolated test (login redirect fails without auth blueprint)+ assert response.status_code in [200, 302, 401, 403, 500]+class TestRagIndexRoutes:"""Tests for RAG indexing routes."""@@ -750,42 +766,40 @@ class TestRagUploadRoutes:assert response.status_code in [200, 302, 400, 401, 403, 404, 500]-class TestExtractTextFromFile:- """Tests for extract_text_from_file function."""+class TestDocumentLoaders:+ """Tests for document_loaders integration in upload workflow."""def test_extract_text_from_txt_file(self):- """Test extracting text from .txt file."""- from local_deep_research.research_library.routes.rag_routes import (- extract_text_from_file,- )+ """Test extracting text from .txt file using document_loaders."""+ from local_deep_research.document_loaders import extract_text_from_bytescontent = b"Hello, this is a test text file."- text = extract_text_from_file(content, "txt", "test.txt")+ text = extract_text_from_bytes(content, ".txt", "test.txt")assert "Hello" in textdef test_extract_text_from_md_file(self):- """Test extracting text from .md file."""- from local_deep_research.research_library.routes.rag_routes import (- extract_text_from_file,- )+ """Test extracting text from .md file using document_loaders."""+ from local_deep_research.document_loaders import extract_text_from_bytescontent = b"# Header\n\nThis is markdown content."- text = extract_text_from_file(content, "md", "test.md")+ text = extract_text_from_bytes(content, ".md", "test.md")assert "Header" in text or "markdown" in text- def test_extract_text_from_unknown_file(self):- """Test extracting text from unknown file type."""- from local_deep_research.research_library.routes.rag_routes import (- extract_text_from_file,- )+ def test_is_extension_supported(self):+ """Test that extension support checking works correctly."""+ from local_deep_research.document_loaders import is_extension_supported- content = b"Some content"+ # Supported extensions+ assert is_extension_supported(".txt") is True+ assert is_extension_supported(".pdf") is True+ assert is_extension_supported(".json") is True+ assert is_extension_supported(".yaml") is True- text = extract_text_from_file(content, "xyz", "test.xyz")- # Should return None for unsupported file types- assert text is None+ # Unsupported extensions+ assert is_extension_supported(".xyz") is False+ assert is_extension_supported(".unknown") is False# ============= Extended Tests for Phase 3.2 Coverage =============