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: add chunks viewer and fix user upload visibility

LearningCircuit9bc799508237
diff --git a/src/local_deep_research/database/models/__init__.py b/src/local_deep_research/database/models/__init__.py
index 743060d921..8016efb0e8 100644
--- a/src/local_deep_research/database/models/__init__.py
+++ b/src/local_deep_research/database/models/__init__.py
@@ -66,11 +66,6 @@ from .library import (
RAGIndexStatus,
)
-# Naming aliases for clarity (these are intentional, not workarounds)
-LibraryDocument = Document
-LibraryCollection = Collection
-LibraryCollectionDocument = DocumentCollection
-LibraryDownloadQueue = DownloadQueue
# Note: Text content is now directly in Document.text_content field
from .download_tracker import (
DownloadTracker,
@@ -163,11 +158,6 @@ __all__ = [
"RAGIndexStatus",
"CollectionFolder",
"CollectionFolderFile",
- # Naming aliases (for clarity, not workarounds)
- "LibraryDocument",
- "LibraryCollection",
- "LibraryCollectionDocument",
- "LibraryDownloadQueue",
# Download Tracker Models
"DownloadTracker",
"DownloadDuplicates",
diff --git a/src/local_deep_research/database/models/library.py b/src/local_deep_research/database/models/library.py
index e3967d3c1c..9239d72f83 100644
--- a/src/local_deep_research/database/models/library.py
+++ b/src/local_deep_research/database/models/library.py
@@ -51,7 +51,9 @@ class SourceType(Base):
created_at = Column(UtcDateTime, default=utcnow(), nullable=False)
def __repr__(self):
- return f"<SourceType(name='{self.name}', display='{self.display_name}')>"
+ return (
+ f"<SourceType(name='{self.name}', display='{self.display_name}')>"
+ )
class UploadBatch(Base):
@@ -84,7 +86,6 @@ class UploadBatch(Base):
class Document(Base):
"""
Unified document table for all documents (research downloads + user uploads).
- Contains all fields from both LibraryDocument and UserDocument.
"""
__tablename__ = "documents"
@@ -129,16 +130,22 @@ class Document(Base):
) # SHA256 for deduplication
original_url = Column(Text, nullable=True) # Source URL (for downloads)
filename = Column(String(500), nullable=True) # Display name (for uploads)
- original_filename = Column(String(500), nullable=True) # Original upload name
+ original_filename = Column(
+ String(500), nullable=True
+ ) # Original upload name
# File information
- file_path = Column(Text, nullable=True) # Path relative to library/uploads root
+ file_path = Column(
+ Text, nullable=True
+ ) # Path relative to library/uploads root
file_size = Column(Integer, nullable=False) # Size in bytes
file_type = Column(String(50), nullable=False) # pdf, txt, md, html, etc.
mime_type = Column(String(100), nullable=True) # MIME type
# Content storage - text always stored in DB
- text_content = Column(Text, nullable=True) # Extracted/uploaded text content
+ text_content = Column(
+ Text, nullable=True
+ ) # Extracted/uploaded text content
# Metadata
title = Column(Text) # Document title
@@ -163,8 +170,12 @@ class Document(Base):
last_accessed = Column(UtcDateTime, nullable=True)
# Text extraction metadata (for research downloads from PDFs)
- extraction_method = Column(String(50), nullable=True) # pdf_extraction, native_api, etc.
- extraction_source = Column(String(50), nullable=True) # arxiv_api, pdfplumber, etc.
+ extraction_method = Column(
+ String(50), nullable=True
+ ) # pdf_extraction, native_api, etc.
+ extraction_source = Column(
+ String(50), nullable=True
+ ) # arxiv_api, pdfplumber, etc.
extraction_quality = Column(String(20), nullable=True) # high, medium, low
has_formatting_issues = Column(Boolean, default=False)
has_encoding_issues = Column(Boolean, default=False)
@@ -201,7 +212,11 @@ class Document(Base):
)
def __repr__(self):
- title_str = self.title[:50] if self.title else (self.filename[:50] if self.filename else 'Untitled')
+ title_str = (
+ self.title[:50]
+ if self.title
+ else (self.filename[:50] if self.filename else "Untitled")
+ )
return f"<Document(title='{title_str}', type={self.file_type}, size={self.file_size})>"
diff --git a/src/local_deep_research/database/views/library_views.py b/src/local_deep_research/database/views/library_views.py
index 4c876d0f3e..43e78ded9a 100644
--- a/src/local_deep_research/database/views/library_views.py
+++ b/src/local_deep_research/database/views/library_views.py
@@ -13,7 +13,7 @@ def create_library_views(session: Session):
These views combine downloaded documents with their classification and research data.
"""
- # View that combines LibraryDocument with all related information
+ # View that combines Document with all related information
library_documents_enriched_view = """
CREATE OR REPLACE VIEW library_documents_enriched AS
SELECT
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 510019a69b..e70dabd4c7 100644
--- a/src/local_deep_research/research_library/routes/library_routes.py
+++ b/src/local_deep_research/research_library/routes/library_routes.py
@@ -27,7 +27,7 @@ from ...web.utils.templates import render_template_with_defaults
from ...database.session_context import get_user_db_session
from ...database.models.research import ResearchResource
from ...database.models.library import (
- Document as LibraryDocument,
+ Document as Document,
DownloadQueue as LibraryDownloadQueue,
)
from ...library.download_management import ResourceFilter
@@ -414,9 +414,7 @@ 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()
- )
+ document = db_session.query(Document).filter_by(id=document_id).first()
if not document:
logger.warning(f"Document not found for document ID {document_id}")
@@ -449,9 +447,7 @@ 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()
- )
+ document = db_session.query(Document).filter_by(id=document_id).first()
if not document:
logger.warning(f"Document not found for document ID {document_id}")
@@ -943,11 +939,11 @@ def queue_all_undownloaded():
undownloaded = (
db_session.query(ResearchResource)
.outerjoin(
- LibraryDocument,
- (ResearchResource.id == LibraryDocument.resource_id)
- & (LibraryDocument.status == "completed"),
+ Document,
+ (ResearchResource.id == Document.resource_id)
+ & (Document.status == "completed"),
)
- .filter(LibraryDocument.id.is_(None))
+ .filter(Document.id.is_(None))
.all()
)
@@ -1123,7 +1119,7 @@ def get_research_sources(research_id):
for idx, resource in enumerate(resources, 1):
# Check if document exists
document = (
- db_session.query(LibraryDocument)
+ db_session.query(Document)
.filter_by(resource_id=resource.id)
.first()
)
@@ -1194,7 +1190,7 @@ def check_downloads():
for resource in resources:
# Check if document exists
document = (
- db_session.query(LibraryDocument)
+ db_session.query(Document)
.filter_by(resource_id=resource.id)
.first()
)
@@ -1245,7 +1241,7 @@ def download_source():
# Check if already downloaded
existing = (
- db_session.query(LibraryDocument)
+ db_session.query(Document)
.filter_by(resource_id=resource.id)
.first()
)
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 613d378604..3946103964 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -29,6 +29,7 @@ from ...database.models.library import (
Document,
Collection,
DocumentCollection,
+ SourceType,
)
rag_bp = Blueprint("rag", __name__, url_prefix="/library")
@@ -76,6 +77,71 @@ def embedding_settings_page():
)
+@rag_bp.route("/document/<string:document_id>/chunks")
+@login_required
+def view_document_chunks(document_id):
+ """View all chunks for a document across all collections."""
+ from ...database.session_context import get_user_db_session
+ from ...database.models.library import DocumentChunk
+
+ username = session.get("username")
+
+ with get_user_db_session(username) as db_session:
+ # Get document info
+ document = db_session.query(Document).filter_by(id=document_id).first()
+
+ if not document:
+ return "Document not found", 404
+
+ # Get all chunks for this document
+ chunks = (
+ db_session.query(DocumentChunk)
+ .filter(DocumentChunk.source_id == document_id)
+ .order_by(DocumentChunk.collection_name, DocumentChunk.chunk_index)
+ .all()
+ )
+
+ # Group chunks by collection
+ chunks_by_collection = {}
+ for chunk in chunks:
+ coll_name = chunk.collection_name
+ if coll_name not in chunks_by_collection:
+ # Get collection display name
+ collection_id = coll_name.replace("collection_", "")
+ collection = (
+ db_session.query(Collection)
+ .filter_by(id=collection_id)
+ .first()
+ )
+ chunks_by_collection[coll_name] = {
+ "name": collection.name if collection else coll_name,
+ "id": collection_id,
+ "chunks": [],
+ }
+
+ chunks_by_collection[coll_name]["chunks"].append(
+ {
+ "id": chunk.id,
+ "index": chunk.chunk_index,
+ "text": chunk.chunk_text,
+ "word_count": chunk.word_count,
+ "start_char": chunk.start_char,
+ "end_char": chunk.end_char,
+ "embedding_model": chunk.embedding_model,
+ "embedding_model_type": chunk.embedding_model_type,
+ "embedding_dimension": chunk.embedding_dimension,
+ "created_at": chunk.created_at,
+ }
+ )
+
+ return render_template(
+ "pages/document_chunks.html",
+ document=document,
+ chunks_by_collection=chunks_by_collection,
+ total_chunks=len(chunks),
+ )
+
+
@rag_bp.route("/collections")
@login_required
def collections_page():
@@ -561,29 +627,36 @@ def get_documents():
if not collection_id:
collection_id = get_default_library_id(username)
+ logger.info(
+ f"Getting documents for collection_id: {collection_id}, filter: {filter_type}, page: {page}"
+ )
+
with get_user_db_session(username) as db_session:
# Expire all cached objects to ensure we get fresh data from DB
db_session.expire_all()
# Build base query - join Document with DocumentCollection for the collection
- query = db_session.query(Document, DocumentCollection).outerjoin(
+ # Use inner join to only show documents that belong to this collection
+ query = db_session.query(Document, DocumentCollection).join(
DocumentCollection,
(DocumentCollection.document_id == Document.id)
& (DocumentCollection.collection_id == collection_id),
)
+ logger.debug(f"Base query for collection {collection_id}: {query}")
+
# Apply filters based on DocumentCollection.indexed
if filter_type == "indexed":
query = query.filter(DocumentCollection.indexed.is_(True))
elif filter_type == "unindexed":
- # Documents in library but not indexed, or not in DocumentCollection yet
- query = query.filter(
- (DocumentCollection.indexed.is_(False))
- | (DocumentCollection.id.is_(None))
- )
+ # Documents in collection but not indexed yet
+ query = query.filter(DocumentCollection.indexed.is_(False))
# Get total count before pagination
total_count = query.count()
+ logger.info(
+ f"Found {total_count} total documents for collection {collection_id} with filter {filter_type}"
+ )
# Apply pagination
results = (
@@ -593,6 +666,8 @@ def get_documents():
.all()
)
+ logger.info(f"Returning {len(results)} documents on page {page}")
+
documents = [
{
"id": doc.id,
@@ -1107,6 +1182,7 @@ def upload_to_collection(collection_id):
from werkzeug.utils import secure_filename
from pathlib import Path
import hashlib
+ import uuid
try:
if "files" not in request.files:
@@ -1150,7 +1226,7 @@ def upload_to_collection(collection_id):
# Check if document already exists
existing_doc = (
db_session.query(Document)
- .filter_by(file_hash=file_hash)
+ .filter_by(document_hash=file_hash)
.first()
)
@@ -1223,12 +1299,46 @@ def upload_to_collection(collection_id):
)
continue
+ # Get or create the user_upload source type
+ logger.info(
+ f"Getting or creating user_upload source type for {filename}"
+ )
+ source_type = (
+ db_session.query(SourceType)
+ .filter_by(name="user_upload")
+ .first()
+ )
+ if not source_type:
+ logger.info("Creating new user_upload source type")
+ source_type = SourceType(
+ id=str(uuid.uuid4()),
+ name="user_upload",
+ display_name="User Upload",
+ description="Documents uploaded by users",
+ icon="fas fa-upload",
+ )
+ db_session.add(source_type)
+ db_session.flush()
+ logger.info(
+ f"Created source type with ID: {source_type.id}"
+ )
+ else:
+ logger.info(
+ f"Found existing source type with ID: {source_type.id}"
+ )
+
# Create document with extracted text (no username needed - in user's own database)
# Note: uploaded_at uses default=utcnow() in the model, so we don't need to set it manually
# We only store extracted text in the encrypted database for better privacy and security
+ doc_id = str(uuid.uuid4())
+ logger.info(
+ f"Creating document {doc_id} for {filename}"
+ )
new_doc = Document(
+ id=doc_id,
+ source_type_id=source_type.id,
filename=filename,
- file_hash=file_hash,
+ document_hash=file_hash,
file_size=len(file_content),
file_type=file_type,
text_content=extracted_text, # Store the extracted text
@@ -1236,6 +1346,9 @@ def upload_to_collection(collection_id):
)
db_session.add(new_doc)
db_session.flush() # Get the ID
+ logger.info(
+ f"Document {new_doc.id} created successfully"
+ )
# Add to collection
collection_link = DocumentCollection(
@@ -1416,7 +1529,13 @@ def index_collection(collection_id):
)
if not force_reindex:
- query = query.filter(not DocumentCollection.indexed)
+ # IMPORTANT: DO NOT CHANGE THIS LINE! DO NOT REMOVE THIS COMMENT!
+ # We MUST use `== False` instead of `not DocumentCollection.indexed`
+ # The Python `not` operator does NOT work correctly in SQLAlchemy filters.
+ # Using `not` will cause the query to return NO results (zero documents).
+ # SQLAlchemy requires explicit comparison: `== False` or `== True`
+ # This has been fixed multiple times - DO NOT change it back to `not`!
+ query = query.filter(DocumentCollection.indexed == False) # noqa: E712
doc_links = query.all()
@@ -1434,8 +1553,6 @@ def index_collection(collection_id):
yield f"data: {json.dumps({'type': 'start', 'message': f'Indexing {total} documents in collection: {collection.name}'})}\n\n"
- collection_name = f"collection_{collection.id}"
-
for idx, (link, doc) in enumerate(doc_links, 1):
yield f"data: {json.dumps({'type': 'progress', 'current': idx, 'total': total, 'filename': doc.filename or doc.title, 'percent': int((idx / total) * 100)})}\n\n"
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 f982513f30..2952e8d704 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -28,7 +28,7 @@ from ...database.models.download_tracker import (
)
from ...security import redact_data
from ...database.models.library import (
- Document as LibraryDocument,
+ Document as Document,
DownloadQueue as LibraryDownloadQueue,
DocumentCollection,
)
@@ -243,7 +243,7 @@ class DownloadService:
# Check if already downloaded (trust the database status)
existing_doc = (
- session.query(LibraryDocument)
+ session.query(Document)
.filter_by(resource_id=resource.id, status="completed")
.first()
)
@@ -315,7 +315,7 @@ class DownloadService:
# Check if already downloaded (trust the database after sync)
existing_doc = (
- session.query(LibraryDocument)
+ session.query(Document)
.filter_by(resource_id=resource_id, status="completed")
.first()
)
@@ -491,7 +491,7 @@ class DownloadService:
# Check if library document already exists
existing_doc = (
- session.query(LibraryDocument)
+ session.query(Document)
.filter_by(resource_id=resource.id)
.first()
)
@@ -527,7 +527,7 @@ class DownloadService:
# Create new unified document entry
doc_id = str(uuid.uuid4())
- doc = LibraryDocument(
+ doc = Document(
id=doc_id,
source_type_id=source_type_id,
resource_id=resource.id,
@@ -578,7 +578,7 @@ class DownloadService:
# Get the document ID we just created/updated
pdf_doc = (
- session.query(LibraryDocument)
+ session.query(Document)
.filter_by(resource_id=resource.id)
.first()
)
@@ -864,9 +864,7 @@ class DownloadService:
) -> Optional[Tuple[bool, Optional[str]]]:
"""Check if text already exists in database (in Document.text_content)."""
existing_doc = (
- session.query(LibraryDocument)
- .filter_by(resource_id=resource_id)
- .first()
+ session.query(Document).filter_by(resource_id=resource_id).first()
)
if not existing_doc:
@@ -919,9 +917,7 @@ class DownloadService:
) -> Optional[Tuple[bool, Optional[str]]]:
"""Try extracting text from existing PDF in database."""
pdf_document = (
- session.query(LibraryDocument)
- .filter_by(resource_id=resource_id)
- .first()
+ session.query(Document).filter_by(resource_id=resource_id).first()
)
if not pdf_document or pdf_document.status != "completed":
@@ -1464,13 +1460,13 @@ class DownloadService:
doc = None
if pdf_document_id:
doc = (
- session.query(LibraryDocument)
+ session.query(Document)
.filter_by(id=pdf_document_id)
.first()
)
else:
doc = (
- session.query(LibraryDocument)
+ session.query(Document)
.filter_by(resource_id=resource.id)
.first()
)
@@ -1532,7 +1528,7 @@ class DownloadService:
# Find the Document by resource_id
doc = (
- session.query(LibraryDocument)
+ session.query(Document)
.filter_by(resource_id=resource.id)
.first()
)
@@ -1565,7 +1561,7 @@ class DownloadService:
try:
# Find the Document by resource_id
doc = (
- session.query(LibraryDocument)
+ session.query(Document)
.filter_by(resource_id=resource.id)
.first()
)
diff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.py
index d0f2b733d5..671a08c588 100644
--- a/src/local_deep_research/research_library/services/library_rag_service.py
+++ b/src/local_deep_research/research_library/services/library_rag_service.py
@@ -12,13 +12,13 @@ Handles indexing and searching library documents using RAG:
from pathlib import Path
from typing import Any, Dict, List, Optional
-from langchain_core.documents import Document
+from langchain_core.documents import Document as LangchainDocument
from langchain_text_splitters import RecursiveCharacterTextSplitter
from loguru import logger
from sqlalchemy import func
from ...database.models.library import (
- Document as LibraryDocument,
+ Document,
DocumentChunk,
DocumentCollection,
Collection,
@@ -300,9 +300,7 @@ class LibraryRAGService:
"""
with get_user_db_session(self.username) as session:
# Get the document
- document = (
- session.query(LibraryDocument).filter_by(id=document_id).first()
- )
+ document = session.query(Document).filter_by(id=document_id).first()
if not document:
return {"status": "error", "error": "Document not found"}
@@ -342,7 +340,7 @@ class LibraryRAGService:
try:
# Create LangChain Document from text
- doc = Document(
+ doc = LangchainDocument(
page_content=document.text_content,
metadata={
"source": document.original_url,
@@ -455,29 +453,18 @@ class LibraryRAGService:
f"Saved FAISS index to {index_path} with integrity tracking"
)
- # Update DocumentCollection with RAG status using direct SQL
- # (Direct SQL is used to ensure immediate persistence with encrypted DB + WAL mode)
+ # Update DocumentCollection with RAG status using ORM
was_already_indexed = (
doc_collection.indexed
) # Check BEFORE updating
- from sqlalchemy import text
from datetime import datetime, UTC
+ from sqlalchemy import text
- # Use direct SQL UPDATE to bypass ORM caching issues with SQLCipher+WAL
- now = datetime.now(UTC).isoformat()
- session.execute(
- text(
- "UPDATE document_collections SET indexed = 1, chunk_count = :chunks, last_indexed_at = :now "
- "WHERE document_id = :doc_id AND collection_id = :coll_id"
- ),
- {
- "chunks": len(chunks),
- "now": now,
- "doc_id": document_id,
- "coll_id": collection_id,
- },
- )
+ # Update using ORM
+ doc_collection.indexed = True
+ doc_collection.chunk_count = len(chunks)
+ doc_collection.last_indexed_at = datetime.now(UTC)
# Update RAGIndex statistics (only if not already indexed)
rag_index_obj = (
@@ -588,7 +575,7 @@ class LibraryRAGService:
for idx, doc_collection in enumerate(doc_collections, 1):
# Get the document for title info
document = (
- session.query(LibraryDocument)
+ session.query(Document)
.filter_by(id=doc_collection.document_id)
.first()
)
@@ -712,9 +699,7 @@ class LibraryRAGService:
with get_user_db_session(self.username) as session:
# Pre-load all documents for this batch
documents = (
- session.query(LibraryDocument)
- .filter(LibraryDocument.id.in_(doc_ids))
- .all()
+ session.query(Document).filter(Document.id.in_(doc_ids)).all()
)
# Create lookup for quick access
@@ -914,7 +899,7 @@ class LibraryRAGService:
}
# Create LangChain Document from text
- doc = Document(
+ doc = LangchainDocument(
page_content=content,
metadata={
"source": str(file_path),
@@ -1020,7 +1005,7 @@ class LibraryRAGService:
}
# Create LangChain Document
- doc = Document(
+ doc = LangchainDocument(
page_content=content,
metadata={
"source": f"user_upload_{user_doc.id}",
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 fb5b4e7c77..d77201004b 100644
--- a/src/local_deep_research/research_library/services/library_service.py
+++ b/src/local_deep_research/research_library/services/library_service.py
@@ -17,7 +17,7 @@ from sqlalchemy import and_, or_, func, Integer, case
from ...database.models.download_tracker import DownloadTracker
from ...database.models.library import (
- Document as LibraryDocument,
+ Document,
Collection,
DocumentCollection,
)
@@ -74,7 +74,7 @@ class LibraryService:
return False
def _apply_domain_filter(self, query, model_class, domain: str):
- """Apply domain filter to query for LibraryDocument."""
+ """Apply domain filter to query for Document."""
if domain == "arxiv.org":
return query.filter(model_class.original_url.like("%arxiv.org%"))
elif domain == "pubmed":
@@ -96,7 +96,7 @@ class LibraryService:
return query.filter(model_class.original_url.like(f"%{domain}%"))
def _apply_search_filter(self, query, model_class, search_query: str):
- """Apply search filter to query for LibraryDocument."""
+ """Apply search filter to query for Document."""
search_pattern = f"%{search_query}%"
return query.filter(
or_(
@@ -111,17 +111,15 @@ class LibraryService:
"""Get overall library statistics."""
with get_user_db_session(self.username) as session:
# Get document counts
- total_docs = session.query(LibraryDocument).count()
+ total_docs = session.query(Document).count()
total_pdfs = (
- session.query(LibraryDocument)
- .filter_by(file_type="pdf")
- .count()
+ session.query(Document).filter_by(file_type="pdf").count()
)
# Get size stats
size_result = session.query(
- func.sum(LibraryDocument.file_size),
- func.avg(LibraryDocument.file_size),
+ func.sum(Document.file_size),
+ func.avg(Document.file_size),
).first()
total_size = size_result[0] or 0
@@ -129,7 +127,7 @@ class LibraryService:
# Get research stats
research_count = session.query(
- func.count(func.distinct(LibraryDocument.research_id))
+ func.count(func.distinct(Document.research_id))
).scalar()
# Get domain stats - count unique domains from URLs
@@ -141,17 +139,15 @@ class LibraryService:
sql_func.distinct(
case(
(
- LibraryDocument.original_url.like("%arxiv.org%"),
+ Document.original_url.like("%arxiv.org%"),
"arxiv.org",
),
(
- LibraryDocument.original_url.like("%pubmed%"),
+ Document.original_url.like("%pubmed%"),
"pubmed",
),
(
- LibraryDocument.original_url.like(
- "%ncbi.nlm.nih.gov%"
- ),
+ Document.original_url.like("%ncbi.nlm.nih.gov%"),
"pubmed",
),
else_="other",
@@ -209,65 +205,73 @@ class LibraryService:
if not collection_id:
collection_id = get_default_library_id(self.username)
+ logger.info(
+ f"[LibraryService] Getting documents for collection_id: {collection_id}, research_id: {research_id}, domain: {domain}"
+ )
+
all_documents = []
# Query documents - join with DocumentCollection to filter by collection
+ # Use outer joins for ResearchResource and ResearchHistory to include user uploads
query = (
session.query(
- LibraryDocument,
+ Document,
ResearchResource,
ResearchHistory,
DocumentCollection,
)
.join(
DocumentCollection,
- LibraryDocument.id == DocumentCollection.document_id,
+ Document.id == DocumentCollection.document_id,
)
- .join(
+ .outerjoin(
ResearchResource,
- LibraryDocument.resource_id == ResearchResource.id,
+ Document.resource_id == ResearchResource.id,
)
- .join(
+ .outerjoin(
ResearchHistory,
- LibraryDocument.research_id == ResearchHistory.id,
+ Document.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(Document.research_id == research_id)
if domain:
- query = self._apply_domain_filter(
- query, LibraryDocument, domain
- )
+ query = self._apply_domain_filter(query, Document, domain)
if file_type:
- query = query.filter(LibraryDocument.file_type == file_type)
+ query = query.filter(Document.file_type == file_type)
if favorites_only:
- query = query.filter(LibraryDocument.favorite.is_(True))
+ query = query.filter(Document.favorite.is_(True))
if search_query:
- query = self._apply_search_filter(
- query, LibraryDocument, search_query
- )
+ query = self._apply_search_filter(query, Document, search_query)
# Filter to only completed documents
- query = query.filter(LibraryDocument.status == "completed")
+ query = query.filter(Document.status == "completed")
# Apply safety limit to prevent memory issues
query = query.limit(500000)
# Execute query
results = query.all()
+ logger.info(
+ f"[LibraryService] Found {len(results)} documents in collection {collection_id}"
+ )
# Process results
for doc, resource, research, doc_collection in results:
# Determine availability flags - use Document.file_path directly
file_absolute_path = None
- if doc.file_path and doc.file_path != "metadata_only":
+ if (
+ doc.file_path
+ and doc.file_path != "metadata_only"
+ and doc.file_path != "text_only_not_stored"
+ ):
file_absolute_path = str(
get_absolute_path_from_settings(doc.file_path)
)
@@ -289,7 +293,8 @@ class LibraryService:
"resource_id": doc.resource_id,
"research_id": doc.research_id,
# Document info
- "document_title": doc.title or resource.title,
+ "document_title": doc.title
+ or (resource.title if resource else doc.filename),
"authors": doc.authors,
"published_date": doc.published_date,
"doi": doc.doi,
@@ -305,22 +310,38 @@ class LibraryService:
"file_type": doc.file_type,
# URLs
"original_url": doc.original_url,
- "domain": self._extract_domain(doc.original_url),
+ "domain": self._extract_domain(doc.original_url)
+ if doc.original_url
+ else "User Upload",
# Status
- "download_status": doc.status,
+ "download_status": doc.status or "completed",
"downloaded_at": doc.processed_at.isoformat()
if doc.processed_at
+ else (
+ doc.uploaded_at.isoformat()
+ if hasattr(doc, "uploaded_at") and doc.uploaded_at
+ else None
+ ),
+ "favorite": doc.favorite
+ if hasattr(doc, "favorite")
+ else False,
+ "tags": doc.tags if hasattr(doc, "tags") else [],
+ # Research info (None for user uploads)
+ "research_title": research.title or research.query[:80]
+ if research
+ else "User Upload",
+ "research_query": research.query if research else None,
+ "research_mode": research.mode if research else None,
+ "research_date": research.created_at
+ if research
else None,
- "favorite": doc.favorite,
- "tags": doc.tags,
- # 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(doc.original_url),
- "is_pubmed": self._is_pubmed_url(doc.original_url),
+ "is_arxiv": self._is_arxiv_url(doc.original_url)
+ if doc.original_url
+ else False,
+ "is_pubmed": self._is_pubmed_url(doc.original_url)
+ if doc.original_url
+ else False,
"is_pdf": doc.file_type == "pdf",
# Availability flags
"has_pdf": has_pdf,
@@ -328,7 +349,12 @@ class LibraryService:
"has_rag_indexed": has_rag_indexed,
"rag_chunk_count": rag_chunk_count,
# Sort key
- "_sort_date": doc.processed_at,
+ "_sort_date": doc.processed_at
+ or (
+ doc.uploaded_at
+ if hasattr(doc, "uploaded_at")
+ else None
+ ),
}
)
@@ -367,8 +393,13 @@ class LibraryService:
.all()
)
+ logger.info(f"[LibraryService] Found {len(results)} collections")
+
collections = []
for collection, doc_count in results:
+ logger.debug(
+ f"[LibraryService] Collection: {collection.name} (ID: {collection.id}), documents: {doc_count}"
+ )
collections.append(
{
"id": collection.id,
@@ -391,7 +422,7 @@ class LibraryService:
func.count(ResearchResource.id).label("total_resources"),
func.count(
case(
- (LibraryDocument.status == "completed", 1),
+ (Document.status == "completed", 1),
else_=None,
)
).label("downloaded_count"),
@@ -411,8 +442,8 @@ class LibraryService:
ResearchHistory.id == ResearchResource.research_id,
)
.outerjoin(
- LibraryDocument,
- ResearchResource.id == LibraryDocument.resource_id,
+ Document,
+ ResearchResource.id == Document.resource_id,
)
.group_by(ResearchHistory.id)
.order_by(ResearchHistory.created_at.desc())
@@ -483,20 +514,18 @@ class LibraryService:
Returns document information with file path.
"""
with get_user_db_session(self.username) as session:
- # Find document
+ # Find document - use outer joins to support both research downloads and user uploads
result = (
- session.query(
- LibraryDocument, ResearchResource, ResearchHistory
- )
- .join(
+ session.query(Document, ResearchResource, ResearchHistory)
+ .outerjoin(
ResearchResource,
- LibraryDocument.resource_id == ResearchResource.id,
+ Document.resource_id == ResearchResource.id,
)
- .join(
+ .outerjoin(
ResearchHistory,
- LibraryDocument.research_id == ResearchHistory.id,
+ Document.research_id == ResearchHistory.id,
)
- .filter(LibraryDocument.id == doc_id)
+ .filter(Document.id == doc_id)
.first()
)
@@ -504,45 +533,84 @@ class LibraryService:
# Found document
doc, resource, research = result
+ # Get RAG indexing status across all collections
+ doc_collections = (
+ session.query(DocumentCollection)
+ .filter(DocumentCollection.document_id == doc_id)
+ .all()
+ )
+
+ # Check if indexed in any collection
+ has_rag_indexed = any(dc.indexed for dc in doc_collections)
+ total_chunks = sum(
+ dc.chunk_count for dc in doc_collections if dc.indexed
+ )
+
+ # Calculate word count from text content
+ word_count = (
+ len(doc.text_content.split()) if doc.text_content else 0
+ )
+
+ # Check if actual PDF file exists (not just text_only_not_stored)
+ has_pdf = bool(
+ doc.file_path
+ and doc.file_path != "metadata_only"
+ and doc.file_path != "text_only_not_stored"
+ )
+
return {
"id": doc.id,
"resource_id": doc.resource_id,
"research_id": doc.research_id,
- "document_title": doc.title or resource.title,
- "original_url": doc.original_url or resource.url,
+ "document_title": doc.title
+ or (resource.title if resource else doc.filename),
+ "original_url": doc.original_url
+ or (resource.url if resource else None),
"file_path": doc.file_path,
"file_absolute_path": str(
get_absolute_path_from_settings(doc.file_path)
)
- if doc.file_path and doc.file_path != "metadata_only"
+ if has_pdf
else None,
"file_name": Path(doc.file_path).name
- if doc.file_path and doc.file_path != "metadata_only"
- else None,
+ if has_pdf
+ else doc.filename,
"file_size": doc.file_size,
"file_type": doc.file_type,
"mime_type": doc.mime_type,
- "domain": self._extract_domain(resource.url),
+ "domain": self._extract_domain(resource.url)
+ if resource
+ else "User Upload",
"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,
- "research_title": research.query[:100],
+ else (
+ doc.uploaded_at.isoformat()
+ if hasattr(doc, "uploaded_at") and doc.uploaded_at
+ else None
+ ),
+ "favorite": doc.favorite
+ if hasattr(doc, "favorite")
+ else False,
+ "tags": doc.tags if hasattr(doc, "tags") else [],
+ "research_title": research.query[:100]
+ if research
+ else "User Upload",
"research_created_at": research.created_at
- if isinstance(research.created_at, str)
+ if research and isinstance(research.created_at, str)
else research.created_at.isoformat()
- if research.created_at
+ if research and research.created_at
else None,
# Document fields
"is_pdf": doc.file_type == "pdf",
- "has_text_db": bool(
- doc.text_content
- ), # Text now in Document
+ "has_pdf": has_pdf,
+ "has_text_db": bool(doc.text_content),
+ "has_rag_indexed": has_rag_indexed,
+ "rag_chunk_count": total_chunks,
+ "word_count": word_count,
}
# Not found
@@ -551,7 +619,7 @@ class LibraryService:
def toggle_favorite(self, document_id: str) -> bool:
"""Toggle favorite status of a document."""
with get_user_db_session(self.username) as session:
- doc = session.query(LibraryDocument).get(document_id)
+ doc = session.query(Document).get(document_id)
if doc:
doc.favorite = not doc.favorite
session.commit()
@@ -561,7 +629,7 @@ class LibraryService:
def delete_document(self, document_id: str) -> bool:
"""Delete a document from library (file and database entry)."""
with get_user_db_session(self.username) as session:
- doc = session.query(LibraryDocument).get(document_id)
+ doc = session.query(Document).get(document_id)
if not doc:
return False
@@ -598,7 +666,7 @@ class LibraryService:
def open_file_location(self, document_id: str) -> bool:
"""Open the folder containing the document."""
with get_user_db_session(self.username) as session:
- doc = session.query(LibraryDocument).get(document_id)
+ doc = session.query(Document).get(document_id)
if not doc:
return False
@@ -628,17 +696,15 @@ class LibraryService:
func.distinct(
case(
(
- LibraryDocument.original_url.like(
- "%arxiv.org%"
- ),
+ Document.original_url.like("%arxiv.org%"),
"arxiv.org",
),
(
- LibraryDocument.original_url.like("%pubmed%"),
+ Document.original_url.like("%pubmed%"),
"pubmed",
),
(
- LibraryDocument.original_url.like(
+ Document.original_url.like(
"%ncbi.nlm.nih.gov%"
),
"pubmed",
@@ -647,7 +713,7 @@ class LibraryService:
)
)
)
- .filter(LibraryDocument.original_url.isnot(None))
+ .filter(Document.original_url.isnot(None))
.all()
)
@@ -698,9 +764,7 @@ class LibraryService:
with get_user_db_session(self.username) as session:
# Get all documents marked as completed
documents = (
- session.query(LibraryDocument)
- .filter_by(status="completed")
- .all()
+ session.query(Document).filter_by(status="completed").all()
)
stats = {
@@ -771,7 +835,7 @@ class LibraryService:
with get_user_db_session(self.username) as session:
count = 0
for doc_id in document_ids:
- doc = session.query(LibraryDocument).get(doc_id)
+ doc = session.query(Document).get(doc_id)
if doc:
# Get tracker and reset it
tracker = (
diff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.py
index d6f3597069..577909e633 100644
--- a/src/local_deep_research/web/routes/history_routes.py
+++ b/src/local_deep_research/web/routes/history_routes.py
@@ -4,7 +4,7 @@ import traceback
from flask import Blueprint, jsonify, make_response, session, request
from ...database.models import ResearchHistory
-from ...database.models.library import Document as LibraryDocument
+from ...database.models.library import Document as Document
from ...database.session_context import get_user_db_session
from ..auth.decorators import login_required
from ..models.database import (
@@ -51,7 +51,7 @@ def get_history():
for research in results:
# Count documents in the library for this research
doc_count = (
- db_session.query(LibraryDocument)
+ db_session.query(Document)
.filter_by(research_id=research.id)
.count()
)
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index 60a4efd0bb..16495f06b9 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -25,7 +25,7 @@ from ...database.models import (
ResearchLog,
UserActiveResearch,
)
-from ...database.models.library import Document as LibraryDocument
+from ...database.models.library import Document as Document
from ...database.session_context import get_user_db_session
from ..auth.decorators import login_required
from ..models.database import calculate_duration
@@ -1023,7 +1023,7 @@ def get_history():
# Count documents in the library for this research
doc_count = (
- db_session.query(LibraryDocument)
+ db_session.query(Document)
.filter_by(research_id=research.id)
.count()
)
diff --git a/src/local_deep_research/web/static/css/collection_details.css b/src/local_deep_research/web/static/css/collection_details.css
index 37ba009ff7..7daed15bf5 100644
--- a/src/local_deep_research/web/static/css/collection_details.css
+++ b/src/local_deep_research/web/static/css/collection_details.css
@@ -3,9 +3,9 @@
max-width: 1200px;
margin: 0 auto;
padding: 2rem;
- background: #f7fafc !important;
+ background: var(--bg-primary, #121212) !important;
min-height: 100vh;
- color: #2d3748 !important;
+ color: var(--text-primary, #e4e4e4) !important;
}
@media (prefers-reduced-motion: no-preference) {
@@ -16,13 +16,13 @@
/* Header Section */
.ldr-rag-header {
- background: #ffffff !important;
+ background: var(--card-bg, #1e1e2d) !important;
border-radius: 16px;
padding: 30px;
margin-bottom: 25px;
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
- border: 1px solid #e2e8f0;
- color: #2d3748 !important;
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
+ border: 1px solid var(--border-color, #333);
+ color: var(--text-primary, #e4e4e4) !important;
}
@media (prefers-reduced-motion: no-preference) {
@@ -32,7 +32,7 @@
}
.ldr-rag-header h1 {
- color: #2d3748 !important;
+ color: var(--text-primary, #e4e4e4) !important;
font-size: 2.5rem;
font-weight: 700;
margin: 15px 0;
@@ -46,7 +46,7 @@
}
.ldr-subtitle {
- color: #4a5568;
+ color: var(--text-secondary, #999);
font-size: 1.1rem;
margin: 10px 0 0 0;
font-style: italic;
@@ -54,12 +54,12 @@
/* Section Styling */
.ldr-rag-section {
- background: #ffffff;
+ background: var(--card-bg, #1e1e2d);
border-radius: 16px;
padding: 25px;
margin-bottom: 25px;
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
- border: 1px solid #e2e8f0;
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
+ border: 1px solid var(--border-color, #333);
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
@@ -80,11 +80,11 @@
align-items: center;
margin-bottom: 20px;
padding-bottom: 15px;
- border-bottom: 2px solid #e2e8f0;
+ border-bottom: 2px solid var(--border-color, #444);
}
.ldr-section-header h2 {
- color: #2d3748;
+ color: var(--text-primary, #e4e4e4);
font-size: 1.5rem;
font-weight: 600;
display: flex;
@@ -873,7 +873,7 @@
display: block;
margin-bottom: 0.5rem;
font-weight: 600;
- color: #2d3748;
+ color: var(--text-primary, #e4e4e4);
font-size: 0.95rem;
}
@@ -881,10 +881,10 @@
.ldr-form-group textarea {
width: 100%;
padding: 0.75rem 1rem;
- border: 2px solid #e2e8f0;
+ border: 2px solid var(--border-color, #444);
border-radius: 10px;
- background-color: #ffffff;
- color: #2d3748;
+ background-color: var(--input-bg, #1a1a1a);
+ color: var(--text-primary, #e4e4e4);
font-family: inherit;
font-size: 1rem;
transition: all 0.3s ease;
@@ -909,11 +909,11 @@
justify-content: flex-end;
margin-top: 2rem;
padding-top: 1.5rem;
- border-top: 1px solid #e2e8f0;
+ border-top: 1px solid var(--border-color, #444);
}
.ldr-form-help {
- color: #4a5568;
+ color: var(--text-secondary, #999);
font-size: 0.9rem;
margin-top: 0.5rem;
font-style: italic;
@@ -1145,14 +1145,13 @@
}
.ldr-featured-section {
- background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
- background-color: #ffffff;
+ background: linear-gradient(135deg, rgba(102, 126, 234, 0.15) 0%, rgba(118, 75, 162, 0.15) 100%), var(--card-bg, #1e1e2d) !important;
border: 2px solid #667eea;
}
.ldr-char-counter {
font-size: 0.875rem;
- color: #718096;
+ color: var(--text-secondary, #999);
margin-top: 0.25rem;
}
@@ -1162,7 +1161,7 @@
.ldr-text-center-muted {
text-align: center;
- color: #718096;
+ color: var(--text-secondary, #999);
font-style: italic;
margin-bottom: 1rem;
}
@@ -1185,7 +1184,7 @@
/* Guidelines styling */
.ldr-content-padding h3 {
- color: #2d3748;
+ color: var(--text-primary, #e4e4e4);
font-size: 1.1rem;
font-weight: 600;
margin-top: 1.5rem;
@@ -1213,7 +1212,7 @@
padding: 0.5rem 0;
padding-left: 1.5rem;
position: relative;
- color: #2d3748;
+ color: var(--text-primary, #e4e4e4);
line-height: 1.6;
}
@@ -1228,7 +1227,7 @@
/* Info Text */
.ldr-info-text {
font-size: 1rem;
- color: #2d3748;
+ color: var(--text-primary, #e4e4e4);
margin-bottom: 1rem;
line-height: 1.6;
}
@@ -1246,7 +1245,7 @@
align-items: flex-start;
gap: 1rem;
padding: 1rem;
- background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
+ background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
border-left: 3px solid #667eea;
border-radius: 8px;
}
@@ -1259,10 +1258,10 @@
}
.ldr-tip-item div {
- color: #2d3748;
+ color: var(--text-primary, #e4e4e4);
line-height: 1.6;
}
.ldr-tip-item strong {
- color: #667eea;
+ color: #8b9cff;
}
diff --git a/src/local_deep_research/web/static/js/collection_create.js b/src/local_deep_research/web/static/js/collection_create.js
index 9ebed1b1ec..2647eb8deb 100644
--- a/src/local_deep_research/web/static/js/collection_create.js
+++ b/src/local_deep_research/web/static/js/collection_create.js
@@ -21,26 +21,40 @@ async function safeFetch(url, options = {}) {
* Initialize the create page
*/
document.addEventListener('DOMContentLoaded', function() {
+ console.log('Collection create page loaded');
+ console.log('URLS available:', typeof URLS !== 'undefined', URLS);
+ console.log('URLValidator available:', typeof URLValidator !== 'undefined', URLValidator);
+ console.log('COLLECTION_CREATE URL:', URLS?.LIBRARY_API?.COLLECTION_CREATE);
+
// Setup form submission
- document.getElementById('create-collection-form').addEventListener('submit', handleCreateCollection);
+ const form = document.getElementById('create-collection-form');
+ if (form) {
+ console.log('Form found, attaching submit handler');
+ form.addEventListener('submit', handleCreateCollection);
+ } else {
+ console.error('Form not found!');
+ }
// Setup name input character counter
const nameInput = document.getElementById('collection-name');
- nameInput.addEventListener('input', function(e) {
- const maxLength = 100;
- const currentLength = e.target.value.length;
- const remaining = maxLength - currentLength;
- const counter = document.getElementById('name-counter');
- if (counter) {
- counter.textContent = `${remaining} characters remaining`;
- }
- });
+ if (nameInput) {
+ nameInput.addEventListener('input', function(e) {
+ const maxLength = 100;
+ const currentLength = e.target.value.length;
+ const remaining = maxLength - currentLength;
+ const counter = document.getElementById('name-counter');
+ if (counter) {
+ counter.textContent = `${remaining} characters remaining`;
+ }
+ });
+ }
});
/**
* Handle collection creation
*/
async function handleCreateCollection(e) {
+ console.log('Create collection submit handler called');
e.preventDefault();
// Get form data
@@ -105,8 +119,9 @@ async function handleCreateCollection(e) {
showError('Failed to create collection: ' + error.message);
} finally {
submitBtn.disabled = false;
- submitBtn.innerHTML = '<i class="fas fa-folder-plus"></i> 🚀 Create Collection';
+ submitBtn.innerHTML = '<i class="fas fa-folder-plus"></i> Create Collection';
createBtn.disabled = false;
+ createBtn.innerHTML = '<i class="fas fa-folder-plus"></i> Create Collection';
}
}
diff --git a/src/local_deep_research/web/static/js/collection_upload.js b/src/local_deep_research/web/static/js/collection_upload.js
index b09c342f45..6ac8f183d4 100644
--- a/src/local_deep_research/web/static/js/collection_upload.js
+++ b/src/local_deep_research/web/static/js/collection_upload.js
@@ -224,7 +224,26 @@ async function handleUploadFiles(e) {
body: formData
});
+ console.log('📨 Response status:', response.status);
+ console.log('📨 Response content-type:', response.headers.get('content-type'));
+
+ // Check if response is OK
+ if (!response.ok) {
+ const errorText = await response.text();
+ console.error('❌ Server error response:', errorText);
+ throw new Error(`Server returned ${response.status}: ${errorText.substring(0, 100)}`);
+ }
+
+ // Check if response is JSON
+ const contentType = response.headers.get('content-type');
+ if (!contentType || !contentType.includes('application/json')) {
+ const responseText = await response.text();
+ console.error('❌ Non-JSON response:', responseText);
+ throw new Error(`Expected JSON but got: ${contentType}. Response: ${responseText.substring(0, 100)}`);
+ }
+
const data = await response.json();
+ console.log('✅ Parsed JSON data:', data);
if (data.success) {
updateProgressComplete(data);
diff --git a/src/local_deep_research/web/static/js/security/url-validator.js b/src/local_deep_research/web/static/js/security/url-validator.js
index a4119dd103..6eab64faad 100644
--- a/src/local_deep_research/web/static/js/security/url-validator.js
+++ b/src/local_deep_research/web/static/js/security/url-validator.js
@@ -138,3 +138,8 @@ const URLValidator = {
if (typeof module !== 'undefined' && module.exports) {
module.exports = URLValidator;
}
+
+// Make URLValidator available globally for browser usage
+if (typeof window !== 'undefined') {
+ window.URLValidator = URLValidator;
+}
diff --git a/src/local_deep_research/web/templates/pages/document_chunks.html b/src/local_deep_research/web/templates/pages/document_chunks.html
new file mode 100644
index 0000000000..94123ad8a0
--- /dev/null
+++ b/src/local_deep_research/web/templates/pages/document_chunks.html
@@ -0,0 +1,192 @@
+{% extends "base.html" %}
+
+{% block extra_head %}
+<style>
+ .ldr-chunks-container {
+ max-width: 1200px;
+ margin: 20px auto;
+ padding: 20px;
+ }
+
+ .ldr-chunks-header {
+ background: var(--card-bg, #1e1e2d);
+ padding: 20px;
+ border-radius: 8px;
+ margin-bottom: 20px;
+ border: 1px solid var(--border-color, #333);
+ }
+
+ .ldr-chunks-header h1 {
+ margin: 0 0 10px 0;
+ color: var(--text-primary, #e4e4e4);
+ }
+
+ .ldr-chunks-stats {
+ color: var(--text-secondary, #999);
+ font-size: 14px;
+ }
+
+ .ldr-collection-section {
+ background: var(--card-bg, #1e1e2d);
+ border: 1px solid var(--border-color, #333);
+ border-radius: 8px;
+ margin-bottom: 20px;
+ overflow: hidden;
+ }
+
+ .ldr-collection-header {
+ background: linear-gradient(135deg, rgba(102, 126, 234, 0.15) 0%, rgba(118, 75, 162, 0.15) 100%);
+ padding: 15px 20px;
+ border-bottom: 1px solid var(--border-color, #333);
+ }
+
+ .ldr-collection-header h2 {
+ margin: 0;
+ color: var(--text-primary, #e4e4e4);
+ font-size: 18px;
+ }
+
+ .ldr-collection-header .ldr-chunk-count {
+ color: var(--text-secondary, #999);
+ font-size: 14px;
+ margin-top: 5px;
+ }
+
+ .ldr-chunk {
+ border-bottom: 1px solid var(--border-color, #2a2a3a);
+ padding: 20px;
+ }
+
+ .ldr-chunk:last-child {
+ border-bottom: none;
+ }
+
+ .ldr-chunk-meta {
+ display: flex;
+ gap: 20px;
+ margin-bottom: 10px;
+ flex-wrap: wrap;
+ }
+
+ .ldr-chunk-meta-item {
+ color: var(--text-secondary, #999);
+ font-size: 13px;
+ }
+
+ .ldr-chunk-meta-item strong {
+ color: var(--text-primary, #e4e4e4);
+ }
+
+ .ldr-chunk-text {
+ background: var(--input-bg, #1a1a1a);
+ border: 1px solid var(--border-color, #333);
+ border-radius: 4px;
+ padding: 15px;
+ color: var(--text-primary, #e4e4e4);
+ line-height: 1.6;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ font-family: 'Courier New', monospace;
+ font-size: 14px;
+ }
+
+ .ldr-embedding-info {
+ margin-top: 10px;
+ padding: 10px;
+ background: rgba(102, 126, 234, 0.1);
+ border-radius: 4px;
+ font-size: 12px;
+ color: var(--text-secondary, #999);
+ }
+
+ .ldr-embedding-info strong {
+ color: var(--text-primary, #e4e4e4);
+ }
+
+ .ldr-back-button {
+ display: inline-block;
+ padding: 10px 20px;
+ background: var(--button-secondary-bg, #6c757d);
+ color: white;
+ text-decoration: none;
+ border-radius: 4px;
+ margin-bottom: 20px;
+ }
+
+ .ldr-back-button:hover {
+ background: var(--button-secondary-hover, #545b62);
+ color: white;
+ }
+
+ .ldr-no-chunks {
+ text-align: center;
+ padding: 40px;
+ color: var(--text-secondary, #999);
+ }
+</style>
+{% endblock %}
+
+{% block content %}
+<div class="ldr-chunks-container">
+ <a href="/library/document/{{ document.id }}" class="ldr-back-button">
+ <i class="fas fa-arrow-left"></i> Back to Document
+ </a>
+
+ <div class="ldr-chunks-header">
+ <h1><i class="fas fa-puzzle-piece"></i> Document Chunks</h1>
+ <div class="ldr-chunks-stats">
+ <strong>Document:</strong> {{ document.filename or document.title or "Untitled" }}<br>
+ <strong>Total Chunks:</strong> {{ total_chunks }} chunk{{ 's' if total_chunks != 1 else '' }} across {{ chunks_by_collection|length }} collection{{ 's' if chunks_by_collection|length != 1 else '' }}
+ </div>
+ </div>
+
+ {% if chunks_by_collection %}
+ {% for collection_name, collection_data in chunks_by_collection.items() %}
+ <div class="ldr-collection-section">
+ <div class="ldr-collection-header">
+ <h2>{{ collection_data.name }}</h2>
+ <div class="ldr-chunk-count">
+ {{ collection_data.chunks|length }} chunk{{ 's' if collection_data.chunks|length != 1 else '' }}
+ </div>
+ </div>
+
+ {% for chunk in collection_data.chunks %}
+ <div class="ldr-chunk">
+ <div class="ldr-chunk-meta">
+ <div class="ldr-chunk-meta-item">
+ <strong>Chunk #{{ chunk.index + 1 }}</strong>
+ </div>
+ <div class="ldr-chunk-meta-item">
+ <strong>Words:</strong> {{ chunk.word_count }}
+ </div>
+ <div class="ldr-chunk-meta-item">
+ <strong>Position:</strong> {{ chunk.start_char }}-{{ chunk.end_char }}
+ </div>
+ <div class="ldr-chunk-meta-item">
+ <strong>ID:</strong> <code>{{ chunk.id }}</code>
+ </div>
+ </div>
+
+ <div class="ldr-chunk-text">{{ chunk.text }}</div>
+
+ <div class="ldr-embedding-info">
+ <i class="fas fa-brain"></i>
+ <strong>Embedding:</strong> {{ chunk.embedding_model }} ({{ chunk.embedding_model_type }})
+ {% if chunk.embedding_dimension %}
+ | <strong>Dimension:</strong> {{ chunk.embedding_dimension }}
+ {% endif %}
+ | <strong>Created:</strong> {{ chunk.created_at.strftime('%Y-%m-%d %H:%M') if chunk.created_at else 'N/A' }}
+ </div>
+ </div>
+ {% endfor %}
+ </div>
+ {% endfor %}
+ {% else %}
+ <div class="ldr-no-chunks">
+ <i class="fas fa-inbox" style="font-size: 48px; margin-bottom: 20px; display: block;"></i>
+ <p>No chunks found for this document.</p>
+ <p>The document may not be indexed yet.</p>
+ </div>
+ {% endif %}
+</div>
+{% endblock %}
diff --git a/src/local_deep_research/web/templates/pages/document_details.html b/src/local_deep_research/web/templates/pages/document_details.html
index 993ccd88f5..af0b24bbd7 100644
--- a/src/local_deep_research/web/templates/pages/document_details.html
+++ b/src/local_deep_research/web/templates/pages/document_details.html
@@ -27,7 +27,7 @@
{% endif %}
<div class="ldr-document-actions">
- {% if document.file_absolute_path or document.is_pdf %}
+ {% if document.has_pdf %}
<a href="/library/document/{{ document.id }}/pdf" target="_blank" class="ldr-btn ldr-btn-primary">
<i class="fas fa-file-pdf"></i> View PDF
</a>
@@ -164,15 +164,19 @@
<div class="ldr-metadata-item">
<div class="ldr-metadata-label">RAG Indexed</div>
<div class="ldr-metadata-value">
+ {% if document.has_rag_indexed %}
+ <a href="/library/document/{{ document.id }}/chunks" style="text-decoration: none; color: inherit;">
+ <div class="ldr-rag-status" style="cursor: pointer;">
+ <i class="fas fa-check-circle" style="color: var(--ldr-success-color, #28a745);"></i>
+ <span>Yes ({{ document.rag_chunk_count }} chunks) <i class="fas fa-external-link-alt" style="font-size: 0.8em; margin-left: 5px;"></i></span>
+ </div>
+ </a>
+ {% else %}
<div class="ldr-rag-status">
- {% if document.rag_indexed %}
- <i class="fas fa-check-circle" style="color: var(--ldr-success-color, #28a745);"></i>
- <span>Yes ({{ document.chunk_count }} chunks)</span>
- {% else %}
<i class="fas fa-times-circle" style="color: var(--ldr-warning-color, #ffc107);"></i>
<span>Not indexed</span>
- {% endif %}
</div>
+ {% endif %}
</div>
</div>
diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.html
index 673c9ad53b..d4dc356517 100644
--- a/src/local_deep_research/web/templates/pages/library.html
+++ b/src/local_deep_research/web/templates/pages/library.html
@@ -221,9 +221,9 @@
</a>
{% endif %}
{% if doc.has_rag_indexed %}
- <div class="ldr-action-btn ldr-action-btn-rag" title="{{ doc.rag_chunk_count }} chunks indexed">
+ <a href="/library/document/{{ doc.id }}/chunks" class="ldr-action-btn ldr-action-btn-rag" title="{{ doc.rag_chunk_count }} chunks indexed">
<i class="fas fa-brain"></i> RAG Indexed
- </div>
+ </a>
{% endif %}
{% if not doc.has_pdf and not doc.has_text_db %}
<div class="ldr-action-btn ldr-action-btn-none">
diff --git a/src/local_deep_research/web_search_engines/search_engines_config.py b/src/local_deep_research/web_search_engines/search_engines_config.py
index 28ec530508..42de4e48c0 100644
--- a/src/local_deep_research/web_search_engines/search_engines_config.py
+++ b/src/local_deep_research/web_search_engines/search_engines_config.py
@@ -242,7 +242,7 @@ def search_config(
# Register document collections as individual search engines
if library_enabled:
try:
- from ..database.models.library import LibraryCollection
+ from ..database.models.library import Collection
from ..database.session_context import get_user_db_session
# Get username from settings_snapshot if available
@@ -254,7 +254,7 @@ def search_config(
if collection_username:
with get_user_db_session(collection_username) as session:
- collections = session.query(LibraryCollection).all()
+ collections = session.query(Collection).all()
for collection in collections:
engine_id = f"collection_{collection.id}"