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: optimize text extraction for RAG - use native APIs

LearningCircuit3afff06b60a7
diff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.py
index 29c292a68f..7917773e75 100644
--- a/src/local_deep_research/research_library/routes/library_routes.py
+++ b/src/local_deep_research/research_library/routes/library_routes.py
@@ -381,6 +381,97 @@ def download_single_resource(resource_id):
return jsonify({"success": success})
+@library_bp.route("/api/download-text/<int:resource_id>", methods=["POST"])
+@login_required
+def download_text_single(resource_id):
+ """Download a single resource as text file."""
+ username = session.get("username")
+ service = DownloadService(username)
+
+ success, error = service.download_as_text(resource_id)
+ return jsonify({"success": success, "error": error})
+
+
+@library_bp.route("/api/download-all-text", methods=["POST"])
+@login_required
+def download_all_text():
+ """Download all undownloaded resources as text files."""
+ username = session.get("username")
+
+ def generate():
+ download_service = DownloadService(username)
+
+ # Get all undownloaded resources
+ with get_user_db_session(username) as session:
+ # Get resources that don't have text files yet
+ resources = session.query(ResearchResource).all()
+
+ # Filter resources that need text extraction
+ txt_path = Path(download_service.library_root) / "txt"
+ resources_to_process = []
+
+ for resource in resources:
+ # Check if text file already exists
+ if txt_path.exists():
+ existing = list(txt_path.glob(f"*_{resource.id}.txt"))
+ if not existing:
+ resources_to_process.append(resource)
+ else:
+ resources_to_process.append(resource)
+
+ total = len(resources_to_process)
+ current = 0
+
+ logger.info(f"Found {total} resources needing text extraction")
+
+ for resource in resources_to_process:
+ current += 1
+ progress = int((current / total) * 100) if total > 0 else 100
+
+ file_name = (
+ resource.title[:50]
+ if resource
+ else f"document_{current}.txt"
+ )
+
+ try:
+ success, error = download_service.download_as_text(
+ resource.id
+ )
+
+ if success:
+ status = "success"
+ error_msg = None
+ else:
+ status = "failed"
+ error_msg = error or "Text extraction failed"
+
+ except Exception as e:
+ logger.exception(
+ f"Error extracting text for resource {resource.id}"
+ )
+ status = "failed"
+ error_msg = str(e)
+
+ # Send update
+ update = {
+ "progress": progress,
+ "current": current,
+ "total": total,
+ "file": file_name,
+ "status": status,
+ "error": error_msg,
+ }
+ yield f"data: {json.dumps(update)}\n\n"
+
+ # Send completion
+ yield f"data: {json.dumps({'complete': True, 'total': total})}\n\n"
+
+ return Response(
+ stream_with_context(generate()), mimetype="text/event-stream"
+ )
+
+
@library_bp.route("/api/download-research/<research_id>", methods=["POST"])
@login_required
def download_research_pdfs(research_id):
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 e5909f7943..820ba94d03 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -19,6 +19,8 @@ from urllib.parse import urlparse
import requests
from loguru import logger
from sqlalchemy.orm import Session
+import pdfplumber
+from pypdf import PdfReader
from ...database.models.download_tracker import (
DownloadAttempt,
@@ -523,6 +525,197 @@ class DownloadService:
return str(validated_path)
+ def _extract_text_from_pdf(self, pdf_content: bytes) -> Optional[str]:
+ """
+ Extract text from PDF content using multiple methods for best results.
+
+ Args:
+ pdf_content: Raw PDF bytes
+
+ Returns:
+ Extracted text or None if extraction fails
+ """
+ try:
+ # First try with pdfplumber (better for complex layouts)
+ import io
+
+ with pdfplumber.open(io.BytesIO(pdf_content)) as pdf:
+ text_parts = []
+ for page in pdf.pages:
+ page_text = page.extract_text()
+ if page_text:
+ text_parts.append(page_text)
+
+ if text_parts:
+ return "\n\n".join(text_parts)
+
+ # Fallback to PyPDF if pdfplumber fails
+ reader = PdfReader(io.BytesIO(pdf_content))
+ text_parts = []
+ for page in reader.pages:
+ text = page.extract_text()
+ if text:
+ text_parts.append(text)
+
+ if text_parts:
+ return "\n\n".join(text_parts)
+
+ logger.warning("No text could be extracted from PDF")
+ return None
+
+ except Exception:
+ logger.exception("Failed to extract text from PDF")
+ return None
+
+ def _save_text(
+ self, resource: ResearchResource, text: str
+ ) -> Optional[str]:
+ """
+ Save extracted text to disk in txt folder.
+
+ Args:
+ resource: The research resource
+ text: Extracted text content
+
+ Returns:
+ Absolute path to saved text file or None if save fails
+ """
+ try:
+ # Generate filename similar to PDF but with .txt extension
+ domain = urlparse(resource.url).netloc.replace(".", "_")
+ timestamp = datetime.now(UTC).strftime("%Y%m%d")
+
+ # Try to extract identifier from URL
+ parsed_url = urlparse(resource.url)
+ hostname = parsed_url.hostname or ""
+
+ if hostname == "arxiv.org" or hostname.endswith(".arxiv.org"):
+ # Extract arXiv ID
+ match = re.search(r"(\d{4}\.\d{4,5})", resource.url)
+ if match:
+ filename = f"arxiv_{match.group(1)}.txt"
+ else:
+ filename = f"arxiv_{timestamp}_{resource.id}.txt"
+ elif hostname == "ncbi.nlm.nih.gov" and "/pmc" in parsed_url.path:
+ # Extract PMC ID
+ match = re.search(r"(PMC\d+)", resource.url)
+ if match:
+ filename = f"pmc_{match.group(1)}.txt"
+ else:
+ filename = f"pubmed_{timestamp}_{resource.id}.txt"
+ else:
+ # Generic filename
+ safe_title = re.sub(r"[^\w\s-]", "", resource.title or "")[:50]
+ filename = f"{domain}_{safe_title}_{resource.id}.txt"
+
+ # Create txt folder structure
+ txt_path = Path(self.library_root) / "txt"
+ txt_path.mkdir(parents=True, exist_ok=True)
+
+ # Use PathValidator with relative path from library_root
+ relative_path = f"txt/{filename}"
+ validated_path = PathValidator.validate_safe_path(
+ relative_path,
+ base_dir=str(self.library_root),
+ required_extensions=(".txt",),
+ )
+
+ if not validated_path:
+ raise ValueError(f"Invalid file path: {filename}")
+
+ # Write the text file with UTF-8 encoding
+ with open(validated_path, "w", encoding="utf-8") as f:
+ # Add metadata header
+ f.write(f"# Source: {resource.url}\n")
+ f.write(f"# Title: {resource.title}\n")
+ f.write(f"# Extracted: {datetime.now(UTC).isoformat()}\n")
+ f.write(f"# Resource ID: {resource.id}\n")
+ f.write("-" * 80 + "\n\n")
+ f.write(text)
+
+ logger.info(f"Saved text extraction to: {validated_path}")
+ return str(validated_path)
+
+ except Exception:
+ logger.exception("Failed to save text file")
+ return None
+
+ def download_as_text(self, resource_id: int) -> Tuple[bool, Optional[str]]:
+ """
+ Download resource and save as text file only.
+
+ Args:
+ resource_id: ID of the resource to download
+
+ Returns:
+ Tuple of (success, error_message)
+ """
+ with get_user_db_session(self.username) as session:
+ # Get the resource
+ resource = (
+ session.query(ResearchResource)
+ .filter_by(id=resource_id)
+ .first()
+ )
+ if not resource:
+ return False, "Resource not found"
+
+ # Check if we already have the text file
+ txt_path = Path(self.library_root) / "txt"
+ existing_files = (
+ list(txt_path.glob(f"*_{resource_id}.txt"))
+ if txt_path.exists()
+ else []
+ )
+ if existing_files:
+ logger.info(f"Text file already exists: {existing_files[0]}")
+ return True, None
+
+ # Try to get text content directly without saving PDF
+ logger.info(f"Extracting text from: {resource.url}")
+
+ # Determine which downloader to use
+ downloader = self._get_downloader(resource.url)
+
+ if downloader:
+ # Use the downloader's text extraction capability
+ result = downloader.download_with_result(
+ resource.url, ContentType.TEXT
+ )
+
+ if result.is_success and result.content:
+ # Decode if bytes
+ if isinstance(result.content, bytes):
+ text = result.content.decode("utf-8", errors="ignore")
+ else:
+ text = result.content
+
+ # Save text file
+ text_path = self._save_text(resource, text)
+ if text_path:
+ return True, None
+ else:
+ return False, "Failed to save text file"
+
+ # Fallback: Download PDF temporarily (in memory only) and extract text
+ logger.info(f"Falling back to PDF extraction for: {resource.url}")
+ result = self._download_pdf(resource, None, session)
+
+ if result.is_success and result.content:
+ # Extract text from PDF (without saving the PDF)
+ text = self._extract_text_from_pdf(result.content)
+ if text:
+ # Save text file
+ text_path = self._save_text(resource, text)
+ if text_path:
+ return True, None
+ else:
+ return False, "Failed to save text file"
+ else:
+ return False, "Failed to extract text from PDF"
+ else:
+ return False, result.skip_reason or "Failed to download content"
+
def _download_generic(self, url: str) -> Optional[bytes]:
"""Generic PDF download method."""
try:
diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.html
index 8b9d4afe57..02ca355bca 100644
--- a/src/local_deep_research/web/templates/pages/library.html
+++ b/src/local_deep_research/web/templates/pages/library.html
@@ -10,9 +10,14 @@
<button class="btn btn-secondary" onclick="showSyncModal()" title="Check if files exist and sync with filesystem">
<i class="fas fa-sync"></i> Sync Library
</button>
- <button class="btn btn-success" onclick="downloadAllNew()" title="Download all articles that haven't been downloaded yet">
- <i class="fas fa-cloud-download-alt"></i> Download All New
- </button>
+ <div class="btn-group">
+ <button class="btn btn-success" onclick="downloadAllNew()" title="Download all articles that haven't been downloaded yet">
+ <i class="fas fa-cloud-download-alt"></i> Download PDFs
+ </button>
+ <button class="btn btn-info" onclick="downloadAllAsText()" title="Extract text from all PDFs for RAG">
+ <i class="fas fa-file-alt"></i> Extract Text (RAG)
+ </button>
+ </div>
<button class="btn btn-primary" onclick="window.location.href='/library/download-manager'">
<i class="fas fa-download"></i> Download Manager
</button>
@@ -324,6 +329,34 @@
gap: 20px;
}
+.btn-group {
+ display: flex;
+ gap: 0;
+}
+
+.btn-group .btn {
+ border-radius: 0;
+}
+
+.btn-group .btn:first-child {
+ border-radius: 4px 0 0 4px;
+}
+
+.btn-group .btn:last-child {
+ border-radius: 0 4px 4px 0;
+}
+
+.btn-info {
+ background: #17a2b8;
+ color: white;
+ border: 1px solid #17a2b8;
+}
+
+.btn-info:hover {
+ background: #138496;
+ border-color: #117a8b;
+}
+
.library-stats {
display: flex;
gap: 15px;
@@ -775,6 +808,127 @@ function filterDocuments() {
// Current download controller for cancellation
let currentDownloadController = null;
+// Download all as text for RAG
+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 {
+ // Get CSRF token
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
+
+ // Show progress modal
+ showDownloadProgressModal();
+ document.querySelector('#download-progress-modal h2').textContent = 'Text Extraction Progress';
+
+ // 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 = '';
+
+ // Create abort controller for cancellation
+ currentDownloadController = new AbortController();
+
+ // Start streaming text extraction
+ const response = await fetch('/library/api/download-all-text', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ 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);
+
+ // Check if extraction is complete
+ if (data.complete) {
+ currentDownloadController = null;
+ setTimeout(() => {
+ closeProgressModal();
+ alert(`Text extraction complete! Extracted ${data.total} documents to the txt/ folder.`);
+ }, 2000);
+ }
+ }
+ }
+ }
+
+ } catch (error) {
+ if (error.name === 'AbortError') {
+ console.log('Text extraction cancelled by user');
+ const log = document.getElementById('download-log');
+ const entry = document.createElement('div');
+ entry.className = 'download-entry cancelled';
+ entry.innerHTML = '<strong>Text extraction cancelled by user</strong>';
+ log.appendChild(entry);
+ } else {
+ console.error('Failed to start text extraction:', error);
+ alert('Failed to start text extraction. Please try again.');
+ }
+ btn.innerHTML = originalContent;
+ btn.disabled = false;
+ } 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 = `download-entry ${data.status}`;
+
+ let statusIcon = '';
+ let statusText = '';
+
+ if (data.status === 'success') {
+ statusIcon = '✓';
+ statusText = 'Text extracted';
+ } else if (data.status === 'failed') {
+ statusIcon = '✗';
+ statusText = data.error || 'Extraction failed';
+ }
+
+ entry.innerHTML = `
+ <span class="status-icon">${statusIcon}</span>
+ <div class="entry-details">
+ <strong>${data.file}</strong>
+ <span class="status-text">${statusText}</span>
+ </div>
+ `;
+
+ log.appendChild(entry);
+ log.scrollTop = log.scrollHeight;
+ }
+}
+
// Download all new articles with progress
async function downloadAllNew() {
const btn = event.target.closest('button');