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.

refactor: remove redundant text file storage, simplify to DB-only

LearningCircuit316f56458d46
diff --git a/src/local_deep_research/defaults/research_library/library_settings.json b/src/local_deep_research/defaults/research_library/library_settings.json
index 1061ebe7bf..a35624d834 100644
--- a/src/local_deep_research/defaults/research_library/library_settings.json
+++ b/src/local_deep_research/defaults/research_library/library_settings.json
@@ -44,21 +44,6 @@
"visible": true,
"env_var": "RESEARCH_LIBRARY_ENABLE_PDF_STORAGE"
},
- "research_library.enable_txt_storage": {
- "category": "research_library",
- "description": "Enable storing text files on disk for RAG/ChromaDB. Text files will be unencrypted.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Enable Text Storage",
- "options": null,
- "step": null,
- "type": "APP",
- "ui_element": "checkbox",
- "value": false,
- "visible": true,
- "env_var": "RESEARCH_LIBRARY_ENABLE_TXT_STORAGE"
- },
"rag.indexing_batch_size": {
"category": "research_library",
"description": "Number of documents to process in parallel during RAG indexing. Higher values are faster but use more memory.",
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 e70dabd4c7..7a950b7e39 100644
--- a/src/local_deep_research/research_library/routes/library_routes.py
+++ b/src/local_deep_research/research_library/routes/library_routes.py
@@ -148,9 +148,6 @@ def library_page():
enable_pdf_storage = settings.get_setting(
"research_library.enable_pdf_storage", False
)
- enable_txt_storage = settings.get_setting(
- "research_library.enable_txt_storage", False
- )
shared_library = settings.get_setting(
"research_library.shared_library", False
)
@@ -189,7 +186,6 @@ def library_page():
selected_collection=collection_filter,
storage_path=stats.get("storage_path", ""),
enable_pdf_storage=enable_pdf_storage,
- enable_txt_storage=enable_txt_storage,
shared_library=shared_library,
)
@@ -226,9 +222,6 @@ def download_manager_page():
enable_pdf_storage = settings.get_setting(
"research_library.enable_pdf_storage", False
)
- enable_txt_storage = settings.get_setting(
- "research_library.enable_txt_storage", False
- )
shared_library = settings.get_setting(
"research_library.shared_library", False
)
@@ -274,7 +267,6 @@ def download_manager_page():
already_downloaded=already_downloaded,
available_to_download=available_to_download,
enable_pdf_storage=enable_pdf_storage,
- enable_txt_storage=enable_txt_storage,
shared_library=shared_library,
)
@@ -653,7 +645,7 @@ def download_bulk():
username = session.get("username")
data = request.json
research_ids = data.get("research_ids", [])
- mode = data.get("mode", "pdf") # pdf, text_with_files, or text_only
+ mode = data.get("mode", "pdf") # pdf or text_only
if not research_ids:
return jsonify({"error": "No research IDs provided"}), 400
@@ -793,11 +785,9 @@ def download_bulk():
result = download_service.download_resource(
queue_item.resource_id
)
- else: # text_with_files or text_only
- # Pass save_files=True for text_with_files, False for text_only
- save_files = mode == "text_with_files"
+ else: # text_only
result = download_service.download_as_text(
- queue_item.resource_id, save_files=save_files
+ queue_item.resource_id
)
# Handle new tuple return format
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 3946103964..6d145538ec 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -666,8 +666,6 @@ def get_documents():
.all()
)
- logger.info(f"Returning {len(results)} documents on page {page}")
-
documents = [
{
"id": doc.id,
@@ -686,6 +684,13 @@ def get_documents():
for doc, doc_collection in results
]
+ # Debug logging to help diagnose indexing status issues
+ indexed_count = sum(1 for d in documents if d["rag_indexed"])
+ logger.info(
+ f"Returning {len(documents)} documents on page {page}: "
+ f"{indexed_count} indexed, {len(documents) - indexed_count} not indexed"
+ )
+
return jsonify(
{
"success": True,
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 2952e8d704..38e4979de0 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -571,11 +571,6 @@ class DownloadService:
text = self._extract_text_from_pdf(pdf_content)
if text:
- # Check if text storage is enabled (default: True for database storage)
- enable_text_storage = self.settings.get_setting(
- "research_library.enable_text_storage", True
- )
-
# Get the document ID we just created/updated
pdf_doc = (
session.query(Document)
@@ -584,7 +579,7 @@ class DownloadService:
)
pdf_document_id = pdf_doc.id if pdf_doc else None
- # Save text to database (and optionally to file)
+ # Save text to encrypted database
self._save_text_with_db(
resource=resource,
text=text,
@@ -592,7 +587,6 @@ class DownloadService:
extraction_method="pdf_extraction",
extraction_source="local_pdf",
pdf_document_id=pdf_document_id,
- save_files=enable_text_storage,
)
logger.info(
f"Successfully extracted and saved text for: {resource.title[:50]}"
@@ -727,97 +721,12 @@ class DownloadService:
logger.exception("Failed to extract text from PDF")
return None
- def _save_text(
- self, resource: ResearchResource, text: str
- ) -> Optional[str]:
+ def download_as_text(self, resource_id: int) -> Tuple[bool, Optional[str]]:
"""
- Save extracted text to disk in txt folder if text storage is enabled.
-
- Args:
- resource: The research resource
- text: Extracted text content
-
- Returns:
- Absolute path to saved text file or None if storage disabled or 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("Invalid file path")
-
- # Build content with metadata header
- from ...security.file_write_verifier import write_file_verified
-
- text_content = f"# Source: {resource.url}\n"
- text_content += f"# Title: {resource.title}\n"
- text_content += f"# Extracted: {datetime.now(UTC).isoformat()}\n"
- text_content += f"# Resource ID: {resource.id}\n"
- text_content += "-" * 80 + "\n\n"
- text_content += text
-
- # Write with security verification
- write_file_verified(
- validated_path,
- text_content,
- "research_library.enable_txt_storage",
- True,
- "library text extraction",
- )
-
- 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, save_files: bool = False
- ) -> Tuple[bool, Optional[str]]:
- """
- Download resource and save as text file only.
+ Download resource and extract text to encrypted database.
Args:
resource_id: ID of the resource to download
- save_files: Whether to save .txt files to disk (True) or DB-only (False)
Returns:
Tuple of (success, error_message)
@@ -844,20 +753,18 @@ class DownloadService:
# Try extracting from existing PDF
result = self._try_existing_pdf_extraction(
- session, resource, resource_id, save_files
+ session, resource, resource_id
)
if result is not None:
return result
# Try API text extraction
- result = self._try_api_text_extraction(
- session, resource, save_files
- )
+ result = self._try_api_text_extraction(session, resource)
if result is not None:
return result
# Fallback: Download PDF and extract
- return self._fallback_pdf_extraction(session, resource, save_files)
+ return self._fallback_pdf_extraction(session, resource)
def _try_existing_text(
self, session, resource_id: int
@@ -913,7 +820,7 @@ class DownloadService:
return True, None
def _try_existing_pdf_extraction(
- self, session, resource, resource_id: int, save_files: bool
+ self, session, resource, resource_id: int
) -> Optional[Tuple[bool, Optional[str]]]:
"""Try extracting text from existing PDF in database."""
pdf_document = (
@@ -943,7 +850,6 @@ class DownloadService:
extraction_method="pdf_extraction",
extraction_source="pdfplumber",
pdf_document_id=pdf_document.id,
- save_files=save_files,
)
session.commit()
return True, None
@@ -955,7 +861,7 @@ class DownloadService:
return None # Fall through to other methods
def _try_api_text_extraction(
- self, session, resource, save_files: bool
+ self, session, resource
) -> Optional[Tuple[bool, Optional[str]]]:
"""Try direct API text extraction."""
logger.info(
@@ -992,7 +898,6 @@ class DownloadService:
session,
extraction_method="native_api",
extraction_source=extraction_source,
- save_files=save_files,
)
session.commit()
logger.info(
@@ -1006,7 +911,7 @@ class DownloadService:
return False, safe_error
def _fallback_pdf_extraction(
- self, session, resource, save_files: bool
+ self, session, resource
) -> Tuple[bool, Optional[str]]:
"""Fallback: Download PDF to memory and extract text."""
logger.info(
@@ -1058,7 +963,6 @@ class DownloadService:
session,
extraction_method="pdf_extraction",
extraction_source="pdfplumber_fallback",
- save_files=save_files,
)
session.commit()
logger.info(
@@ -1424,10 +1328,9 @@ class DownloadService:
extraction_method: str,
extraction_source: str,
pdf_document_id: Optional[int] = None,
- save_files: bool = True,
) -> Optional[str]:
"""
- Save extracted text to disk and database.
+ Save extracted text to encrypted database.
Args:
resource: The research resource
@@ -1436,26 +1339,15 @@ class DownloadService:
extraction_method: How the text was extracted
extraction_source: Specific tool/API used
pdf_document_id: ID of PDF document if extracted from PDF
- save_files: Whether to save .txt files to disk (True) or DB-only (False)
Returns:
- Absolute path to saved text file or None if save fails
+ None (previously returned text file path, now removed)
"""
try:
- # Try to save the file to disk (returns None if storage disabled or save_files=False)
- text_path = self._save_text(resource, text) if save_files else None
-
# Calculate text metadata for database
word_count = len(text.split())
character_count = len(text)
- # Get relative path from library root (if file was saved)
- relative_path = (
- str(Path(text_path).relative_to(self.library_root))
- if text_path
- else None
- )
-
# Find the document by pdf_document_id or resource_id
doc = None
if pdf_document_id:
@@ -1499,16 +1391,13 @@ class DownloadService:
"Text content will not be saved to database."
)
- if text_path:
- logger.info(f"Saved text to database and disk: {relative_path}")
- else:
- logger.info(
- "Saved text to database only (file storage disabled)"
- )
- return text_path # Return path if saved to disk, None if DB-only
+ logger.info(
+ f"Saved text to encrypted database ({word_count} words)"
+ )
+ return None
except Exception:
- logger.exception("Error saving text file with DB")
+ logger.exception("Error saving text to encrypted database")
raise # Re-raise so caller can handle the error
def _create_text_document_record(
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 458cb5caab..cf6f655567 100644
--- a/src/local_deep_research/web/templates/pages/download_manager.html
+++ b/src/local_deep_research/web/templates/pages/download_manager.html
@@ -19,17 +19,9 @@
{% endif %}>
<i class="fas fa-file-pdf"></i> Download PDFs (<span class="ldr-selected-count-pdf">0</span>)
</button>
- <button class="btn btn-warning" id="download-text-rag" disabled
- {% if not enable_txt_storage %}
- title="Text file storage is disabled. Enable in Settings → Research Library to save .txt files for RAG/search integration"
- {% else %}
- title="Extract text to encrypted database AND save .txt files to disk for RAG/search integration"
- {% endif %}>
- <i class="fas fa-file-alt"></i> Extract + RAG (<span class="ldr-selected-count-text-rag">0</span>)
- </button>
<button class="btn btn-info" id="download-text-db" disabled
- title="Extract text to encrypted database only (no files saved to disk - maximum privacy)">
- <i class="fas fa-database"></i> Extract to DB (<span class="ldr-selected-count-text-db">0</span>)
+ title="Extract text to encrypted database">
+ <i class="fas fa-database"></i> Extract Text (<span class="ldr-selected-count-text-db">0</span>)
</button>
</div>
</div>
@@ -56,17 +48,10 @@
</p>
{% endif %}
- {% if not enable_txt_storage %}
<p class="ldr-info-message">
<i class="fas fa-database"></i>
- Text extraction saves to the encrypted database only. RAG/search integration is disabled.
+ Text extraction saves to the encrypted database.
</p>
- {% else %}
- <p class="ldr-warning-message">
- <i class="fas fa-exclamation-triangle"></i>
- Text files will be saved unencrypted to disk for RAG/search capabilities.
- </p>
- {% endif %}
{% if shared_library %}
<p class="ldr-warning-message">
@@ -284,20 +269,10 @@
{% endif %}>
<i class="fas fa-file-pdf"></i> PDFs
</button>
- <button class="btn btn-sm btn-warning"
- onclick="downloadResearch('{{ research.id }}', 'text_with_files')"
- {% if not enable_txt_storage %}
- disabled
- title="Text file storage is disabled. Enable in Settings"
- {% else %}
- title="Extract text + save RAG files from this research"
- {% endif %}>
- <i class="fas fa-file-alt"></i> Text+RAG
- </button>
<button class="btn btn-sm btn-info"
onclick="downloadResearch('{{ research.id }}', 'text_only')"
- title="Extract text to encrypted DB only from this research">
- <i class="fas fa-database"></i> Text DB
+ title="Extract text to encrypted database from this research">
+ <i class="fas fa-database"></i> Extract Text
</button>
{% if research.downloaded_count > 0 %}
<button class="btn btn-sm" onclick="viewDownloaded('{{ research.id }}')">
@@ -1061,21 +1036,17 @@ function updateSelectedCount() {
const count = selectedResearches.size;
// Update all count displays
- document.querySelectorAll('.ldr-selected-count-pdf, .ldr-selected-count-text-rag, .ldr-selected-count-text-db').forEach(el => {
+ document.querySelectorAll('.ldr-selected-count-pdf, .ldr-selected-count-text-db').forEach(el => {
el.textContent = count;
});
// Enable/disable buttons based on count and settings
const pdfBtn = document.getElementById('download-pdfs');
- const textRagBtn = document.getElementById('download-text-rag');
const textDbBtn = document.getElementById('download-text-db');
if (pdfBtn) {
pdfBtn.disabled = count === 0 {% if not enable_pdf_storage %}|| true{% endif %};
}
- if (textRagBtn) {
- textRagBtn.disabled = count === 0 {% if not enable_txt_storage %}|| true{% endif %};
- }
if (textDbBtn) {
textDbBtn.disabled = count === 0;
}
@@ -1110,12 +1081,6 @@ document.getElementById('download-pdfs')?.addEventListener('click', () => {
startBulkDownload(Array.from(selectedResearches), 'pdf');
});
-document.getElementById('download-text-rag')?.addEventListener('click', () => {
- if (selectedResearches.size === 0) return;
- document.getElementById('download-progress-modal').style.display = 'block';
- startBulkDownload(Array.from(selectedResearches), 'text_with_files');
-});
-
document.getElementById('download-text-db')?.addEventListener('click', () => {
if (selectedResearches.size === 0) return;
document.getElementById('download-progress-modal').style.display = 'block';
@@ -1134,7 +1099,6 @@ async function startBulkDownload(researchIds, mode = 'pdf') {
// Set modal title based on mode
const modalTitles = {
'pdf': 'Downloading PDFs',
- 'text_with_files': 'Extracting Text + RAG Files',
'text_only': 'Extracting Text to Database'
};
document.querySelector('#download-progress-modal h2').textContent = modalTitles[mode] || 'Processing';
diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.html
index d4dc356517..771cece6ba 100644
--- a/src/local_deep_research/web/templates/pages/library.html
+++ b/src/local_deep_research/web/templates/pages/library.html
@@ -22,17 +22,10 @@
{% endif %}>
<i class="fas fa-file-pdf"></i> Download ALL PDFs
</button>
- {% if enable_txt_storage %}
- <button class="btn btn-warning"
- onclick="downloadAllAsText(true)"
- title="Extract ALL text to encrypted database AND save .txt files to disk for RAG/search integration">
- <i class="fas fa-file-alt"></i> Extract ALL + RAG Files
- </button>
- {% endif %}
<button class="btn btn-info"
- onclick="downloadAllAsText(false)"
- title="Extract ALL text to encrypted database only (no files saved to disk - maximum privacy)">
- <i class="fas fa-database"></i> Extract ALL to DB Only
+ onclick="downloadAllAsText()"
+ title="Extract ALL text to encrypted database">
+ <i class="fas fa-database"></i> Extract ALL Text
</button>
</div>
<button class="btn btn-primary" onclick="window.location.href='/library/download-manager'">
@@ -89,22 +82,6 @@
{% endif %}
</div>
- <div class="status-item">
- <span class="status-label">RAG Integration:</span>
- <span class="badge {% if enable_txt_storage %}badge-success{% else %}badge-secondary{% endif %}">
- {% if enable_txt_storage %}
- <i class="fas fa-check-circle"></i> Active
- {% else %}
- <i class="fas fa-database"></i> Database Only
- {% endif %}
- </span>
- {% if not enable_txt_storage %}
- <span class="status-hint" title="Text files are stored in encrypted database only. Enable text file storage for RAG/ChromaDB integration.">
- <i class="fas fa-info-circle"></i>
- </span>
- {% endif %}
- </div>
-
<div class="status-item">
<a href="/settings#research-library" class="btn btn-sm btn-outline-primary">
<i class="fas fa-cog"></i> Configure Settings
@@ -1322,7 +1299,7 @@ function filterDocuments() {
let currentDownloadController = null;
// Download all as text for RAG
-async function downloadAllAsText(saveFiles = false) {
+async function downloadAllAsText() {
const btn = event.target.closest('button');
const originalContent = btn.innerHTML;
btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Extracting...';
@@ -1334,8 +1311,7 @@ async function downloadAllAsText(saveFiles = false) {
// Show progress modal
showDownloadProgressModal();
- const modalTitle = saveFiles ? 'Text Extraction + RAG Files' : 'Text Extraction to Database';
- document.querySelector('#download-progress-modal h2').textContent = modalTitle;
+ document.querySelector('#download-progress-modal h2').textContent = 'Text Extraction to Database';
// Reset progress
document.getElementById('overall-progress').style.width = '0%';
@@ -1353,7 +1329,7 @@ async function downloadAllAsText(saveFiles = false) {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
},
- body: JSON.stringify({save_files: saveFiles}),
+ body: JSON.stringify({}),
signal: currentDownloadController.signal
});