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.

current state RAG

LearningCircuit9edccafe1593
diff --git a/src/local_deep_research/database/models/__init__.py b/src/local_deep_research/database/models/__init__.py
index 06bc9d2709..0ec8a8555d 100644
--- a/src/local_deep_research/database/models/__init__.py
+++ b/src/local_deep_research/database/models/__init__.py
@@ -58,6 +58,10 @@ from .library import (
LibraryStatistics,
LibraryTextDocument,
RAGIndex,
+ UserDocument,
+ UserDocumentCollection,
+ CollectionFolder,
+ CollectionFolderFile,
)
from .download_tracker import (
DownloadTracker,
@@ -140,6 +144,10 @@ __all__ = [
"LibraryStatistics",
"LibraryTextDocument",
"RAGIndex",
+ "UserDocument",
+ "UserDocumentCollection",
+ "CollectionFolder",
+ "CollectionFolderFile",
# 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 5e5cc5d2b8..ad55f98721 100644
--- a/src/local_deep_research/database/models/library.py
+++ b/src/local_deep_research/database/models/library.py
@@ -11,6 +11,7 @@ from sqlalchemy import (
ForeignKey,
Index,
Integer,
+ LargeBinary,
String,
Text,
UniqueConstraint,
@@ -29,7 +30,7 @@ class LibraryDocument(Base):
__tablename__ = "library_documents"
- id = Column(Integer, primary_key=True, autoincrement=True)
+ id = Column(String(36), primary_key=True) # UUID as string
# Link to the original resource
resource_id = Column(
@@ -115,7 +116,7 @@ class LibraryTextDocument(Base):
__tablename__ = "library_text_documents"
- id = Column(Integer, primary_key=True, autoincrement=True)
+ id = Column(String(36), primary_key=True) # UUID as string
# Link to the original resource
resource_id = Column(
@@ -134,7 +135,7 @@ class LibraryTextDocument(Base):
# Link to PDF document if extracted from PDF
document_id = Column(
- Integer,
+ String(36),
ForeignKey("library_documents.id", ondelete="SET NULL"),
nullable=True,
)
@@ -241,16 +242,16 @@ class DocumentChunk(Base):
# Chunk identification
chunk_hash = Column(
- String(64), nullable=False, unique=True, index=True
- ) # SHA256 for deduplication
+ String(64), nullable=False, index=True
+ ) # SHA256 for deduplication (not unique - same chunk can be in multiple collections)
# Source tracking
source_type = Column(
String(20), nullable=False, index=True
- ) # 'library', 'local_file'
+ ) # 'library', 'user_upload', 'folder_file'
source_id = Column(
- Integer, nullable=True
- ) # LibraryTextDocument.id if library source
+ String(36), nullable=True
+ ) # LibraryTextDocument.id if library source (UUID as string)
source_path = Column(
Text, nullable=True
) # File path if local collection source
@@ -289,6 +290,7 @@ class DocumentChunk(Base):
# Indexes for efficient queries
__table_args__ = (
+ UniqueConstraint("chunk_hash", "collection_name", name="uix_chunk_collection"),
Index("idx_chunk_source", "source_type", "source_id"),
Index("idx_chunk_collection", "collection_name", "created_at"),
Index("idx_chunk_embedding", "embedding_id"),
@@ -305,14 +307,19 @@ class LibraryCollection(Base):
__tablename__ = "library_collections"
- id = Column(Integer, primary_key=True, autoincrement=True)
+ id = Column(String(36), primary_key=True) # UUID as string
name = Column(String(255), nullable=False)
description = Column(Text)
- # Collection metadata
- color = Column(String(7)) # Hex color for UI
- icon = Column(String(50)) # Icon identifier
- is_public = Column(Boolean, default=False) # For future sharing features
+ # Collection type (user_uploads, linked_folder, research_library)
+ collection_type = Column(String(50), default="user_uploads")
+
+ # Embedding model used for this collection (stored when first indexed)
+ embedding_model = Column(String(100), nullable=True) # e.g., 'all-MiniLM-L6-v2'
+ embedding_model_type = Column(String(50), nullable=True) # 'sentence_transformers', 'ollama'
+ embedding_dimension = Column(Integer, nullable=True) # Vector dimension
+ chunk_size = Column(Integer, nullable=True) # Chunk size used
+ chunk_overlap = Column(Integer, nullable=True) # Chunk overlap used
# Timestamps
created_at = Column(UtcDateTime, default=utcnow(), nullable=False)
@@ -321,14 +328,11 @@ class LibraryCollection(Base):
)
# Relationships
- documents = relationship(
- "LibraryDocument",
- secondary="library_collection_documents",
- backref="collections",
- )
+ # Note: user_documents relationship is defined via backref in UserDocumentCollection
+ # linked_folders relationship is defined via backref in CollectionFolder
def __repr__(self):
- return f"<LibraryCollection(name='{self.name}', documents={len(self.documents)})>"
+ return f"<LibraryCollection(id='{self.id}', name='{self.name}', type='{self.collection_type}')>"
class LibraryCollectionDocument(Base):
@@ -340,12 +344,12 @@ class LibraryCollectionDocument(Base):
id = Column(Integer, primary_key=True, autoincrement=True)
collection_id = Column(
- Integer,
+ String(36),
ForeignKey("library_collections.id", ondelete="CASCADE"),
nullable=False,
)
document_id = Column(
- Integer,
+ String(36),
ForeignKey("library_documents.id", ondelete="CASCADE"),
nullable=False,
)
@@ -508,3 +512,188 @@ class RAGIndex(Base):
def __repr__(self):
return f"<RAGIndex(collection='{self.collection_name}', model='{self.embedding_model}', chunks={self.chunk_count})>"
+
+
+class UserDocument(Base):
+ """
+ Documents uploaded by users (not from research).
+ Can be in multiple collections via UserDocumentCollection junction table.
+ """
+
+ __tablename__ = "user_documents"
+
+ id = Column(Integer, primary_key=True, autoincrement=True)
+
+ # File identification
+ filename = Column(String(500), nullable=False) # Display name
+ original_filename = Column(String(500)) # Original name when uploaded
+ file_path = Column(Text, nullable=True) # Path relative to data/user_uploads/ (optional - we store text directly)
+ file_hash = Column(
+ String(64), nullable=False, unique=True, index=True
+ ) # SHA256 for deduplication
+
+ # File information
+ file_size = Column(Integer) # Size in bytes
+ file_type = Column(String(50)) # Extension: pdf, txt, md, etc.
+ mime_type = Column(String(100)) # MIME type
+
+ # Content storage (extracted text stored in DB)
+ text_content = Column(Text) # Extracted text content
+
+ # Metadata
+ title = Column(Text) # Document title (extracted or user-provided)
+ description = Column(Text) # User description
+ tags = Column(JSON) # User-defined tags
+
+ # Upload information
+ uploaded_at = Column(UtcDateTime, default=utcnow(), nullable=False)
+ last_accessed = Column(UtcDateTime, nullable=True)
+
+ # Relationships
+ collections = relationship(
+ "UserDocumentCollection", back_populates="document", cascade="all, delete-orphan"
+ )
+
+ def __repr__(self):
+ return f"<UserDocument(filename='{self.filename}', type={self.file_type}, size={self.file_size})>"
+
+
+class UserDocumentCollection(Base):
+ """
+ Many-to-many relationship between user documents and collections.
+ Tracks indexing status per collection.
+ """
+
+ __tablename__ = "user_document_collections"
+
+ id = Column(Integer, primary_key=True, autoincrement=True)
+
+ # Foreign keys
+ document_id = Column(
+ Integer,
+ ForeignKey("user_documents.id", ondelete="CASCADE"),
+ nullable=False,
+ )
+ collection_id = Column(
+ String(36),
+ ForeignKey("library_collections.id", ondelete="CASCADE"),
+ nullable=False,
+ )
+
+ # Indexing status (per collection!)
+ indexed = Column(Boolean, default=False) # Whether indexed for this collection
+ chunk_count = Column(Integer, default=0) # Number of chunks in this collection
+ last_indexed_at = Column(UtcDateTime, nullable=True)
+
+ # Timestamps
+ added_at = Column(UtcDateTime, default=utcnow(), nullable=False)
+
+ # Relationships
+ document = relationship("UserDocument", back_populates="collections")
+ collection = relationship("LibraryCollection", backref="user_documents")
+
+ # Ensure one entry per document-collection pair
+ __table_args__ = (
+ UniqueConstraint(
+ "document_id", "collection_id", name="uix_user_doc_collection"
+ ),
+ )
+
+ def __repr__(self):
+ return f"<UserDocumentCollection(doc_id={self.document_id}, coll_id={self.collection_id}, indexed={self.indexed})>"
+
+
+class CollectionFolder(Base):
+ """
+ Local folders linked to a collection for indexing.
+ """
+
+ __tablename__ = "collection_folders"
+
+ id = Column(Integer, primary_key=True, autoincrement=True)
+
+ # Collection association
+ collection_id = Column(
+ String(36),
+ ForeignKey("library_collections.id", ondelete="CASCADE"),
+ nullable=False,
+ )
+
+ # Folder configuration
+ folder_path = Column(Text, nullable=False) # Absolute path to folder
+ include_patterns = Column(
+ JSON, default=["*.pdf", "*.txt", "*.md", "*.html"]
+ ) # File patterns to include
+ exclude_patterns = Column(JSON) # Patterns to exclude (e.g., ["**/node_modules/**"])
+ recursive = Column(Boolean, default=True) # Search subfolders
+
+ # Monitoring
+ watch_enabled = Column(Boolean, default=False) # Auto-reindex on changes (future)
+ last_scanned_at = Column(UtcDateTime, nullable=True)
+ file_count = Column(Integer, default=0) # Total files found
+ indexed_file_count = Column(Integer, default=0) # Files indexed
+
+ # Timestamps
+ created_at = Column(UtcDateTime, default=utcnow(), nullable=False)
+ updated_at = Column(
+ UtcDateTime, default=utcnow(), onupdate=utcnow(), nullable=False
+ )
+
+ # Relationships
+ collection = relationship("LibraryCollection", backref="linked_folders")
+ files = relationship(
+ "CollectionFolderFile", back_populates="folder", cascade="all, delete-orphan"
+ )
+
+ def __repr__(self):
+ return f"<CollectionFolder(path='{self.folder_path}', files={self.file_count})>"
+
+
+class CollectionFolderFile(Base):
+ """
+ Files found in linked folders.
+ Lightweight tracking for deduplication and indexing status.
+ """
+
+ __tablename__ = "collection_folder_files"
+
+ id = Column(Integer, primary_key=True, autoincrement=True)
+
+ # Folder association
+ folder_id = Column(
+ Integer,
+ ForeignKey("collection_folders.id", ondelete="CASCADE"),
+ nullable=False,
+ )
+
+ # File identification
+ relative_path = Column(Text, nullable=False) # Path relative to folder_path
+ file_hash = Column(String(64), index=True) # SHA256 for deduplication
+ file_size = Column(Integer) # Size in bytes
+ file_type = Column(String(50)) # Extension
+
+ # File metadata
+ last_modified = Column(UtcDateTime) # File modification time
+
+ # Indexing status
+ indexed = Column(Boolean, default=False)
+ chunk_count = Column(Integer, default=0)
+ last_indexed_at = Column(UtcDateTime, nullable=True)
+ index_error = Column(Text, nullable=True) # Error if indexing failed
+
+ # Timestamps
+ discovered_at = Column(UtcDateTime, default=utcnow(), nullable=False)
+ updated_at = Column(
+ UtcDateTime, default=utcnow(), onupdate=utcnow(), nullable=False
+ )
+
+ # Relationships
+ folder = relationship("CollectionFolder", back_populates="files")
+
+ # Ensure one entry per file in folder
+ __table_args__ = (
+ UniqueConstraint("folder_id", "relative_path", name="uix_folder_file"),
+ )
+
+ def __repr__(self):
+ return f"<CollectionFolderFile(path='{self.relative_path}', indexed={self.indexed})>"
\ No newline at end of file
diff --git a/src/local_deep_research/research_library/downloaders/base.py b/src/local_deep_research/research_library/downloaders/base.py
index 80b6511dc7..00ea41fef0 100644
--- a/src/local_deep_research/research_library/downloaders/base.py
+++ b/src/local_deep_research/research_library/downloaders/base.py
@@ -313,7 +313,8 @@ class BaseDownloader(ABC):
return None
- def _extract_text_from_pdf(self, pdf_content: bytes) -> Optional[str]:
+ @staticmethod
+ def _extract_text_from_pdf(pdf_content: bytes) -> Optional[str]:
"""
Extract text from PDF content using in-memory processing.
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 71cfea9a80..82dd37e374 100644
--- a/src/local_deep_research/research_library/routes/library_routes.py
+++ b/src/local_deep_research/research_library/routes/library_routes.py
@@ -180,6 +180,25 @@ def library_page():
)
+@library_bp.route("/document/<string:document_id>")
+@login_required
+def document_details_page(document_id):
+ """Document details page showing all metadata and links."""
+ username = session.get("username")
+ service = LibraryService(username)
+
+ # Get document details
+ document = service.get_document_by_id(document_id)
+
+ if not document:
+ return "Document not found", 404
+
+ return render_template_with_defaults(
+ "pages/document_details.html",
+ document=document
+ )
+
+
@library_bp.route("/download-manager")
@login_required
def download_manager_page():
@@ -289,42 +308,42 @@ def get_documents():
return jsonify({"documents": documents})
-@library_bp.route("/api/document/<int:doc_id>/favorite", methods=["POST"])
+@library_bp.route("/api/document/<string:document_id>/favorite", methods=["POST"])
@login_required
-def toggle_favorite(doc_id):
+def toggle_favorite(document_id):
"""Toggle favorite status of a document."""
username = session.get("username")
service = LibraryService(username)
- is_favorite = service.toggle_favorite(doc_id)
+ is_favorite = service.toggle_favorite(document_id)
return jsonify({"favorite": is_favorite})
-@library_bp.route("/api/document/<int:doc_id>", methods=["DELETE"])
+@library_bp.route("/api/document/<string:document_id>", methods=["DELETE"])
@login_required
-def delete_document(doc_id):
+def delete_document(document_id):
"""Delete a document from library."""
username = session.get("username")
service = LibraryService(username)
- success = service.delete_document(doc_id)
+ success = service.delete_document(document_id)
return jsonify({"success": success})
-@library_bp.route("/api/document/<int:doc_id>/pdf-url")
+@library_bp.route("/api/document/<string:document_id>/pdf-url")
@login_required
-def get_pdf_url(doc_id):
+def get_pdf_url(document_id):
"""Get URL for viewing PDF."""
# Return URL that will serve the PDF
return jsonify(
{
- "url": f"/library/api/document/{doc_id}/pdf",
+ "url": f"/library/api/document/{document_id}/pdf",
"title": "Document", # Could fetch actual title
}
)
-@library_bp.route("/api/document/<int:doc_id>/pdf")
+@library_bp.route("/api/document/<string:document_id>/pdf")
@login_required
-def serve_pdf(doc_id):
+def serve_pdf(document_id):
"""Serve PDF file for viewing."""
from loguru import logger
@@ -332,16 +351,16 @@ def serve_pdf(doc_id):
service = LibraryService(username)
# Get the specific document by ID
- document = service.get_document_by_id(doc_id)
+ document = service.get_document_by_id(document_id)
if not document:
logger.warning(
- f"Document ID {doc_id} not found in database for user {username}"
+ f"Document ID {document_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}"
+ f"Document {document_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
@@ -367,9 +386,9 @@ def serve_pdf(doc_id):
return "PDF file not found", 404
-@library_bp.route("/api/document/<int:doc_id>/text")
+@library_bp.route("/api/document/<string:document_id>/text")
@login_required
-def serve_text(doc_id):
+def serve_text(document_id):
"""Serve text content from database for viewing."""
from loguru import logger
from ...database.models.library import LibraryTextDocument
@@ -381,7 +400,7 @@ def serve_text(doc_id):
# Try to get text document by document_id (PDF with extracted text)
text_doc = (
db_session.query(LibraryTextDocument)
- .filter_by(document_id=doc_id)
+ .filter_by(document_id=document_id)
.first()
)
@@ -389,20 +408,20 @@ def serve_text(doc_id):
if not text_doc:
text_doc = (
db_session.query(LibraryTextDocument)
- .filter_by(id=doc_id)
+ .filter_by(id=document_id)
.first()
)
if not text_doc:
- logger.warning(f"Text document not found for document ID {doc_id}")
+ logger.warning(f"Text document not found for document ID {document_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")
+ logger.warning(f"Text document {document_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"
+ f"Serving text content for document {document_id}: {len(text_doc.text_content)} characters"
)
return jsonify(
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 2c802ecefe..707d725fe6 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -19,6 +19,9 @@ from flask import (
)
from loguru import logger
import json
+import uuid
+from typing import Optional
+from datetime import datetime, timezone
from ...web.auth.decorators import login_required
from ...utilities.db_utils import get_settings_manager
@@ -60,6 +63,20 @@ def rag_manager_page():
return render_template("pages/rag_manager.html")
+@rag_bp.route("/collections")
+@login_required
+def collections_page():
+ """Render the Collections page."""
+ return render_template("pages/collections.html", active_page="collections")
+
+
+@rag_bp.route("/collections/<string:collection_id>")
+@login_required
+def collection_details_page(collection_id):
+ """Render the Collection Details page."""
+ return render_template("pages/collection_details.html", active_page="collections", collection_id=collection_id)
+
+
# API Routes
@@ -443,3 +460,756 @@ def get_documents():
except Exception as e:
logger.exception("Error getting documents")
return jsonify({"success": False, "error": str(e)}), 500
+
+
+@rag_bp.route("/api/rag/index-local", methods=["GET"])
+@login_required
+def index_local_library():
+ """Index documents from a local folder with Server-Sent Events progress."""
+ from pathlib import Path
+ import glob
+
+ folder_path = request.args.get("path")
+ file_patterns = request.args.get("patterns", "*.pdf,*.txt,*.md,*.html").split(",")
+ recursive = request.args.get("recursive", "true").lower() == "true"
+
+ if not folder_path:
+ return jsonify({"success": False, "error": "Path is required"}), 400
+
+ # Validate path exists and is a directory
+ path = Path(folder_path).expanduser().resolve()
+ if not path.exists():
+ return jsonify({"success": False, "error": f"Path does not exist: {folder_path}"}), 400
+ if not path.is_dir():
+ return jsonify({"success": False, "error": f"Path is not a directory: {folder_path}"}), 400
+
+ # Create RAG service in request context
+ rag_service = get_rag_service()
+
+ def generate():
+ """Generator function for SSE progress updates."""
+ try:
+ # Send initial status
+ yield f"data: {json.dumps({'type': 'start', 'message': f'Scanning folder: {path}'})}\n\n"
+
+ # Find all matching files
+ files_to_index = []
+ for pattern in file_patterns:
+ pattern = pattern.strip()
+ if recursive:
+ search_pattern = str(path / "**" / pattern)
+ else:
+ search_pattern = str(path / pattern)
+
+ matching_files = glob.glob(search_pattern, recursive=recursive)
+ files_to_index.extend(matching_files)
+
+ # Remove duplicates and sort
+ files_to_index = sorted(set(files_to_index))
+
+ if not files_to_index:
+ yield f"data: {json.dumps({'type': 'complete', 'results': {'successful': 0, 'skipped': 0, 'failed': 0, 'message': 'No matching files found'}})}\n\n"
+ return
+
+ results = {"successful": 0, "skipped": 0, "failed": 0, "errors": []}
+ total = len(files_to_index)
+
+ # Index each file
+ for idx, file_path in enumerate(files_to_index, 1):
+ file_name = Path(file_path).name
+
+ # Send progress update
+ yield f"data: {json.dumps({'type': 'progress', 'current': idx, 'total': total, 'filename': file_name, 'percent': int((idx / total) * 100)})}\n\n"
+
+ try:
+ # Index the file directly using RAG service
+ result = rag_service.index_local_file(file_path)
+
+ if result.get("status") == "success":
+ results["successful"] += 1
+ elif result.get("status") == "skipped":
+ results["skipped"] += 1
+ else:
+ results["failed"] += 1
+ results["errors"].append({
+ "file": file_name,
+ "error": result.get("error", "Unknown error")
+ })
+ except Exception as e:
+ results["failed"] += 1
+ results["errors"].append({
+ "file": file_name,
+ "error": str(e)
+ })
+ logger.exception(f"Error indexing file {file_path}")
+
+ # Send completion status
+ yield f"data: {json.dumps({'type': 'complete', 'results': results})}\n\n"
+
+ logger.info(
+ f"Local library indexing complete for {path}: "
+ f"{results['successful']} successful, "
+ f"{results['skipped']} skipped, "
+ f"{results['failed']} failed"
+ )
+
+ except Exception as e:
+ logger.exception("Error in local library indexing")
+ yield f"data: {json.dumps({'type': 'error', 'error': str(e)})}\n\n"
+
+ return Response(
+ stream_with_context(generate()), mimetype="text/event-stream"
+ )
+
+
+# Collection Management Routes
+
+
+@rag_bp.route("/api/collections", methods=["GET"])
+@login_required
+def get_collections():
+ """Get all document collections for the current user."""
+ from ...database.models import LibraryCollection
+ from ...database.session_context import get_user_db_session
+
+ try:
+ username = session["username"]
+ with get_user_db_session(username) as db_session:
+ # No need to filter by username - each user has their own database
+ collections = db_session.query(LibraryCollection).all()
+
+ result = []
+ for coll in collections:
+ collection_data = {
+ "id": coll.id,
+ "name": coll.name,
+ "description": coll.description,
+ "created_at": coll.created_at.isoformat() if coll.created_at else None,
+ "collection_type": coll.collection_type,
+ "document_count": len(coll.user_documents) if hasattr(coll, 'user_documents') else 0,
+ "folder_count": len(coll.linked_folders) if hasattr(coll, 'linked_folders') else 0,
+ }
+
+ # Include embedding metadata if available
+ if coll.embedding_model:
+ collection_data["embedding"] = {
+ "model": coll.embedding_model,
+ "provider": coll.embedding_model_type,
+ "dimension": coll.embedding_dimension,
+ "chunk_size": coll.chunk_size,
+ "chunk_overlap": coll.chunk_overlap,
+ }
+ else:
+ collection_data["embedding"] = None
+
+ result.append(collection_data)
+
+ return jsonify({"success": True, "collections": result})
+ except Exception as e:
+ logger.exception("Error getting collections")
+ return jsonify({"success": False, "error": str(e)}), 500
+
+
+@rag_bp.route("/api/collections", methods=["POST"])
+@login_required
+def create_collection():
+ """Create a new document collection."""
+ from ...database.models import LibraryCollection
+ from ...database.session_context import get_user_db_session
+
+ try:
+ data = request.get_json()
+ name = data.get("name", "").strip()
+ description = data.get("description", "").strip()
+ collection_type = data.get("type", "user_uploads")
+
+ if not name:
+ return jsonify({"success": False, "error": "Name is required"}), 400
+
+ username = session["username"]
+ with get_user_db_session(username) as db_session:
+ # Check if collection with this name already exists in this user's database
+ existing = db_session.query(LibraryCollection).filter_by(
+ name=name
+ ).first()
+
+ if existing:
+ return jsonify(
+ {"success": False, "error": f"Collection '{name}' already exists"}
+ ), 400
+
+ # Create new collection (no username needed - each user has their own DB)
+ # Note: created_at uses default=utcnow() in the model, so we don't need to set it manually
+ collection = LibraryCollection(
+ id=str(uuid.uuid4()), # Generate UUID for collection
+ name=name,
+ description=description,
+ collection_type=collection_type,
+ )
+
+ db_session.add(collection)
+ db_session.commit()
+
+ return jsonify({
+ "success": True,
+ "collection": {
+ "id": collection.id,
+ "name": collection.name,
+ "description": collection.description,
+ "created_at": collection.created_at.isoformat(),
+ "collection_type": collection.collection_type
+ }
+ })
+ except Exception as e:
+ logger.exception("Error creating collection")
+ return jsonify({"success": False, "error": str(e)}), 500
+
+
+@rag_bp.route("/api/collections/<string:collection_id>", methods=["PUT"])
+@login_required
+def update_collection(collection_id):
+ """Update a collection's details."""
+ from ...database.models import LibraryCollection
+ from ...database.session_context import get_user_db_session
+
+ try:
+ data = request.get_json()
+ name = data.get("name", "").strip()
+ description = data.get("description", "").strip()
+
+ username = session["username"]
+ with get_user_db_session(username) as db_session:
+ # No need to filter by username - each user has their own database
+ collection = db_session.query(LibraryCollection).filter_by(
+ id=collection_id
+ ).first()
+
+ if not collection:
+ return jsonify(
+ {"success": False, "error": "Collection not found"}
+ ), 404
+
+ if name:
+ # Check if new name conflicts with existing collection
+ existing = db_session.query(LibraryCollection).filter(
+ LibraryCollection.name == name,
+ LibraryCollection.id != collection_id
+ ).first()
+
+ if existing:
+ return jsonify(
+ {"success": False, "error": f"Collection '{name}' already exists"}
+ ), 400
+
+ collection.name = name
+
+ if description is not None: # Allow empty description
+ collection.description = description
+
+ db_session.commit()
+
+ return jsonify({
+ "success": True,
+ "collection": {
+ "id": collection.id,
+ "name": collection.name,
+ "description": collection.description,
+ "created_at": collection.created_at.isoformat() if collection.created_at else None,
+ "collection_type": collection.collection_type
+ }
+ })
+ except Exception as e:
+ logger.exception("Error updating collection")
+ return jsonify({"success": False, "error": str(e)}), 500
+
+
+@rag_bp.route("/api/collections/<string:collection_id>", methods=["DELETE"])
+@login_required
+def delete_collection(collection_id):
+ """Delete a collection and optionally its documents."""
+ from ...database.models import (
+ LibraryCollection,
+ UserDocumentCollection,
+ CollectionFolder,
+ DocumentChunk,
+ )
+ from ...database.session_context import get_user_db_session
+
+ try:
+ delete_documents = request.args.get("delete_documents", "false").lower() == "true"
+
+ username = session["username"]
+ with get_user_db_session(username) as db_session:
+ # No need to filter by username - each user has their own database
+ collection = db_session.query(LibraryCollection).filter_by(
+ id=collection_id
+ ).first()
+
+ if not collection:
+ return jsonify(
+ {"success": False, "error": "Collection not found"}
+ ), 404
+
+ # Get collection name for deleting chunks
+ collection_name = f"collection_{collection.id}"
+
+ # Delete associated document chunks from vector store
+ deleted_chunks = db_session.query(DocumentChunk).filter_by(
+ collection_name=collection_name
+ ).delete()
+
+ # Delete junction table entries
+ db_session.query(UserDocumentCollection).filter_by(
+ collection_id=collection_id
+ ).delete()
+
+ # Delete linked folders
+ db_session.query(CollectionFolder).filter_by(
+ collection_id=collection_id
+ ).delete()
+
+ # Delete the collection itself
+ db_session.delete(collection)
+ db_session.commit()
+
+ # Also remove from vector index if it exists
+ try:
+ rag_service = get_rag_service()
+ rag_service.remove_collection_from_index(collection_name)
+ except Exception as e:
+ logger.warning(f"Could not remove collection from vector index: {e}")
+
+ return jsonify({
+ "success": True,
+ "message": f"Collection deleted successfully",
+ "deleted_chunks": deleted_chunks
+ })
+ except Exception as e:
+ logger.exception("Error deleting collection")
+ return jsonify({"success": False, "error": str(e)}), 500
+
+
+def extract_text_from_file(file_content: bytes, file_type: str, filename: str) -> Optional[str]:
+ """
+ Extract text from uploaded file content.
+
+ Args:
+ file_content: Raw file content as bytes
+ file_type: Type of file (pdf, text, markdown, html, etc.)
+ filename: Original filename for logging
+
+ Returns:
+ Extracted text as string, or None if extraction failed
+ """
+ try:
+ if file_type == "pdf":
+ # Use the existing PDF text extraction functionality
+ from ..downloaders.base import BaseDownloader
+ text = BaseDownloader._extract_text_from_pdf(file_content)
+ if text:
+ logger.info(f"Successfully extracted text from PDF: {filename}")
+ return text
+ else:
+ logger.warning(f"Could not extract text from PDF: {filename}")
+ return None
+
+ elif file_type in ["text", "txt", "markdown", "md"]:
+ # Plain text files - just decode
+ try:
+ text = file_content.decode("utf-8")
+ logger.info(f"Successfully read text file: {filename}")
+ return text
+ except UnicodeDecodeError:
+ # Try with different encoding
+ try:
+ text = file_content.decode("utf-8", errors="ignore")
+ logger.warning(f"Read text file with encoding errors ignored: {filename}")
+ return text
+ except Exception:
+ logger.exception(f"Failed to decode text file: {filename}")
+ return None
+
+ elif file_type in ["html", "htm"]:
+ # HTML files - extract text content
+ try:
+ from bs4 import BeautifulSoup
+ html_content = file_content.decode("utf-8", errors="ignore")
+ soup = BeautifulSoup(html_content, "html.parser")
+
+ # Remove script and style elements
+ for script in soup(["script", "style"]):
+ script.decompose()
+
+ # Get text
+ text = soup.get_text()
+
+ # Clean up whitespace
+ lines = (line.strip() for line in text.splitlines())
+ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
+ text = '\n'.join(chunk for chunk in chunks if chunk)
+
+ logger.info(f"Successfully extracted text from HTML: {filename}")
+ return text
+ except Exception:
+ logger.exception(f"Failed to extract text from HTML: {filename}")
+ return None
+
+ elif file_type in ["docx", "doc"]:
+ # Word documents - would need python-docx library
+ logger.warning(f"Word document extraction not yet implemented: {filename}")
+ return None
+
+ else:
+ logger.warning(f"Unsupported file type for text extraction: {file_type} ({filename})")
+ return None
+
+ except Exception:
+ logger.exception(f"Error extracting text from {filename}")
+ return None
+
+
+@rag_bp.route("/api/collections/<string:collection_id>/upload", methods=["POST"])
+@login_required
+def upload_to_collection(collection_id):
+ """Upload files to a collection."""
+ from ...database.models import (
+ LibraryCollection,
+ UserDocument,
+ UserDocumentCollection,
+ )
+ from ...database.session_context import get_user_db_session
+ from werkzeug.utils import secure_filename
+ from pathlib import Path
+ import hashlib
+
+ try:
+ if "files" not in request.files:
+ return jsonify({"success": False, "error": "No files provided"}), 400
+
+ files = request.files.getlist("files")
+ if not files:
+ return jsonify({"success": False, "error": "No files selected"}), 400
+
+ username = session["username"]
+ with get_user_db_session(username) as db_session:
+ # Verify collection exists in this user's database
+ collection = db_session.query(LibraryCollection).filter_by(
+ id=collection_id
+ ).first()
+
+ if not collection:
+ return jsonify(
+ {"success": False, "error": "Collection not found"}
+ ), 404
+
+ uploaded_files = []
+ errors = []
+
+ for file in files:
+ if not file.filename:
+ continue
+
+ try:
+ # Read file content
+ file_content = file.read()
+ file.seek(0) # Reset for potential re-reading
+
+ # Calculate file hash for deduplication
+ file_hash = hashlib.sha256(file_content).hexdigest()
+
+ # Check if document already exists
+ existing_doc = db_session.query(UserDocument).filter_by(
+ file_hash=file_hash
+ ).first()
+
+ if existing_doc:
+ # Document exists, just add to collection
+ # Check if already in collection
+ existing_link = db_session.query(UserDocumentCollection).filter_by(
+ document_id=existing_doc.id,
+ collection_id=collection_id
+ ).first()
+
+ if not existing_link:
+ # Add to collection
+ collection_link = UserDocumentCollection(
+ document_id=existing_doc.id,
+ collection_id=collection_id,
+ indexed=False,
+ chunk_count=0,
+ )
+ db_session.add(collection_link)
+ uploaded_files.append({
+ "filename": existing_doc.filename,
+ "status": "added_to_collection",
+ "id": existing_doc.id
+ })
+ else:
+ uploaded_files.append({
+ "filename": existing_doc.filename,
+ "status": "already_in_collection",
+ "id": existing_doc.id
+ })
+ else:
+ # Create new document
+ filename = secure_filename(file.filename)
+
+ # Determine file type
+ file_extension = Path(filename).suffix.lower()
+ file_type = {
+ ".pdf": "pdf",
+ ".txt": "text",
+ ".md": "markdown",
+ ".html": "html",
+ ".htm": "html",
+ ".docx": "docx",
+ ".doc": "doc",
+ }.get(file_extension, "unknown")
+
+ # Extract text from the file
+ extracted_text = extract_text_from_file(file_content, file_type, filename)
+
+ if not extracted_text:
+ errors.append({
+ "filename": filename,
+ "error": f"Could not extract text from {file_type} file"
+ })
+ logger.warning(f"Skipping file {filename} - no text could be extracted")
+ continue
+
+ # 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
+ # TODO: Add functionality to optionally store files on disk (with setting in default_settings.json)
+ # For now, we only store extracted text in the encrypted database for better privacy
+ new_doc = UserDocument(
+ filename=filename,
+ file_hash=file_hash,
+ file_size=len(file_content),
+ file_type=file_type,
+ text_content=extracted_text, # Store the extracted text
+ file_path="text_only_not_stored", # Placeholder - file not stored on disk, only text in encrypted DB
+ )
+ db_session.add(new_doc)
+ db_session.flush() # Get the ID
+
+ # Add to collection
+ collection_link = UserDocumentCollection(
+ document_id=new_doc.id,
+ collection_id=collection_id,
+ indexed=False,
+ chunk_count=0,
+ )
+ db_session.add(collection_link)
+
+ uploaded_files.append({
+ "filename": filename,
+ "status": "uploaded",
+ "id": new_doc.id,
+ "text_length": len(extracted_text)
+ })
+
+ except Exception as e:
+ errors.append({
+ "filename": file.filename,
+ "error": str(e)
+ })
+ logger.exception(f"Error uploading file {file.filename}")
+
+ db_session.commit()
+
+ return jsonify({
+ "success": True,
+ "uploaded": uploaded_files,
+ "errors": errors,
+ "summary": {
+ "total": len(files),
+ "successful": len(uploaded_files),
+ "failed": len(errors)
+ }
+ })
+
+ except Exception as e:
+ logger.exception("Error uploading files")
+ return jsonify({"success": False, "error": str(e)}), 500
+
+
+@rag_bp.route("/api/collections/<string:collection_id>/documents", methods=["GET"])
+@login_required
+def get_collection_documents(collection_id):
+ """Get all documents in a collection."""
+ from ...database.models import (
+ LibraryCollection,
+ UserDocument,
+ UserDocumentCollection,
+ )
+ from ...database.session_context import get_user_db_session
+
+ try:
+ username = session["username"]
+ with get_user_db_session(username) as db_session:
+ # Verify collection exists in this user's database
+ collection = db_session.query(LibraryCollection).filter_by(
+ id=collection_id
+ ).first()
+
+ if not collection:
+ return jsonify(
+ {"success": False, "error": "Collection not found"}
+ ), 404
+
+ # Get documents through junction table
+ doc_links = db_session.query(
+ UserDocumentCollection, UserDocument
+ ).join(
+ UserDocument
+ ).filter(
+ UserDocumentCollection.collection_id == collection_id
+ ).all()
+
+ documents = []
+ for link, doc in doc_links:
+ documents.append({
+ "id": doc.id,
+ "filename": doc.filename,
+ "file_type": doc.file_type,
+ "file_size": doc.file_size,
+ "uploaded_at": doc.uploaded_at.isoformat() if doc.uploaded_at else None,
+ "indexed": link.indexed,
+ "chunk_count": link.chunk_count,
+ "last_indexed_at": link.last_indexed_at.isoformat() if link.last_indexed_at else None,
+ })
+
+ return jsonify({
+ "success": True,
+ "collection": {
+ "id": collection.id,
+ "name": collection.name,
+ "description": collection.description,
+ },
+ "documents": documents
+ })
+
+ except Exception as e:
+ logger.exception("Error getting collection documents")
+ return jsonify({"success": False, "error": str(e)}), 500
+
+
+@rag_bp.route("/api/collections/<string:collection_id>/index", methods=["GET"])
+@login_required
+def index_collection(collection_id):
+ """Index all documents in a collection with Server-Sent Events progress."""
+ from ...database.models import (
+ LibraryCollection,
+ UserDocument,
+ UserDocumentCollection,
+ )
+ from ...database.session_context import get_user_db_session
+
+ force_reindex = request.args.get("force_reindex", "false").lower() == "true"
+ username = session["username"]
+
+ # Create RAG service
+ rag_service = get_rag_service()
+
+ def generate():
+ """Generator for SSE progress updates."""
+ try:
+ with get_user_db_session(username) as db_session:
+ # Verify collection exists in this user's database
+ collection = db_session.query(LibraryCollection).filter_by(
+ id=collection_id
+ ).first()
+
+ if not collection:
+ yield f"data: {json.dumps({'type': 'error', 'error': 'Collection not found'})}\n\n"
+ return
+
+ # Store embedding metadata if this is the first time indexing
+ if collection.embedding_model is None:
+ # Get embedding dimension from the embedding manager
+ embedding_dim = None
+ try:
+ # Try to get dimension from the embedding manager's provider
+ if hasattr(rag_service.embedding_manager, 'provider'):
+ provider = rag_service.embedding_manager.provider
+ if hasattr(provider, 'embedding_dimension'):
+ embedding_dim = provider.embedding_dimension
+ except Exception as e:
+ logger.warning(f"Could not get embedding dimension: {e}")
+
+ # Store the embedding configuration used for this collection
+ collection.embedding_model = rag_service.embedding_model
+ collection.embedding_model_type = rag_service.embedding_provider
+ collection.embedding_dimension = embedding_dim
+ collection.chunk_size = rag_service.chunk_size
+ collection.chunk_overlap = rag_service.chunk_overlap
+ db_session.commit()
+ logger.info(f"Stored embedding metadata for collection {collection.id}: {rag_service.embedding_provider}/{rag_service.embedding_model}")
+
+ # Get documents to index
+ query = db_session.query(
+ UserDocumentCollection, UserDocument
+ ).join(
+ UserDocument
+ ).filter(
+ UserDocumentCollection.collection_id == collection_id
+ )
+
+ if not force_reindex:
+ query = query.filter(UserDocumentCollection.indexed == False)
+
+ doc_links = query.all()
+
+ if not doc_links:
+ yield f"data: {json.dumps({'type': 'complete', 'results': {'successful': 0, 'skipped': 0, 'failed': 0, 'message': 'No documents to index'}})}\n\n"
+ return
+
+ total = len(doc_links)
+ results = {"successful": 0, "skipped": 0, "failed": 0, "errors": []}
+
+ 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, 'percent': int((idx / total) * 100)})}\n\n"
+
+ try:
+ # Index the document
+ result = rag_service.index_user_document(
+ doc, collection_name, force_reindex
+ )
+
+ if result.get("status") == "success":
+ results["successful"] += 1
+ # Update indexing status
+ link.indexed = True
+ link.chunk_count = result.get("chunk_count", 0)
+ link.last_indexed_at = datetime.now(timezone.utc)
+ elif result.get("status") == "skipped":
+ results["skipped"] += 1
+ else:
+ results["failed"] += 1
+ results["errors"].append({
+ "filename": doc.filename,
+ "error": result.get("error", "Unknown error")
+ })
+ except Exception as e:
+ results["failed"] += 1
+ results["errors"].append({
+ "filename": doc.filename,
+ "error": str(e)
+ })
+ logger.exception(f"Error indexing document {doc.filename}")
+
+ db_session.commit()
+
+ yield f"data: {json.dumps({'type': 'complete', 'results': results})}\n\n"
+
+ except Exception as e:
+ logger.exception("Error in collection indexing")
+ yield f"data: {json.dumps({'type': 'error', 'error': str(e)})}\n\n"
+
+ return Response(
+ stream_with_context(generate()), mimetype="text/event-stream"
+ )
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 85eeb4d392..b6f24538c0 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -11,6 +11,7 @@ Handles downloading PDFs from various academic sources with:
import hashlib
import re
import time
+import uuid
from datetime import datetime, UTC
from pathlib import Path
from typing import Optional, Tuple
@@ -467,6 +468,7 @@ class DownloadService:
else:
# Create new library document entry
doc = LibraryDocument(
+ id=str(uuid.uuid4()), # Generate UUID for document
resource_id=resource.id,
research_id=resource.research_id,
document_hash=tracker.file_hash,
@@ -1331,6 +1333,7 @@ class DownloadService:
else:
# Create new record
text_doc = LibraryTextDocument(
+ id=str(uuid.uuid4()), # Generate UUID for text document
resource_id=resource.id,
research_id=resource.research_id,
document_id=pdf_document_id,
@@ -1385,6 +1388,7 @@ class DownloadService:
# Create record
text_doc = LibraryTextDocument(
+ id=str(uuid.uuid4()), # Generate UUID for text document
resource_id=resource.id,
research_id=resource.research_id,
text_hash=text_hash,
@@ -1420,6 +1424,7 @@ class DownloadService:
if not text_doc:
text_doc = LibraryTextDocument(
+ id=str(uuid.uuid4()), # Generate UUID for text document
resource_id=resource.id,
research_id=resource.research_id,
text_hash=hashlib.sha256(b"").hexdigest(),
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 8da6588d94..30b1086209 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
@@ -211,7 +211,6 @@ class LibraryRAGService:
.filter_by(
collection_name="library",
source_type="library",
- index_hash=rag_index.index_hash,
)
.count()
)
@@ -642,6 +641,289 @@ class LibraryRAGService:
"chunk_overlap": self.chunk_overlap,
}
+ def index_local_file(self, file_path: str) -> Dict[str, Any]:
+ """
+ Index a local file from the filesystem into RAG.
+
+ Args:
+ file_path: Path to the file to index
+
+ Returns:
+ Dict with status, chunk_count, and any errors
+ """
+ from pathlib import Path
+ import mimetypes
+
+ file_path = Path(file_path)
+
+ if not file_path.exists():
+ return {"status": "error", "error": f"File not found: {file_path}"}
+
+ if not file_path.is_file():
+ return {"status": "error", "error": f"Not a file: {file_path}"}
+
+ # Determine file type
+ mime_type, _ = mimetypes.guess_type(str(file_path))
+
+ # Read file content based on type
+ try:
+ if file_path.suffix.lower() in ['.txt', '.md', '.markdown']:
+ # Text files
+ with open(file_path, 'r', encoding='utf-8') as f:
+ content = f.read()
+ elif file_path.suffix.lower() in ['.html', '.htm']:
+ # HTML files - strip tags
+ from bs4 import BeautifulSoup
+ with open(file_path, 'r', encoding='utf-8') as f:
+ soup = BeautifulSoup(f.read(), 'html.parser')
+ content = soup.get_text()
+ elif file_path.suffix.lower() == '.pdf':
+ # PDF files - extract text
+ import PyPDF2
+ content = ""
+ with open(file_path, 'rb') as f:
+ pdf_reader = PyPDF2.PdfReader(f)
+ for page in pdf_reader.pages:
+ content += page.extract_text()
+ else:
+ return {"status": "skipped", "error": f"Unsupported file type: {file_path.suffix}"}
+
+ if not content or len(content.strip()) < 10:
+ return {"status": "error", "error": "File has no extractable text content"}
+
+ # Create LangChain Document from text
+ doc = Document(
+ page_content=content,
+ metadata={
+ "source": str(file_path),
+ "source_id": f"local_{file_path.stem}_{hash(str(file_path))}",
+ "title": file_path.stem,
+ "document_title": file_path.stem,
+ "file_type": file_path.suffix.lower(),
+ "file_size": file_path.stat().st_size,
+ "source_type": "local_file",
+ "collection": "local_library"
+ }
+ )
+
+ # Split into chunks
+ chunks = self.text_splitter.split_documents([doc])
+ logger.info(f"Split local file {file_path} into {len(chunks)} chunks")
+
+ # Generate unique IDs for chunks
+ import hashlib
+ file_hash = hashlib.sha256(str(file_path).encode()).hexdigest()[:8]
+ embedding_ids = [f"local_{file_hash}_{i}" for i in range(len(chunks))]
+
+ # Store chunks in database
+ self.embedding_manager._store_chunks_to_db(
+ chunks=chunks,
+ collection_name="local_library",
+ source_type="local_file",
+ source_id=str(file_path),
+ )
+
+ # Load or create FAISS index
+ if self.faiss_index is None:
+ self.faiss_index = self._load_or_create_faiss_index()
+
+ # Add embeddings to FAISS index
+ self.faiss_index.add_documents(chunks, ids=embedding_ids)
+
+ # Save FAISS index
+ index_path = Path(self.rag_index_record.index_path) if self.rag_index_record else None
+ if index_path:
+ self.faiss_index.save_local(
+ str(index_path.parent), index_name=index_path.stem
+ )
+ logger.info(f"Saved FAISS index to {index_path}")
+
+ logger.info(f"Successfully indexed local file {file_path} with {len(chunks)} chunks")
+
+ return {
+ "status": "success",
+ "chunk_count": len(chunks),
+ "embedding_ids": embedding_ids
+ }
+
+ except Exception as e:
+ logger.exception(f"Error indexing local file {file_path}: {str(e)}")
+ return {"status": "error", "error": str(e)}
+
+ def index_user_document(
+ self, user_doc, collection_name: str, force_reindex: bool = False
+ ) -> Dict[str, Any]:
+ """
+ Index a user-uploaded document into a specific collection.
+
+ Args:
+ user_doc: UserDocument object
+ collection_name: Name of the collection (e.g., "collection_123")
+ force_reindex: Whether to force reindexing
+
+ Returns:
+ Dict with status, chunk_count, and any errors
+ """
+ from ...database.models import UserDocumentCollection, DocumentChunk
+ from ...database.session_context import get_user_db_session
+
+ try:
+ # Use the pre-extracted text content
+ content = user_doc.text_content
+
+ if not content or len(content.strip()) < 10:
+ return {"status": "error", "error": "Document has no extractable text content"}
+
+ # Create LangChain Document
+ doc = Document(
+ page_content=content,
+ metadata={
+ "source": f"user_upload_{user_doc.id}",
+ "source_id": user_doc.id,
+ "title": user_doc.filename,
+ "document_title": user_doc.filename,
+ "file_type": user_doc.file_type,
+ "file_size": user_doc.file_size,
+ "collection": collection_name,
+ }
+ )
+
+ # Split into chunks
+ chunks = self.text_splitter.split_documents([doc])
+ logger.info(f"Split user document {user_doc.filename} into {len(chunks)} chunks")
+
+ # Store chunks in database
+ embedding_ids = self.embedding_manager._store_chunks_to_db(
+ chunks=chunks,
+ collection_name=collection_name,
+ source_type="user_document",
+ source_id=user_doc.id,
+ )
+
+ # Load or create FAISS index for this collection
+ if self.faiss_index is None:
+ self.faiss_index = self._load_or_create_faiss_index()
+
+ # If force_reindex, remove old chunks from FAISS before adding new ones
+ if force_reindex:
+ existing_ids = (
+ set(self.faiss_index.docstore._dict.keys())
+ if hasattr(self.faiss_index, "docstore")
+ else set()
+ )
+ old_chunk_ids = [
+ eid for eid in embedding_ids if eid in existing_ids
+ ]
+ if old_chunk_ids:
+ logger.info(
+ f"Force re-index: removing {len(old_chunk_ids)} existing chunks from FAISS"
+ )
+ self.faiss_index.delete(old_chunk_ids)
+
+ # Filter out chunks that already exist in FAISS (unless force_reindex)
+ if not force_reindex:
+ existing_ids = (
+ set(self.faiss_index.docstore._dict.keys())
+ if hasattr(self.faiss_index, "docstore")
+ else set()
+ )
+ new_chunks = []
+ new_ids = []
+ for chunk, chunk_id in zip(chunks, embedding_ids):
+ if chunk_id not in existing_ids:
+ new_chunks.append(chunk)
+ new_ids.append(chunk_id)
+ else:
+ # force_reindex: add all chunks
+ new_chunks = chunks
+ new_ids = embedding_ids
+
+ # Add embeddings to FAISS index
+ if new_chunks:
+ if force_reindex:
+ logger.info(
+ f"Force re-index: adding {len(new_chunks)} chunks with updated metadata to FAISS index"
+ )
+ else:
+ logger.info(
+ f"Adding {len(new_chunks)} new chunks to FAISS index ({len(chunks) - len(new_chunks)} already exist)"
+ )
+ self.faiss_index.add_documents(new_chunks, ids=new_ids)
+ else:
+ logger.info(
+ f"All {len(chunks)} chunks already exist in FAISS index, skipping"
+ )
+
+ # Save FAISS index
+ index_path = Path(self.rag_index_record.index_path) if self.rag_index_record else None
+ if index_path:
+ self.faiss_index.save_local(
+ str(index_path.parent), index_name=index_path.stem
+ )
+
+ logger.info(f"Successfully indexed user document {user_doc.filename} with {len(chunks)} chunks")
+
+ return {
+ "status": "success",
+ "chunk_count": len(chunks),
+ "embedding_ids": embedding_ids
+ }
+
+ except Exception as e:
+ logger.exception(f"Error indexing user document {user_doc.filename}: {str(e)}")
+ return {"status": "error", "error": str(e)}
+
+ def remove_collection_from_index(self, collection_name: str) -> Dict[str, Any]:
+ """
+ Remove all documents from a collection from the FAISS index.
+
+ Args:
+ collection_name: Name of the collection (e.g., "collection_123")
+
+ Returns:
+ Dict with status and count of removed chunks
+ """
+ from ...database.models import DocumentChunk
+ from ...database.session_context import get_user_db_session
+
+ try:
+ with get_user_db_session(self.username) as session:
+ # Get all chunk IDs for this collection
+ chunks = session.query(DocumentChunk).filter_by(
+ collection_name=collection_name
+ ).all()
+
+ if not chunks:
+ return {"status": "success", "deleted_count": 0}
+
+ chunk_ids = [f"{collection_name}_{chunk.id}" for chunk in chunks]
+
+ # Load FAISS index if not already loaded
+ if self.faiss_index is None:
+ self.faiss_index = self._load_or_create_faiss_index()
+
+ # Remove from FAISS index
+ if hasattr(self.faiss_index, 'delete'):
+ try:
+ self.faiss_index.delete(chunk_ids)
+
+ # Save updated index
+ index_path = Path(self.rag_index_record.index_path) if self.rag_index_record else None
+ if index_path:
+ self.faiss_index.save_local(
+ str(index_path.parent), index_name=index_path.stem
+ )
+ except Exception as e:
+ logger.warning(f"Could not delete chunks from FAISS: {e}")
+
+ logger.info(f"Removed {len(chunk_ids)} chunks from collection {collection_name}")
+
+ return {"status": "success", "deleted_count": len(chunk_ids)}
+
+ except Exception as e:
+ logger.exception(f"Error removing collection {collection_name} from index: {str(e)}")
+ return {"status": "error", "error": str(e)}
+
def search_library(
self, query: str, limit: int = 10, score_threshold: float = 0.0
) -> List[Dict[str, Any]]:
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 f2b921ce0c..ecc19f50ff 100644
--- a/src/local_deep_research/research_library/services/library_service.py
+++ b/src/local_deep_research/research_library/services/library_service.py
@@ -240,9 +240,9 @@ class LibraryService:
pdf_query, LibraryDocument, search_query
)
- # Filter to only non-downloaded documents
+ # Filter to only downloaded documents
pdf_query = pdf_query.filter(
- LibraryDocument.download_status != "completed"
+ LibraryDocument.download_status == "completed"
)
# Apply safety limit to prevent memory issues
@@ -393,9 +393,9 @@ class LibraryService:
text_query, LibraryTextDocument, search_query
)
- # Filter to only non-extracted documents
+ # Filter to only extracted documents
text_query = text_query.filter(
- LibraryTextDocument.extraction_status != "completed"
+ LibraryTextDocument.extraction_status == "completed"
)
# Apply safety limit to prevent memory issues
@@ -580,7 +580,7 @@ class LibraryService:
return research_list
- def get_document_by_id(self, doc_id: int) -> Optional[Dict]:
+ def get_document_by_id(self, doc_id: str) -> Optional[Dict]:
"""
Get a specific document by its ID.
@@ -652,7 +652,7 @@ class LibraryService:
else None,
}
- def toggle_favorite(self, document_id: int) -> bool:
+ 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)
@@ -662,7 +662,7 @@ class LibraryService:
return doc.favorite
return False
- def delete_document(self, document_id: int) -> bool:
+ 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)
@@ -699,7 +699,7 @@ class LibraryService:
return True
- def open_file_location(self, document_id: int) -> bool:
+ 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)
@@ -907,7 +907,7 @@ class LibraryService:
return stats
- def mark_for_redownload(self, document_ids: List[int]) -> int:
+ def mark_for_redownload(self, document_ids: List[str]) -> int:
"""
Mark specific documents for re-download.
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index d066100885..6e9aec0292 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -1540,6 +1540,47 @@ def api_get_available_models():
), 500
+def _get_engine_icon_and_category(engine_data: dict, engine_class=None) -> tuple:
+ """
+ Get icon emoji and category label for a search engine based on its attributes.
+
+ Args:
+ engine_data: Engine configuration dictionary
+ engine_class: Optional loaded engine class to check attributes
+
+ Returns:
+ Tuple of (icon, category) strings
+ """
+ # Check attributes from either the class or the engine data
+ if engine_class:
+ is_scientific = getattr(engine_class, 'is_scientific', False)
+ is_generic = getattr(engine_class, 'is_generic', False)
+ is_local = getattr(engine_class, 'is_local', False)
+ is_news = getattr(engine_class, 'is_news', False)
+ is_code = getattr(engine_class, 'is_code', False)
+ else:
+ is_scientific = engine_data.get('is_scientific', False)
+ is_generic = engine_data.get('is_generic', False)
+ is_local = engine_data.get('is_local', False)
+ is_news = engine_data.get('is_news', False)
+ is_code = engine_data.get('is_code', False)
+
+ # Return icon and category based on engine type
+ # Priority: local > scientific > news > code > generic > default
+ if is_local:
+ return "📁", "Local RAG"
+ elif is_scientific:
+ return "🔬", "Scientific"
+ elif is_news:
+ return "📰", "News"
+ elif is_code:
+ return "💻", "Code"
+ elif is_generic:
+ return "🌐", "Web Search"
+ else:
+ return "🔍", "Search"
+
+
@settings_bp.route("/api/available-search-engines", methods=["GET"])
@login_required
def api_get_available_search_engines():
@@ -1560,20 +1601,46 @@ def api_get_available_search_engines():
engine_options = []
if search_engines:
- # Format engines for API response
+ # Format engines for API response with metadata
+ from importlib import import_module
+
for engine_id, engine_data in search_engines.items():
+ # Try to load the engine class to get metadata
+ engine_class = None
+ try:
+ module_path = engine_data.get("module_path")
+ class_name = engine_data.get("class_name")
+ if module_path and class_name:
+ # Handle relative imports
+ package = None
+ if module_path.startswith("."):
+ package = "local_deep_research.web_search_engines"
+ module = import_module(module_path, package=package)
+ engine_class = getattr(module, class_name, None)
+ except Exception as e:
+ logger.debug(f"Could not load engine class for {engine_id}: {e}")
+
+ # Get icon and category from engine attributes
+ icon, category = _get_engine_icon_and_category(engine_data, engine_class)
+
+ # Build display name with icon and category
+ base_name = engine_data.get("display_name", engine_id)
+ label = f"{icon} {base_name} ({category})"
+
engines_dict[engine_id] = {
- "display_name": engine_data.get(
- "display_name", engine_id
- ),
+ "display_name": base_name,
"description": engine_data.get("description", ""),
"strengths": engine_data.get("strengths", []),
+ "icon": icon,
+ "category": category,
}
engine_options.append(
{
"value": engine_id,
- "label": engine_data.get("display_name", engine_id),
+ "label": label,
+ "icon": icon,
+ "category": category,
}
)
diff --git a/src/local_deep_research/web/static/js/collection_details.js b/src/local_deep_research/web/static/js/collection_details.js
new file mode 100644
index 0000000000..619d551942
--- /dev/null
+++ b/src/local_deep_research/web/static/js/collection_details.js
@@ -0,0 +1,476 @@
+/**
+ * Collection Details Page JavaScript
+ * Handles individual collection management and document indexing
+ */
+
+let collectionData = null;
+let documentsData = [];
+let currentFilter = 'all';
+
+/**
+ * Safe fetch wrapper with URL validation
+ */
+async function safeFetch(url, options = {}) {
+ // Internal URLs starting with '/' are safe
+ if (!url.startsWith('/')) {
+ if (!URLValidator.isSafeUrl(url)) {
+ throw new Error(`Blocked unsafe URL: ${url}`);
+ }
+ }
+ return fetch(url, options);
+}
+
+/**
+ * Initialize the page
+ */
+document.addEventListener('DOMContentLoaded', function() {
+ loadCollectionDetails();
+
+ // Setup button handlers
+ document.getElementById('upload-files-btn').addEventListener('click', showUploadModal);
+ document.getElementById('index-collection-btn').addEventListener('click', () => indexCollection(false));
+ document.getElementById('reindex-collection-btn').addEventListener('click', () => indexCollection(true));
+ document.getElementById('delete-collection-btn').addEventListener('click', deleteCollection);
+
+ // Setup modal handlers
+ document.getElementById('upload-files-form').addEventListener('submit', handleUploadFiles);
+ document.getElementById('cancel-upload-btn').addEventListener('click', hideUploadModal);
+
+ // Setup close buttons
+ document.querySelectorAll('.modal .close').forEach(btn => {
+ btn.addEventListener('click', () => {
+ hideUploadModal();
+ });
+ });
+
+ // Click outside modal to close
+ window.addEventListener('click', (event) => {
+ if (event.target.classList.contains('modal')) {
+ event.target.style.display = 'none';
+ }
+ });
+
+ // Setup drag and drop
+ const dropZone = document.getElementById('drop-zone');
+ const fileInput = document.getElementById('files-input');
+
+ if (dropZone && fileInput) {
+ dropZone.addEventListener('click', (e) => {
+ if (e.target.tagName !== 'BUTTON') {
+ fileInput.click();
+ }
+ });
+
+ dropZone.addEventListener('dragover', handleDragOver);
+ dropZone.addEventListener('dragleave', handleDragLeave);
+ dropZone.addEventListener('drop', handleDrop);
+
+ fileInput.addEventListener('change', handleFileSelect);
+ }
+});
+
+/**
+ * Load collection details and documents
+ */
+async function loadCollectionDetails() {
+ try {
+ const response = await safeFetch(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_DOCUMENTS, COLLECTION_ID));
+ const data = await response.json();
+
+ if (data.success) {
+ collectionData = data.collection;
+ documentsData = data.documents || [];
+
+ // Update header
+ document.getElementById('collection-name').textContent = collectionData.name;
+ document.getElementById('collection-description').textContent = collectionData.description || '';
+
+ // Update statistics
+ updateStatistics();
+
+ // Render documents
+ renderDocuments();
+ } else {
+ showError('Failed to load collection details: ' + data.error);
+ }
+ } catch (error) {
+ console.error('Error loading collection details:', error);
+ showError('Failed to load collection details');
+ }
+}
+
+/**
+ * Update statistics
+ */
+function updateStatistics() {
+ const totalDocs = documentsData.length;
+ const indexedDocs = documentsData.filter(doc => doc.indexed).length;
+ const unindexedDocs = totalDocs - indexedDocs;
+ const totalChunks = documentsData.reduce((sum, doc) => sum + (doc.chunk_count || 0), 0);
+
+ document.getElementById('stat-total-docs').textContent = totalDocs;
+ document.getElementById('stat-indexed-docs').textContent = indexedDocs;
+ document.getElementById('stat-unindexed-docs').textContent = unindexedDocs;
+ document.getElementById('stat-total-chunks').textContent = totalChunks;
+}
+
+/**
+ * Render documents list
+ */
+function renderDocuments() {
+ const container = document.getElementById('documents-list');
+ const noDocsMessage = document.getElementById('no-documents-message');
+
+ // Filter documents based on current filter
+ let filteredDocs = documentsData;
+ if (currentFilter === 'indexed') {
+ filteredDocs = documentsData.filter(doc => doc.indexed);
+ } else if (currentFilter === 'unindexed') {
+ filteredDocs = documentsData.filter(doc => !doc.indexed);
+ }
+
+ if (filteredDocs.length === 0) {
+ container.style.display = 'none';
+ noDocsMessage.style.display = 'flex';
+ return;
+ }
+
+ container.style.display = 'block';
+ noDocsMessage.style.display = 'none';
+
+ container.innerHTML = filteredDocs.map(doc => `
+ <div class="document-item">
+ <div class="document-info">
+ <div class="document-title">${escapeHtml(doc.filename)}</div>
+ <div class="document-meta">
+ ${doc.file_size ? `Size: ${formatBytes(doc.file_size)} • ` : ''}
+ ${doc.indexed ?
+ `<span class="badge-success">Indexed (${doc.chunk_count} chunks)</span>` :
+ '<span class="badge-warning">Not indexed</span>'
+ }
+ ${doc.last_indexed_at ? ` • Last indexed: ${new Date(doc.last_indexed_at).toLocaleString()}` : ''}
+ </div>
+ </div>
+ </div>
+ `).join('');
+}
+
+/**
+ * Filter documents
+ */
+function filterDocuments(filter) {
+ currentFilter = filter;
+
+ // Update button states
+ document.querySelectorAll('.filter-controls .btn').forEach(btn => {
+ btn.classList.remove('active');
+ });
+ event.target.classList.add('active');
+
+ renderDocuments();
+}
+
+/**
+ * Show upload modal
+ */
+function showUploadModal() {
+ document.getElementById('upload-files-modal').style.display = 'flex';
+}
+
+/**
+ * Hide upload modal
+ */
+function hideUploadModal() {
+ document.getElementById('upload-files-modal').style.display = 'none';
+ document.getElementById('upload-files-form').reset();
+ document.getElementById('upload-progress').style.display = 'none';
+ document.getElementById('upload-results').style.display = 'none';
+ document.getElementById('selected-files').style.display = 'none';
+}
+
+/**
+ * Handle drag over event
+ */
+function handleDragOver(event) {
+ event.preventDefault();
+ event.stopPropagation();
+ event.currentTarget.classList.add('drag-over');
+}
+
+/**
+ * Handle drag leave event
+ */
+function handleDragLeave(event) {
+ event.preventDefault();
+ event.stopPropagation();
+ event.currentTarget.classList.remove('drag-over');
+}
+
+/**
+ * Handle drop event
+ */
+function handleDrop(event) {
+ event.preventDefault();
+ event.stopPropagation();
+ event.currentTarget.classList.remove('drag-over');
+
+ const files = event.dataTransfer.files;
+ if (files.length > 0) {
+ // Set files to the input element
+ const fileInput = document.getElementById('files-input');
+ const dataTransfer = new DataTransfer();
+ for (let i = 0; i < files.length; i++) {
+ dataTransfer.items.add(files[i]);
+ }
+ fileInput.files = dataTransfer.files;
+
+ // Trigger file select handler
+ handleFileSelect({ target: fileInput });
+ }
+}
+
+/**
+ * Handle file selection (from input or drop)
+ */
+function handleFileSelect(event) {
+ const files = event.target.files;
+ const fileList = document.getElementById('file-list');
+ const selectedFilesDiv = document.getElementById('selected-files');
+
+ if (files.length === 0) {
+ selectedFilesDiv.style.display = 'none';
+ return;
+ }
+
+ // Show selected files
+ fileList.innerHTML = '';
+ for (let file of files) {
+ const li = document.createElement('li');
+ li.innerHTML = `
+ <i class="fas fa-file"></i>
+ <span>${escapeHtml(file.name)} (${formatBytes(file.size)})</span>
+ `;
+ fileList.appendChild(li);
+ }
+
+ selectedFilesDiv.style.display = 'block';
+}
+
+/**
+ * Handle file upload form submission
+ */
+async function handleUploadFiles(event) {
+ event.preventDefault();
+
+ const fileInput = document.getElementById('files-input');
+ const files = fileInput.files;
+
+ if (files.length === 0) {
+ showError('Please select files to upload');
+ return;
+ }
+
+ const formData = new FormData();
+ for (let file of files) {
+ formData.append('files', file);
+ }
+
+ const progressDiv = document.getElementById('upload-progress');
+ const resultsDiv = document.getElementById('upload-results');
+ const submitBtn = document.getElementById('upload-submit-btn');
+
+ try {
+ progressDiv.style.display = 'block';
+ submitBtn.disabled = true;
+
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await safeFetch(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_UPLOAD, COLLECTION_ID), {
+ method: 'POST',
+ headers: {
+ 'X-CSRFToken': csrfToken
+ },
+ body: formData
+ });
+
+ const data = await response.json();
+
+ progressDiv.style.display = 'none';
+ resultsDiv.style.display = 'block';
+
+ if (data.success) {
+ const uploadedCount = data.uploaded ? data.uploaded.length : 0;
+ const failedCount = data.errors ? data.errors.length : 0;
+
+ let resultsHTML = `<p class="success-message"><i class="fas fa-check-circle"></i> Successfully uploaded ${uploadedCount} files</p>`;
+
+ if (failedCount > 0) {
+ resultsHTML += `<p class="error-message"><i class="fas fa-exclamation-circle"></i> Failed to upload ${failedCount} files:</p>`;
+ resultsHTML += '<ul class="error-list">';
+ data.errors.forEach(err => {
+ resultsHTML += `<li>${escapeHtml(err.filename)}: ${escapeHtml(err.error)}</li>`;
+ });
+ resultsHTML += '</ul>';
+ }
+
+ resultsDiv.innerHTML = resultsHTML;
+
+ setTimeout(() => {
+ hideUploadModal();
+ loadCollectionDetails();
+ }, 3000);
+ } else {
+ resultsDiv.innerHTML = `<p class="error-message"><i class="fas fa-times-circle"></i> Upload failed: ${escapeHtml(data.error)}</p>`;
+ }
+ } catch (error) {
+ console.error('Error uploading files:', error);
+ progressDiv.style.display = 'none';
+ resultsDiv.style.display = 'block';
+ resultsDiv.innerHTML = `<p class="error-message"><i class="fas fa-times-circle"></i> Failed to upload files</p>`;
+ } finally {
+ submitBtn.disabled = false;
+ }
+}
+
+/**
+ * Index collection documents
+ */
+async function indexCollection(forceReindex) {
+ const action = forceReindex ? 're-index' : 'index';
+ if (!confirm(`${action.charAt(0).toUpperCase() + action.slice(1)} all documents in this collection?`)) return;
+
+ const progressSection = document.getElementById('indexing-progress');
+ const progressFill = document.getElementById('progress-fill');
+ const progressText = document.getElementById('progress-text');
+ const progressLog = document.getElementById('progress-log');
+
+ try {
+ // Show progress section
+ progressSection.style.display = 'block';
+ progressFill.style.width = '0%';
+ progressText.textContent = 'Starting...';
+ progressLog.innerHTML = '';
+
+ // Use Server-Sent Events for progress updates
+ const url = URLBuilder.build(URLS.LIBRARY_API.COLLECTION_INDEX, COLLECTION_ID) + `?force_reindex=${forceReindex}`;
+ const eventSource = new EventSource(url);
+
+ eventSource.onmessage = function(event) {
+ const data = JSON.parse(event.data);
+
+ if (data.type === 'start') {
+ progressText.textContent = data.message;
+ addLogEntry(data.message, 'info');
+ } else if (data.type === 'progress') {
+ const percent = data.percent || 0;
+ progressFill.style.width = percent + '%';
+ progressText.textContent = `Processing ${data.current}/${data.total}: ${data.filename}`;
+ addLogEntry(`[${data.current}/${data.total}] ${data.filename}`, 'info');
+ } else if (data.type === 'complete') {
+ const results = data.results;
+ progressFill.style.width = '100%';
+ progressText.textContent = `Complete! ${results.successful} indexed, ${results.failed} failed.`;
+ addLogEntry(`Indexing complete! ${results.successful} documents indexed, ${results.failed} failed.`, 'success');
+
+ eventSource.close();
+
+ // Reload collection details after a delay
+ setTimeout(() => {
+ loadCollectionDetails();
+ progressSection.style.display = 'none';
+ }, 3000);
+ } else if (data.type === 'error') {
+ addLogEntry(`Error: ${data.error}`, 'error');
+ progressText.textContent = 'Indexing failed';
+ eventSource.close();
+ }
+ };
+
+ eventSource.onerror = function(error) {
+ console.error('EventSource error:', error);
+ addLogEntry('Connection error during indexing', 'error');
+ progressText.textContent = 'Indexing failed';
+ eventSource.close();
+ };
+ } catch (error) {
+ console.error('Error indexing collection:', error);
+ showError('Failed to index collection');
+ }
+}
+
+/**
+ * Add log entry to progress log
+ */
+function addLogEntry(message, type = 'info') {
+ const progressLog = document.getElementById('progress-log');
+ const entry = document.createElement('div');
+ entry.className = `log-entry log-${type}`;
+ entry.textContent = message;
+ progressLog.appendChild(entry);
+ progressLog.scrollTop = progressLog.scrollHeight;
+}
+
+/**
+ * Delete collection
+ */
+async function deleteCollection() {
+ if (!confirm(`Are you sure you want to delete "${collectionData.name}"? This action cannot be undone.`)) return;
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await safeFetch(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_DETAILS, COLLECTION_ID), {
+ method: 'DELETE',
+ headers: {
+ 'X-CSRFToken': csrfToken
+ }
+ });
+
+ const data = await response.json();
+ if (data.success) {
+ showSuccess(`Collection "${collectionData.name}" deleted successfully`);
+ // Redirect to collections page
+ setTimeout(() => {
+ window.location.href = '/library/collections';
+ }, 1000);
+ } else {
+ showError('Failed to delete collection: ' + data.error);
+ }
+ } catch (error) {
+ console.error('Error deleting collection:', error);
+ showError('Failed to delete collection');
+ }
+}
+
+/**
+ * Format bytes to human readable
+ */
+function formatBytes(bytes) {
+ if (bytes === 0) return '0 B';
+ const k = 1024;
+ const sizes = ['B', 'KB', 'MB', 'GB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+ return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
+}
+
+/**
+ * Escape HTML to prevent XSS
+ */
+function escapeHtml(text) {
+ if (!text) return '';
+ const div = document.createElement('div');
+ div.textContent = text;
+ return div.innerHTML;
+}
+
+/**
+ * Show success message
+ */
+function showSuccess(message) {
+ alert('Success: ' + message);
+}
+
+/**
+ * Show error message
+ */
+function showError(message) {
+ alert('Error: ' + message);
+}
diff --git a/src/local_deep_research/web/static/js/collections_manager.js b/src/local_deep_research/web/static/js/collections_manager.js
new file mode 100644
index 0000000000..9258bf1aac
--- /dev/null
+++ b/src/local_deep_research/web/static/js/collections_manager.js
@@ -0,0 +1,225 @@
+/**
+ * Collections Manager JavaScript
+ * Handles the Collections page UI interactions and API calls
+ */
+
+// Store collections data
+let collections = [];
+let currentCollectionId = null;
+
+/**
+ * Safe fetch wrapper with URL validation
+ */
+async function safeFetch(url, options = {}) {
+ // Internal URLs starting with '/' are safe
+ if (!url.startsWith('/')) {
+ if (!URLValidator.isSafeUrl(url)) {
+ throw new Error(`Blocked unsafe URL: ${url}`);
+ }
+ }
+ return fetch(url, options);
+}
+
+/**
+ * Initialize the page
+ */
+document.addEventListener('DOMContentLoaded', function() {
+ loadCollections();
+
+ // Setup modal handlers
+ document.getElementById('create-collection-btn').addEventListener('click', showCreateCollectionModal);
+ document.getElementById('create-collection-form').addEventListener('submit', handleCreateCollection);
+ document.getElementById('cancel-create-btn').addEventListener('click', hideCreateCollectionModal);
+
+ // Setup close buttons
+ document.querySelectorAll('.modal .close').forEach(btn => {
+ btn.addEventListener('click', () => {
+ hideCreateCollectionModal();
+ });
+ });
+
+ // Click outside modal to close
+ window.addEventListener('click', (event) => {
+ if (event.target.classList.contains('modal')) {
+ event.target.style.display = 'none';
+ }
+ });
+});
+
+/**
+ * Load document collections
+ */
+async function loadCollections() {
+ const container = document.getElementById('collections-container');
+ const noCollectionsMessage = document.getElementById('no-collections-message');
+
+ try {
+ const response = await safeFetch(URLS.LIBRARY_API.COLLECTIONS);
+ const data = await response.json();
+
+ if (data.success) {
+ collections = data.collections || [];
+
+ if (collections.length === 0) {
+ container.style.display = 'none';
+ noCollectionsMessage.style.display = 'flex';
+ } else {
+ container.style.display = 'grid';
+ noCollectionsMessage.style.display = 'none';
+ renderCollections();
+ }
+ } else {
+ showError('Failed to load collections: ' + data.error);
+ }
+ } catch (error) {
+ console.error('Error loading collections:', error);
+ showError('Failed to load collections');
+ }
+}
+
+/**
+ * Render collections grid
+ */
+function renderCollections() {
+ const container = document.getElementById('collections-container');
+
+ container.innerHTML = collections.map(collection => `
+ <div class="collection-card" data-id="${collection.id}">
+ <div class="collection-header">
+ <h3>${escapeHtml(collection.name)}</h3>
+ ${collection.description ? `<p class="collection-description">${escapeHtml(collection.description)}</p>` : ''}
+ </div>
+
+ <div class="collection-stats">
+ <div class="stat-item">
+ <i class="fas fa-file"></i>
+ <span>${collection.document_count || 0} documents</span>
+ </div>
+ ${collection.created_at ? `
+ <div class="stat-item">
+ <i class="fas fa-clock"></i>
+ <span>${new Date(collection.created_at).toLocaleDateString()}</span>
+ </div>
+ ` : ''}
+ ${collection.embedding ? `
+ <div class="stat-item embedding-info">
+ <i class="fas fa-microchip"></i>
+ <span title="Embedding: ${escapeHtml(collection.embedding.provider)}/${escapeHtml(collection.embedding.model)}">${escapeHtml(collection.embedding.model)}</span>
+ </div>
+ ` : `
+ <div class="stat-item embedding-warning">
+ <i class="fas fa-exclamation-triangle"></i>
+ <span title="Collection not yet indexed">Not indexed</span>
+ </div>
+ `}
+ </div>
+
+ <div class="collection-actions">
+ <button class="btn btn-primary" onclick="window.location.href='/library/collections/${collection.id}'">
+ <i class="fas fa-folder-open"></i> Open Collection
+ </button>
+ </div>
+ </div>
+ `).join('');
+}
+
+/**
+ * Show create collection modal
+ */
+function showCreateCollectionModal() {
+ document.getElementById('create-collection-modal').style.display = 'flex';
+ document.getElementById('collection-name').focus();
+}
+
+/**
+ * Hide create collection modal
+ */
+function hideCreateCollectionModal() {
+ document.getElementById('create-collection-modal').style.display = 'none';
+ document.getElementById('create-collection-form').reset();
+}
+
+/**
+ * Handle create collection form submission
+ */
+async function handleCreateCollection(event) {
+ event.preventDefault();
+
+ const name = document.getElementById('collection-name').value.trim();
+ const description = document.getElementById('collection-description').value.trim();
+
+ if (!name) {
+ showError('Collection name is required');
+ return;
+ }
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await safeFetch(URLS.LIBRARY_API.COLLECTIONS, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({
+ name: name,
+ description: description,
+ type: 'user_uploads'
+ })
+ });
+
+ const data = await response.json();
+ if (data.success) {
+ showSuccess(`Collection "${name}" created successfully`);
+ hideCreateCollectionModal();
+ loadCollections();
+ } else {
+ showError('Failed to create collection: ' + data.error);
+ }
+ } catch (error) {
+ console.error('Error creating collection:', error);
+ showError('Failed to create collection');
+ }
+}
+
+/**
+ * Format bytes to human readable
+ */
+function formatBytes(bytes) {
+ if (bytes === 0) return '0 B';
+ const k = 1024;
+ const sizes = ['B', 'KB', 'MB', 'GB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+ return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
+}
+
+/**
+ * Escape HTML to prevent XSS
+ */
+function escapeHtml(text) {
+ if (!text) return '';
+ const div = document.createElement('div');
+ div.textContent = text;
+ return div.innerHTML;
+}
+
+/**
+ * Show success message
+ */
+function showSuccess(message) {
+ alert('Success: ' + message);
+}
+
+/**
+ * Show error message
+ */
+function showError(message) {
+ alert('Error: ' + message);
+}
+
+/**
+ * Show info message
+ */
+function showInfo(message) {
+ console.log('Info: ' + message);
+}
diff --git a/src/local_deep_research/web/static/js/config/urls.js b/src/local_deep_research/web/static/js/config/urls.js
index 19748977f1..3a7bb41583 100644
--- a/src/local_deep_research/web/static/js/config/urls.js
+++ b/src/local_deep_research/web/static/js/config/urls.js
@@ -35,7 +35,11 @@ const URLS = {
SETTINGS: '/settings/',
METRICS: '/metrics/',
METRICS_COSTS: '/metrics/costs', // Added metrics subpage
- METRICS_STAR_REVIEWS: '/metrics/star-reviews' // Added metrics subpage
+ METRICS_STAR_REVIEWS: '/metrics/star-reviews', // Added metrics subpage
+ LIBRARY: '/library/',
+ COLLECTIONS: '/library/collections',
+ COLLECTION_DETAILS: '/library/collections/{id}',
+ RAG_MANAGER: '/library/rag'
},
// History API routes
@@ -83,6 +87,22 @@ const URLS = {
RATINGS_GET: '/metrics/api/ratings/{id}',
RATINGS_SAVE: '/metrics/api/ratings/{id}',
RESEARCH_COSTS: '/metrics/api/research-costs/{id}'
+ },
+
+ // Library & Collections API routes
+ LIBRARY_API: {
+ // Collections management
+ COLLECTIONS: '/library/api/collections',
+ COLLECTION_DETAILS: '/library/api/collections/{id}',
+ COLLECTION_DOCUMENTS: '/library/api/collections/{id}/documents',
+ COLLECTION_UPLOAD: '/library/api/collections/{id}/upload',
+ COLLECTION_INDEX: '/library/api/collections/{id}/index',
+
+ // RAG management
+ RAG_CONFIG: '/library/api/rag/config',
+ RAG_STATUS: '/library/api/rag/status',
+ RAG_INDEX_ALL: '/library/api/rag/index-all',
+ RAG_DOCUMENTS: '/library/api/rag/documents'
}
};
diff --git a/src/local_deep_research/web/static/js/rag_manager.js b/src/local_deep_research/web/static/js/rag_manager.js
index 6eb3ae8ff3..94af9c849b 100644
--- a/src/local_deep_research/web/static/js/rag_manager.js
+++ b/src/local_deep_research/web/static/js/rag_manager.js
@@ -6,6 +6,7 @@
// Available providers and models loaded from API
let providerOptions = [];
let availableModels = {};
+let currentIndexInfo = null; // Store current index info for comparison
/**
* Safe fetch wrapper with URL validation
@@ -39,7 +40,17 @@ document.addEventListener('DOMContentLoaded', function() {
loadDocuments();
// Setup provider change handler
- document.getElementById('embedding-provider').addEventListener('change', updateModelOptions);
+ document.getElementById('embedding-provider').addEventListener('change', function() {
+ updateModelOptions();
+ checkSettingsMismatch();
+ });
+
+ // Setup model change handler
+ document.getElementById('embedding-model').addEventListener('change', checkSettingsMismatch);
+
+ // Setup chunk size/overlap change handlers
+ document.getElementById('chunk-size').addEventListener('input', checkSettingsMismatch);
+ document.getElementById('chunk-overlap').addEventListener('input', checkSettingsMismatch);
// Setup config form submission
document.getElementById('rag-config-form').addEventListener('submit', handleConfigSubmit);
@@ -233,6 +244,9 @@ async function loadCurrentIndexInfo() {
function renderIndexInfo(info) {
const infoContainer = document.getElementById('current-index-info');
+ // Store index info for comparison
+ currentIndexInfo = info;
+
infoContainer.innerHTML = `
<div class="ldr-info-item">
<span class="ldr-info-label">Embedding Model:</span>
@@ -267,6 +281,67 @@ function renderIndexInfo(info) {
<span class="ldr-info-value">${new Date(info.last_updated_at).toLocaleString()}</span>
</div>
`;
+
+ // Check if current form settings match the index
+ checkSettingsMismatch();
+}
+
+/**
+ * Check if current form settings match the indexed settings
+ */
+function checkSettingsMismatch() {
+ // Only check if we have index info
+ if (!currentIndexInfo) {
+ return;
+ }
+
+ const provider = document.getElementById('embedding-provider').value;
+ const model = document.getElementById('embedding-model').value;
+ const chunkSize = parseInt(document.getElementById('chunk-size').value);
+ const chunkOverlap = parseInt(document.getElementById('chunk-overlap').value);
+
+ // Check for mismatches
+ const providerMismatch = provider !== currentIndexInfo.embedding_model_type;
+ const modelMismatch = model !== currentIndexInfo.embedding_model;
+ const chunkSizeMismatch = chunkSize !== currentIndexInfo.chunk_size;
+ const chunkOverlapMismatch = chunkOverlap !== currentIndexInfo.chunk_overlap;
+
+ const hasMismatch = providerMismatch || modelMismatch || chunkSizeMismatch || chunkOverlapMismatch;
+
+ // Get or create warning container
+ let warningContainer = document.getElementById('embedding-warning');
+ if (!warningContainer) {
+ warningContainer = document.createElement('div');
+ warningContainer.id = 'embedding-warning';
+ warningContainer.style.marginTop = '15px';
+ const configSection = document.querySelector('.ldr-config-section:nth-child(2)');
+ if (configSection) {
+ configSection.appendChild(warningContainer);
+ }
+ }
+
+ if (hasMismatch) {
+ const changes = [];
+ if (providerMismatch) changes.push(`Provider: ${currentIndexInfo.embedding_model_type} → ${provider}`);
+ if (modelMismatch) changes.push(`Model: ${currentIndexInfo.embedding_model} → ${model}`);
+ if (chunkSizeMismatch) changes.push(`Chunk Size: ${currentIndexInfo.chunk_size} → ${chunkSize}`);
+ if (chunkOverlapMismatch) changes.push(`Chunk Overlap: ${currentIndexInfo.chunk_overlap} → ${chunkOverlap}`);
+
+ warningContainer.innerHTML = `
+ <div class="ldr-alert ldr-alert-warning" style="margin-top: 10px;">
+ <i class="fas fa-exclamation-triangle"></i>
+ <strong>Settings Changed!</strong><br>
+ <small>${changes.join(', ')}</small><br>
+ <small style="display: block; margin-top: 8px;">
+ ⚠️ <strong>You'll need to re-index all documents</strong> for these changes to take effect.
+ The current index was created with different settings and won't work properly with the new configuration.
+ </small>
+ </div>
+ `;
+ warningContainer.style.display = 'block';
+ } else {
+ warningContainer.style.display = 'none';
+ }
}
/**
@@ -697,3 +772,418 @@ function escapeHtml(text) {
div.textContent = text;
return div.innerHTML;
}
+
+// Store collections data
+let collections = [];
+let currentCollectionId = null;
+let selectedFiles = [];
+
+/**
+ * Load document collections
+ */
+async function loadCollections() {
+ try {
+ const response = await safeFetch('/library/api/collections');
+ const data = await response.json();
+
+ if (data.success) {
+ collections = data.collections;
+ renderCollections();
+ } else {
+ showError('Failed to load collections: ' + data.error);
+ }
+ } catch (error) {
+ console.error('Error loading collections:', error);
+ showError('Failed to load collections');
+ }
+}
+
+/**
+ * Render collections grid
+ */
+function renderCollections() {
+ const container = document.getElementById('collections-container');
+
+ if (collections.length === 0) {
+ container.innerHTML = `
+ <div class="ldr-empty-state">
+ <i class="fas fa-folder-plus fa-3x"></i>
+ <p>No collections yet. Create your first collection to get started!</p>
+ </div>
+ `;
+ return;
+ }
+
+ container.innerHTML = collections.map(collection => `
+ <div class="ldr-collection-card" data-id="${collection.id}">
+ <div class="ldr-collection-header">
+ <div class="ldr-collection-icon">
+ <i class="fas fa-folder fa-2x"></i>
+ </div>
+ <div>
+ <div class="ldr-collection-title">${escapeHtml(collection.name)}</div>
+ ${collection.description ? `<small class="ldr-text-muted">${escapeHtml(collection.description)}</small>` : ''}
+ </div>
+ </div>
+
+ <div class="ldr-collection-stats">
+ <span><i class="fas fa-file"></i> ${collection.document_count || 0} docs</span>
+ <span><i class="fas fa-folder"></i> ${collection.folder_count || 0} folders</span>
+ <span><i class="fas fa-clock"></i> ${collection.created_at ? new Date(collection.created_at).toLocaleDateString() : 'Unknown'}</span>
+ </div>
+
+ <div class="ldr-collection-actions">
+ <button class="ldr-btn ldr-btn-sm ldr-btn-primary" onclick="showUploadModal(${collection.id}, '${escapeHtml(collection.name)}')">
+ <i class="fas fa-upload"></i> Upload
+ </button>
+ <button class="ldr-btn ldr-btn-sm ldr-btn-success" onclick="indexCollection(${collection.id})">
+ <i class="fas fa-sync"></i> Index
+ </button>
+ <button class="ldr-btn ldr-btn-sm ldr-btn-info" onclick="viewCollectionDocs(${collection.id})">
+ <i class="fas fa-list"></i> View
+ </button>
+ <button class="ldr-btn ldr-btn-sm ldr-btn-danger" onclick="deleteCollection(${collection.id})">
+ <i class="fas fa-trash"></i>
+ </button>
+ </div>
+ </div>
+ `).join('');
+}
+
+/**
+ * Get emoji for collection icon
+ */
+function getCollectionEmoji(icon) {
+ const icons = {
+ 'folder': '📁',
+ 'briefcase': '💼',
+ 'book': '📚',
+ 'file-alt': '📄',
+ 'graduation-cap': '🎓',
+ 'code': '💻',
+ 'heart': '❤️'
+ };
+ return icons[icon] || '📁';
+}
+
+/**
+ * Format bytes to human readable
+ */
+function formatBytes(bytes) {
+ if (bytes === 0) return '0 B';
+ const k = 1024;
+ const sizes = ['B', 'KB', 'MB', 'GB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+ return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
+}
+
+/**
+ * Show create collection modal
+ */
+function showCreateCollectionModal() {
+ document.getElementById('create-collection-modal').style.display = 'flex';
+}
+
+/**
+ * Hide create collection modal
+ */
+function hideCreateCollectionModal() {
+ document.getElementById('create-collection-modal').style.display = 'none';
+ document.getElementById('create-collection-form').reset();
+}
+
+/**
+ * Create new collection
+ */
+async function createCollection() {
+ const name = document.getElementById('collection-name').value.trim();
+ const description = document.getElementById('collection-description').value.trim();
+
+ if (!name) {
+ showError('Collection name is required');
+ return;
+ }
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await safeFetch('/library/api/collections', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({
+ name: name,
+ description: description,
+ type: 'user_uploads' // Default to user uploads type
+ })
+ });
+
+ const data = await response.json();
+ if (data.success) {
+ showSuccess(`Collection "${name}" created successfully`);
+ hideCreateCollectionModal();
+ loadCollections();
+ } else {
+ showError('Failed to create collection: ' + data.error);
+ }
+ } catch (error) {
+ console.error('Error creating collection:', error);
+ showError('Failed to create collection');
+ }
+}
+
+/**
+ * Show upload modal
+ */
+function showUploadModal(collectionId, collectionName) {
+ currentCollectionId = collectionId;
+ document.getElementById('upload-collection-name').textContent = collectionName;
+ document.getElementById('upload-files-modal').style.display = 'flex';
+ setupDragAndDrop();
+}
+
+/**
+ * Hide upload modal
+ */
+function hideUploadModal() {
+ document.getElementById('upload-files-modal').style.display = 'none';
+ selectedFiles = [];
+ document.getElementById('file-list').style.display = 'none';
+ document.getElementById('file-items').innerHTML = '';
+ document.getElementById('upload-btn').disabled = true;
+ hideNewDocumentForm();
+}
+
+/**
+ * Setup drag and drop
+ */
+function setupDragAndDrop() {
+ const dropZone = document.getElementById('drop-zone');
+ const fileInput = document.getElementById('file-input');
+
+ // Click to browse
+ dropZone.addEventListener('click', () => fileInput.click());
+
+ // File input change
+ fileInput.addEventListener('change', (e) => {
+ handleFiles(e.target.files);
+ });
+
+ // Drag events
+ dropZone.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ dropZone.classList.add('dragging');
+ });
+
+ dropZone.addEventListener('dragleave', () => {
+ dropZone.classList.remove('dragging');
+ });
+
+ dropZone.addEventListener('drop', (e) => {
+ e.preventDefault();
+ dropZone.classList.remove('dragging');
+ handleFiles(e.dataTransfer.files);
+ });
+}
+
+/**
+ * Handle selected files
+ */
+function handleFiles(files) {
+ selectedFiles = Array.from(files);
+
+ if (selectedFiles.length > 0) {
+ document.getElementById('file-list').style.display = 'block';
+ document.getElementById('upload-btn').disabled = false;
+
+ const fileItems = document.getElementById('file-items');
+ fileItems.innerHTML = selectedFiles.map((file, index) => `
+ <div class="ldr-file-item">
+ <span>${escapeHtml(file.name)} (${formatBytes(file.size)})</span>
+ <button class="ldr-btn ldr-btn-sm ldr-btn-danger" onclick="removeFile(${index})">Remove</button>
+ </div>
+ `).join('');
+ }
+}
+
+/**
+ * Remove file from selection
+ */
+function removeFile(index) {
+ selectedFiles.splice(index, 1);
+ handleFiles(selectedFiles);
+ if (selectedFiles.length === 0) {
+ document.getElementById('file-list').style.display = 'none';
+ document.getElementById('upload-btn').disabled = true;
+ }
+}
+
+/**
+ * Show new document form
+ */
+function showNewDocumentForm() {
+ document.getElementById('new-document-form').style.display = 'block';
+}
+
+/**
+ * Hide new document form
+ */
+function hideNewDocumentForm() {
+ document.getElementById('new-document-form').style.display = 'none';
+ document.getElementById('new-doc-title').value = '';
+ document.getElementById('new-doc-content').value = '';
+}
+
+/**
+ * Add new text document
+ */
+function addNewDocument() {
+ const title = document.getElementById('new-doc-title').value.trim() || 'Untitled Document';
+ const content = document.getElementById('new-doc-content').value.trim();
+
+ if (!content) {
+ showError('Document content is required');
+ return;
+ }
+
+ // Create a Blob from the text content
+ const blob = new Blob([content], { type: 'text/plain' });
+ const file = new File([blob], title + '.txt', { type: 'text/plain' });
+
+ selectedFiles.push(file);
+ handleFiles(selectedFiles);
+ hideNewDocumentForm();
+ showSuccess('Document added to upload queue');
+}
+
+/**
+ * Upload files to collection
+ */
+async function uploadFiles() {
+ if (!currentCollectionId || selectedFiles.length === 0) return;
+
+ const formData = new FormData();
+ selectedFiles.forEach(file => {
+ formData.append('files', file);
+ });
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await safeFetch(`/library/api/collections/${currentCollectionId}/upload`, {
+ method: 'POST',
+ headers: {
+ 'X-CSRFToken': csrfToken
+ },
+ body: formData
+ });
+
+ const data = await response.json();
+ if (data.success) {
+ const uploadedCount = data.uploaded ? data.uploaded.length : 0;
+ showSuccess(`Successfully uploaded ${uploadedCount} files`);
+ hideUploadModal();
+ loadCollections();
+ } else {
+ showError('Upload failed: ' + data.error);
+ }
+ } catch (error) {
+ console.error('Error uploading files:', error);
+ showError('Failed to upload files');
+ }
+}
+
+/**
+ * Index all documents in a collection
+ */
+async function indexCollection(collectionId) {
+ if (!confirm('Index all documents in this collection?')) return;
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await safeFetch(`/library/api/collections/${collectionId}/index`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({ force_reindex: false })
+ });
+
+ if (response.ok) {
+ // Handle SSE for progress
+ const eventSource = new EventSource(`/library/api/collections/${collectionId}/index`);
+
+ eventSource.onmessage = function(event) {
+ const data = JSON.parse(event.data);
+
+ if (data.type === 'complete') {
+ showSuccess(`Indexing complete! ${data.results.successful} documents indexed.`);
+ eventSource.close();
+ loadCollections();
+ } else if (data.type === 'error') {
+ showError(`Indexing error: ${data.error}`);
+ eventSource.close();
+ }
+ };
+ }
+ } catch (error) {
+ console.error('Error indexing collection:', error);
+ showError('Failed to index collection');
+ }
+}
+
+/**
+ * View documents in a collection
+ */
+async function viewCollectionDocs(collectionId) {
+ try {
+ const response = await safeFetch(`/library/api/collections/${collectionId}/documents`);
+ const data = await response.json();
+
+ if (data.success) {
+ // Show documents in a modal or redirect to a detailed view
+ console.log('Collection documents:', data.documents);
+ showSuccess(`Collection has ${data.documents.length} documents`);
+ } else {
+ showError('Failed to load collection documents');
+ }
+ } catch (error) {
+ console.error('Error loading collection documents:', error);
+ showError('Failed to load collection documents');
+ }
+}
+
+/**
+ * Delete a collection
+ */
+async function deleteCollection(collectionId) {
+ if (!confirm('Are you sure you want to delete this collection? This action cannot be undone.')) return;
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await safeFetch(`/library/api/collections/${collectionId}`, {
+ method: 'DELETE',
+ headers: {
+ 'X-CSRFToken': csrfToken
+ }
+ });
+
+ const data = await response.json();
+ if (data.success) {
+ showSuccess('Collection deleted successfully');
+ loadCollections();
+ } else {
+ showError('Failed to delete collection: ' + data.error);
+ }
+ } catch (error) {
+ console.error('Error deleting collection:', error);
+ showError('Failed to delete collection');
+ }
+}
+
+// Initialize collections on page load
+document.addEventListener('DOMContentLoaded', function() {
+ loadCollections();
+ // Keep existing initialization code...
+});
diff --git a/src/local_deep_research/web/templates/components/sidebar.html b/src/local_deep_research/web/templates/components/sidebar.html
index ce845f5393..2ddbbfd537 100644
--- a/src/local_deep_research/web/templates/components/sidebar.html
+++ b/src/local_deep_research/web/templates/components/sidebar.html
@@ -13,6 +13,9 @@
<li {% if active_page == 'library' %}class="active"{% endif %} data-page="library">
<a href="{{ url_for('library.library_page') }}"><i class="fas fa-book"></i> Library</a>
</li>
+ <li {% if active_page == 'collections' %}class="active"{% endif %} data-page="collections">
+ <a href="{{ url_for('rag.collections_page') }}"><i class="fas fa-folder-open"></i> Collections</a>
+ </li>
<li {% if active_page == 'news' %}class="active"{% endif %} data-page="news">
<a href="{{ url_for('news.news_page') }}"><i class="fas fa-newspaper"></i> News</a>
</li>
diff --git a/src/local_deep_research/web/templates/pages/collection_details.html b/src/local_deep_research/web/templates/pages/collection_details.html
new file mode 100644
index 0000000000..6ce6c4208b
--- /dev/null
+++ b/src/local_deep_research/web/templates/pages/collection_details.html
@@ -0,0 +1,224 @@
+{% extends "base.html" %}
+
+{% block extra_head %}
+<link rel="stylesheet" href="/static/css/rag_manager.css">
+<style>
+.drop-zone {
+ border: 2px dashed var(--ldr-border-color, #ccc);
+ border-radius: 8px;
+ padding: 40px 20px;
+ text-align: center;
+ background-color: var(--ldr-card-bg, #f8f9fa);
+ transition: all 0.3s ease;
+ cursor: pointer;
+}
+
+.drop-zone:hover {
+ border-color: var(--ldr-primary-color, #007bff);
+ background-color: var(--ldr-hover-bg, #e9ecef);
+}
+
+.drop-zone.drag-over {
+ border-color: var(--ldr-success-color, #28a745);
+ background-color: var(--ldr-success-bg, #d4edda);
+ border-style: solid;
+}
+
+.drop-zone-text {
+ margin: 15px 0 5px;
+ font-size: 18px;
+ font-weight: 500;
+}
+
+.drop-zone-subtext {
+ margin: 5px 0 15px;
+ color: var(--ldr-text-secondary, #6c757d);
+}
+
+.selected-files {
+ margin-top: 15px;
+ padding: 15px;
+ background-color: var(--ldr-card-bg, #f8f9fa);
+ border-radius: 6px;
+}
+
+.selected-files ul {
+ list-style: none;
+ padding: 0;
+ margin: 10px 0 0;
+}
+
+.selected-files li {
+ padding: 8px 12px;
+ margin: 5px 0;
+ background-color: var(--ldr-bg, white);
+ border: 1px solid var(--ldr-border-color, #dee2e6);
+ border-radius: 4px;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+}
+
+.selected-files li i {
+ color: var(--ldr-primary-color, #007bff);
+}
+</style>
+{% endblock %}
+
+{% block content %}
+<div class="rag-manager-container">
+ <!-- Back button and header -->
+ <div class="rag-header">
+ <div style="display: flex; align-items: center; gap: 15px; margin-bottom: 10px;">
+ <a href="/library/collections" class="btn btn-secondary">
+ <i class="fas fa-arrow-left"></i> Back to Collections
+ </a>
+ </div>
+ <h1 id="collection-title"><i class="fas fa-folder-open"></i> <span id="collection-name">Loading...</span></h1>
+ <p class="subtitle" id="collection-description"></p>
+ </div>
+
+ <!-- Collection Actions -->
+ <div class="rag-section">
+ <div class="section-header">
+ <h2><i class="fas fa-tasks"></i> Actions</h2>
+ </div>
+
+ <div class="collection-actions-grid">
+ <button id="upload-files-btn" class="btn btn-primary btn-lg">
+ <i class="fas fa-upload"></i> Upload Files
+ </button>
+ <button id="index-collection-btn" class="btn btn-success btn-lg">
+ <i class="fas fa-sync"></i> Index All Documents
+ </button>
+ <button id="reindex-collection-btn" class="btn btn-warning btn-lg">
+ <i class="fas fa-redo"></i> Re-Index All Documents
+ </button>
+ <button id="delete-collection-btn" class="btn btn-danger btn-lg">
+ <i class="fas fa-trash"></i> Delete Collection
+ </button>
+ </div>
+ </div>
+
+ <!-- Statistics -->
+ <div class="rag-section">
+ <div class="section-header">
+ <h2><i class="fas fa-chart-bar"></i> Statistics</h2>
+ </div>
+
+ <div class="stats-grid">
+ <div class="stat-card">
+ <div class="stat-value" id="stat-total-docs">-</div>
+ <div class="stat-label">Total Documents</div>
+ </div>
+ <div class="stat-card stat-success">
+ <div class="stat-value" id="stat-indexed-docs">-</div>
+ <div class="stat-label">Indexed Documents</div>
+ </div>
+ <div class="stat-card stat-warning">
+ <div class="stat-value" id="stat-unindexed-docs">-</div>
+ <div class="stat-label">Not Indexed</div>
+ </div>
+ <div class="stat-card">
+ <div class="stat-value" id="stat-total-chunks">-</div>
+ <div class="stat-label">Total Chunks</div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Indexing Progress -->
+ <div id="indexing-progress" class="rag-section" style="display: none;">
+ <div class="section-header">
+ <h2><i class="fas fa-spinner fa-spin"></i> Indexing Progress</h2>
+ </div>
+
+ <div class="progress-container">
+ <div class="progress-bar">
+ <div id="progress-fill" class="progress-fill" style="width: 0%"></div>
+ </div>
+ <p id="progress-text" class="progress-text">Starting...</p>
+ </div>
+
+ <div id="progress-log" class="progress-log"></div>
+ </div>
+
+ <!-- Documents List -->
+ <div class="rag-section">
+ <div class="section-header">
+ <h2><i class="fas fa-file"></i> Documents</h2>
+ <div class="filter-controls">
+ <button class="btn btn-outline-primary active" onclick="filterDocuments('all')">All</button>
+ <button class="btn btn-outline-success" onclick="filterDocuments('indexed')">Indexed</button>
+ <button class="btn btn-outline-warning" onclick="filterDocuments('unindexed')">Not Indexed</button>
+ </div>
+ </div>
+
+ <div id="documents-list" class="documents-list">
+ <div class="loading-spinner">
+ <i class="fas fa-spinner fa-spin"></i> Loading documents...
+ </div>
+ </div>
+
+ <div id="no-documents-message" class="empty-state" style="display: none;">
+ <i class="fas fa-file fa-3x"></i>
+ <p>No documents in this collection yet</p>
+ <button class="btn btn-primary" onclick="document.getElementById('upload-files-btn').click()">
+ <i class="fas fa-upload"></i> Upload Files
+ </button>
+ </div>
+ </div>
+</div>
+
+<!-- Upload Files Modal -->
+<div id="upload-files-modal" class="modal">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h3>Upload Files to Collection</h3>
+ <span class="close">&times;</span>
+ </div>
+ <div class="modal-body">
+ <form id="upload-files-form">
+ <div class="form-group">
+ <label>Upload Files (PDF, TXT, MD, HTML)</label>
+
+ <!-- Drag and drop zone -->
+ <div id="drop-zone" class="drop-zone">
+ <i class="fas fa-cloud-upload-alt fa-3x"></i>
+ <p class="drop-zone-text">Drag and drop files here</p>
+ <p class="drop-zone-subtext">or</p>
+ <button type="button" class="btn btn-primary" onclick="document.getElementById('files-input').click()">
+ <i class="fas fa-folder-open"></i> Browse Files
+ </button>
+ <input type="file" id="files-input" name="files" multiple accept=".pdf,.txt,.md,.html,.htm" style="display: none;">
+ </div>
+
+ <!-- Selected files preview -->
+ <div id="selected-files" class="selected-files" style="display: none;">
+ <p><strong>Selected files:</strong></p>
+ <ul id="file-list"></ul>
+ </div>
+
+ <p class="form-help">Accepted formats: PDF, TXT, MD, HTML. Text will be extracted and stored securely.</p>
+ </div>
+ <div id="upload-progress" class="upload-progress" style="display: none;">
+ <div class="progress-bar">
+ <div class="progress-fill"></div>
+ </div>
+ <p class="progress-text"></p>
+ </div>
+ <div id="upload-results" class="upload-results" style="display: none;"></div>
+ <div class="form-actions">
+ <button type="button" class="btn btn-secondary" id="cancel-upload-btn">Cancel</button>
+ <button type="submit" class="btn btn-primary" id="upload-submit-btn">Upload Files</button>
+ </div>
+ </form>
+ </div>
+ </div>
+</div>
+
+<!-- Pass collection_id to JavaScript -->
+<script>
+ const COLLECTION_ID = {{ collection_id }};
+</script>
+<script src="/static/js/collection_details.js"></script>
+{% endblock %}
diff --git a/src/local_deep_research/web/templates/pages/collections.html b/src/local_deep_research/web/templates/pages/collections.html
new file mode 100644
index 0000000000..a420b3a44d
--- /dev/null
+++ b/src/local_deep_research/web/templates/pages/collections.html
@@ -0,0 +1,62 @@
+{% extends "base.html" %}
+
+{% block extra_head %}
+<link rel="stylesheet" href="/static/css/rag_manager.css">
+{% endblock %}
+
+{% block content %}
+<div class="rag-manager-container">
+ <div class="rag-header">
+ <h1><i class="fas fa-folder-open"></i> Document Collections</h1>
+ <p class="subtitle">Manage your document collections for RAG-enabled searches</p>
+ </div>
+
+ <!-- Collections Section -->
+ <div class="rag-section">
+ <div class="section-header">
+ <h2><i class="fas fa-folder"></i> My Collections</h2>
+ <button id="create-collection-btn" class="btn btn-primary">
+ <i class="fas fa-plus"></i> Create Collection
+ </button>
+ </div>
+
+ <div id="collections-container" class="collections-grid">
+ <!-- Collections will be loaded here -->
+ </div>
+
+ <div id="no-collections-message" class="empty-state" style="display: none;">
+ <i class="fas fa-folder-open fa-3x"></i>
+ <p>No collections yet</p>
+ <p class="text-muted">Create your first collection to organize your documents</p>
+ </div>
+ </div>
+</div>
+
+<!-- Create Collection Modal -->
+<div id="create-collection-modal" class="modal">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h3>Create New Collection</h3>
+ <span class="close">&times;</span>
+ </div>
+ <div class="modal-body">
+ <form id="create-collection-form">
+ <div class="form-group">
+ <label for="collection-name">Collection Name *</label>
+ <input type="text" id="collection-name" name="name" required placeholder="e.g., Research Papers, Work Documents">
+ </div>
+ <div class="form-group">
+ <label for="collection-description">Description</label>
+ <textarea id="collection-description" name="description" rows="3" placeholder="Describe what this collection is for..."></textarea>
+ </div>
+ <div class="form-actions">
+ <button type="button" class="btn btn-secondary" id="cancel-create-btn">Cancel</button>
+ <button type="submit" class="btn btn-primary">Create Collection</button>
+ </div>
+ </form>
+ </div>
+ </div>
+</div>
+
+<script src="/static/js/collections_manager.js"></script>
+{% 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
new file mode 100644
index 0000000000..5204a1cbf4
--- /dev/null
+++ b/src/local_deep_research/web/templates/pages/document_details.html
@@ -0,0 +1,485 @@
+{% extends "base.html" %}
+
+{% block extra_head %}
+<style>
+.document-details-container {
+ max-width: 1200px;
+ margin: 0 auto;
+ padding: 20px;
+}
+
+.document-header {
+ margin-bottom: 30px;
+}
+
+.document-title {
+ font-size: 28px;
+ font-weight: 600;
+ margin-bottom: 10px;
+ color: var(--ldr-text-primary, #212529);
+}
+
+.document-subtitle {
+ font-size: 16px;
+ color: var(--ldr-text-secondary, #6c757d);
+ margin-bottom: 15px;
+}
+
+.document-actions {
+ display: flex;
+ gap: 10px;
+ flex-wrap: wrap;
+ margin-top: 20px;
+}
+
+.metadata-section {
+ background-color: var(--ldr-card-bg, #ffffff);
+ border: 1px solid var(--ldr-border-color, #dee2e6);
+ border-radius: 8px;
+ padding: 20px;
+ margin-bottom: 20px;
+}
+
+.metadata-section h2 {
+ font-size: 20px;
+ font-weight: 600;
+ margin-bottom: 15px;
+ color: var(--ldr-text-primary, #212529);
+ border-bottom: 2px solid var(--ldr-primary-color, #007bff);
+ padding-bottom: 10px;
+}
+
+.metadata-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
+ gap: 15px;
+}
+
+.metadata-item {
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+}
+
+.metadata-label {
+ font-weight: 600;
+ color: var(--ldr-text-secondary, #6c757d);
+ font-size: 13px;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+}
+
+.metadata-value {
+ color: var(--ldr-text-primary, #212529);
+ font-size: 15px;
+ word-break: break-word;
+}
+
+.metadata-value a {
+ color: var(--ldr-primary-color, #007bff);
+ text-decoration: none;
+}
+
+.metadata-value a:hover {
+ text-decoration: underline;
+}
+
+.badge {
+ display: inline-block;
+ padding: 4px 12px;
+ border-radius: 4px;
+ font-size: 13px;
+ font-weight: 500;
+}
+
+.badge-success {
+ background-color: var(--ldr-success-bg, #d4edda);
+ color: var(--ldr-success-color, #155724);
+}
+
+.badge-info {
+ background-color: var(--ldr-info-bg, #d1ecf1);
+ color: var(--ldr-info-color, #0c5460);
+}
+
+.badge-warning {
+ background-color: var(--ldr-warning-bg, #fff3cd);
+ color: var(--ldr-warning-color, #856404);
+}
+
+.authors-list {
+ list-style: none;
+ padding: 0;
+ margin: 0;
+}
+
+.authors-list li {
+ display: inline;
+}
+
+.authors-list li:not(:last-child):after {
+ content: ", ";
+}
+
+.content-preview {
+ background-color: var(--ldr-bg, #f8f9fa);
+ padding: 15px;
+ border-radius: 4px;
+ border-left: 3px solid var(--ldr-primary-color, #007bff);
+ white-space: pre-wrap;
+ font-family: monospace;
+ font-size: 13px;
+ max-height: 400px;
+ overflow-y: auto;
+}
+
+.rag-status {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+}
+
+.rag-status i {
+ font-size: 18px;
+}
+
+.btn {
+ padding: 8px 16px;
+ border: none;
+ border-radius: 4px;
+ font-size: 14px;
+ font-weight: 500;
+ cursor: pointer;
+ text-decoration: none;
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ transition: all 0.2s;
+}
+
+.btn-primary {
+ background-color: var(--ldr-primary-color, #007bff);
+ color: white;
+}
+
+.btn-primary:hover {
+ background-color: var(--ldr-primary-hover, #0056b3);
+}
+
+.btn-secondary {
+ background-color: var(--ldr-secondary-bg, #6c757d);
+ color: white;
+}
+
+.btn-secondary:hover {
+ background-color: var(--ldr-secondary-hover, #545b62);
+}
+
+.btn-success {
+ background-color: var(--ldr-success-color, #28a745);
+ color: white;
+}
+
+.btn-success:hover {
+ background-color: var(--ldr-success-hover, #218838);
+}
+
+.empty-value {
+ color: var(--ldr-text-secondary, #6c757d);
+ font-style: italic;
+}
+</style>
+{% endblock %}
+
+{% block content %}
+<div class="document-details-container">
+ <!-- Back button and header -->
+ <div class="document-header">
+ <a href="/library" class="btn btn-secondary">
+ <i class="fas fa-arrow-left"></i> Back to Library
+ </a>
+
+ <h1 class="document-title">
+ <i class="fas fa-file-pdf"></i> {{ document.document_title or "Untitled Document" }}
+ </h1>
+
+ {% if document.authors %}
+ <div class="document-subtitle">
+ <ul class="authors-list">
+ {% for author in document.authors %}
+ <li>{{ author }}</li>
+ {% endfor %}
+ </ul>
+ </div>
+ {% endif %}
+
+ <div class="document-actions">
+ {% if document.file_exists and document.file_absolute_path %}
+ <a href="/library/api/document/{{ document.id }}/pdf" target="_blank" class="btn btn-primary">
+ <i class="fas fa-file-pdf"></i> View PDF
+ </a>
+ {% endif %}
+
+ {% if document.has_text %}
+ <button onclick="viewText()" class="btn btn-success">
+ <i class="fas fa-file-alt"></i> View Text
+ </button>
+ {% endif %}
+
+ {% if document.original_url %}
+ <a href="{{ document.original_url }}" target="_blank" class="btn btn-secondary">
+ <i class="fas fa-external-link-alt"></i> Original Source
+ </a>
+ {% endif %}
+ </div>
+ </div>
+
+ <!-- Document Information -->
+ <div class="metadata-section">
+ <h2><i class="fas fa-info-circle"></i> Document Information</h2>
+ <div class="metadata-grid">
+ <div class="metadata-item">
+ <div class="metadata-label">Document ID</div>
+ <div class="metadata-value"><code>{{ document.id }}</code></div>
+ </div>
+
+ <div class="metadata-item">
+ <div class="metadata-label">File Type</div>
+ <div class="metadata-value">
+ <span class="badge badge-info">{{ document.file_type | upper }}</span>
+ </div>
+ </div>
+
+ <div class="metadata-item">
+ <div class="metadata-label">File Size</div>
+ <div class="metadata-value">{{ document.file_size_formatted }}</div>
+ </div>
+
+ <div class="metadata-item">
+ <div class="metadata-label">Download Status</div>
+ <div class="metadata-value">
+ {% if document.download_status == 'completed' %}
+ <span class="badge badge-success">Completed</span>
+ {% else %}
+ <span class="badge badge-warning">{{ document.download_status | title }}</span>
+ {% endif %}
+ </div>
+ </div>
+
+ <div class="metadata-item">
+ <div class="metadata-label">Downloaded At</div>
+ <div class="metadata-value">{{ document.downloaded_at or "N/A" }}</div>
+ </div>
+
+ {% if document.domain %}
+ <div class="metadata-item">
+ <div class="metadata-label">Source Domain</div>
+ <div class="metadata-value">{{ document.domain }}</div>
+ </div>
+ {% endif %}
+ </div>
+ </div>
+
+ <!-- Academic Identifiers -->
+ {% if document.doi or document.arxiv_id or document.pmid or document.pmcid or document.isbn %}
+ <div class="metadata-section">
+ <h2><i class="fas fa-fingerprint"></i> Academic Identifiers</h2>
+ <div class="metadata-grid">
+ {% if document.doi %}
+ <div class="metadata-item">
+ <div class="metadata-label">DOI</div>
+ <div class="metadata-value">
+ <a href="https://doi.org/{{ document.doi }}" target="_blank">{{ document.doi }}</a>
+ </div>
+ </div>
+ {% endif %}
+
+ {% if document.arxiv_id %}
+ <div class="metadata-item">
+ <div class="metadata-label">arXiv ID</div>
+ <div class="metadata-value">
+ <a href="https://arxiv.org/abs/{{ document.arxiv_id }}" target="_blank">{{ document.arxiv_id }}</a>
+ </div>
+ </div>
+ {% endif %}
+
+ {% if document.pmid %}
+ <div class="metadata-item">
+ <div class="metadata-label">PubMed ID</div>
+ <div class="metadata-value">
+ <a href="https://pubmed.ncbi.nlm.nih.gov/{{ document.pmid }}" target="_blank">{{ document.pmid }}</a>
+ </div>
+ </div>
+ {% endif %}
+
+ {% if document.pmcid %}
+ <div class="metadata-item">
+ <div class="metadata-label">PMC ID</div>
+ <div class="metadata-value">
+ <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/{{ document.pmcid }}" target="_blank">{{ document.pmcid }}</a>
+ </div>
+ </div>
+ {% endif %}
+
+ {% if document.isbn %}
+ <div class="metadata-item">
+ <div class="metadata-label">ISBN</div>
+ <div class="metadata-value">{{ document.isbn }}</div>
+ </div>
+ {% endif %}
+ </div>
+ </div>
+ {% endif %}
+
+ <!-- Publication Information -->
+ {% if document.published_date %}
+ <div class="metadata-section">
+ <h2><i class="fas fa-calendar"></i> Publication Information</h2>
+ <div class="metadata-grid">
+ <div class="metadata-item">
+ <div class="metadata-label">Published Date</div>
+ <div class="metadata-value">{{ document.published_date }}</div>
+ </div>
+ </div>
+ </div>
+ {% endif %}
+
+ <!-- RAG/Indexing Status -->
+ <div class="metadata-section">
+ <h2><i class="fas fa-search"></i> RAG & Indexing Status</h2>
+ <div class="metadata-grid">
+ <div class="metadata-item">
+ <div class="metadata-label">RAG Indexed</div>
+ <div class="metadata-value">
+ <div class="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>
+ </div>
+ </div>
+
+ {% if document.last_indexed_at %}
+ <div class="metadata-item">
+ <div class="metadata-label">Last Indexed</div>
+ <div class="metadata-value">{{ document.last_indexed_at }}</div>
+ </div>
+ {% endif %}
+
+ {% if document.has_text %}
+ <div class="metadata-item">
+ <div class="metadata-label">Text Content</div>
+ <div class="metadata-value">
+ <div class="rag-status">
+ <i class="fas fa-file-alt" style="color: var(--ldr-success-color, #28a745);"></i>
+ <span>Available ({{ document.word_count or 0 }} words)</span>
+ </div>
+ </div>
+ </div>
+ {% endif %}
+ </div>
+ </div>
+
+ <!-- File Path Information -->
+ {% if document.file_path %}
+ <div class="metadata-section">
+ <h2><i class="fas fa-folder-open"></i> File Location</h2>
+ <div class="metadata-grid">
+ <div class="metadata-item">
+ <div class="metadata-label">File Path</div>
+ <div class="metadata-value">
+ <code>{{ document.file_path }}</code>
+ </div>
+ </div>
+
+ {% if document.file_absolute_path %}
+ <div class="metadata-item">
+ <div class="metadata-label">Absolute Path</div>
+ <div class="metadata-value">
+ <code>{{ document.file_absolute_path }}</code>
+ </div>
+ </div>
+ {% endif %}
+ </div>
+ </div>
+ {% endif %}
+
+ <!-- Original URL -->
+ {% if document.original_url %}
+ <div class="metadata-section">
+ <h2><i class="fas fa-link"></i> Source URL</h2>
+ <div class="metadata-item">
+ <div class="metadata-value">
+ <a href="{{ document.original_url }}" target="_blank">{{ document.original_url }}</a>
+ </div>
+ </div>
+ </div>
+ {% endif %}
+</div>
+
+<script>
+function viewText() {
+ fetch('/library/api/document/{{ document.id }}/text')
+ .then(response => response.json())
+ .then(data => {
+ if (data.text_content) {
+ // Open text in a new window or modal
+ const textWindow = window.open('', '_blank');
+ textWindow.document.write(`
+ <!DOCTYPE html>
+ <html>
+ <head>
+ <title>${data.title || 'Document Text'}</title>
+ <style>
+ body {
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
+ max-width: 900px;
+ margin: 40px auto;
+ padding: 20px;
+ line-height: 1.6;
+ }
+ pre {
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ font-family: inherit;
+ }
+ .header {
+ border-bottom: 2px solid #007bff;
+ padding-bottom: 10px;
+ margin-bottom: 20px;
+ }
+ .meta {
+ color: #6c757d;
+ font-size: 14px;
+ margin-bottom: 20px;
+ }
+ </style>
+ </head>
+ <body>
+ <div class="header">
+ <h1>${data.title || 'Document Text'}</h1>
+ </div>
+ <div class="meta">
+ <strong>Extraction Method:</strong> ${data.extraction_method || 'Unknown'}<br>
+ <strong>Word Count:</strong> ${data.word_count || 'Unknown'}
+ </div>
+ <pre>${data.text_content}</pre>
+ </body>
+ </html>
+ `);
+ textWindow.document.close();
+ } else {
+ alert('Text content not available');
+ }
+ })
+ .catch(error => {
+ console.error('Error fetching text:', error);
+ alert('Failed to load text content');
+ });
+}
+</script>
+{% endblock %}
diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.html
index 7ebc4e476b..c837f4bbd6 100644
--- a/src/local_deep_research/web/templates/pages/library.html
+++ b/src/local_deep_research/web/templates/pages/library.html
@@ -194,7 +194,7 @@
</div>
<!-- Card Body -->
- <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 %}>
+ <div class="card-body" {% if doc.has_pdf or doc.has_text_db %}onclick="window.location.href='/library/document/{{ doc.id }}'"{% else %}style="cursor: not-allowed; opacity: 0.6;"{% endif %}>
<!-- Storage availability badges -->
<div class="ldr-storage-badges">
{% if doc.has_pdf %}
diff --git a/src/local_deep_research/web/templates/pages/rag_manager.html b/src/local_deep_research/web/templates/pages/rag_manager.html
index 89865fee36..14b6e43d54 100644
--- a/src/local_deep_research/web/templates/pages/rag_manager.html
+++ b/src/local_deep_research/web/templates/pages/rag_manager.html
@@ -95,6 +95,27 @@
</button>
</div>
+ <!-- Document Collections Section -->
+ <div class="ldr-collections-section ldr-mt-4">
+ <h3><i class="fas fa-layer-group"></i> Document Collections</h3>
+ <p class="ldr-form-text ldr-text-muted">Organize your documents into collections. Each collection can be searched independently.</p>
+
+ <!-- Create New Collection -->
+ <div class="ldr-new-collection-form">
+ <button class="ldr-btn ldr-btn-primary" onclick="showCreateCollectionModal()">
+ <i class="fas fa-plus"></i> Create New Collection
+ </button>
+ </div>
+
+ <!-- Collections List -->
+ <div id="collections-container" class="ldr-collections-grid ldr-mt-3">
+ <!-- Collections will be loaded here dynamically -->
+ <div class="ldr-loading-spinner">
+ <i class="fas fa-spinner fa-spin"></i> Loading collections...
+ </div>
+ </div>
+ </div>
+
<!-- Progress Display -->
<div id="progress-container" class="ldr-mt-4" style="display: none;">
<h3>Indexing Progress</h3>
@@ -133,6 +154,94 @@
</div>
</div>
+<!-- Create Collection Modal -->
+<div id="create-collection-modal" class="ldr-modal" style="display: none;">
+ <div class="ldr-modal-content">
+ <div class="ldr-modal-header">
+ <h2>Create New Collection</h2>
+ <span class="ldr-modal-close" onclick="hideCreateCollectionModal()">&times;</span>
+ </div>
+ <div class="ldr-modal-body">
+ <form id="create-collection-form">
+ <div class="ldr-form-group">
+ <label for="collection-name">Collection Name</label>
+ <input type="text" id="collection-name" class="ldr-form-control" placeholder="e.g., Work Documents" required>
+ </div>
+ <div class="ldr-form-group">
+ <label for="collection-description">Description</label>
+ <textarea id="collection-description" class="ldr-form-control" rows="3" placeholder="Optional description"></textarea>
+ </div>
+ <div class="ldr-form-group">
+ <label for="collection-icon">Icon</label>
+ <select id="collection-icon" class="ldr-form-control">
+ <option value="folder">📁 Folder</option>
+ <option value="briefcase">💼 Briefcase</option>
+ <option value="book">📚 Book</option>
+ <option value="file-alt">📄 Document</option>
+ <option value="graduation-cap">🎓 Academic</option>
+ <option value="code">💻 Code</option>
+ <option value="heart">❤️ Personal</option>
+ </select>
+ </div>
+ <div class="ldr-form-group">
+ <label for="collection-color">Color</label>
+ <input type="color" id="collection-color" class="ldr-form-control" value="#007bff">
+ </div>
+ </form>
+ </div>
+ <div class="ldr-modal-footer">
+ <button class="ldr-btn ldr-btn-secondary" onclick="hideCreateCollectionModal()">Cancel</button>
+ <button class="ldr-btn ldr-btn-primary" onclick="createCollection()">Create Collection</button>
+ </div>
+ </div>
+</div>
+
+<!-- Upload Files Modal -->
+<div id="upload-files-modal" class="ldr-modal" style="display: none;">
+ <div class="ldr-modal-content ldr-modal-large">
+ <div class="ldr-modal-header">
+ <h2>Upload Documents to <span id="upload-collection-name"></span></h2>
+ <span class="ldr-modal-close" onclick="hideUploadModal()">&times;</span>
+ </div>
+ <div class="ldr-modal-body">
+ <!-- Drag & Drop Zone -->
+ <div id="drop-zone" class="ldr-drop-zone">
+ <i class="fas fa-cloud-upload-alt fa-3x"></i>
+ <p>Drag and drop files here or click to browse</p>
+ <p class="ldr-text-muted">Supported: PDF, TXT, MD, HTML, DOC, DOCX</p>
+ <input type="file" id="file-input" multiple accept=".pdf,.txt,.md,.html,.doc,.docx" style="display: none;">
+ </div>
+
+ <!-- File List -->
+ <div id="file-list" class="ldr-file-list ldr-mt-3" style="display: none;">
+ <h4>Selected Files</h4>
+ <div id="file-items"></div>
+ </div>
+
+ <!-- Create New Text Document -->
+ <div class="ldr-new-document-section ldr-mt-3">
+ <button class="ldr-btn ldr-btn-outline-primary" onclick="showNewDocumentForm()">
+ <i class="fas fa-file-plus"></i> Create New Text Document
+ </button>
+ <div id="new-document-form" style="display: none;" class="ldr-mt-3">
+ <input type="text" id="new-doc-title" class="ldr-form-control ldr-mb-2" placeholder="Document title">
+ <textarea id="new-doc-content" class="ldr-form-control" rows="10" placeholder="Enter or paste your text here..."></textarea>
+ <div class="ldr-mt-2">
+ <button class="ldr-btn ldr-btn-primary" onclick="addNewDocument()">Add Document</button>
+ <button class="ldr-btn ldr-btn-secondary" onclick="hideNewDocumentForm()">Cancel</button>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div class="ldr-modal-footer">
+ <button class="ldr-btn ldr-btn-secondary" onclick="hideUploadModal()">Cancel</button>
+ <button class="ldr-btn ldr-btn-primary" onclick="uploadFiles()" id="upload-btn" disabled>
+ <i class="fas fa-upload"></i> Upload & Index Files
+ </button>
+ </div>
+ </div>
+</div>
+
<style>
.ldr-library-container {
padding: 20px;
@@ -280,6 +389,202 @@
gap: 20px;
}
+.ldr-collections-section {
+ margin-top: 30px;
+ padding-top: 30px;
+ border-top: 2px solid var(--border-color, #444);
+}
+
+.ldr-collections-section h3 {
+ margin-bottom: 15px;
+ font-size: 1.3em;
+ color: var(--text-primary, #e4e4e4);
+}
+
+.ldr-collections-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
+ gap: 20px;
+ margin-top: 20px;
+}
+
+.ldr-collection-card {
+ background: var(--card-bg, #2a2a2a);
+ border: 2px solid var(--border-color, #444);
+ border-radius: 8px;
+ padding: 20px;
+ transition: all 0.3s;
+ cursor: pointer;
+}
+
+.ldr-collection-card:hover {
+ border-color: var(--primary-color, #007bff);
+ box-shadow: 0 4px 12px rgba(0,0,0,0.2);
+}
+
+.ldr-collection-header {
+ display: flex;
+ align-items: center;
+ margin-bottom: 15px;
+}
+
+.ldr-collection-icon {
+ font-size: 2em;
+ margin-right: 15px;
+}
+
+.ldr-collection-title {
+ font-size: 1.2em;
+ font-weight: 600;
+ color: var(--text-primary, #e4e4e4);
+}
+
+.ldr-collection-stats {
+ display: flex;
+ gap: 15px;
+ margin: 15px 0;
+ font-size: 0.9em;
+ color: var(--text-secondary, #999);
+}
+
+.ldr-collection-actions {
+ display: flex;
+ gap: 10px;
+ margin-top: 15px;
+}
+
+/* Modal Styles */
+.ldr-modal {
+ position: fixed;
+ z-index: 1000;
+ left: 0;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ background-color: rgba(0, 0, 0, 0.7);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.ldr-modal-content {
+ background: var(--card-bg, #2a2a2a);
+ border-radius: 8px;
+ width: 90%;
+ max-width: 500px;
+ max-height: 90vh;
+ overflow-y: auto;
+}
+
+.ldr-modal-large {
+ max-width: 800px;
+}
+
+.ldr-modal-header {
+ padding: 20px;
+ border-bottom: 1px solid var(--border-color, #444);
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+}
+
+.ldr-modal-close {
+ font-size: 28px;
+ font-weight: bold;
+ color: var(--text-secondary, #999);
+ cursor: pointer;
+}
+
+.ldr-modal-close:hover {
+ color: var(--text-primary, #e4e4e4);
+}
+
+.ldr-modal-body {
+ padding: 20px;
+}
+
+.ldr-modal-footer {
+ padding: 15px 20px;
+ border-top: 1px solid var(--border-color, #444);
+ display: flex;
+ justify-content: flex-end;
+ gap: 10px;
+}
+
+/* Drag & Drop Zone */
+.ldr-drop-zone {
+ border: 2px dashed var(--border-color, #444);
+ border-radius: 8px;
+ padding: 40px;
+ text-align: center;
+ cursor: pointer;
+ transition: all 0.3s;
+}
+
+.ldr-drop-zone:hover {
+ border-color: var(--primary-color, #007bff);
+ background: rgba(13, 110, 253, 0.1);
+}
+
+.ldr-drop-zone.dragging {
+ border-color: var(--success-color, #28a745);
+ background: rgba(40, 167, 69, 0.1);
+}
+
+.ldr-drop-zone i {
+ color: var(--primary-color, #007bff);
+ margin-bottom: 15px;
+}
+
+.ldr-file-list {
+ max-height: 300px;
+ overflow-y: auto;
+ border: 1px solid var(--border-color, #444);
+ border-radius: 4px;
+ padding: 15px;
+}
+
+.ldr-file-item {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 10px;
+ margin-bottom: 10px;
+ background: var(--input-bg, #1a1a1a);
+ border-radius: 4px;
+}
+
+.ldr-file-item button {
+ padding: 4px 8px;
+ font-size: 0.85em;
+}
+
+.ldr-mb-2 {
+ margin-bottom: 10px;
+}
+
+.ldr-mt-2 {
+ margin-top: 10px;
+}
+
+.ldr-mt-3 {
+ margin-top: 15px;
+}
+
+.ldr-form-row {
+ display: flex;
+ gap: 20px;
+ margin-bottom: 15px;
+}
+
+.ldr-col-md-6 {
+ flex: 1;
+}
+
+.ldr-mt-4 {
+ margin-top: 20px;
+}
+
.ldr-loading-spinner {
text-align: center;
padding: 40px;
@@ -401,6 +706,12 @@
border-color: #c3e6cb;
}
+.ldr-alert-warning {
+ color: #856404;
+ background-color: #fff3cd;
+ border-color: #ffeaa7;
+}
+
.ldr-alert i {
margin-right: 8px;
}
diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.html
index 204a04a9ed..bc9818b023 100644
--- a/src/local_deep_research/web/templates/pages/research.html
+++ b/src/local_deep_research/web/templates/pages/research.html
@@ -156,8 +156,6 @@
<span class="ldr-input-help">Source-Based: Proven strategy for detailed research. Focused Iteration: 2x faster for direct answers. Iterative Refinement: Automatically refines results until comprehensive. Performance varies with LLM and configuration.</span>
</div>
- <!-- Empty div for layout balance -->
- <div class="ldr-form-group ldr-half"></div>
</div>
</div>
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_collection.py b/src/local_deep_research/web_search_engines/engines/search_engine_collection.py
new file mode 100644
index 0000000000..adc354e387
--- /dev/null
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_collection.py
@@ -0,0 +1,140 @@
+"""
+Collection-specific RAG Search Engine
+
+Provides semantic search within a specific document collection using RAG.
+"""
+
+from typing import List, Dict, Any, Optional
+from loguru import logger
+
+from .search_engine_library import LibraryRAGSearchEngine
+
+
+class CollectionSearchEngine(LibraryRAGSearchEngine):
+ """
+ Search engine for a specific document collection using RAG.
+ Extends LibraryRAGSearchEngine to filter results by collection ID.
+ Each collection uses its own embedding model that was used during indexing.
+ """
+
+ # Mark as local RAG engine
+ is_local = True
+
+ def __init__(
+ self,
+ collection_id: str,
+ collection_name: str,
+ llm: Optional[Any] = None,
+ max_filtered_results: Optional[int] = None,
+ max_results: int = 10,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
+ **kwargs,
+ ):
+ """
+ Initialize the collection-specific search engine.
+
+ Args:
+ collection_id: UUID of the collection to search within
+ collection_name: Name of the collection for display
+ llm: Language model for relevance filtering
+ max_filtered_results: Maximum number of results to keep after filtering
+ max_results: Maximum number of search results
+ settings_snapshot: Settings snapshot from thread context
+ **kwargs: Additional engine-specific parameters
+ """
+ super().__init__(
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
+ settings_snapshot=settings_snapshot,
+ **kwargs,
+ )
+ self.collection_id = collection_id
+ self.collection_name = collection_name
+ self.collection_key = f"collection_{collection_id}"
+
+ # Override embedding settings with collection-specific settings if available
+ self._load_collection_embedding_settings()
+
+ def _load_collection_embedding_settings(self):
+ """
+ Load embedding settings from the collection's metadata.
+ If the collection has stored embedding settings, use those instead of global settings.
+ """
+ if not self.username:
+ logger.warning(f"Cannot load collection settings without username")
+ return
+
+ try:
+ from ...database.models import LibraryCollection
+ from ...database.session_context import get_user_db_session
+
+ with get_user_db_session(self.username) as db_session:
+ collection = db_session.query(LibraryCollection).filter_by(
+ id=self.collection_id
+ ).first()
+
+ if not collection:
+ logger.warning(f"Collection {self.collection_id} not found")
+ return
+
+ # If collection has embedding metadata, use it
+ if collection.embedding_model:
+ logger.info(
+ f"Using collection-specific embedding settings: "
+ f"{collection.embedding_model_type}/{collection.embedding_model}"
+ )
+ self.embedding_model = collection.embedding_model
+ self.embedding_provider = collection.embedding_model_type
+ self.chunk_size = collection.chunk_size or self.chunk_size
+ self.chunk_overlap = collection.chunk_overlap or self.chunk_overlap
+ else:
+ logger.warning(
+ f"Collection {self.collection_id} has no embedding metadata stored. "
+ f"Using global settings: {self.embedding_provider}/{self.embedding_model}"
+ )
+
+ except Exception:
+ logger.exception(f"Error loading collection {self.collection_id} settings")
+
+ def search(
+ self,
+ query: str,
+ limit: int = 10,
+ llm_callback=None,
+ extra_params: Optional[Dict[str, Any]] = None,
+ ) -> List[Dict[str, Any]]:
+ """
+ Search within the specific collection using semantic search.
+
+ Args:
+ query: Search query
+ limit: Maximum number of results to return
+ llm_callback: Optional LLM callback for processing results
+ extra_params: Additional search parameters
+
+ Returns:
+ List of search results filtered to this collection
+ """
+ # Get results from parent (all library documents)
+ # Request 3x the limit to ensure we have enough after filtering
+ all_results = super().search(
+ query, limit=limit * 3, llm_callback=llm_callback, extra_params=extra_params
+ )
+
+ # Filter to only results from this collection
+ filtered_results = [
+ result
+ for result in all_results
+ if result.get("metadata", {}).get("collection") == self.collection_key
+ ]
+
+ # Limit to requested number
+ filtered_results = filtered_results[:limit]
+
+ logger.info(
+ f"Collection '{self.collection_name}' search returned {len(filtered_results)} results "
+ f"(filtered from {len(all_results)} total library results) for query: {query}"
+ )
+
+ return filtered_results
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_library.py b/src/local_deep_research/web_search_engines/engines/search_engine_library.py
index 411d1de923..08dcd120f9 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_library.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_library.py
@@ -17,6 +17,9 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
Search engine that queries the user's research library using RAG/semantic search.
"""
+ # Mark as local RAG engine
+ is_local = True
+
def __init__(
self,
llm: Optional[Any] = None,
diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.py
index 06e16be14a..3b7ecaaeba 100644
--- a/src/local_deep_research/web_search_engines/search_engine_base.py
+++ b/src/local_deep_research/web_search_engines/search_engine_base.py
@@ -50,6 +50,18 @@ class BaseSearchEngine(ABC):
# Scientific engines include arXiv, PubMed, Semantic Scholar, etc.
is_scientific = False
+ # Class attribute to indicate if this is a local RAG/document search engine
+ # Local engines search private document collections stored locally
+ is_local = False
+
+ # Class attribute to indicate if this is a news search engine
+ # News engines specialize in news articles and current events
+ is_news = False
+
+ # Class attribute to indicate if this is a code search engine
+ # Code engines specialize in searching code repositories
+ is_code = False
+
@classmethod
def _load_engine_class(cls, name: str, config: Dict[str, Any]):
"""
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 c03a47e54f..11132e6e56 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
@@ -239,6 +239,60 @@ def search_config(
}
logger.info("Registered Library RAG as search engine")
+ # Register document collections as individual search engines
+ if library_enabled:
+ try:
+ from ..database.models.library import LibraryCollection
+ from ..database.session_context import get_user_db_session
+
+ # Get username from settings_snapshot if available
+ collection_username = (
+ settings_snapshot.get("_username") if settings_snapshot else username
+ )
+
+ if collection_username:
+ with get_user_db_session(collection_username) as session:
+ collections = session.query(LibraryCollection).all()
+
+ for collection in collections:
+ engine_id = f"collection_{collection.id}"
+ search_engines[engine_id] = {
+ "module_path": "local_deep_research.web_search_engines.engines.search_engine_collection",
+ "class_name": "CollectionSearchEngine",
+ "requires_llm": True,
+ "is_local": True,
+ "display_name": collection.name,
+ "default_params": {
+ "collection_id": collection.id,
+ "collection_name": collection.name,
+ },
+ "description": (
+ collection.description
+ if collection.description
+ else f"Search documents in {collection.name} collection"
+ ),
+ "strengths": [
+ f"Searches only documents in {collection.name}",
+ "Focused semantic search within specific topic area",
+ "Returns documents from a curated collection",
+ ],
+ "weaknesses": [
+ "Limited to documents in this collection",
+ "Smaller result pool than full library search",
+ ],
+ "reliability": "High - searches a specific collection",
+ }
+
+ logger.info(
+ f"Registered {len(collections)} document collections as search engines"
+ )
+ else:
+ logger.debug(
+ "No username available for collection registration"
+ )
+ except Exception as e:
+ logger.warning(f"Could not register document collections: {e}")
+
return search_engines