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.

fix: complete unified Document model migration and add collection filter

LearningCircuit63f579b75db1
diff --git a/src/local_deep_research/database/models/download_tracker.py b/src/local_deep_research/database/models/download_tracker.py
index 91842295fc..df0a4f9212 100644
--- a/src/local_deep_research/database/models/download_tracker.py
+++ b/src/local_deep_research/database/models/download_tracker.py
@@ -64,7 +64,7 @@ class DownloadTracker(Base):
# Link to full document record if it exists
library_document_id = Column(
Integer,
- ForeignKey("library_documents.id", ondelete="SET NULL"),
+ ForeignKey("documents.id", ondelete="SET NULL"),
nullable=True,
)
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 4cff0493fa..510019a69b 100644
--- a/src/local_deep_research/research_library/routes/library_routes.py
+++ b/src/local_deep_research/research_library/routes/library_routes.py
@@ -161,9 +161,13 @@ def library_page():
# Get documents with optional filters
domain_filter = request.args.get("domain")
research_filter = request.args.get("research")
+ collection_filter = request.args.get("collection") # New collection filter
documents = service.get_documents(
- research_id=research_filter, domain=domain_filter, limit=100
+ research_id=research_filter,
+ domain=domain_filter,
+ collection_id=collection_filter,
+ limit=100,
)
# Get unique domains for filter dropdown
@@ -172,12 +176,17 @@ def library_page():
# Get research list for filter dropdown
research_list = service.get_research_list_with_stats()
+ # Get collections list for filter dropdown
+ collections = service.get_all_collections()
+
return render_template_with_defaults(
"pages/library.html",
stats=stats,
documents=documents,
unique_domains=unique_domains,
research_list=research_list,
+ collections=collections,
+ selected_collection=collection_filter,
storage_path=stats.get("storage_path", ""),
enable_pdf_storage=enable_pdf_storage,
enable_txt_storage=enable_txt_storage,
@@ -406,15 +415,11 @@ def view_text_page(document_id):
with get_user_db_session(username) as db_session:
# Get document by ID (text now stored in Document.text_content)
document = (
- db_session.query(LibraryDocument)
- .filter_by(id=document_id)
- .first()
+ db_session.query(LibraryDocument).filter_by(id=document_id).first()
)
if not document:
- logger.warning(
- f"Document not found for document ID {document_id}"
- )
+ logger.warning(f"Document not found for document ID {document_id}")
return "Document not found", 404
if not document.text_content:
@@ -445,15 +450,11 @@ def serve_text_api(document_id):
with get_user_db_session(username) as db_session:
# Get document by ID (text now stored in Document.text_content)
document = (
- db_session.query(LibraryDocument)
- .filter_by(id=document_id)
- .first()
+ db_session.query(LibraryDocument).filter_by(id=document_id).first()
)
if not document:
- logger.warning(
- f"Document not found for document ID {document_id}"
- )
+ logger.warning(f"Document not found for document ID {document_id}")
return jsonify({"error": "Document not found"}), 404
if not document.text_content:
@@ -719,12 +720,6 @@ def download_bulk():
# Process each research
for research_id in research_ids:
# Get queued downloads for this research
- from ...database.models import (
- LibraryDownloadQueue,
- ResearchResource,
- )
- from ...database.session_context import get_user_db_session
-
with get_user_db_session(username) as session:
# Get pending queue items for this research
queue_items = (
@@ -950,7 +945,7 @@ def queue_all_undownloaded():
.outerjoin(
LibraryDocument,
(ResearchResource.id == LibraryDocument.resource_id)
- & (LibraryDocument.download_status == "completed"),
+ & (LibraryDocument.status == "completed"),
)
.filter(LibraryDocument.id.is_(None))
.all()
@@ -1156,7 +1151,7 @@ def get_research_sources(research_id):
"file_type": None,
}
- if document and document.download_status == "completed":
+ if document and document.status == "completed":
source_data.update(
{
"downloaded": True,
@@ -1204,7 +1199,7 @@ def check_downloads():
.first()
)
- if document and document.download_status == "completed":
+ if document and document.status == "completed":
download_status[resource.url] = {
"downloaded": True,
"document_id": document.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 b59b04c687..f982513f30 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -8,7 +8,6 @@ Handles downloading PDFs from various academic sources with:
- File organization and storage
"""
-import hashlib
import re
import time
import uuid
@@ -32,7 +31,6 @@ from ...database.models.library import (
Document as LibraryDocument,
DownloadQueue as LibraryDownloadQueue,
DocumentCollection,
- Collection,
)
from ...database.models.research import ResearchResource
from ...database.session_context import get_user_db_session
@@ -246,9 +244,7 @@ class DownloadService:
# Check if already downloaded (trust the database status)
existing_doc = (
session.query(LibraryDocument)
- .filter_by(
- resource_id=resource.id, download_status="completed"
- )
+ .filter_by(resource_id=resource.id, status="completed")
.first()
)
@@ -320,7 +316,7 @@ class DownloadService:
# Check if already downloaded (trust the database after sync)
existing_doc = (
session.query(LibraryDocument)
- .filter_by(resource_id=resource_id, download_status="completed")
+ .filter_by(resource_id=resource_id, status="completed")
.first()
)
@@ -511,13 +507,22 @@ 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
+ 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")
- library_collection_id = get_default_library_id(self.username)
- except Exception as e:
- logger.error(f"Failed to get source type or library collection: {e}")
+ source_type_id = get_source_type_id(
+ self.username, "research_download"
+ )
+ library_collection_id = get_default_library_id(
+ self.username
+ )
+ except Exception:
+ logger.exception(
+ "Failed to get source type or library collection"
+ )
raise
# Create new unified document entry
@@ -560,7 +565,9 @@ class DownloadService:
# Automatically extract and save text after successful PDF download
try:
- logger.info(f"Extracting text from downloaded PDF for: {resource.title[:50]}")
+ logger.info(
+ f"Extracting text from downloaded PDF for: {resource.title[:50]}"
+ )
text = self._extract_text_from_pdf(pdf_content)
if text:
@@ -585,13 +592,19 @@ class DownloadService:
extraction_method="pdf_extraction",
extraction_source="local_pdf",
pdf_document_id=pdf_document_id,
- save_files=enable_text_storage
+ save_files=enable_text_storage,
+ )
+ logger.info(
+ f"Successfully extracted and saved text for: {resource.title[:50]}"
)
- logger.info(f"Successfully extracted and saved text for: {resource.title[:50]}")
else:
- logger.warning(f"Text extraction returned empty text for: {resource.title[:50]}")
+ logger.warning(
+ f"Text extraction returned empty text for: {resource.title[:50]}"
+ )
except Exception as e:
- logger.exception(f"Failed to extract text from PDF, but PDF download succeeded: {e}")
+ logger.exception(
+ f"Failed to extract text from PDF, but PDF download succeeded: {e}"
+ )
# Don't fail the entire download if text extraction fails
return True, None
@@ -860,7 +873,11 @@ class DownloadService:
return None
# Check if text content exists and extraction was successful
- if existing_doc.text_content and existing_doc.extraction_method and existing_doc.extraction_method != "failed":
+ if (
+ existing_doc.text_content
+ and existing_doc.extraction_method
+ and existing_doc.extraction_method != "failed"
+ ):
logger.info(
f"Text content already exists in Document for resource_id={resource_id}, extraction_method={existing_doc.extraction_method}"
)
@@ -907,7 +924,7 @@ class DownloadService:
.first()
)
- if not pdf_document or pdf_document.download_status != "completed":
+ if not pdf_document or pdf_document.status != "completed":
return None
pdf_path = Path(self.library_root) / pdf_document.file_path
@@ -1432,9 +1449,7 @@ class DownloadService:
# 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 file metadata (needed for database even if no file)
- file_size = len(text.encode("utf-8"))
- text_hash = hashlib.sha256(text.encode("utf-8")).hexdigest()
+ # Calculate text metadata for database
word_count = len(text.split())
character_count = len(text)
@@ -1448,9 +1463,17 @@ class DownloadService:
# Find the document by pdf_document_id or resource_id
doc = None
if pdf_document_id:
- doc = session.query(LibraryDocument).filter_by(id=pdf_document_id).first()
+ doc = (
+ session.query(LibraryDocument)
+ .filter_by(id=pdf_document_id)
+ .first()
+ )
else:
- doc = session.query(LibraryDocument).filter_by(resource_id=resource.id).first()
+ doc = (
+ session.query(LibraryDocument)
+ .filter_by(resource_id=resource.id)
+ .first()
+ )
if doc:
# Update document with extracted text
@@ -1471,7 +1494,9 @@ class DownloadService:
else:
doc.extraction_quality = "low"
- logger.debug(f"Updated document {doc.id} with extracted text ({word_count} words)")
+ logger.debug(
+ 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}. "
@@ -1506,7 +1531,11 @@ class DownloadService:
character_count = len(text)
# Find the Document by resource_id
- doc = session.query(LibraryDocument).filter_by(resource_id=resource.id).first()
+ doc = (
+ session.query(LibraryDocument)
+ .filter_by(resource_id=resource.id)
+ .first()
+ )
if doc:
# Update existing document with text content
@@ -1515,7 +1544,9 @@ class DownloadService:
doc.word_count = word_count
doc.extraction_method = extraction_method
doc.extraction_source = extraction_source
- doc.extraction_quality = "low" # Unknown quality for legacy files
+ doc.extraction_quality = (
+ "low" # Unknown quality for legacy files
+ )
logger.info(
f"Updated document {doc.id} with text from file: {file_path.name}"
)
@@ -1533,7 +1564,11 @@ class DownloadService:
"""Record a failed text extraction attempt in the Document."""
try:
# Find the Document by resource_id
- doc = session.query(LibraryDocument).filter_by(resource_id=resource.id).first()
+ doc = (
+ session.query(LibraryDocument)
+ .filter_by(resource_id=resource.id)
+ .first()
+ )
if doc:
# Update document with extraction error
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 3baadb9d41..fb5b4e7c77 100644
--- a/src/local_deep_research/research_library/services/library_service.py
+++ b/src/local_deep_research/research_library/services/library_service.py
@@ -193,6 +193,7 @@ class LibraryService:
file_type: Optional[str] = None,
favorites_only: bool = False,
search_query: Optional[str] = None,
+ collection_id: Optional[str] = None,
limit: int = 100,
offset: int = 0,
) -> List[Dict]:
@@ -202,16 +203,25 @@ class LibraryService:
Returns enriched document information with research details.
"""
with get_user_db_session(self.username) as session:
- # Get default Library collection ID for RAG status
+ # Get default Library collection ID if not specified
from ...database.library_init import get_default_library_id
- library_id = get_default_library_id(self.username)
+
+ if not collection_id:
+ collection_id = get_default_library_id(self.username)
all_documents = []
- # Query documents
+ # Query documents - join with DocumentCollection to filter by collection
query = (
session.query(
- LibraryDocument, ResearchResource, ResearchHistory
+ LibraryDocument,
+ ResearchResource,
+ ResearchHistory,
+ DocumentCollection,
+ )
+ .join(
+ DocumentCollection,
+ LibraryDocument.id == DocumentCollection.document_id,
)
.join(
ResearchResource,
@@ -221,13 +231,12 @@ class LibraryService:
ResearchHistory,
LibraryDocument.research_id == ResearchHistory.id,
)
+ .filter(DocumentCollection.collection_id == collection_id)
)
# Apply filters
if research_id:
- query = query.filter(
- LibraryDocument.research_id == research_id
- )
+ query = query.filter(LibraryDocument.research_id == research_id)
if domain:
query = self._apply_domain_filter(
@@ -235,9 +244,7 @@ class LibraryService:
)
if file_type:
- query = query.filter(
- LibraryDocument.file_type == file_type
- )
+ query = query.filter(LibraryDocument.file_type == file_type)
if favorites_only:
query = query.filter(LibraryDocument.favorite.is_(True))
@@ -247,10 +254,8 @@ class LibraryService:
query, LibraryDocument, search_query
)
- # Filter to only downloaded documents
- query = query.filter(
- LibraryDocument.download_status == "completed"
- )
+ # Filter to only completed documents
+ query = query.filter(LibraryDocument.status == "completed")
# Apply safety limit to prevent memory issues
query = query.limit(500000)
@@ -259,32 +264,24 @@ class LibraryService:
results = query.all()
# Process results
- for doc, resource, research in results:
- # Get download tracker info
- tracker = (
- session.query(DownloadTracker)
- .filter_by(url_hash=self._get_url_hash(resource.url))
- .first()
- )
-
- # Determine availability flags
+ for doc, resource, research, doc_collection in results:
+ # Determine availability flags - use Document.file_path directly
file_absolute_path = None
- if tracker and tracker.file_path:
+ if doc.file_path and doc.file_path != "metadata_only":
file_absolute_path = str(
- get_absolute_path_from_settings(tracker.file_path)
+ get_absolute_path_from_settings(doc.file_path)
)
has_pdf = bool(file_absolute_path)
has_text_db = bool(doc.text_content) # Text now in Document
- # Check RAG indexing status from DocumentCollection
- doc_collection = (
- session.query(DocumentCollection)
- .filter_by(document_id=doc.id, collection_id=library_id)
- .first()
+ # Use DocumentCollection from query results
+ has_rag_indexed = (
+ doc_collection.indexed if doc_collection else False
+ )
+ rag_chunk_count = (
+ doc_collection.chunk_count if doc_collection else 0
)
- has_rag_indexed = doc_collection.indexed if doc_collection else False
- rag_chunk_count = doc_collection.chunk_count if doc_collection else 0
all_documents.append(
{
@@ -301,22 +298,18 @@ class LibraryService:
# File info
"file_path": doc.file_path,
"file_absolute_path": file_absolute_path,
- "file_name": tracker.file_name
- if tracker
- else (
- Path(doc.file_path).name
- if doc.file_path != "metadata_only"
- else "metadata_only"
- ),
+ "file_name": Path(doc.file_path).name
+ if doc.file_path and doc.file_path != "metadata_only"
+ else "metadata_only",
"file_size": doc.file_size,
"file_type": doc.file_type,
# URLs
"original_url": doc.original_url,
"domain": self._extract_domain(doc.original_url),
# Status
- "download_status": doc.download_status,
- "downloaded_at": doc.downloaded_at.isoformat()
- if doc.downloaded_at
+ "download_status": doc.status,
+ "downloaded_at": doc.processed_at.isoformat()
+ if doc.processed_at
else None,
"favorite": doc.favorite,
"tags": doc.tags,
@@ -335,7 +328,7 @@ class LibraryService:
"has_rag_indexed": has_rag_indexed,
"rag_chunk_count": rag_chunk_count,
# Sort key
- "_sort_date": doc.downloaded_at,
+ "_sort_date": doc.processed_at,
}
)
@@ -354,6 +347,40 @@ class LibraryService:
return paginated_documents
+ def get_all_collections(self) -> List[Dict]:
+ """Get all collections with document counts."""
+ with get_user_db_session(self.username) as session:
+ # Query collections with document counts
+ results = (
+ session.query(
+ Collection,
+ func.count(DocumentCollection.document_id).label(
+ "document_count"
+ ),
+ )
+ .outerjoin(
+ DocumentCollection,
+ Collection.id == DocumentCollection.collection_id,
+ )
+ .group_by(Collection.id)
+ .order_by(Collection.is_default.desc(), Collection.name)
+ .all()
+ )
+
+ collections = []
+ for collection, doc_count in results:
+ collections.append(
+ {
+ "id": collection.id,
+ "name": collection.name,
+ "description": collection.description,
+ "is_default": collection.is_default,
+ "document_count": doc_count or 0,
+ }
+ )
+
+ return collections
+
def get_research_list_with_stats(self) -> List[Dict]:
"""Get all research sessions with download statistics."""
with get_user_db_session(self.username) as session:
@@ -364,7 +391,7 @@ class LibraryService:
func.count(ResearchResource.id).label("total_resources"),
func.count(
case(
- (LibraryDocument.download_status == "completed", 1),
+ (LibraryDocument.status == "completed", 1),
else_=None,
)
).label("downloaded_count"),
@@ -477,13 +504,6 @@ class LibraryService:
# Found document
doc, resource, research = result
- # Get download tracker info
- tracker = (
- session.query(DownloadTracker)
- .filter_by(url_hash=self._get_url_hash(resource.url))
- .first()
- )
-
return {
"id": doc.id,
"resource_id": doc.resource_id,
@@ -492,14 +512,10 @@ class LibraryService:
"original_url": doc.original_url or resource.url,
"file_path": doc.file_path,
"file_absolute_path": str(
- get_absolute_path_from_settings(tracker.file_path)
+ get_absolute_path_from_settings(doc.file_path)
)
- if tracker and tracker.file_path
- else (
- None
- if doc.file_path == "metadata_only"
- else doc.file_path
- ),
+ if doc.file_path and doc.file_path != "metadata_only"
+ else None,
"file_name": Path(doc.file_path).name
if doc.file_path and doc.file_path != "metadata_only"
else None,
@@ -507,12 +523,12 @@ class LibraryService:
"file_type": doc.file_type,
"mime_type": doc.mime_type,
"domain": self._extract_domain(resource.url),
- "download_status": doc.download_status,
- "downloaded_at": doc.downloaded_at.isoformat()
- if doc.downloaded_at
- and hasattr(doc.downloaded_at, "isoformat")
- else str(doc.downloaded_at)
- if doc.downloaded_at
+ "download_status": doc.status,
+ "downloaded_at": doc.processed_at.isoformat()
+ if doc.processed_at
+ and hasattr(doc.processed_at, "isoformat")
+ else str(doc.processed_at)
+ if doc.processed_at
else None,
"favorite": doc.favorite,
"tags": doc.tags,
@@ -524,7 +540,9 @@ class LibraryService:
else None,
# Document fields
"is_pdf": doc.file_type == "pdf",
- "has_text_db": bool(doc.text_content), # Text now in Document
+ "has_text_db": bool(
+ doc.text_content
+ ), # Text now in Document
}
# Not found
@@ -678,10 +696,10 @@ class LibraryService:
Statistics about the sync operation
"""
with get_user_db_session(self.username) as session:
- # Get all documents marked as downloaded
+ # Get all documents marked as completed
documents = (
session.query(LibraryDocument)
- .filter_by(download_status="completed")
+ .filter_by(status="completed")
.all()
)
@@ -769,7 +787,7 @@ class LibraryService:
tracker.file_path = None
# Mark document as pending
- doc.download_status = "pending"
+ doc.status = "pending"
count += 1
session.commit()
diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.html
index 2db858f2ac..673c9ad53b 100644
--- a/src/local_deep_research/web/templates/pages/library.html
+++ b/src/local_deep_research/web/templates/pages/library.html
@@ -115,6 +115,19 @@
<!-- Filters Section -->
<div class="filters-section">
<div class="filter-row">
+ <!-- Collection Filter -->
+ <div class="filter-group">
+ <label>Collection</label>
+ <select id="filter-collection" class="form-control">
+ <option value="">All Collections</option>
+ {% for collection in collections %}
+ <option value="{{ collection.id }}" {% if selected_collection == collection.id %}selected{% endif %}>
+ {{ collection.name }}{% if collection.is_default %} (Default){% endif %} ({{ collection.document_count }})
+ </option>
+ {% endfor %}
+ </select>
+ </div>
+
<!-- Domain Filter -->
<div class="filter-group">
<label>Domain</label>
@@ -1266,6 +1279,18 @@ function copyPath(path) {
}
// Filter documents
+document.getElementById('filter-collection').addEventListener('change', function() {
+ // Collection filter requires server-side reload
+ const collection = this.value;
+ const urlParams = new URLSearchParams(window.location.search);
+ if (collection) {
+ urlParams.set('collection', collection);
+ } else {
+ urlParams.delete('collection');
+ }
+ window.location.search = urlParams.toString();
+});
+
document.getElementById('filter-domain').addEventListener('change', filterDocuments);
document.getElementById('filter-research').addEventListener('change', filterDocuments);
document.getElementById('filter-date').addEventListener('change', filterDocuments);