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: show text-only documents in library and fix text viewer

LearningCircuit5a12b76b7651
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 1e8b99dee2..87e68bac77 100644
--- a/src/local_deep_research/research_library/routes/library_routes.py
+++ b/src/local_deep_research/research_library/routes/library_routes.py
@@ -326,17 +326,36 @@ def get_pdf_url(doc_id):
@login_required
def serve_pdf(doc_id):
"""Serve PDF file for viewing."""
+ from loguru import logger
+
username = session.get("username")
service = LibraryService(username)
# Get the specific document by ID
document = service.get_document_by_id(doc_id)
if not document:
+ logger.warning(
+ f"Document ID {doc_id} not found in database for user {username}"
+ )
return "Document not found", 404
file_path = document.get("file_absolute_path")
+ logger.info(
+ f"Document {doc_id}: title='{document.get('document_title')}', file_exists={document.get('file_exists')}, downloaded_successfully={document.get('downloaded_successfully')}, file_path={file_path}"
+ )
+
+ # Check if PDF storage is enabled
+ if file_path is None:
+ logger.warning(
+ f"Document {doc_id} has no file path - PDF may not have been downloaded (privacy mode or download failed)"
+ )
+ return (
+ "PDF not downloaded. Enable PDF storage in settings and use Download Manager to download this file.",
+ 404,
+ )
if file_path and Path(file_path).exists():
+ logger.info(f"Serving PDF: {file_path}")
return send_file(
file_path,
mimetype="application/pdf",
@@ -344,9 +363,58 @@ def serve_pdf(doc_id):
download_name=document.get("file_name", "document.pdf"),
)
+ logger.error(f"PDF file not found on disk: {file_path}")
return "PDF file not found", 404
+@library_bp.route("/api/document/<int:doc_id>/text")
+@login_required
+def serve_text(doc_id):
+ """Serve text content from database for viewing."""
+ from loguru import logger
+ from ...database.models.library import LibraryTextDocument
+ from ...database.session_context import get_user_db_session
+
+ username = session.get("username")
+
+ with get_user_db_session(username) as db_session:
+ # Try to get text document by document_id (PDF with extracted text)
+ text_doc = (
+ db_session.query(LibraryTextDocument)
+ .filter_by(document_id=doc_id)
+ .first()
+ )
+
+ # If not found, try by LibraryTextDocument.id (text-only document)
+ if not text_doc:
+ text_doc = (
+ db_session.query(LibraryTextDocument)
+ .filter_by(id=doc_id)
+ .first()
+ )
+
+ if not text_doc:
+ logger.warning(f"Text document not found for document ID {doc_id}")
+ return jsonify({"error": "Text not found"}), 404
+
+ if not text_doc.text_content:
+ logger.warning(f"Text document {doc_id} has no text content")
+ return jsonify({"error": "Text content not available"}), 404
+
+ logger.info(
+ f"Serving text content for document {doc_id}: {len(text_doc.text_content)} characters"
+ )
+
+ return jsonify(
+ {
+ "text_content": text_doc.text_content,
+ "title": text_doc.title or "Document",
+ "extraction_method": text_doc.extraction_method,
+ "word_count": text_doc.word_count,
+ }
+ )
+
+
@library_bp.route("/api/open-folder", methods=["POST"])
@login_required
def open_folder():
@@ -524,10 +592,11 @@ def download_research_pdfs(research_id):
@library_bp.route("/api/download-bulk", methods=["POST"])
@login_required
def download_bulk():
- """Download PDFs from multiple research sessions."""
+ """Download PDFs or extract text from multiple research sessions."""
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
if not research_ids:
return jsonify({"error": "No research IDs provided"}), 400
@@ -612,11 +681,21 @@ def download_bulk():
try:
logger.debug(
- f"Attempting download for resource {queue_item.resource_id}"
- )
- result = download_service.download_resource(
- queue_item.resource_id
+ f"Attempting {'PDF download' if mode == 'pdf' else 'text extraction'} for resource {queue_item.resource_id}"
)
+
+ # Call appropriate service method based on mode
+ if mode == "pdf":
+ result = download_service.download_resource(
+ queue_item.resource_id
+ )
+ else: # text_with_files or text_only
+ # TODO: Update download_as_text to accept save_files parameter
+ # For now, always saves files (text_with_files behavior)
+ result = download_service.download_as_text(
+ queue_item.resource_id
+ )
+
# Handle new tuple return format
if isinstance(result, tuple):
success, skip_reason = result
@@ -628,11 +707,11 @@ def download_bulk():
if skip_reason and not success:
error_msg = skip_reason
logger.info(
- f"Download skipped for resource {queue_item.resource_id}: {skip_reason}"
+ f"{'Download' if mode == 'pdf' else 'Text extraction'} skipped for resource {queue_item.resource_id}: {skip_reason}"
)
logger.debug(
- f"Download result: success={success}, status={status}, skip_reason={skip_reason}"
+ f"{'Download' if mode == 'pdf' else 'Text extraction'} result: success={success}, status={status}, skip_reason={skip_reason}"
)
except Exception as e:
# Log error but continue processing
diff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.py
index aff3467f0f..054b68cd49 100644
--- a/src/local_deep_research/research_library/services/library_service.py
+++ b/src/local_deep_research/research_library/services/library_service.py
@@ -162,10 +162,13 @@ class LibraryService:
Get documents with filtering options.
Returns enriched document information with research details.
+ Includes both PDF documents and text-only documents.
"""
with get_user_db_session(self.username) as session:
- # Build query
- query = (
+ all_documents = []
+
+ # Query 1: Get PDF documents (LibraryDocument)
+ pdf_query = (
session.query(
LibraryDocument, ResearchResource, ResearchHistory
)
@@ -179,17 +182,19 @@ class LibraryService:
)
)
- # Apply filters
+ # Apply filters to PDF query
if research_id:
- query = query.filter(LibraryDocument.research_id == research_id)
+ pdf_query = pdf_query.filter(
+ LibraryDocument.research_id == research_id
+ )
if domain:
if domain == "arxiv.org":
- query = query.filter(
+ pdf_query = pdf_query.filter(
LibraryDocument.original_url.like("%arxiv.org%")
)
elif domain == "pubmed":
- query = query.filter(
+ pdf_query = pdf_query.filter(
or_(
LibraryDocument.original_url.like("%pubmed%"),
LibraryDocument.original_url.like(
@@ -198,7 +203,7 @@ class LibraryService:
)
)
elif domain == "other":
- query = query.filter(
+ pdf_query = pdf_query.filter(
and_(
~LibraryDocument.original_url.like("%arxiv.org%"),
~LibraryDocument.original_url.like("%pubmed%"),
@@ -208,20 +213,21 @@ class LibraryService:
)
)
else:
- # For specific domain, filter by URL pattern
- query = query.filter(
+ pdf_query = pdf_query.filter(
LibraryDocument.original_url.like(f"%{domain}%")
)
if file_type:
- query = query.filter(LibraryDocument.file_type == file_type)
+ pdf_query = pdf_query.filter(
+ LibraryDocument.file_type == file_type
+ )
if favorites_only:
- query = query.filter(LibraryDocument.favorite.is_(True))
+ pdf_query = pdf_query.filter(LibraryDocument.favorite.is_(True))
if search_query:
search_pattern = f"%{search_query}%"
- query = query.filter(
+ pdf_query = pdf_query.filter(
or_(
LibraryDocument.title.ilike(search_pattern),
LibraryDocument.authors.ilike(search_pattern),
@@ -230,15 +236,25 @@ class LibraryService:
)
)
- # Order by download date descending
- query = query.order_by(LibraryDocument.downloaded_at.desc())
+ # Execute PDF query
+ pdf_results = pdf_query.all()
- # Apply pagination
- results = query.limit(limit).offset(offset).all()
+ # Bulk fetch text documents for PDFs (avoid N+1 queries)
+ text_docs_map = {}
+ if pdf_results:
+ try:
+ doc_ids = [doc.id for doc, _, _ in pdf_results]
+ text_docs = (
+ session.query(LibraryTextDocument)
+ .filter(LibraryTextDocument.document_id.in_(doc_ids))
+ .all()
+ )
+ text_docs_map = {td.document_id: td for td in text_docs}
+ except Exception:
+ pass
- # Format results
- documents = []
- for doc, resource, research in results:
+ # Process PDF results
+ for doc, resource, research in pdf_results:
# Get download tracker info
tracker = (
session.query(DownloadTracker)
@@ -246,7 +262,29 @@ class LibraryService:
.first()
)
- documents.append(
+ # Get text document from pre-fetched map
+ text_doc = text_docs_map.get(doc.id)
+
+ # Determine availability flags
+ file_absolute_path = None
+ if tracker and tracker.file_path:
+ file_absolute_path = str(
+ get_absolute_path_from_settings(tracker.file_path)
+ )
+
+ has_pdf = bool(file_absolute_path)
+ has_text_rag = bool(
+ text_doc
+ and hasattr(text_doc, "file_path")
+ and text_doc.file_path
+ )
+ has_text_db = bool(
+ text_doc
+ and hasattr(text_doc, "text_content")
+ and text_doc.text_content
+ )
+
+ all_documents.append(
{
"id": doc.id,
"resource_id": doc.resource_id,
@@ -260,13 +298,7 @@ class LibraryService:
"pmid": doc.pmid,
# File info
"file_path": doc.file_path,
- "file_absolute_path": str(
- get_absolute_path_from_settings(tracker.file_path)
- )
- if tracker.file_path
- else None
- if tracker
- else None,
+ "file_absolute_path": file_absolute_path,
"file_name": tracker.file_name
if tracker
else (
@@ -295,10 +327,163 @@ class LibraryService:
"is_arxiv": self._is_arxiv_url(doc.original_url),
"is_pubmed": self._is_pubmed_url(doc.original_url),
"is_pdf": doc.file_type == "pdf",
+ # Availability flags
+ "has_pdf": has_pdf,
+ "has_text_rag": has_text_rag,
+ "has_text_db": has_text_db,
+ # Sort key
+ "_sort_date": doc.downloaded_at,
}
)
- return documents
+ # Query 2: Get text-only documents (only if not filtering by PDF-specific fields)
+ if not file_type and not favorites_only:
+ text_query = (
+ session.query(
+ LibraryTextDocument, ResearchResource, ResearchHistory
+ )
+ .join(
+ ResearchResource,
+ LibraryTextDocument.resource_id == ResearchResource.id,
+ )
+ .join(
+ ResearchHistory,
+ LibraryTextDocument.research_id == ResearchHistory.id,
+ )
+ .filter(LibraryTextDocument.document_id.is_(None))
+ )
+
+ # Apply filters to text query
+ if research_id:
+ text_query = text_query.filter(
+ LibraryTextDocument.research_id == research_id
+ )
+
+ if domain:
+ if domain == "arxiv.org":
+ text_query = text_query.filter(
+ LibraryTextDocument.original_url.like("%arxiv.org%")
+ )
+ elif domain == "pubmed":
+ text_query = text_query.filter(
+ or_(
+ LibraryTextDocument.original_url.like(
+ "%pubmed%"
+ ),
+ LibraryTextDocument.original_url.like(
+ "%ncbi.nlm.nih.gov%"
+ ),
+ )
+ )
+ elif domain == "other":
+ text_query = text_query.filter(
+ and_(
+ ~LibraryTextDocument.original_url.like(
+ "%arxiv.org%"
+ ),
+ ~LibraryTextDocument.original_url.like(
+ "%pubmed%"
+ ),
+ ~LibraryTextDocument.original_url.like(
+ "%ncbi.nlm.nih.gov%"
+ ),
+ )
+ )
+ else:
+ text_query = text_query.filter(
+ LibraryTextDocument.original_url.like(f"%{domain}%")
+ )
+
+ if search_query:
+ search_pattern = f"%{search_query}%"
+ text_query = text_query.filter(
+ or_(
+ LibraryTextDocument.title.ilike(search_pattern),
+ LibraryTextDocument.authors.ilike(search_pattern),
+ LibraryTextDocument.doi.ilike(search_pattern),
+ ResearchResource.title.ilike(search_pattern),
+ )
+ )
+
+ # Execute text query
+ text_results = text_query.all()
+
+ # Process text-only results
+ for text_doc, resource, research in text_results:
+ # Determine availability flags
+ has_pdf = False # No PDF for text-only documents
+ has_text_rag = bool(text_doc.file_path)
+ has_text_db = bool(text_doc.text_content)
+
+ all_documents.append(
+ {
+ "id": text_doc.id,
+ "resource_id": text_doc.resource_id,
+ "research_id": text_doc.research_id,
+ # Document info
+ "document_title": text_doc.title or resource.title,
+ "authors": text_doc.authors,
+ "published_date": text_doc.published_date,
+ "doi": text_doc.doi,
+ "arxiv_id": text_doc.arxiv_id,
+ "pmid": text_doc.pmid,
+ # File info (text-only, no PDF)
+ "file_path": text_doc.file_path or "text_only",
+ "file_absolute_path": None,
+ "file_name": Path(text_doc.file_path).name
+ if text_doc.file_path
+ else "text_only",
+ "file_size": text_doc.file_size,
+ "file_type": "txt",
+ # URLs
+ "original_url": text_doc.original_url,
+ "domain": self._extract_domain(
+ text_doc.original_url
+ ),
+ # Status
+ "download_status": text_doc.extraction_status,
+ "downloaded_at": text_doc.extracted_at.isoformat()
+ if text_doc.extracted_at
+ else None,
+ "favorite": False, # Text-only docs don't have favorite flag
+ "tags": None,
+ # Research info
+ "research_title": research.title
+ or research.query[:80],
+ "research_query": research.query,
+ "research_mode": research.mode,
+ "research_date": research.created_at,
+ # Classification flags
+ "is_arxiv": self._is_arxiv_url(
+ text_doc.original_url
+ ),
+ "is_pubmed": self._is_pubmed_url(
+ text_doc.original_url
+ ),
+ "is_pdf": False,
+ # Availability flags
+ "has_pdf": has_pdf,
+ "has_text_rag": has_text_rag,
+ "has_text_db": has_text_db,
+ # Sort key
+ "_sort_date": text_doc.extracted_at,
+ }
+ )
+
+ # Sort all documents by date (descending)
+ all_documents.sort(
+ key=lambda d: d["_sort_date"] if d["_sort_date"] else "",
+ reverse=True,
+ )
+
+ # Apply pagination
+ paginated_documents = all_documents[offset : offset + limit]
+
+ # Remove internal sort key
+ for doc in paginated_documents:
+ doc.pop("_sort_date", None)
+
+ return paginated_documents
def get_research_list_with_stats(self) -> List[Dict]:
"""Get all research sessions with download statistics."""
diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.html
index 123795852a..7ac44e0b21 100644
--- a/src/local_deep_research/web/templates/pages/library.html
+++ b/src/local_deep_research/web/templates/pages/library.html
@@ -14,18 +14,25 @@
<button class="btn btn-success"
{% if not enable_pdf_storage %}
disabled
- title="PDF downloads are disabled for privacy. Enable PDF storage in Settings → Research Library"
+ title="PDF downloads are disabled. Enable PDF storage in Settings → Research Library"
data-toggle="tooltip"
{% else %}
onclick="downloadAllNew()"
- title="Download all articles that haven't been downloaded yet"
+ title="Download PDF files to disk and store metadata in encrypted database"
{% endif %}>
- <i class="fas fa-cloud-download-alt"></i> Download PDFs
+ <i class="fas fa-file-pdf"></i> Download PDFs
</button>
+ {% if enable_txt_storage %}
+ <button class="btn btn-warning"
+ onclick="downloadAllAsText(true)"
+ title="Extract text to encrypted database AND save .txt files to disk for RAG/search integration">
+ <i class="fas fa-file-alt"></i> Extract + RAG Files
+ </button>
+ {% endif %}
<button class="btn btn-info"
- onclick="downloadAllAsText()"
- title="Extract text from all PDFs for searchable database{% if not enable_txt_storage %} (saves to encrypted database only){% else %} and RAG integration{% endif %}">
- <i class="fas fa-file-alt"></i> Extract Text{% if enable_txt_storage %} (RAG){% endif %}
+ onclick="downloadAllAsText(false)"
+ title="Extract text to encrypted database only (no files saved to disk - maximum privacy)">
+ <i class="fas fa-database"></i> Extract to DB Only
</button>
</div>
<button class="btn btn-primary" onclick="window.location.href='/library/download-manager'">
@@ -184,7 +191,30 @@
</div>
<!-- Card Body -->
- <div class="card-body" onclick="openPDF({{ doc.id }})">
+ <div class="card-body" {% if doc.has_pdf or doc.has_text_db %}onclick="openDocument({{ doc.id }}, {{ 'true' if doc.has_pdf else 'false' }}, {{ 'true' if doc.has_text_db else 'false' }})"{% else %}style="cursor: not-allowed; opacity: 0.6;"{% endif %}>
+ <!-- Storage availability badges -->
+ <div class="storage-badges">
+ {% if doc.has_pdf %}
+ <div class="storage-badge storage-badge-pdf">
+ <i class="fas fa-file-pdf"></i> PDF Available
+ </div>
+ {% endif %}
+ {% if doc.has_text_rag %}
+ <div class="storage-badge storage-badge-rag">
+ <i class="fas fa-file-alt"></i> Text for RAG
+ </div>
+ {% endif %}
+ {% if doc.has_text_db %}
+ <div class="storage-badge storage-badge-db">
+ <i class="fas fa-database"></i> Text in DB
+ </div>
+ {% endif %}
+ {% if not doc.has_pdf and not doc.has_text_rag and not doc.has_text_db %}
+ <div class="storage-badge storage-badge-none">
+ <i class="fas fa-exclamation-triangle"></i> Not Downloaded
+ </div>
+ {% endif %}
+ </div>
<h3 class="doc-title" title="{{ doc.document_title }}">
{{ doc.document_title or doc.file_name }}
</h3>
@@ -251,10 +281,31 @@
<div class="empty-state">
<i class="fas fa-book fa-3x"></i>
<h3>No documents in your library yet</h3>
+ {% if not enable_pdf_storage %}
+ <div class="empty-state-info">
+ <p><strong>PDF storage is currently disabled for privacy.</strong></p>
+ <p>By default, PDFs are not downloaded to protect your privacy. Enabling PDF storage will save files <strong>unencrypted to the server's disk</strong> (wherever LDR is running), which may be a privacy concern if others have access to the server.</p>
+ <p>Currently, only encrypted metadata is stored in your database.</p>
+ <p>To build your library:</p>
+ <ol>
+ <li>Enable PDF storage in <strong>Settings → Research Library</strong> (search for "library" in Settings)</li>
+ <li>Use the Download Manager to download PDFs from your research</li>
+ </ol>
+ </div>
+ <div class="empty-state-actions">
+ <button class="btn btn-primary" onclick="window.location.href='/settings#research-library'">
+ <i class="fas fa-cog"></i> Configure Library Settings
+ </button>
+ <button class="btn btn-secondary" onclick="window.location.href='/library/download-manager'">
+ <i class="fas fa-download"></i> Download Manager
+ </button>
+ </div>
+ {% else %}
<p>Start downloading PDFs from your research to build your library</p>
<button class="btn btn-primary" onclick="window.location.href='/library/download-manager'">
- Go to Download Manager
+ <i class="fas fa-download"></i> Go to Download Manager
</button>
+ {% endif %}
</div>
{% endif %}
</div>
@@ -290,6 +341,29 @@
</div>
</div>
+<!-- Text Viewer Modal -->
+<div id="text-modal" class="pdf-modal">
+ <div class="pdf-modal-content">
+ <div class="pdf-modal-header">
+ <h2 id="text-title" class="pdf-title">Text Viewer</h2>
+ <div class="pdf-header-actions">
+ <button class="pdf-action-btn" onclick="copyTextContent()" title="Copy to clipboard">
+ <i class="fas fa-copy"></i>
+ </button>
+ <button class="pdf-action-btn" onclick="downloadTextContent()" title="Download as .txt">
+ <i class="fas fa-download"></i>
+ </button>
+ <button class="pdf-close-btn" onclick="closeTextModal()" title="Close">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ </div>
+ <div class="pdf-modal-body">
+ <div id="text-viewer" class="text-viewer-content"></div>
+ </div>
+ </div>
+</div>
+
<!-- Download Progress Modal -->
<div id="download-progress-modal" class="modal" style="display: none;">
<div class="modal-content">
@@ -568,6 +642,46 @@
.card-body {
padding: 15px;
+ position: relative;
+}
+
+/* Storage availability badges */
+.storage-badges {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin-bottom: 12px;
+}
+
+.storage-badge {
+ padding: 4px 8px;
+ border-radius: 4px;
+ font-size: 10px;
+ font-weight: 600;
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ white-space: nowrap;
+}
+
+.storage-badge-pdf {
+ background: #dc3545;
+ color: white;
+}
+
+.storage-badge-rag {
+ background: #ffc107;
+ color: #212529;
+}
+
+.storage-badge-db {
+ background: #17a2b8;
+ color: white;
+}
+
+.storage-badge-none {
+ background: #ff9800;
+ color: white;
}
.doc-title {
@@ -667,6 +781,39 @@
color: var(--text-secondary);
}
+.empty-state-info {
+ max-width: 600px;
+ margin: 20px auto;
+ text-align: left;
+ background: var(--bg-secondary);
+ padding: 20px;
+ border-radius: 8px;
+ border-left: 4px solid #ff9800;
+}
+
+.empty-state-info p {
+ margin: 10px 0;
+ line-height: 1.6;
+}
+
+.empty-state-info ol {
+ margin: 15px 0;
+ padding-left: 25px;
+}
+
+.empty-state-info ol li {
+ margin: 8px 0;
+ line-height: 1.6;
+}
+
+.empty-state-actions {
+ display: flex;
+ gap: 15px;
+ justify-content: center;
+ margin-top: 20px;
+ flex-wrap: wrap;
+}
+
/* Modal */
.modal {
display: none;
@@ -806,6 +953,22 @@
border-radius: 0 0 12px 12px;
}
+/* Text viewer styles */
+.text-viewer-content {
+ width: 100%;
+ height: 100%;
+ padding: 20px;
+ overflow-y: auto;
+ background: var(--bg-primary, #1a1a1a);
+ color: var(--text-primary, #e4e4e4);
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
+ font-size: 14px;
+ line-height: 1.6;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ border-radius: 0 0 12px 12px;
+}
+
/* Dark mode adjustments */
@media (prefers-color-scheme: dark) {
.pdf-modal-content {
@@ -841,6 +1004,19 @@
// Store current PDF data globally
let currentPDFData = null;
+// Route to appropriate viewer based on availability
+function openDocument(docId, hasPdf, hasTextDb) {
+ // Prefer PDF if available, otherwise fall back to text
+ if (hasPdf) {
+ openPDF(docId);
+ } else if (hasTextDb) {
+ openText(docId);
+ } else {
+ console.error('No content available for document', docId);
+ alert('No content available for this document');
+ }
+}
+
// Open PDF in modal
function openPDF(docId) {
fetch(`/library/api/document/${docId}/pdf-url`)
@@ -897,6 +1073,85 @@ document.getElementById('pdf-modal').addEventListener('click', function(e) {
}
});
+// Text viewer functions
+let currentTextData = null;
+
+function openText(docId) {
+ fetch(`/library/api/document/${docId}/text`)
+ .then(res => res.json())
+ .then(data => {
+ currentTextData = data;
+ document.getElementById('text-viewer').textContent = data.text_content;
+ document.getElementById('text-title').textContent = data.title;
+ document.getElementById('text-modal').style.display = 'block';
+
+ // Add escape key listener
+ document.addEventListener('keydown', handleTextEscapeKey);
+ })
+ .catch(err => {
+ console.error('Error loading text:', err);
+ alert('Failed to load text content');
+ });
+}
+
+function closeTextModal() {
+ document.getElementById('text-modal').style.display = 'none';
+ document.getElementById('text-viewer').textContent = '';
+ currentTextData = null;
+
+ // Remove escape key listener
+ document.removeEventListener('keydown', handleTextEscapeKey);
+}
+
+function handleTextEscapeKey(e) {
+ if (e.key === 'Escape') {
+ closeTextModal();
+ }
+}
+
+function copyTextContent() {
+ if (currentTextData && currentTextData.text_content) {
+ navigator.clipboard.writeText(currentTextData.text_content)
+ .then(() => {
+ // Show toast notification
+ const btn = event.target.closest('button');
+ const originalHTML = btn.innerHTML;
+ btn.innerHTML = '<i class="fas fa-check"></i>';
+ setTimeout(() => {
+ btn.innerHTML = originalHTML;
+ }, 2000);
+ })
+ .catch(err => {
+ console.error('Failed to copy:', err);
+ alert('Failed to copy to clipboard');
+ });
+ }
+}
+
+function downloadTextContent() {
+ if (currentTextData && currentTextData.text_content) {
+ const blob = new Blob([currentTextData.text_content], { type: 'text/plain' });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = (currentTextData.title || 'document') + '.txt';
+ link.click();
+ URL.revokeObjectURL(url);
+ }
+}
+
+// Close text modal when clicking outside (wait for DOM to load)
+document.addEventListener('DOMContentLoaded', function() {
+ const textModal = document.getElementById('text-modal');
+ if (textModal) {
+ textModal.addEventListener('click', function(e) {
+ if (e.target === this) {
+ closeTextModal();
+ }
+ });
+ }
+});
+
// Copy path to clipboard
function copyPath(path) {
navigator.clipboard.writeText(path);
@@ -935,7 +1190,7 @@ function filterDocuments() {
let currentDownloadController = null;
// Download all as text for RAG
-async function downloadAllAsText() {
+async function downloadAllAsText(saveFiles = false) {
const btn = event.target.closest('button');
const originalContent = btn.innerHTML;
btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Extracting...';
@@ -947,7 +1202,8 @@ async function downloadAllAsText() {
// Show progress modal
showDownloadProgressModal();
- document.querySelector('#download-progress-modal h2').textContent = 'Text Extraction Progress';
+ const modalTitle = saveFiles ? 'Text Extraction + RAG Files' : 'Text Extraction to Database';
+ document.querySelector('#download-progress-modal h2').textContent = modalTitle;
// Reset progress
document.getElementById('overall-progress').style.width = '0%';
@@ -965,6 +1221,7 @@ async function downloadAllAsText() {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
},
+ body: JSON.stringify({save_files: saveFiles}),
signal: currentDownloadController.signal
});
@@ -988,7 +1245,10 @@ async function downloadAllAsText() {
currentDownloadController = null;
setTimeout(() => {
closeProgressModal();
- alert(`Text extraction complete! Extracted ${data.total} documents to the txt/ folder.`);
+ const message = saveFiles
+ ? `Text extraction complete! Extracted ${data.total} documents to encrypted database and txt/ folder for RAG.`
+ : `Text extraction complete! Extracted ${data.total} documents to encrypted database only.`;
+ alert(message);
}, 2000);
}
}
@@ -1330,9 +1590,6 @@ async function performSync() {
// Format dates on page load
document.addEventListener('DOMContentLoaded', function() {
- // Initialize Bootstrap tooltips
- $('[data-toggle="tooltip"]').tooltip();
-
// Initialize date formatting
document.querySelectorAll('.download-date').forEach(span => {
const dateStr = span.dataset.date;