~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
unified rag and library collection this will be more maintanable
LearningCircuit590e0112c25a
diff --git a/scripts/create_integrity_tables.py b/scripts/create_integrity_tables.pynew file mode 100644index 0000000000..ae441d98fa--- /dev/null+++ b/scripts/create_integrity_tables.py@@ -0,0 +1,51 @@+#!/usr/bin/env python3+"""+Create missing file_integrity tables in the database.+Run this script to add the tables needed for the file integrity system.+"""++import sys+from pathlib import Path++# Add src to path+sys.path.insert(0, str(Path(__file__).parent.parent / "src"))++from local_deep_research.database.models.file_integrity import (+ FileIntegrityRecord,+ FileVerificationFailure,+)+from local_deep_research.database.session_context import get_user_db_session+from loguru import logger+++def create_integrity_tables(username: str):+ """Create file integrity tables for a user."""+ logger.info(f"Creating file integrity tables for user: {username}")++ try:+ with get_user_db_session(username) as session:+ connection = session.connection()++ # Create tables if they don't exist+ FileIntegrityRecord.__table__.create(bind=connection, checkfirst=True)+ FileVerificationFailure.__table__.create(bind=connection, checkfirst=True)++ # Commit the DDL changes+ session.commit()++ logger.info("✓ File integrity tables created successfully!")+ return True+ except Exception as e:+ logger.exception(f"✗ Failed to create tables: {e}")+ return False+++if __name__ == "__main__":+ if len(sys.argv) < 2:+ print("Usage: python create_integrity_tables.py <username>")+ print("Example: python create_integrity_tables.py a0006")+ sys.exit(1)++ username = sys.argv[1]+ success = create_integrity_tables(username)+ sys.exit(0 if success else 1)diff --git a/scripts/create_unified_library_tables.py b/scripts/create_unified_library_tables.pynew file mode 100644index 0000000000..3e0b66bfe7--- /dev/null+++ b/scripts/create_unified_library_tables.py@@ -0,0 +1,85 @@+#!/usr/bin/env python3+"""+Create new unified library tables in the database.+Run this script to add the tables for the unified document architecture.+"""++import sys+from pathlib import Path++# Add src to path+sys.path.insert(0, str(Path(__file__).parent.parent / "src"))++from local_deep_research.database.models.library import (+ SourceType,+ UploadBatch,+ Document,+ Collection,+ DocumentCollection,+ DownloadQueue,+)+from local_deep_research.database.session_context import get_user_db_session+from local_deep_research.database.library_init import initialize_library_for_user+from loguru import logger+++def create_unified_library_tables(username: str):+ """Create unified library tables for a user."""+ logger.info(f"Creating unified library tables for user: {username}")++ try:+ with get_user_db_session(username) as session:+ connection = session.connection()++ # Create tables if they don't exist+ logger.info("Creating source_types table...")+ SourceType.__table__.create(bind=connection, checkfirst=True)++ logger.info("Creating upload_batches table...")+ UploadBatch.__table__.create(bind=connection, checkfirst=True)++ logger.info("Creating documents table...")+ Document.__table__.create(bind=connection, checkfirst=True)++ logger.info("Creating collections table...")+ Collection.__table__.create(bind=connection, checkfirst=True)++ logger.info("Creating document_collections junction table...")+ DocumentCollection.__table__.create(bind=connection, checkfirst=True)++ logger.info("Creating download_queue table...")+ DownloadQueue.__table__.create(bind=connection, checkfirst=True)++ # Commit the DDL changes+ session.commit()++ logger.info("✓ Unified library tables created successfully!")++ # Initialize source types and default Library collection+ logger.info("Initializing library system (source types + default collection)...")+ init_results = initialize_library_for_user(username)++ if init_results.get("success"):+ logger.info(f"✓ Library system initialized!")+ logger.info(f" - Source types seeded: {init_results.get('source_types_seeded')}")+ logger.info(f" - Library collection ID: {init_results.get('library_collection_id')}")+ else:+ logger.error(f"✗ Library initialization failed: {init_results.get('error')}")+ return False++ return True++ except Exception as e:+ logger.exception(f"✗ Failed to create tables: {e}")+ return False+++if __name__ == "__main__":+ if len(sys.argv) < 2:+ print("Usage: python create_unified_library_tables.py <username>")+ print("Example: python create_unified_library_tables.py a0006")+ sys.exit(1)++ username = sys.argv[1]+ success = create_unified_library_tables(username)+ sys.exit(0 if success else 1)diff --git a/scripts/test_unified_indexing.py b/scripts/test_unified_indexing.pynew file mode 100644index 0000000000..deb014db3a--- /dev/null+++ b/scripts/test_unified_indexing.py@@ -0,0 +1,129 @@+#!/usr/bin/env python3+"""+Test script for unified document architecture with proper collection-based indexing.+This script verifies that the refactoring works correctly.+"""++import sys+from pathlib import Path++# Add src to path+sys.path.insert(0, str(Path(__file__).parent.parent / "src"))++from local_deep_research.database.session_context import get_user_db_session+from local_deep_research.database.library_init import (+ get_default_library_id,+ get_source_type_id,+)+from local_deep_research.database.models.library import (+ Document,+ Collection,+ DocumentCollection,+)+from loguru import logger+++def test_unified_indexing(username: str):+ """Test the unified document indexing system."""+ logger.info(f"Testing unified indexing for user: {username}")++ try:+ with get_user_db_session(username) as session:+ # Test 1: Check source types exist+ logger.info("\n=== Test 1: Source Types ===")+ source_types = ["research_download", "user_upload", "manual_entry", "api_import"]+ for st_name in source_types:+ try:+ st_id = get_source_type_id(username, st_name)+ logger.info(f" ✓ {st_name}: {st_id}")+ except Exception as e:+ logger.error(f" ✗ {st_name}: {e}")+ return False++ # Test 2: Check Library collection exists+ logger.info("\n=== Test 2: Library Collection ===")+ library_id = get_default_library_id(username)+ library = session.query(Collection).filter_by(id=library_id).first()+ if library:+ logger.info(f" ✓ Library collection found: {library.name} (ID: {library_id})")+ logger.info(f" - is_default: {library.is_default}")+ else:+ logger.error(f" ✗ Library collection not found")+ return False++ # Test 3: Check Document model structure+ logger.info("\n=== Test 3: Document Model ===")+ doc_count = session.query(Document).count()+ logger.info(f" Total documents: {doc_count}")++ if doc_count > 0:+ sample_doc = session.query(Document).first()+ logger.info(f" Sample document:")+ logger.info(f" - ID: {sample_doc.id}")+ logger.info(f" - Title: {sample_doc.title}")+ logger.info(f" - Source Type ID: {sample_doc.source_type_id}")+ logger.info(f" - Has text content: {bool(sample_doc.text_content)}")+ logger.info(f" - Text length: {len(sample_doc.text_content) if sample_doc.text_content else 0} chars")++ # Check for deprecated fields (should NOT exist)+ if hasattr(sample_doc, 'rag_indexed'):+ logger.error(" ✗ DEPRECATED: Document still has rag_indexed field!")+ return False+ if hasattr(sample_doc, 'chunk_count') and hasattr(sample_doc, 'indexed'):+ logger.error(" ✗ DEPRECATED: Document still has chunk_count field!")+ return False+ logger.info(" ✓ Document model clean (no deprecated fields)")++ # Test 4: Check DocumentCollection structure+ logger.info("\n=== Test 4: DocumentCollection ===")+ doc_collection_count = session.query(DocumentCollection).count()+ logger.info(f" Total DocumentCollection entries: {doc_collection_count}")++ if doc_collection_count > 0:+ sample_link = session.query(DocumentCollection).first()+ logger.info(f" Sample DocumentCollection:")+ logger.info(f" - Document ID: {sample_link.document_id}")+ logger.info(f" - Collection ID: {sample_link.collection_id}")+ logger.info(f" - Indexed: {sample_link.indexed}")+ logger.info(f" - Chunk count: {sample_link.chunk_count}")+ logger.info(f" - Last indexed: {sample_link.last_indexed_at}")+ logger.info(" ✓ DocumentCollection structure correct")++ # Test 5: Check indexing statistics per collection+ logger.info("\n=== Test 5: Indexing Statistics ===")+ collections = session.query(Collection).all()+ for coll in collections:+ indexed_count = (+ session.query(DocumentCollection)+ .filter_by(collection_id=coll.id, indexed=True)+ .count()+ )+ total_count = (+ session.query(DocumentCollection)+ .filter_by(collection_id=coll.id)+ .count()+ )+ logger.info(f" Collection '{coll.name}' (ID: {coll.id}):")+ logger.info(f" - Total documents: {total_count}")+ logger.info(f" - Indexed documents: {indexed_count}")+ logger.info(f" - Not indexed: {total_count - indexed_count}")++ logger.info("\n" + "=" * 50)+ logger.info("✓ ALL TESTS PASSED - Unified indexing working correctly!")+ logger.info("=" * 50 + "\n")+ return True++ except Exception as e:+ logger.exception(f"✗ Test failed: {e}")+ return False+++if __name__ == "__main__":+ if len(sys.argv) < 2:+ print("Usage: python test_unified_indexing.py <username>")+ print("Example: python test_unified_indexing.py a0006")+ sys.exit(1)++ username = sys.argv[1]+ success = test_unified_indexing(username)+ sys.exit(0 if success else 1)diff --git a/src/local_deep_research/database/library_init.py b/src/local_deep_research/database/library_init.pynew file mode 100644index 0000000000..52ba045175--- /dev/null+++ b/src/local_deep_research/database/library_init.py@@ -0,0 +1,208 @@+"""+Database initialization for Library - Unified Document Architecture.++This module handles:+- Seeding source_types table with predefined types+- Creating the default "Library" collection+- Must be called on app startup for each user+"""++import uuid+from loguru import logger+from sqlalchemy.exc import IntegrityError++from .models import SourceType, Collection+from .session_context import get_user_db_session+++def seed_source_types(username: str, password: str = None) -> None:+ """+ Seed the source_types table with predefined document source types.++ Args:+ username: User to seed types for+ password: User's password (optional, uses session context)+ """+ predefined_types = [+ {+ "name": "research_download",+ "display_name": "Research Download",+ "description": "Documents downloaded from research sessions (arXiv, PubMed, etc.)",+ "icon": "download",+ },+ {+ "name": "user_upload",+ "display_name": "User Upload",+ "description": "Documents manually uploaded by the user",+ "icon": "upload",+ },+ {+ "name": "manual_entry",+ "display_name": "Manual Entry",+ "description": "Documents manually created or entered",+ "icon": "edit",+ },+ {+ "name": "api_import",+ "display_name": "API Import",+ "description": "Documents imported via API integration",+ "icon": "api",+ },+ ]++ try:+ with get_user_db_session(username, password) as session:+ for type_data in predefined_types:+ # Check if type already exists+ existing = (+ session.query(SourceType)+ .filter_by(name=type_data["name"])+ .first()+ )++ if not existing:+ source_type = SourceType(+ id=str(uuid.uuid4()),+ **type_data+ )+ session.add(source_type)+ logger.info(f"Created source type: {type_data['name']}")++ session.commit()+ logger.info("Source types seeded successfully")++ except IntegrityError as e:+ logger.warning(f"Source types may already exist: {e}")+ except Exception as e:+ logger.exception(f"Error seeding source types: {e}")+ raise+++def ensure_default_library_collection(username: str, password: str = None) -> str:+ """+ Ensure the default "Library" collection exists for a user.+ Creates it if it doesn't exist.++ Args:+ username: User to check/create library for+ password: User's password (optional, uses session context)++ Returns:+ UUID of the Library collection+ """+ try:+ with get_user_db_session(username, password) as session:+ # Check if default library exists+ library = (+ session.query(Collection)+ .filter_by(is_default=True)+ .first()+ )++ if library:+ logger.debug(f"Default Library collection exists: {library.id}")+ return library.id++ # Create default Library collection+ library_id = str(uuid.uuid4())+ library = Collection(+ id=library_id,+ name="Library",+ description="Default collection for research downloads and documents",+ collection_type="default_library",+ is_default=True,+ )+ session.add(library)+ session.commit()++ logger.info(f"Created default Library collection: {library_id}")+ return library_id++ except Exception as e:+ logger.exception(f"Error ensuring default Library collection: {e}")+ raise+++def initialize_library_for_user(username: str, password: str = None) -> dict:+ """+ Complete initialization of library system for a user.+ Seeds source types and ensures default Library collection exists.++ Args:+ username: User to initialize for+ password: User's password (optional, uses session context)++ Returns:+ Dict with initialization results+ """+ results = {+ "source_types_seeded": False,+ "library_collection_id": None,+ "success": False,+ }++ try:+ # Seed source types+ seed_source_types(username, password)+ results["source_types_seeded"] = True++ # Ensure Library collection+ library_id = ensure_default_library_collection(username, password)+ results["library_collection_id"] = library_id++ results["success"] = True+ logger.info(f"Library initialization complete for user: {username}")++ except Exception as e:+ logger.exception(f"Library initialization failed for {username}: {e}")+ results["error"] = str(e)++ return results+++def get_default_library_id(username: str, password: str = None) -> str:+ """+ Get the ID of the default Library collection for a user.+ Creates it if it doesn't exist.++ Args:+ username: User to get library for+ password: User's password (optional, uses session context)++ Returns:+ UUID of the Library collection+ """+ return ensure_default_library_collection(username, password)+++def get_source_type_id(username: str, type_name: str, password: str = None) -> str:+ """+ Get the ID of a source type by name.++ Args:+ username: User to query for+ type_name: Name of source type (e.g., 'research_download', 'user_upload')+ password: User's password (optional, uses session context)++ Returns:+ UUID of the source type++ Raises:+ ValueError: If source type not found+ """+ try:+ with get_user_db_session(username, password) as session:+ source_type = (+ session.query(SourceType)+ .filter_by(name=type_name)+ .first()+ )++ if not source_type:+ raise ValueError(f"Source type not found: {type_name}")++ return source_type.id++ except Exception as e:+ logger.exception(f"Error getting source type ID: {e}")+ raisediff --git a/src/local_deep_research/database/models/__init__.py b/src/local_deep_research/database/models/__init__.pyindex 834f24fc43..743060d921 100644--- a/src/local_deep_research/database/models/__init__.py+++ b/src/local_deep_research/database/models/__init__.py@@ -48,21 +48,30 @@ from .news import (SubscriptionStatus,)-# Import Library models+# Import Library models - Unified architecturefrom .library import (+ # New unified models+ SourceType,+ UploadBatch,+ Document,+ Collection,+ DocumentCollection,+ DownloadQueue,+ # Existing modelsDocumentChunk,- LibraryDocument,- LibraryCollection,- LibraryCollectionDocument,- LibraryDownloadQueue,LibraryStatistics,- LibraryTextDocument,RAGIndex,- UserDocument,- UserDocumentCollection,CollectionFolder,CollectionFolderFile,+ RAGIndexStatus,)++# Naming aliases for clarity (these are intentional, not workarounds)+LibraryDocument = Document+LibraryCollection = Collection+LibraryCollectionDocument = DocumentCollection+LibraryDownloadQueue = DownloadQueue+# Note: Text content is now directly in Document.text_content fieldfrom .download_tracker import (DownloadTracker,DownloadDuplicates,@@ -141,19 +150,24 @@ __all__ = ["RatingType","SubscriptionType","SubscriptionStatus",- # Library Models+ # Library Models - Unified Architecture+ "SourceType",+ "UploadBatch",+ "Document",+ "Collection",+ "DocumentCollection",+ "DownloadQueue","DocumentChunk",- "LibraryDocument",- "LibraryCollection",- "LibraryCollectionDocument",- "LibraryDownloadQueue","LibraryStatistics",- "LibraryTextDocument","RAGIndex",- "UserDocument",- "UserDocumentCollection",+ "RAGIndexStatus","CollectionFolder","CollectionFolderFile",+ # Naming aliases (for clarity, not workarounds)+ "LibraryDocument",+ "LibraryCollection",+ "LibraryCollectionDocument",+ "LibraryDownloadQueue",# Download Tracker Models"DownloadTracker","DownloadDuplicates",diff --git a/src/local_deep_research/database/models/library.py b/src/local_deep_research/database/models/library.pyindex 5b8ef4b7e8..e3967d3c1c 100644--- a/src/local_deep_research/database/models/library.py+++ b/src/local_deep_research/database/models/library.py@@ -1,6 +1,7 @@"""-Library and document download models.-Tracks downloaded PDFs and other documents from research sources.+Library and document models - Unified architecture.+All documents (research downloads and user uploads) are stored in one table.+Collections organize documents, with "Library" as the default collection."""import enum@@ -32,28 +33,93 @@ class RAGIndexStatus(enum.Enum):DEPRECATED = "deprecated"-class LibraryDocument(Base):+class SourceType(Base):"""- Documents downloaded and stored in the user's library.- Links to ResearchResource entries.+ Document source types (research_download, user_upload, manual_entry, etc.).+ Normalized table for consistent categorization."""- __tablename__ = "library_documents"+ __tablename__ = "source_types"++ id = Column(String(36), primary_key=True) # UUID+ name = Column(String(50), nullable=False, unique=True, index=True)+ display_name = Column(String(100), nullable=False)+ description = Column(Text)+ icon = Column(String(50)) # Icon name for UI++ # Timestamps+ created_at = Column(UtcDateTime, default=utcnow(), nullable=False)++ def __repr__(self):+ return f"<SourceType(name='{self.name}', display='{self.display_name}')>"+++class UploadBatch(Base):+ """+ Tracks batches of user-uploaded files.+ Groups uploads for traceability and batch operations.+ """++ __tablename__ = "upload_batches"++ id = Column(String(36), primary_key=True) # UUID+ collection_id = Column(+ String(36),+ ForeignKey("collections.id", ondelete="CASCADE"),+ nullable=False,+ index=True,+ )+ uploaded_at = Column(UtcDateTime, default=utcnow(), nullable=False)+ file_count = Column(Integer, default=0)+ total_size = Column(Integer, default=0) # Total bytes++ # Relationships+ collection = relationship("Collection", backref="upload_batches")+ documents = relationship("Document", backref="upload_batch")++ def __repr__(self):+ return f"<UploadBatch(id='{self.id}', files={self.file_count}, size={self.total_size})>"+++class Document(Base):+ """+ Unified document table for all documents (research downloads + user uploads).+ Contains all fields from both LibraryDocument and UserDocument.+ """++ __tablename__ = "documents"id = Column(String(36), primary_key=True) # UUID as string- # Link to the original resource+ # Source type (research_download, user_upload, etc.)+ source_type_id = Column(+ String(36),+ ForeignKey("source_types.id"),+ nullable=False,+ index=True,+ )++ # Link to original research resource (for research downloads) - nullable for uploadsresource_id = Column(Integer,ForeignKey("research_resources.id", ondelete="CASCADE"),- nullable=False,+ nullable=True,+ index=True,)- # Link to research for easy querying+ # Link to research (for research downloads) - nullable for uploadsresearch_id = Column(String(36),ForeignKey("research_history.id", ondelete="CASCADE"),- nullable=False,+ nullable=True,+ index=True,+ )++ # Link to upload batch (for user uploads) - nullable for research downloads+ upload_batch_id = Column(+ String(36),+ ForeignKey("upload_batches.id", ondelete="SET NULL"),+ nullable=True,index=True,)@@ -61,41 +127,54 @@ class LibraryDocument(Base):document_hash = Column(String(64), nullable=False, unique=True, index=True) # SHA256 for deduplication- original_url = Column(Text, nullable=False) # Source URL+ original_url = Column(Text, nullable=True) # Source URL (for downloads)+ filename = Column(String(500), nullable=True) # Display name (for uploads)+ original_filename = Column(String(500), nullable=True) # Original upload name# File information- file_path = Column(Text, nullable=False) # Path relative to library root+ file_path = Column(Text, nullable=True) # Path relative to library/uploads rootfile_size = Column(Integer, nullable=False) # Size in bytes- file_type = Column(String(50), nullable=False) # pdf, html, epub, etc.- mime_type = Column(- String(100), nullable=True- ) # application/pdf, text/html, etc.+ file_type = Column(String(50), nullable=False) # pdf, txt, md, html, etc.+ mime_type = Column(String(100), nullable=True) # MIME type++ # Content storage - text always stored in DB+ text_content = Column(Text, nullable=True) # Extracted/uploaded text content# Metadatatitle = Column(Text) # Document title- authors = Column(JSON) # List of authors if available- published_date = Column(Date, nullable=True) # Publication date if known+ description = Column(Text) # User description+ authors = Column(JSON) # List of authors (for research papers)+ published_date = Column(Date, nullable=True) # Publication date- # Academic identifiers+ # Academic identifiers (for research papers)doi = Column(String(255), nullable=True, index=True)arxiv_id = Column(String(100), nullable=True, index=True)pmid = Column(String(50), nullable=True, index=True)pmcid = Column(String(50), nullable=True, index=True)isbn = Column(String(20), nullable=True)- # Download information- download_status = Column(+ # Download/Upload information+ status = Column(String(50), nullable=False, default="completed"- ) # pending, downloading, completed, failed- download_attempts = Column(Integer, default=1)- download_error = Column(Text, nullable=True)- downloaded_at = Column(UtcDateTime, nullable=False, default=utcnow())+ ) # pending, processing, completed, failed+ attempts = Column(Integer, default=1)+ error_message = Column(Text, nullable=True)+ processed_at = Column(UtcDateTime, nullable=False, default=utcnow())last_accessed = Column(UtcDateTime, nullable=True)+ # Text extraction metadata (for research downloads from PDFs)+ extraction_method = Column(String(50), nullable=True) # pdf_extraction, native_api, etc.+ extraction_source = Column(String(50), nullable=True) # arxiv_api, pdfplumber, etc.+ extraction_quality = Column(String(20), nullable=True) # high, medium, low+ has_formatting_issues = Column(Boolean, default=False)+ has_encoding_issues = Column(Boolean, default=False)+ character_count = Column(Integer, nullable=True)+ word_count = Column(Integer, nullable=True)+# Organizationtags = Column(JSON) # User-defined tags- notes = Column(Text) # User notes about the document- favorite = Column(Boolean, default=False) # Mark as favorite+ notes = Column(Text) # User notes+ favorite = Column(Boolean, default=False)# Timestampscreated_at = Column(UtcDateTime, default=utcnow(), nullable=False)@@ -104,140 +183,130 @@ class LibraryDocument(Base):)# Relationships- resource = relationship("ResearchResource", backref="library_document")- research = relationship("ResearchHistory", backref="library_documents")+ source_type = relationship("SourceType", backref="documents")+ resource = relationship("ResearchResource", backref="documents")+ research = relationship("ResearchHistory", backref="documents")+ collections = relationship(+ "DocumentCollection",+ back_populates="document",+ cascade="all, delete-orphan",+ )- # Ensure one document per resource+ # Indexes for efficient queries__table_args__ = (- UniqueConstraint("resource_id", name="uix_one_doc_per_resource"),- Index("idx_research_documents", "research_id", "download_status"),- Index("idx_document_type", "file_type", "download_status"),+ Index("idx_source_type", "source_type_id", "status"),+ Index("idx_research_documents", "research_id", "status"),+ Index("idx_document_type", "file_type", "status"),+ Index("idx_document_hash", "document_hash"),)def __repr__(self):- return f"<LibraryDocument(title='{self.title[:50] if self.title else 'Untitled'}', type={self.file_type}, size={self.file_size})>"+ title_str = self.title[:50] if self.title else (self.filename[:50] if self.filename else 'Untitled')+ return f"<Document(title='{title_str}', type={self.file_type}, size={self.file_size})>"-class LibraryTextDocument(Base):+class Collection(Base):"""- Text files extracted from documents for RAG/analysis.- Links to LibraryDocument entries.+ Collections for organizing documents.+ 'Library' is the default collection for research downloads.+ Users can create custom collections for organization."""- __tablename__ = "library_text_documents"+ __tablename__ = "collections"id = Column(String(36), primary_key=True) # UUID as string+ name = Column(String(255), nullable=False)+ description = Column(Text)- # Link to the original resource- resource_id = Column(- Integer,- ForeignKey("research_resources.id", ondelete="CASCADE"),- nullable=False,- )+ # Collection type (default_library, user_collection, linked_folder)+ collection_type = Column(String(50), default="user_collection")- # Link to research for easy querying- research_id = Column(- String(36),- ForeignKey("research_history.id", ondelete="CASCADE"),- nullable=False,- index=True,- )+ # Is this the default library collection?+ is_default = Column(Boolean, default=False)- # Link to PDF document if extracted from PDF- document_id = Column(- String(36),- ForeignKey("library_documents.id", ondelete="SET NULL"),- nullable=True,- )+ # Embedding model used for this collection (stored when first indexed)+ embedding_model = Column(+ String(100), nullable=True+ ) # e.g., 'all-MiniLM-L6-v2', 'nomic-embed-text:latest'+ 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- # Text document identification- text_hash = Column(- String(64), nullable=False, unique=True, index=True- ) # SHA256 for deduplication- original_url = Column(Text, nullable=False) # Source URL+ # Timestamps+ created_at = Column(UtcDateTime, default=utcnow(), nullable=False)+ updated_at = Column(+ UtcDateTime, default=utcnow(), onupdate=utcnow(), nullable=False+ )- # File information- file_path = Column(- Text, nullable=True- ) # Path relative to library root (txt/ folder) - can be None if storage disabled- file_size = Column(Integer, nullable=False) # Size in bytes- character_count = Column(Integer, nullable=True) # Number of characters- word_count = Column(Integer, nullable=True) # Number of words+ # Relationships+ document_links = relationship(+ "DocumentCollection",+ back_populates="collection",+ cascade="all, delete-orphan",+ )+ linked_folders = relationship(+ "CollectionFolder",+ back_populates="collection",+ cascade="all, delete-orphan",+ )- # Extraction metadata- extraction_method = Column(- String(50), nullable=False- ) # native_api, pdf_extraction, html_extraction- extraction_source = Column(- String(50), nullable=True- ) # arxiv_api, pubmed_api, pdfplumber, pypdf, etc.+ def __repr__(self):+ return f"<Collection(id='{self.id}', name='{self.name}', type='{self.collection_type}')>"- # Content metadata (same as LibraryDocument for consistency)- title = Column(Text) # Document title- authors = Column(JSON) # List of authors if available- published_date = Column(String(50)) # Publication date if known- # Academic identifiers (copied from source document)- doi = Column(String(255), nullable=True, index=True)- arxiv_id = Column(String(100), nullable=True, index=True)- pmid = Column(String(50), nullable=True, index=True)- pmcid = Column(String(50), nullable=True, index=True)+class DocumentCollection(Base):+ """+ Many-to-many relationship between documents and collections.+ Tracks indexing status per collection (documents can be in multiple collections).+ """- # Processing status- extraction_status = Column(- String(50), nullable=False, default="completed"- ) # pending, extracting, completed, failed- extraction_error = Column(Text, nullable=True)- extracted_at = Column(UtcDateTime, nullable=False, default=utcnow())- last_accessed = Column(UtcDateTime, nullable=True)+ __tablename__ = "document_collections"- # Quality metrics- extraction_quality = Column(- String(20), nullable=True- ) # high, medium, low (based on extraction method)- has_formatting_issues = Column(Boolean, default=False)- has_encoding_issues = Column(Boolean, default=False)+ id = Column(Integer, primary_key=True, autoincrement=True)- # Text content storage- text_content = Column(- Text, nullable=True- ) # Always store text content for quick access+ # Foreign keys+ document_id = Column(+ String(36),+ ForeignKey("documents.id", ondelete="CASCADE"),+ nullable=False,+ index=True,+ )+ collection_id = Column(+ String(36),+ ForeignKey("collections.id", ondelete="CASCADE"),+ nullable=False,+ index=True,+ )- # RAG/Search indexing- rag_indexed = Column(+ # Indexing status (per collection!)+ indexed = Column(Boolean, default=False- ) # Whether this document has been indexed for RAG- chunk_count = Column(Integer, default=0) # Number of chunks created- last_indexed_at = Column(- UtcDateTime, nullable=True- ) # Last time RAG index was updated+ ) # 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- created_at = Column(UtcDateTime, default=utcnow(), nullable=False)- updated_at = Column(- UtcDateTime, default=utcnow(), onupdate=utcnow(), nullable=False- )+ added_at = Column(UtcDateTime, default=utcnow(), nullable=False)# Relationships- resource = relationship("ResearchResource", backref="text_document")- research = relationship("ResearchHistory", backref="text_documents")- pdf_document = relationship("LibraryDocument", backref="text_extracts")+ document = relationship("Document", back_populates="collections")+ collection = relationship("Collection", back_populates="document_links")- # Ensure one text file per resource+ # Ensure one entry per document-collection pair__table_args__ = (- UniqueConstraint("resource_id", name="uix_one_text_per_resource"),- Index(- "idx_research_text_documents", "research_id", "extraction_status"- ),- Index(- "idx_text_extraction_method",- "extraction_method",- "extraction_status",+ UniqueConstraint(+ "document_id", "collection_id", name="uix_document_collection"),+ Index("idx_collection_indexed", "collection_id", "indexed"),)def __repr__(self):- return f"<LibraryTextDocument(title='{self.title[:50] if self.title else 'Untitled'}', method={self.extraction_method}, size={self.file_size})>"+ return f"<DocumentCollection(doc_id={self.document_id}, coll_id={self.collection_id}, indexed={self.indexed})>"class DocumentChunk(Base):@@ -253,21 +322,21 @@ class DocumentChunk(Base):# Chunk identificationchunk_hash = Column(String(64), nullable=False, index=True- ) # SHA256 for deduplication (not unique - same chunk can be in multiple collections)+ ) # SHA256 for deduplication- # Source tracking+ # Source tracking - now points to unified Document tablesource_type = Column(String(20), nullable=False, index=True- ) # 'library', 'user_upload', 'folder_file'+ ) # 'document', 'folder_file'source_id = Column(- String(36), nullable=True- ) # LibraryTextDocument.id if library source (UUID as string)+ String(36), nullable=True, index=True+ ) # Document.id (UUID as string)source_path = Column(Text, nullable=True) # File path if local collection sourcecollection_name = Column(String(100), nullable=False, index=True- ) # 'library', 'personal_notes', 'project_docs', etc.+ ) # collection_<uuid># Chunk content (encrypted in SQLCipher DB)chunk_text = Column(Text, nullable=False) # The actual chunk text@@ -312,78 +381,13 @@ class DocumentChunk(Base):return f"<DocumentChunk(collection='{self.collection_name}', source_type='{self.source_type}', index={self.chunk_index}, words={self.word_count})>"-class LibraryCollection(Base):- """- User-defined collections for organizing documents.- """-- __tablename__ = "library_collections"-- id = Column(String(36), primary_key=True) # UUID as string- name = Column(String(255), nullable=False)- description = Column(Text)-- # 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)- updated_at = Column(- UtcDateTime, default=utcnow(), onupdate=utcnow(), nullable=False- )-- # Relationships- # 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(id='{self.id}', name='{self.name}', type='{self.collection_type}')>"---class LibraryCollectionDocument(Base):- """- Many-to-many relationship between collections and documents.- """-- __tablename__ = "library_collection_documents"-- id = Column(Integer, primary_key=True, autoincrement=True)- collection_id = Column(- String(36),- ForeignKey("library_collections.id", ondelete="CASCADE"),- nullable=False,- )- document_id = Column(- String(36),- ForeignKey("library_documents.id", ondelete="CASCADE"),- nullable=False,- )- added_at = Column(UtcDateTime, default=utcnow(), nullable=False)-- __table_args__ = (- UniqueConstraint(- "collection_id", "document_id", name="uix_collection_document"- ),- )---class LibraryDownloadQueue(Base):+class DownloadQueue(Base):"""Queue for pending document downloads.+ Renamed from LibraryDownloadQueue for consistency."""- __tablename__ = "library_download_queue"+ __tablename__ = "download_queue"id = Column(Integer, primary_key=True, autoincrement=True)@@ -396,6 +400,14 @@ class LibraryDownloadQueue(Base):)research_id = Column(String(36), nullable=False, index=True)+ # Target collection (defaults to Library collection)+ collection_id = Column(+ String(36),+ ForeignKey("collections.id", ondelete="SET NULL"),+ nullable=True,+ index=True,+ )+# Queue managementpriority = Column(Integer, default=0) # Higher = more importantstatus = Column(@@ -412,11 +424,12 @@ class LibraryDownloadQueue(Base):queued_at = Column(UtcDateTime, default=utcnow(), nullable=False)completed_at = Column(UtcDateTime, nullable=True)- # Relationship+ # Relationshipsresource = relationship("ResearchResource", backref="download_queue")+ collection = relationship("Collection", backref="download_queue_items")def __repr__(self):- return f"<LibraryDownloadQueue(resource_id={self.resource_id}, status={self.status}, attempts={self.attempts})>"+ return f"<DownloadQueue(resource_id={self.resource_id}, status={self.status}, attempts={self.attempts})>"class LibraryStatistics(Base):@@ -475,7 +488,7 @@ class RAGIndex(Base):# Collection and model identificationcollection_name = Column(String(100), nullable=False, index=True- ) # 'library', 'personal_notes', etc.+ ) # 'collection_<uuid>'embedding_model = Column(String(100), nullable=False) # e.g., 'all-MiniLM-L6-v2'@@ -534,103 +547,6 @@ class RAGIndex(Base):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.@@ -643,8 +559,9 @@ class CollectionFolder(Base):# Collection associationcollection_id = Column(String(36),- ForeignKey("library_collections.id", ondelete="CASCADE"),+ ForeignKey("collections.id", ondelete="CASCADE"),nullable=False,+ index=True,)# Folder configuration@@ -672,7 +589,7 @@ class CollectionFolder(Base):)# Relationships- collection = relationship("LibraryCollection", backref="linked_folders")+ collection = relationship("Collection", back_populates="linked_folders")files = relationship("CollectionFolderFile",back_populates="folder",@@ -698,6 +615,7 @@ class CollectionFolderFile(Base):Integer,ForeignKey("collection_folders.id", ondelete="CASCADE"),nullable=False,+ index=True,)# File identification@@ -727,6 +645,7 @@ class CollectionFolderFile(Base):# Ensure one entry per file in folder__table_args__ = (UniqueConstraint("folder_id", "relative_path", name="uix_folder_file"),+ Index("idx_folder_indexed", "folder_id", "indexed"),)def __repr__(self):diff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.pyindex 107bc61893..4cff0493fa 100644--- a/src/local_deep_research/research_library/routes/library_routes.py+++ b/src/local_deep_research/research_library/routes/library_routes.py@@ -26,7 +26,10 @@ from ...web.auth.decorators import login_requiredfrom ...web.utils.templates import render_template_with_defaultsfrom ...database.session_context import get_user_db_sessionfrom ...database.models.research import ResearchResource-from ...database.models.library import LibraryDocument, LibraryDownloadQueue+from ...database.models.library import (+ Document as LibraryDocument,+ DownloadQueue as LibraryDownloadQueue,+)from ...library.download_management import ResourceFilterfrom ..services.download_service import DownloadServicefrom ..services.library_service import LibraryService@@ -398,49 +401,38 @@ def serve_pdf_api(document_id):@login_requireddef view_text_page(document_id):"""Page for viewing text content."""- from ...database.models.library import LibraryTextDocument- from ...database.session_context import get_user_db_session-username = session.get("username")with get_user_db_session(username) as db_session:- # Try to get text document by document_id (PDF with extracted text)- text_doc = (- db_session.query(LibraryTextDocument)- .filter_by(document_id=document_id)+ # Get document by ID (text now stored in Document.text_content)+ document = (+ db_session.query(LibraryDocument)+ .filter_by(id=document_id).first())- # If not found, try by LibraryTextDocument.id (text-only document)- if not text_doc:- text_doc = (- db_session.query(LibraryTextDocument)- .filter_by(id=document_id)- .first()- )-- if not text_doc:+ if not document:logger.warning(- f"Text document not found for document ID {document_id}"+ f"Document not found for document ID {document_id}")- return "Text not found", 404+ return "Document not found", 404- if not text_doc.text_content:- logger.warning(f"Text document {document_id} has no text content")+ if not document.text_content:+ logger.warning(f"Document {document_id} has no text content")return "Text content not available", 404logger.info(- f"Serving text content for document {document_id}: {len(text_doc.text_content)} characters"+ f"Serving text content for document {document_id}: {len(document.text_content)} characters")# Render as HTML pagereturn render_template_with_defaults("pages/document_text.html",document_id=document_id,- title=text_doc.title or "Document Text",- text_content=text_doc.text_content,- extraction_method=text_doc.extraction_method,- word_count=text_doc.word_count,+ title=document.title or "Document Text",+ text_content=document.text_content,+ extraction_method=document.extraction_method,+ word_count=document.word_count,)@@ -448,47 +440,36 @@ def view_text_page(document_id):@login_requireddef serve_text_api(document_id):"""API endpoint for serving text content (kept for backward compatibility)."""- from ...database.models.library import LibraryTextDocument- from ...database.session_context import get_user_db_session-username = session.get("username")with get_user_db_session(username) as db_session:- # Try to get text document by document_id (PDF with extracted text)- text_doc = (- db_session.query(LibraryTextDocument)- .filter_by(document_id=document_id)+ # Get document by ID (text now stored in Document.text_content)+ document = (+ db_session.query(LibraryDocument)+ .filter_by(id=document_id).first())- # If not found, try by LibraryTextDocument.id (text-only document)- if not text_doc:- text_doc = (- db_session.query(LibraryTextDocument)- .filter_by(id=document_id)- .first()- )-- if not text_doc:+ if not document:logger.warning(- f"Text document not found for document ID {document_id}"+ f"Document not found for document ID {document_id}")- return jsonify({"error": "Text not found"}), 404+ return jsonify({"error": "Document not found"}), 404- if not text_doc.text_content:- logger.warning(f"Text document {document_id} has no text content")+ if not document.text_content:+ logger.warning(f"Document {document_id} has no text content")return jsonify({"error": "Text content not available"}), 404logger.info(- f"Serving text content for document {document_id}: {len(text_doc.text_content)} characters"+ f"Serving text content for document {document_id}: {len(document.text_content)} characters")return jsonify({- "text_content": text_doc.text_content,- "title": text_doc.title or "Document",- "extraction_method": text_doc.extraction_method,- "word_count": text_doc.word_count,+ "text_content": document.text_content,+ "title": document.title or "Document",+ "extraction_method": document.extraction_method,+ "word_count": document.word_count,})@@ -718,9 +699,6 @@ def download_bulk():total = 0current = 0- from ...database.session_context import get_user_db_session- from ...database.models.library import LibraryDownloadQueue-with get_user_db_session(username) as session:for research_id in research_ids:count = (diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.pyindex 574749d0a4..035aab01c6 100644--- a/src/local_deep_research/research_library/routes/rag_routes.py+++ b/src/local_deep_research/research_library/routes/rag_routes.py@@ -26,6 +26,11 @@ from datetime import datetime, timezonefrom ...web.auth.decorators import login_requiredfrom ...utilities.db_utils import get_settings_managerfrom ..services.library_rag_service import LibraryRAGService+from ...database.models.library import (+ Document,+ Collection,+ DocumentCollection,+)rag_bp = Blueprint("rag", __name__, url_prefix="/library")@@ -340,12 +345,13 @@ def index_research():@rag_bp.route("/api/rag/index-all", methods=["GET"])@login_requireddef index_all():- """Index all library documents with Server-Sent Events progress."""- from ...database.models.library import LibraryTextDocument+ """Index all documents in the Library collection with Server-Sent Events progress."""from ...database.session_context import get_user_db_session+ from ...database.library_init import get_default_library_idforce_reindex = request.args.get("force_reindex", "false").lower() == "true"username = session["username"]+ library_id = get_default_library_id(username)# Create RAG service in request context before generator runsrag_service = get_rag_service()@@ -356,13 +362,19 @@ def index_all():# Send initial statusyield f"data: {json.dumps({'type': 'start', 'message': 'Starting bulk indexing...'})}\n\n"- # Get document IDs to index (not full objects to avoid stale session data)+ # Get document IDs to index from DocumentCollectionwith get_user_db_session(username) as db_session:- query = db_session.query(- LibraryTextDocument.id, LibraryTextDocument.title+ # Query Document joined with DocumentCollection for the Library+ query = (+ db_session.query(Document.id, Document.title)+ .join(DocumentCollection, Document.id == DocumentCollection.document_id)+ .filter(DocumentCollection.collection_id == library_id))+if not force_reindex:- query = query.filter_by(rag_indexed=False)+ # Only index documents that haven't been indexed yet+ query = query.filter(DocumentCollection.indexed.is_(False))+doc_info = [(doc_id, title) for doc_id, title in query.all()]if not doc_info:@@ -383,9 +395,9 @@ def index_all():for i in range(0, len(doc_info), batch_size):batch = doc_info[i : i + batch_size]- # Process batch in single database session+ # Process batch with collection_idbatch_results = rag_service.index_documents_batch(- batch, force_reindex+ batch, library_id, force_reindex)# Process results and send progress updates@@ -396,19 +408,19 @@ def index_all():# Send progress updateyield f"data: {json.dumps({'type': 'progress', 'current': processed, 'total': total, 'title': title, 'percent': int((processed / total) * 100)})}\n\n"- if result["status"] == "success":- results["successful"] += 1- elif result["status"] == "skipped":- results["skipped"] += 1- else:- results["failed"] += 1- results["errors"].append(- {- "doc_id": doc_id,- "title": title,- "error": result.get("error"),- }- )+ if result["status"] == "success":+ results["successful"] += 1+ elif result["status"] == "skipped":+ results["skipped"] += 1+ else:+ results["failed"] += 1+ results["errors"].append(+ {+ "doc_id": doc_id,+ "title": title,+ "error": result.get("error"),+ }+ )# Send completion statusyield f"data: {json.dumps({'type': 'complete', 'results': results})}\n\n"@@ -490,9 +502,9 @@ def configure_rag():@rag_bp.route("/api/rag/documents", methods=["GET"])@login_requireddef get_documents():- """Get library text documents with their RAG status (paginated)."""- from ...database.models.library import LibraryTextDocument+ """Get library documents with their RAG status for the default Library collection (paginated)."""from ...database.session_context import get_user_db_session+ from ...database.library_init import get_default_library_idtry:# Get pagination parameters@@ -512,22 +524,35 @@ def get_documents():cleanup_current_thread()username = session["username"]+ library_id = get_default_library_id(username)+with get_user_db_session(username) as db_session:- # Build base query- query = db_session.query(LibraryTextDocument)+ # Build base query - join Document with DocumentCollection for the Library+ query = (+ db_session.query(Document, DocumentCollection)+ .outerjoin(+ DocumentCollection,+ (DocumentCollection.document_id == Document.id) &+ (DocumentCollection.collection_id == library_id)+ )+ )- # Apply filters+ # Apply filters based on DocumentCollection.indexedif filter_type == "indexed":- query = query.filter(LibraryTextDocument.rag_indexed.is_(True))+ query = query.filter(DocumentCollection.indexed.is_(True))elif filter_type == "unindexed":- query = query.filter(LibraryTextDocument.rag_indexed.is_(False))+ # Documents in library but not indexed, or not in DocumentCollection yet+ query = query.filter(+ (DocumentCollection.indexed.is_(False)) |+ (DocumentCollection.id.is_(None))+ )# Get total count before paginationtotal_count = query.count()# Apply pagination- text_docs = (- query.order_by(LibraryTextDocument.created_at.desc())+ results = (+ query.order_by(Document.created_at.desc()).limit(per_page).offset((page - 1) * per_page).all()@@ -538,13 +563,13 @@ def get_documents():"id": doc.id,"title": doc.title,"original_url": doc.original_url,- "rag_indexed": doc.rag_indexed,- "chunk_count": doc.chunk_count or 0,+ "rag_indexed": doc_collection.indexed if doc_collection else False,+ "chunk_count": doc_collection.chunk_count if doc_collection else 0,"created_at": doc.created_at.isoformat()if doc.created_atelse None,}- for doc in text_docs+ for doc, doc_collection in results]return jsonify(@@ -686,14 +711,13 @@ def index_local_library():@login_requireddef get_collections():"""Get all document collections for the current user."""- from ...database.models import LibraryCollectionfrom ...database.session_context import get_user_db_sessiontry: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()+ collections = db_session.query(Collection).all()result = []for coll in collections:@@ -739,7 +763,6 @@ def get_collections():@login_requireddef create_collection():"""Create a new document collection."""- from ...database.models import LibraryCollectionfrom ...database.session_context import get_user_db_sessiontry:@@ -755,7 +778,7 @@ def create_collection():with get_user_db_session(username) as db_session:# Check if collection with this name already exists in this user's databaseexisting = (- db_session.query(LibraryCollection).filter_by(name=name).first()+ db_session.query(Collection).filter_by(name=name).first())if existing:@@ -768,7 +791,7 @@ def create_collection():# 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(+ collection = Collection(id=str(uuid.uuid4()), # Generate UUID for collectionname=name,description=description,@@ -801,7 +824,6 @@ def create_collection():@login_requireddef update_collection(collection_id):"""Update a collection's details."""- from ...database.models import LibraryCollectionfrom ...database.session_context import get_user_db_sessiontry:@@ -813,7 +835,7 @@ def update_collection(collection_id):with get_user_db_session(username) as db_session:# No need to filter by username - each user has their own databasecollection = (- db_session.query(LibraryCollection)+ db_session.query(Collection).filter_by(id=collection_id).first())@@ -826,10 +848,10 @@ def update_collection(collection_id):if name:# Check if new name conflicts with existing collectionexisting = (- db_session.query(LibraryCollection)+ db_session.query(Collection).filter(- LibraryCollection.name == name,- LibraryCollection.id != collection_id,+ Collection.name == name,+ Collection.id != collection_id,).first())@@ -874,9 +896,7 @@ def update_collection(collection_id):@login_requireddef delete_collection(collection_id):"""Delete a collection and optionally its documents."""- from ...database.models import (- LibraryCollection,- UserDocumentCollection,+ from ...database.models.library import (CollectionFolder,DocumentChunk,)@@ -887,7 +907,7 @@ def delete_collection(collection_id):with get_user_db_session(username) as db_session:# No need to filter by username - each user has their own databasecollection = (- db_session.query(LibraryCollection)+ db_session.query(Collection).filter_by(id=collection_id).first())@@ -908,7 +928,7 @@ def delete_collection(collection_id):)# Delete junction table entries- db_session.query(UserDocumentCollection).filter_by(+ db_session.query(DocumentCollection).filter_by(collection_id=collection_id).delete()@@ -1047,11 +1067,6 @@ def extract_text_from_file(@login_requireddef 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_sessionfrom werkzeug.utils import secure_filenamefrom pathlib import Path@@ -1073,7 +1088,7 @@ def upload_to_collection(collection_id):with get_user_db_session(username) as db_session:# Verify collection exists in this user's databasecollection = (- db_session.query(LibraryCollection)+ db_session.query(Collection).filter_by(id=collection_id).first())@@ -1100,7 +1115,7 @@ def upload_to_collection(collection_id):# Check if document already existsexisting_doc = (- db_session.query(UserDocument)+ db_session.query(Document).filter_by(file_hash=file_hash).first())@@ -1109,7 +1124,7 @@ def upload_to_collection(collection_id):# Document exists, just add to collection# Check if already in collectionexisting_link = (- db_session.query(UserDocumentCollection)+ db_session.query(DocumentCollection).filter_by(document_id=existing_doc.id,collection_id=collection_id,@@ -1119,7 +1134,7 @@ def upload_to_collection(collection_id):if not existing_link:# Add to collection- collection_link = UserDocumentCollection(+ collection_link = DocumentCollection(document_id=existing_doc.id,collection_id=collection_id,indexed=False,@@ -1177,7 +1192,7 @@ def upload_to_collection(collection_id):# Create document with extracted text (no username needed - in user's own database)# Note: uploaded_at uses default=utcnow() in the model, so we don't need to set it manually# We only store extracted text in the encrypted database for better privacy and security- new_doc = UserDocument(+ new_doc = Document(filename=filename,file_hash=file_hash,file_size=len(file_content),@@ -1189,7 +1204,7 @@ def upload_to_collection(collection_id):db_session.flush() # Get the ID# Add to collection- collection_link = UserDocumentCollection(+ collection_link = DocumentCollection(document_id=new_doc.id,collection_id=collection_id,indexed=False,@@ -1243,11 +1258,6 @@ def upload_to_collection(collection_id):@login_requireddef 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_sessiontry:@@ -1255,7 +1265,7 @@ def get_collection_documents(collection_id):with get_user_db_session(username) as db_session:# Verify collection exists in this user's databasecollection = (- db_session.query(LibraryCollection)+ db_session.query(Collection).filter_by(id=collection_id).first())@@ -1267,9 +1277,9 @@ def get_collection_documents(collection_id):# Get documents through junction tabledoc_links = (- db_session.query(UserDocumentCollection, UserDocument)- .join(UserDocument)- .filter(UserDocumentCollection.collection_id == collection_id)+ db_session.query(DocumentCollection, Document)+ .join(Document)+ .filter(DocumentCollection.collection_id == collection_id).all())@@ -1315,11 +1325,6 @@ def get_collection_documents(collection_id):@login_requireddef 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_sessionforce_reindex = request.args.get("force_reindex", "false").lower() == "true"@@ -1334,7 +1339,7 @@ def index_collection(collection_id):with get_user_db_session(username) as db_session:# Verify collection exists in this user's databasecollection = (- db_session.query(LibraryCollection)+ db_session.query(Collection).filter_by(id=collection_id).first())@@ -1373,15 +1378,15 @@ def index_collection(collection_id):# Get documents to indexquery = (- db_session.query(UserDocumentCollection, UserDocument)- .join(UserDocument)+ db_session.query(DocumentCollection, Document)+ .join(Document).filter(- UserDocumentCollection.collection_id == collection_id+ DocumentCollection.collection_id == collection_id))if not force_reindex:- query = query.filter(not UserDocumentCollection.indexed)+ query = query.filter(not DocumentCollection.indexed)doc_links = query.all()@@ -1402,20 +1407,20 @@ def index_collection(collection_id):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"+ yield f"data: {json.dumps({'type': 'progress', 'current': idx, 'total': total, 'filename': doc.filename or doc.title, 'percent': int((idx / total) * 100)})}\n\n"try:- # Index the document- result = rag_service.index_user_document(- doc, collection_name, force_reindex+ # Index the document using collection-based method+ result = rag_service.index_document(+ document_id=doc.id,+ collection_id=collection_id,+ force_reindex=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)+ # DocumentCollection status is already updated in index_document+ # No need to update link hereelif result.get("status") == "skipped":results["skipped"] += 1else:diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex 76b5537f2d..b59b04c687 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -29,9 +29,10 @@ from ...database.models.download_tracker import ()from ...security import redact_datafrom ...database.models.library import (- LibraryDocument,- LibraryDownloadQueue,- LibraryTextDocument,+ Document as LibraryDocument,+ DownloadQueue as LibraryDownloadQueue,+ DocumentCollection,+ Collection,)from ...database.models.research import ResearchResourcefrom ...database.session_context import get_user_db_session@@ -506,13 +507,24 @@ class DownloadService:tracker.file_path if tracker.file_path else "metadata_only")existing_doc.file_size = len(pdf_content)- existing_doc.download_status = "completed"- existing_doc.downloaded_at = datetime.now(UTC)- existing_doc.domain = urlparse(url).netloc+ existing_doc.status = "completed"+ existing_doc.processed_at = datetime.now(UTC)else:- # Create new library document entry+ # Get source type ID for research downloads+ from ...database.library_init import get_source_type_id, get_default_library_id++ try:+ source_type_id = get_source_type_id(self.username, "research_download")+ library_collection_id = get_default_library_id(self.username)+ except Exception as e:+ logger.error(f"Failed to get source type or library collection: {e}")+ raise++ # Create new unified document entry+ doc_id = str(uuid.uuid4())doc = LibraryDocument(- id=str(uuid.uuid4()), # Generate UUID for document+ id=doc_id,+ source_type_id=source_type_id,resource_id=resource.id,research_id=resource.research_id,document_hash=tracker.file_hash,@@ -524,13 +536,19 @@ class DownloadService:file_type="pdf",mime_type="application/pdf",title=resource.title,- download_status="completed",- downloaded_at=datetime.now(UTC),+ status="completed",+ processed_at=datetime.now(UTC),)- # Extract domain for filtering- doc.domain = urlparse(url).netlocsession.add(doc)+ # Link document to default Library collection+ doc_collection = DocumentCollection(+ document_id=doc_id,+ collection_id=library_collection_id,+ indexed=False,+ )+ session.add(doc_collection)+# Update attemptattempt.succeeded = Trueattempt.bytes_downloaded = len(pdf_content)@@ -539,6 +557,43 @@ class DownloadService:logger.info(f"Successfully downloaded: {tracker.file_path}")else:logger.info(f"Successfully extracted text from: {resource.url}")++ # Automatically extract and save text after successful PDF download+ try:+ logger.info(f"Extracting text from downloaded PDF for: {resource.title[:50]}")+ text = self._extract_text_from_pdf(pdf_content)++ if text:+ # Check if text storage is enabled (default: True for database storage)+ enable_text_storage = self.settings.get_setting(+ "research_library.enable_text_storage", True+ )++ # Get the document ID we just created/updated+ pdf_doc = (+ session.query(LibraryDocument)+ .filter_by(resource_id=resource.id)+ .first()+ )+ pdf_document_id = pdf_doc.id if pdf_doc else None++ # Save text to database (and optionally to file)+ self._save_text_with_db(+ resource=resource,+ text=text,+ session=session,+ extraction_method="pdf_extraction",+ extraction_source="local_pdf",+ pdf_document_id=pdf_document_id,+ save_files=enable_text_storage+ )+ logger.info(f"Successfully extracted and saved text for: {resource.title[:50]}")+ else:+ logger.warning(f"Text extraction returned empty text for: {resource.title[:50]}")+ except Exception as e:+ logger.exception(f"Failed to extract text from PDF, but PDF download succeeded: {e}")+ # Don't fail the entire download if text extraction fails+return True, Noneexcept Exception as e:@@ -794,51 +849,27 @@ class DownloadService:def _try_existing_text(self, session, resource_id: int) -> Optional[Tuple[bool, Optional[str]]]:- """Check if text already exists in database."""- existing_text = (- session.query(LibraryTextDocument)+ """Check if text already exists in database (in Document.text_content)."""+ existing_doc = (+ session.query(LibraryDocument).filter_by(resource_id=resource_id).first())- if not existing_text or existing_text.extraction_status != "completed":+ if not existing_doc:return None- logger.debug(- f"Checking existing text: library_root={self.library_root}, file_path={existing_text.file_path}"- )-- if self.library_root is None:- logger.error("CRITICAL: self.library_root is None!")- raise ValueError(- "DownloadService not properly initialized - library_root is None"- )-- # Check if file exists- if existing_text.file_path is None:- text_path = None- else:- text_path = Path(self.library_root) / existing_text.file_path-- if text_path and text_path.exists():+ # Check if text content exists and extraction was successful+ if existing_doc.text_content and existing_doc.extraction_method and existing_doc.extraction_method != "failed":logger.info(- f"Text file already exists (from DB): {existing_text.file_path}"+ f"Text content already exists in Document for resource_id={resource_id}, extraction_method={existing_doc.extraction_method}")- existing_text.last_accessed = datetime.now(UTC)- session.commit()return True, None- # File missing - mark for re-extraction+ # No text content or failed extractionlogger.debug(- f"Text file in DB but missing on disk: {existing_text.file_path}"+ f"Document exists but no valid text content: resource_id={resource_id}, extraction_method={existing_doc.extraction_method}")- existing_text.extraction_status = "failed"- existing_text.extraction_error = (- "File path is None in database"- if text_path is None- else "File missing on disk"- )- session.commit()return None # Fall through to re-extractiondef _try_legacy_text_file(@@ -1414,64 +1445,38 @@ class DownloadService:else None)- # Check if record exists- text_doc = (- session.query(LibraryTextDocument)- .filter_by(resource_id=resource.id)- .first()- )+ # Find the document by pdf_document_id or resource_id+ doc = None+ if pdf_document_id:+ doc = session.query(LibraryDocument).filter_by(id=pdf_document_id).first()+ else:+ doc = session.query(LibraryDocument).filter_by(resource_id=resource.id).first()- if text_doc:- # Update existing record- text_doc.text_hash = text_hash- text_doc.file_path = (- relative_path # Can be None if storage disabled- )- text_doc.file_size = file_size- text_doc.character_count = character_count- text_doc.word_count = word_count- text_doc.extraction_method = extraction_method- text_doc.extraction_source = extraction_source- text_doc.extraction_status = "completed"- text_doc.extraction_error = None- text_doc.extracted_at = datetime.now(UTC)- text_doc.document_id = pdf_document_id- # Always store text content in database- text_doc.text_content = text+ if doc:+ # Update document with extracted text+ doc.text_content = text+ doc.character_count = character_count+ doc.word_count = word_count+ doc.extraction_method = extraction_method+ doc.extraction_source = extraction_source# Set quality based on methodif extraction_method == "native_api":- text_doc.extraction_quality = "high"+ doc.extraction_quality = "high"elif (extraction_method == "pdf_extraction"and extraction_source == "pdfplumber"):- text_doc.extraction_quality = "medium"+ doc.extraction_quality = "medium"else:- text_doc.extraction_quality = "low"+ doc.extraction_quality = "low"++ logger.debug(f"Updated document {doc.id} with extracted text ({word_count} words)")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,- text_hash=text_hash,- original_url=resource.url,- file_path=relative_path, # Can be None if storage disabled- file_size=file_size,- character_count=character_count,- word_count=word_count,- extraction_method=extraction_method,- extraction_source=extraction_source,- extraction_status="completed",- title=resource.title,- extraction_quality="high"- if extraction_method == "native_api"- else "medium",- text_content=text, # Always store text content in database+ logger.warning(+ f"No document found to store text for resource {resource.id}. "+ "Text content will not be saved to database.")- session.add(text_doc)if text_path:logger.info(f"Saved text to database and disk: {relative_path}")@@ -1493,76 +1498,55 @@ class DownloadService:extraction_method: str,extraction_source: str,):- """Create a database record for an existing text file."""+ """Update existing Document with text from file (for legacy text files)."""try:# Read file to get metadatatext = file_path.read_text(encoding="utf-8", errors="ignore")- file_size = len(text.encode("utf-8"))- text_hash = hashlib.sha256(text.encode("utf-8")).hexdigest()word_count = len(text.split())character_count = len(text)- # Get relative path- relative_path = file_path.relative_to(self.library_root)-- # 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,- original_url=resource.url,- file_path=str(relative_path),- file_size=file_size,- character_count=character_count,- word_count=word_count,- extraction_method=extraction_method,- extraction_source=extraction_source,- extraction_status="completed",- title=resource.title,- extraction_quality="low", # Unknown quality for legacy files- )- session.add(text_doc)- logger.info(- f"Added existing text file to database: {relative_path}"- )+ # Find the Document by resource_id+ doc = session.query(LibraryDocument).filter_by(resource_id=resource.id).first()++ if doc:+ # Update existing document with text content+ doc.text_content = text+ doc.character_count = character_count+ doc.word_count = word_count+ doc.extraction_method = extraction_method+ doc.extraction_source = extraction_source+ doc.extraction_quality = "low" # Unknown quality for legacy files+ logger.info(+ f"Updated document {doc.id} with text from file: {file_path.name}"+ )+ else:+ logger.warning(+ f"No document found to update for resource {resource.id}"+ )except Exception:- logger.exception("Error creating text document record")+ logger.exception("Error updating document with text from file")def _record_failed_text_extraction(self, session: Session, resource: ResearchResource, error: str):- """Record a failed text extraction attempt in the database."""+ """Record a failed text extraction attempt in the Document."""try:- text_doc = (- session.query(LibraryTextDocument)- .filter_by(resource_id=resource.id)- .first()- )-- 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(),- original_url=resource.url,- file_path="",- file_size=0,- extraction_method="failed",- extraction_status="failed",- extraction_error=error,- title=resource.title,+ # Find the Document by resource_id+ doc = session.query(LibraryDocument).filter_by(resource_id=resource.id).first()++ if doc:+ # Update document with extraction error+ doc.error_message = error+ doc.extraction_method = "failed"+ doc.extraction_quality = "low"+ logger.info(+ f"Recorded failed text extraction for document {doc.id}: {error}")- session.add(text_doc)else:- text_doc.extraction_status = "failed"- text_doc.extraction_error = error-- logger.info(- f"Recorded failed text extraction for resource {resource.id}: {error}"- )+ logger.warning(+ f"No document found to record extraction failure for resource {resource.id}"+ )except Exception:logger.exception("Error recording failed text extraction")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.pyindex 79c3e2f271..7d9651a8a7 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@@ -16,10 +16,13 @@ from typing import Any, Dict, List, Optionalfrom langchain_core.documents import Documentfrom langchain_text_splitters import RecursiveCharacterTextSplitterfrom loguru import logger+from sqlalchemy import funcfrom ...database.models.library import (+ Document as LibraryDocument,DocumentChunk,- LibraryTextDocument,+ DocumentCollection,+ Collection,RAGIndex,)from ...database.session_context import get_user_db_session@@ -222,31 +225,43 @@ class LibraryRAGService:)return faiss_index- def get_current_index_info(self) -> Optional[Dict[str, Any]]:- """Get information about the current RAG index."""+ def get_current_index_info(self, collection_id: Optional[str] = None) -> Optional[Dict[str, Any]]:+ """+ Get information about the current RAG index for a collection.++ Args:+ collection_id: UUID of collection (defaults to Library if None)+ """with get_user_db_session(self.username) as session:+ # Get collection name+ if collection_id:+ collection = session.query(Collection).filter_by(id=collection_id).first()+ collection_name = collection.name if collection else "unknown"+ else:+ # Default to Library collection+ from ...database.library_init import get_default_library_id+ collection_id = get_default_library_id(self.username)+ collection_name = "Library"+rag_index = (session.query(RAGIndex)- .filter_by(collection_name="library", is_current=True)+ .filter_by(collection_name=collection_name, is_current=True).first())if not rag_index:return None- # Calculate actual counts from database (don't rely on stale RAGIndex fields)+ # Calculate actual counts from DocumentCollection (not from chunks)actual_chunk_count = (- session.query(DocumentChunk)- .filter_by(- collection_name="library",- source_type="library",- )- .count()+ session.query(func.sum(DocumentCollection.chunk_count))+ .filter_by(collection_id=collection_id, indexed=True)+ .scalar() or 0)actual_doc_count = (- session.query(LibraryTextDocument)- .filter_by(rag_indexed=True)+ session.query(DocumentCollection)+ .filter_by(collection_id=collection_id, indexed=True).count())@@ -263,39 +278,58 @@ class LibraryRAGService:}def index_document(- self, text_doc_id: int, force_reindex: bool = False+ self, document_id: str, collection_id: str, force_reindex: bool = False) -> Dict[str, Any]:"""- Index a single library text document into RAG.+ Index a single document into RAG for a specific collection.Args:- text_doc_id: ID of the LibraryTextDocument to index+ document_id: UUID of the Document to index+ collection_id: UUID of the Collection to index forforce_reindex: Whether to force reindexing even if already indexedReturns:Dict with status, chunk_count, and any errors"""with get_user_db_session(self.username) as session:- # Get the text document- text_doc = (- session.query(LibraryTextDocument)- .filter_by(id=text_doc_id)+ # Get the document+ document = (+ session.query(LibraryDocument)+ .filter_by(id=document_id).first())- if not text_doc:+ if not document:return {"status": "error", "error": "Document not found"}- # Check if already indexed- if text_doc.rag_indexed and not force_reindex:+ # Get or create DocumentCollection entry+ doc_collection = (+ session.query(DocumentCollection)+ .filter_by(document_id=document_id, collection_id=collection_id)+ .first()+ )++ if not doc_collection:+ # Create new DocumentCollection entry+ doc_collection = DocumentCollection(+ document_id=document_id,+ collection_id=collection_id,+ indexed=False,+ chunk_count=0,+ )+ session.add(doc_collection)+ session.flush()++ # Check if already indexed for this collection+ if doc_collection.indexed and not force_reindex:return {"status": "skipped",- "message": "Document already indexed",- "chunk_count": text_doc.chunk_count,+ "message": "Document already indexed for this collection",+ "chunk_count": doc_collection.chunk_count,}# Validate text content- if not text_doc.text_content:+ if not document.text_content:return {"status": "error","error": "Document has no text content",@@ -304,38 +338,43 @@ class LibraryRAGService:try:# Create LangChain Document from textdoc = Document(- page_content=text_doc.text_content,+ page_content=document.text_content,metadata={- "source": text_doc.original_url,- "source_id": text_doc_id, # Add document ID for source linking- "title": text_doc.title or "Untitled",- "document_title": text_doc.title+ "source": document.original_url,+ "document_id": document_id, # Add document ID for source linking+ "collection_id": collection_id, # Add collection ID+ "title": document.title or "Untitled",+ "document_title": document.titleor "Untitled", # Add for compatibility- "authors": text_doc.authors,- "published_date": str(text_doc.published_date)- if text_doc.published_date+ "authors": document.authors,+ "published_date": str(document.published_date)+ if document.published_dateelse None,- "doi": text_doc.doi,- "arxiv_id": text_doc.arxiv_id,- "pmid": text_doc.pmid,- "pmcid": text_doc.pmcid,- "extraction_method": text_doc.extraction_method,- "word_count": text_doc.word_count,+ "doi": document.doi,+ "arxiv_id": document.arxiv_id,+ "pmid": document.pmid,+ "pmcid": document.pmcid,+ "extraction_method": document.extraction_method,+ "word_count": document.word_count,},)# Split into chunkschunks = self.text_splitter.split_documents([doc])logger.info(- f"Split document {text_doc_id} into {len(chunks)} chunks"+ f"Split document {document_id} into {len(chunks)} chunks")+ # Get collection name for chunk storage+ collection = session.query(Collection).filter_by(id=collection_id).first()+ collection_name = collection.name if collection else "unknown"+# Store chunks in database using embedding managerembedding_ids = self.embedding_manager._store_chunks_to_db(chunks=chunks,- collection_name="library", # Library collection- source_type="library",- source_id=text_doc_id,+ collection_name=collection_name,+ source_type="document",+ source_id=document_id,)# Load or create FAISS index@@ -407,20 +446,11 @@ class LibraryRAGService:f"Saved FAISS index to {index_path} with integrity tracking")- # Update LibraryTextDocument with RAG status- # Re-query to ensure we have fresh object in this session- text_doc = (- session.query(LibraryTextDocument)- .filter_by(id=text_doc_id)- .first()- )-- was_already_indexed = (- text_doc.rag_indexed- ) # Check BEFORE updating- text_doc.rag_indexed = True- text_doc.chunk_count = len(chunks)- text_doc.last_indexed_at = datetime.now(UTC)+ # Update DocumentCollection with RAG status+ was_already_indexed = doc_collection.indexed # Check BEFORE updating+ doc_collection.indexed = True+ doc_collection.chunk_count = len(chunks)+ doc_collection.last_indexed_at = datetime.now(UTC)# Update RAGIndex statistics (only if not already indexed)rag_index_obj = (@@ -440,7 +470,7 @@ class LibraryRAGService:session.commit()logger.info(- f"Successfully indexed document {text_doc_id} "+ f"Successfully indexed document {document_id} for collection {collection_id} "f"with {len(chunks)} chunks")@@ -452,7 +482,7 @@ class LibraryRAGService:except Exception as e:logger.exception(- f"Error indexing document {text_doc_id}: {str(e)}"+ f"Error indexing document {document_id} for collection {collection_id}: {str(e)}")return {"status": "error",@@ -463,7 +493,10 @@ class LibraryRAGService:self, research_id: str, force_reindex: bool = False) -> Dict[str, Any]:"""- Index all text documents from a research into RAG.+ DEPRECATED: This method uses old research_id concept.+ Use collection-based indexing with index_document(document_id, collection_id) instead.++ TODO: Refactor to take collection_id and query DocumentCollection to find documents.Args:research_id: ID of the research@@ -472,55 +505,22 @@ class LibraryRAGService:Returns:Dict with counts of successful, skipped, and failed documents"""- with get_user_db_session(self.username) as session:- # Get all text documents for this research- text_docs = (- session.query(LibraryTextDocument)- .filter_by(research_id=research_id)- .all()- )-- if not text_docs:- return {- "status": "error",- "error": "No text documents found for research",- }-- results = {"successful": 0, "skipped": 0, "failed": 0, "errors": []}-- for text_doc in text_docs:- result = self.index_document(text_doc.id, force_reindex)-- if result["status"] == "success":- results["successful"] += 1- elif result["status"] == "skipped":- results["skipped"] += 1- else:- results["failed"] += 1- results["errors"].append(- {- "doc_id": text_doc.id,- "title": text_doc.title,- "error": result.get("error"),- }- )-- logger.info(- f"Indexed research {research_id}: "- f"{results['successful']} successful, "- f"{results['skipped']} skipped, "- f"{results['failed']} failed"- )-- return results+ logger.warning(+ "index_research_documents() is deprecated. Use collection-based indexing instead."+ )+ return {+ "status": "error",+ "error": "This method is deprecated. Use collection-based indexing with index_document(document_id, collection_id) instead.",+ }def index_all_documents(- self, force_reindex: bool = False, progress_callback=None+ self, collection_id: str, force_reindex: bool = False, progress_callback=None) -> Dict[str, Any]:"""- Index all library text documents into RAG.+ Index all documents in a collection into RAG.Args:+ collection_id: UUID of the collection to indexforce_reindex: Whether to force reindexing already indexed documentsprogress_callback: Optional callback function called after each document with (current, total, doc_title, status)@@ -528,16 +528,16 @@ class LibraryRAGService:Dict with counts of successful, skipped, and failed documents"""with get_user_db_session(self.username) as session:- # Get all text documents- query = session.query(LibraryTextDocument)+ # Get all DocumentCollection entries for this collection+ query = session.query(DocumentCollection).filter_by(collection_id=collection_id)if not force_reindex:# Only index documents that haven't been indexed yet- query = query.filter_by(rag_indexed=False)+ query = query.filter_by(indexed=False)- text_docs = query.all()+ doc_collections = query.all()- if not text_docs:+ if not doc_collections:return {"status": "info","message": "No documents to index",@@ -547,10 +547,14 @@ class LibraryRAGService:}results = {"successful": 0, "skipped": 0, "failed": 0, "errors": []}- total = len(text_docs)+ total = len(doc_collections)- for idx, text_doc in enumerate(text_docs, 1):- result = self.index_document(text_doc.id, force_reindex)+ for idx, doc_collection in enumerate(doc_collections, 1):+ # Get the document for title info+ document = session.query(LibraryDocument).filter_by(id=doc_collection.document_id).first()+ title = document.title if document else "Unknown"++ result = self.index_document(doc_collection.document_id, collection_id, force_reindex)if result["status"] == "success":results["successful"] += 1@@ -560,20 +564,18 @@ class LibraryRAGService:results["failed"] += 1results["errors"].append({- "doc_id": text_doc.id,- "title": text_doc.title,+ "doc_id": doc_collection.document_id,+ "title": title,"error": result.get("error"),})# Call progress callback if providedif progress_callback:- progress_callback(- idx, total, text_doc.title, result["status"]- )+ progress_callback(idx, total, title, result["status"])logger.info(- f"Indexed all library documents: "+ f"Indexed collection {collection_id}: "f"{results['successful']} successful, "f"{results['skipped']} skipped, "f"{results['failed']} failed"@@ -581,49 +583,54 @@ class LibraryRAGService:return results- def remove_document_from_rag(self, text_doc_id: int) -> Dict[str, Any]:+ def remove_document_from_rag(self, document_id: str, collection_id: str) -> Dict[str, Any]:"""- Remove a document's chunks from RAG.+ Remove a document's chunks from RAG for a specific collection.Args:- text_doc_id: ID of the LibraryTextDocument to remove+ document_id: UUID of the Document to remove+ collection_id: UUID of the Collection to remove fromReturns:Dict with status and count of removed chunks"""with get_user_db_session(self.username) as session:- # Get the text document- text_doc = (- session.query(LibraryTextDocument)- .filter_by(id=text_doc_id)+ # Get the DocumentCollection entry+ doc_collection = (+ session.query(DocumentCollection)+ .filter_by(document_id=document_id, collection_id=collection_id).first())- if not text_doc:- return {"status": "error", "error": "Document not found"}+ if not doc_collection:+ return {"status": "error", "error": "Document not found in collection"}try:+ # Get collection name+ collection = session.query(Collection).filter_by(id=collection_id).first()+ collection_name = collection.name if collection else "unknown"+# Delete chunks from databasedeleted_count = self.embedding_manager._delete_chunks_from_db(- collection_name="library",- source_id=text_doc_id,+ collection_name=collection_name,+ source_id=document_id,)- # Update LibraryTextDocument RAG status- text_doc.rag_indexed = False- text_doc.chunk_count = 0- text_doc.last_indexed_at = None+ # Update DocumentCollection RAG status+ doc_collection.indexed = False+ doc_collection.chunk_count = 0+ doc_collection.last_indexed_at = Nonesession.commit()logger.info(- f"Removed {deleted_count} chunks for document {text_doc_id}"+ f"Removed {deleted_count} chunks for document {document_id} from collection {collection_id}")return {"status": "success", "deleted_count": deleted_count}except Exception as e:logger.exception(- f"Error removing document {text_doc_id}: {str(e)}"+ f"Error removing document {document_id} from collection {collection_id}: {str(e)}")return {"status": "error",@@ -631,13 +638,14 @@ class LibraryRAGService:}def index_documents_batch(- self, doc_info: List[tuple], force_reindex: bool = False- ) -> Dict[int, Dict[str, Any]]:+ self, doc_info: List[tuple], collection_id: str, force_reindex: bool = False+ ) -> Dict[str, Dict[str, Any]]:"""- Index multiple documents in a single database session for better efficiency.+ Index multiple documents in a batch for a specific collection.Args:doc_info: List of (doc_id, title) tuples+ collection_id: UUID of the collection to index forforce_reindex: Whether to force reindexing even if already indexedReturns:@@ -646,81 +654,64 @@ class LibraryRAGService:results = {}doc_ids = [doc_id for doc_id, _ in doc_info]- # Use single database session for the entire batch+ # Use single database session for queryingwith get_user_db_session(self.username) as session:# Pre-load all documents for this batch- text_docs = (- session.query(LibraryTextDocument)- .filter(LibraryTextDocument.id.in_(doc_ids))+ documents = (+ session.query(LibraryDocument)+ .filter(LibraryDocument.id.in_(doc_ids)).all())# Create lookup for quick access- doc_lookup = {doc.id: doc for doc in text_docs}+ doc_lookup = {doc.id: doc for doc in documents}++ # Pre-load DocumentCollection entries+ doc_collections = (+ session.query(DocumentCollection)+ .filter(+ DocumentCollection.document_id.in_(doc_ids),+ DocumentCollection.collection_id == collection_id+ )+ .all()+ )+ doc_collection_lookup = {dc.document_id: dc for dc in doc_collections}# Process each document in the batchfor doc_id, title in doc_info:- text_doc = doc_lookup.get(doc_id)+ document = doc_lookup.get(doc_id)- if not text_doc:+ if not document:results[doc_id] = {"status": "error","error": "Document not found",}continue- # Check if already indexed- if text_doc.rag_indexed and not force_reindex:+ # Check if already indexed via DocumentCollection+ doc_collection = doc_collection_lookup.get(doc_id)+ if doc_collection and doc_collection.indexed and not force_reindex:results[doc_id] = {"status": "skipped",- "message": "Document already indexed",- "chunk_count": text_doc.chunk_count,+ "message": "Document already indexed for this collection",+ "chunk_count": doc_collection.chunk_count,}continue# Validate text content- if not text_doc.text_content:+ if not document.text_content:results[doc_id] = {"status": "error","error": "Document has no text content",}continue+ # Index the documenttry:- # Use the existing single-document logic but with current session- # This avoids creating additional database connections- from langchain.schema import Document-- # Create LangChain Document from text- Document(- page_content=text_doc.text_content,- metadata={- "source": text_doc.original_url,- "source_id": doc_id,- "title": text_doc.title or "Untitled",- "document_title": text_doc.title or "Untitled",- "authors": text_doc.authors,- "publication_date": text_doc.published_date- if text_doc.published_date- else None,- "document_type": "library_text",- "library_doc_id": doc_id,- },- )-- # Get or create RAG index for this session- self._get_or_create_rag_index(session)-- # Process embeddings and chunks- # Use existing single-document method (it will create its own session)- # No need to expire - each call manages its own session independently- result = self.index_document(doc_id, force_reindex)+ result = self.index_document(doc_id, collection_id, force_reindex)results[doc_id] = result-except Exception as e:- logger.exception(- f"Error indexing document {doc_id} in batch"- )+ logger.exception(f"Error indexing document {doc_id} in batch")results[doc_id] = {"status": "error","error": f"Indexing failed: {type(e).__name__}",@@ -728,35 +719,51 @@ class LibraryRAGService:return results- def get_rag_stats(self) -> Dict[str, Any]:+ def get_rag_stats(self, collection_id: Optional[str] = None) -> Dict[str, Any]:"""- Get RAG statistics for the library.+ Get RAG statistics for a collection.++ Args:+ collection_id: UUID of the collection (defaults to Library)Returns:Dict with counts and metadata about indexed documents"""with get_user_db_session(self.username) as session:- # Count total text documents- total_text_docs = session.query(LibraryTextDocument).count()+ # Get collection ID (default to Library)+ if not collection_id:+ from ...database.library_init import get_default_library_id+ collection_id = get_default_library_id(self.username)++ # Count total documents in collection+ total_docs = (+ session.query(DocumentCollection)+ .filter_by(collection_id=collection_id)+ .count()+ )# Count indexed documentsindexed_docs = (- session.query(LibraryTextDocument)- .filter_by(rag_indexed=True)+ session.query(DocumentCollection)+ .filter_by(collection_id=collection_id, indexed=True).count())# Count total chunkstotal_chunks = (- session.query(DocumentChunk)- .filter_by(collection_name="library", source_type="library")- .count()+ session.query(func.sum(DocumentCollection.chunk_count))+ .filter_by(collection_id=collection_id, indexed=True)+ .scalar() or 0)+ # Get collection name+ collection = session.query(Collection).filter_by(id=collection_id).first()+ collection_name = collection.name if collection else "library"+# Get embedding model info from chunkschunk_sample = (session.query(DocumentChunk)- .filter_by(collection_name="library")+ .filter_by(collection_name=collection_name).first())@@ -769,9 +776,9 @@ class LibraryRAGService:}return {- "total_text_documents": total_text_docs,+ "total_documents": total_docs,"indexed_documents": indexed_docs,- "unindexed_documents": total_text_docs - indexed_docs,+ "unindexed_documents": total_docs - indexed_docs,"total_chunks": total_chunks,"embedding_info": embedding_info,"chunk_size": self.chunk_size,diff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.pyindex be45b104b2..3baadb9d41 100644--- a/src/local_deep_research/research_library/services/library_service.py+++ b/src/local_deep_research/research_library/services/library_service.py@@ -16,7 +16,11 @@ from loguru import loggerfrom sqlalchemy import and_, or_, func, Integer, casefrom ...database.models.download_tracker import DownloadTracker-from ...database.models.library import LibraryDocument, LibraryTextDocument+from ...database.models.library import (+ Document as LibraryDocument,+ Collection,+ DocumentCollection,+)from ...database.models.research import ResearchHistory, ResearchResourcefrom ...database.models.metrics import ResearchRatingfrom ...database.session_context import get_user_db_session@@ -70,7 +74,7 @@ class LibraryService:return Falsedef _apply_domain_filter(self, query, model_class, domain: str):- """Apply domain filter to query for either LibraryDocument or LibraryTextDocument."""+ """Apply domain filter to query for LibraryDocument."""if domain == "arxiv.org":return query.filter(model_class.original_url.like("%arxiv.org%"))elif domain == "pubmed":@@ -92,7 +96,7 @@ class LibraryService:return query.filter(model_class.original_url.like(f"%{domain}%"))def _apply_search_filter(self, query, model_class, search_query: str):- """Apply search filter to query for either LibraryDocument or LibraryTextDocument."""+ """Apply search filter to query for LibraryDocument."""search_pattern = f"%{search_query}%"return query.filter(or_(@@ -196,13 +200,16 @@ class LibraryService:Get documents with filtering options.Returns enriched document information with research details.- Includes both PDF documents and text-only documents."""with get_user_db_session(self.username) as session:+ # Get default Library collection ID for RAG status+ from ...database.library_init import get_default_library_id+ library_id = get_default_library_id(self.username)+all_documents = []- # Query 1: Get PDF documents (LibraryDocument)- pdf_query = (+ # Query documents+ query = (session.query(LibraryDocument, ResearchResource, ResearchHistory)@@ -216,57 +223,43 @@ class LibraryService:))- # Apply filters to PDF query+ # Apply filtersif research_id:- pdf_query = pdf_query.filter(+ query = query.filter(LibraryDocument.research_id == research_id)if domain:- pdf_query = self._apply_domain_filter(- pdf_query, LibraryDocument, domain+ query = self._apply_domain_filter(+ query, LibraryDocument, domain)if file_type:- pdf_query = pdf_query.filter(+ query = query.filter(LibraryDocument.file_type == file_type)if favorites_only:- pdf_query = pdf_query.filter(LibraryDocument.favorite.is_(True))+ query = query.filter(LibraryDocument.favorite.is_(True))if search_query:- pdf_query = self._apply_search_filter(- pdf_query, LibraryDocument, search_query+ query = self._apply_search_filter(+ query, LibraryDocument, search_query)# Filter to only downloaded documents- pdf_query = pdf_query.filter(+ query = query.filter(LibraryDocument.download_status == "completed")# Apply safety limit to prevent memory issues- pdf_query = pdf_query.limit(500000)+ query = query.limit(500000)- # Execute PDF query- pdf_results = pdf_query.all()-- # Bulk fetch text documents for PDFs (avoid N+1 queries)- text_docs_map = {}- if pdf_results:- try:- doc_ids = [doc.id for doc, _, _ in pdf_results]- text_docs = (- session.query(LibraryTextDocument)- .filter(LibraryTextDocument.document_id.in_(doc_ids))- .all()- )- text_docs_map = {td.document_id: td for td in text_docs}- except Exception:- pass+ # Execute query+ results = query.all()- # Process PDF results- for doc, resource, research in pdf_results:+ # Process results+ for doc, resource, research in results:# Get download tracker infotracker = (session.query(DownloadTracker)@@ -274,9 +267,6 @@ class LibraryService:.first())- # Get text document from pre-fetched map- text_doc = text_docs_map.get(doc.id)-# Determine availability flagsfile_absolute_path = Noneif tracker and tracker.file_path:@@ -285,26 +275,16 @@ class LibraryService:)has_pdf = bool(file_absolute_path)- has_text_rag = bool(- text_doc- and hasattr(text_doc, "file_path")- and text_doc.file_path- )- has_text_db = bool(- text_doc- and hasattr(text_doc, "text_content")- and text_doc.text_content- )- has_rag_indexed = bool(- text_doc- and hasattr(text_doc, "rag_indexed")- and text_doc.rag_indexed- )- rag_chunk_count = (- text_doc.chunk_count- if text_doc and hasattr(text_doc, "chunk_count")- else 0+ has_text_db = bool(doc.text_content) # Text now in Document++ # Check RAG indexing status from DocumentCollection+ doc_collection = (+ session.query(DocumentCollection)+ .filter_by(document_id=doc.id, collection_id=library_id)+ .first())+ has_rag_indexed = doc_collection.indexed if doc_collection else False+ rag_chunk_count = doc_collection.chunk_count if doc_collection else 0all_documents.append({@@ -351,7 +331,6 @@ class LibraryService:"is_pdf": doc.file_type == "pdf",# Availability flags"has_pdf": has_pdf,- "has_text_rag": has_text_rag,"has_text_db": has_text_db,"has_rag_indexed": has_rag_indexed,"rag_chunk_count": rag_chunk_count,@@ -360,116 +339,6 @@ class LibraryService:})- # Query 2: Get text-only documents (only if not filtering by PDF-specific fields)- if not file_type and not favorites_only:- text_query = (- session.query(- LibraryTextDocument, ResearchResource, ResearchHistory- )- .join(- ResearchResource,- LibraryTextDocument.resource_id == ResearchResource.id,- )- .join(- ResearchHistory,- LibraryTextDocument.research_id == ResearchHistory.id,- )- .filter(LibraryTextDocument.document_id.is_(None))- )-- # Apply filters to text query- if research_id:- text_query = text_query.filter(- LibraryTextDocument.research_id == research_id- )-- if domain:- text_query = self._apply_domain_filter(- text_query, LibraryTextDocument, domain- )-- if search_query:- text_query = self._apply_search_filter(- text_query, LibraryTextDocument, search_query- )-- # Filter to only extracted documents- text_query = text_query.filter(- LibraryTextDocument.extraction_status == "completed"- )-- # Apply safety limit to prevent memory issues- text_query = text_query.limit(500000)-- # Execute text query- text_results = text_query.all()-- # Process text-only results- for text_doc, resource, research in text_results:- # Determine availability flags- has_pdf = False # No PDF for text-only documents- has_text_rag = bool(text_doc.file_path)- has_text_db = bool(text_doc.text_content)- has_rag_indexed = bool(text_doc.rag_indexed)- rag_chunk_count = text_doc.chunk_count or 0-- all_documents.append(- {- "id": text_doc.id,- "resource_id": text_doc.resource_id,- "research_id": text_doc.research_id,- # Document info- "document_title": text_doc.title or resource.title,- "authors": text_doc.authors,- "published_date": text_doc.published_date,- "doi": text_doc.doi,- "arxiv_id": text_doc.arxiv_id,- "pmid": text_doc.pmid,- # File info (text-only, no PDF)- "file_path": text_doc.file_path or "text_only",- "file_absolute_path": None,- "file_name": Path(text_doc.file_path).name- if text_doc.file_path- else "text_only",- "file_size": text_doc.file_size,- "file_type": "txt",- # URLs- "original_url": text_doc.original_url,- "domain": self._extract_domain(- text_doc.original_url- ),- # Status- "download_status": text_doc.extraction_status,- "downloaded_at": text_doc.extracted_at.isoformat()- if text_doc.extracted_at- else None,- "favorite": False, # Text-only docs don't have favorite flag- "tags": None,- # Research info- "research_title": research.title- or research.query[:80],- "research_query": research.query,- "research_mode": research.mode,- "research_date": research.created_at,- # Classification flags- "is_arxiv": self._is_arxiv_url(- text_doc.original_url- ),- "is_pubmed": self._is_pubmed_url(- text_doc.original_url- ),- "is_pdf": False,- # Availability flags- "has_pdf": has_pdf,- "has_text_rag": has_text_rag,- "has_text_db": has_text_db,- "has_rag_indexed": has_rag_indexed,- "rag_chunk_count": rag_chunk_count,- # Sort key- "_sort_date": text_doc.extracted_at,- }- )-# Sort all documents by date (descending)all_documents.sort(key=lambda d: d["_sort_date"] if d["_sort_date"] else "",@@ -585,10 +454,9 @@ class LibraryService:Get a specific document by its ID.Returns document information with file path.- Searches both LibraryDocument (PDFs) and LibraryTextDocument (text-only)."""with get_user_db_session(self.username) as session:- # First try to find PDF document (LibraryDocument)+ # Find documentresult = (session.query(LibraryDocument, ResearchResource, ResearchHistory@@ -606,7 +474,7 @@ class LibraryService:)if result:- # Found PDF document+ # Found documentdoc, resource, research = result# Get download tracker info@@ -654,74 +522,12 @@ class LibraryService:else research.created_at.isoformat()if research.created_atelse None,- # PDF-specific fields- "is_pdf": True,- "has_text_db": bool(- session.query(LibraryTextDocument)- .filter_by(document_id=doc_id)- .first()- ),- }-- # If not found in LibraryDocument, try LibraryTextDocument (text-only)- text_result = (- session.query(- LibraryTextDocument, ResearchResource, ResearchHistory- )- .join(- ResearchResource,- LibraryTextDocument.resource_id == ResearchResource.id,- )- .join(- ResearchHistory,- LibraryTextDocument.research_id == ResearchHistory.id,- )- .filter(LibraryTextDocument.id == doc_id)- .first()- )-- if text_result:- # Found text-only document- text_doc, resource, research = text_result-- return {- "id": text_doc.id,- "resource_id": text_doc.resource_id,- "research_id": text_doc.research_id,- "document_title": text_doc.title or resource.title,- "original_url": text_doc.original_url or resource.url,- "file_path": text_doc.file_path or "text_only",- "file_absolute_path": None,- "file_name": Path(text_doc.file_path).name- if text_doc.file_path- else "text_only",- "file_size": text_doc.file_size,- "file_type": "txt",- "mime_type": "text/plain",- "domain": self._extract_domain(resource.url),- "download_status": text_doc.extraction_status,- "downloaded_at": text_doc.extracted_at.isoformat()- if text_doc.extracted_at- and hasattr(text_doc.extracted_at, "isoformat")- else str(text_doc.extracted_at)- if text_doc.extracted_at- else None,- "favorite": False, # Text-only docs don't have favorite flag- "tags": None,- "research_title": research.query[:100],- "research_created_at": research.created_at- if isinstance(research.created_at, str)- else research.created_at.isoformat()- if research.created_at- else None,- # Text-specific fields- "is_pdf": False,- "has_text_db": bool(text_doc.text_content),- "extraction_method": text_doc.extraction_method,- "word_count": text_doc.word_count,+ # Document fields+ "is_pdf": doc.file_type == "pdf",+ "has_text_db": bool(doc.text_content), # Text now in Document}- # Not found in either table+ # Not foundreturn Nonedef toggle_favorite(self, document_id: str) -> bool:@@ -867,40 +673,27 @@ class LibraryService:"""Sync library database with filesystem.Check which PDF files exist and update database accordingly.- Text documents in database are not synced - only PDF files are checked.Returns:Statistics about the sync operation"""with get_user_db_session(self.username) as session:- # Get all PDF documents marked as downloaded+ # Get all documents marked as downloadeddocuments = (session.query(LibraryDocument).filter_by(download_status="completed")- .filter_by(file_type="pdf") # Only sync PDF files.all())- # Get count of text documents for reporting (but don't sync them)- text_documents_count = (- session.query(LibraryTextDocument)- .filter_by(extraction_status="completed")- .count()- )-stats = {"total_documents": len(documents),- "total_text_documents": text_documents_count,"files_found": 0,"files_missing": 0,- "text_files_found": text_documents_count, # All assumed present in DB- "text_files_missing": 0, # Not checking text files"trackers_updated": 0,"missing_files": [],- "missing_text_files": [], # Not tracking text file issues}- # Sync PDF documents+ # Sync documents with filesystemfor doc in documents:# Get download trackertracker = (@@ -925,7 +718,6 @@ class LibraryService:"title": doc.title,"path": str(file_path),"url": doc.original_url,- "type": "pdf",})@@ -941,13 +733,9 @@ class LibraryService:stats["files_missing"] += 1session.delete(doc)- # Text documents are not synced - they exist in database as RAG content- # No action needed for text documents-session.commit()logger.info(- f"Library sync completed: PDFs: {stats['files_found']} found, {stats['files_missing']} missing; "- f"Text: {stats['text_files_found']} found, {stats['text_files_missing']} missing"+ f"Library sync completed: {stats['files_found']} found, {stats['files_missing']} missing")return statsdiff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.pyindex edbad201cd..4275f4f7f9 100644--- a/src/local_deep_research/web/auth/routes.py+++ b/src/local_deep_research/web/auth/routes.py@@ -109,6 +109,21 @@ def login():f"Missing default settings loaded and version updated for user {username}")+ # Initialize library system (source types and default collection)+ from ...database.library_init import initialize_library_for_user++ try:+ init_results = initialize_library_for_user(username, password)+ if init_results.get("success"):+ logger.info(f"Library system initialized for user {username}")+ else:+ logger.warning(+ f"Library initialization issue for {username}: {init_results.get('error', 'Unknown error')}"+ )+ except Exception as e:+ logger.exception(f"Error initializing library for {username}: {e}")+ # Don't block login on library init failure+# Success! Create sessionsession_id = session_manager.create_session(username, remember)session["session_id"] = session_iddiff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.pyindex 30afc17ad7..d6f3597069 100644--- a/src/local_deep_research/web/routes/history_routes.py+++ b/src/local_deep_research/web/routes/history_routes.py@@ -4,7 +4,7 @@ import tracebackfrom flask import Blueprint, jsonify, make_response, session, requestfrom ...database.models import ResearchHistory-from ...database.models.library import LibraryDocument+from ...database.models.library import Document as LibraryDocumentfrom ...database.session_context import get_user_db_sessionfrom ..auth.decorators import login_requiredfrom ..models.database import (diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex cf4508f39a..60a4efd0bb 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -25,7 +25,7 @@ from ...database.models import (ResearchLog,UserActiveResearch,)-from ...database.models.library import LibraryDocument+from ...database.models.library import Document as LibraryDocumentfrom ...database.session_context import get_user_db_sessionfrom ..auth.decorators import login_requiredfrom ..models.database import calculate_durationdiff --git a/src/local_deep_research/web/static/js/collection_upload.js b/src/local_deep_research/web/static/js/collection_upload.jsindex c350acf0a1..b09c342f45 100644--- a/src/local_deep_research/web/static/js/collection_upload.js+++ b/src/local_deep_research/web/static/js/collection_upload.js@@ -200,10 +200,12 @@ async function handleUploadFiles(e) {try {console.log('⏳ Showing progress UI...');- progressDiv.style.display = 'block';submitBtn.disabled = true;submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Uploading...';+ // Show clean progress display+ showCleanProgress(selectedFiles);+console.log('🔐 Getting CSRF token...');const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');console.log('🔑 CSRF token found:', !!csrfToken);@@ -225,11 +227,14 @@ async function handleUploadFiles(e) {const data = await response.json();if (data.success) {- showUploadResults(data);- // Reset form and clear stored files- document.getElementById('upload-files-form').reset();- selectedFiles = []; // Clear stored files- hideSelectedFiles();+ updateProgressComplete(data);+ setTimeout(() => {+ showUploadResults(data);+ // Reset form and clear stored files+ document.getElementById('upload-files-form').reset();+ selectedFiles = []; // Clear stored files+ hideSelectedFiles();+ }, 500);} else {showError(data.error || 'Upload failed');}@@ -237,18 +242,122 @@ async function handleUploadFiles(e) {console.error('Error uploading files:', error);showError('Upload failed: ' + error.message);} finally {- progressDiv.style.display = 'none';submitBtn.disabled = false;submitBtn.innerHTML = '<i class="fas fa-upload"></i> 🚀 Upload Files';}}+/**+ * Show clean progress display with file list+ */+function showCleanProgress(files) {+ const progressDiv = document.getElementById('upload-progress');+ const totalFiles = files.length;++ let html = `+ <div style="padding: 1.5rem; background: #f8f9fa; border-radius: 8px;">+ <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem;">+ <h3 style="margin: 0; font-size: 1.1rem; color: #333;">+ <i class="fas fa-cloud-upload-alt" style="color: #667eea;"></i>+ Uploading Files+ </h3>+ <span id="progress-summary" style="font-weight: 600; color: #667eea;">+ Processing ${totalFiles} file${totalFiles !== 1 ? 's' : ''}...+ </span>+ </div>++ <div style="background: #e9ecef; border-radius: 8px; height: 8px; overflow: hidden; margin-bottom: 1rem;">+ <div id="progress-bar-fill" style="background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); height: 100%; width: 0%; transition: width 0.3s ease;"></div>+ </div>++ <div id="file-progress-list" style="max-height: 300px; overflow-y: auto;">+ `;++ files.forEach((file, index) => {+ const fileSize = (file.size / 1024 / 1024).toFixed(2);+ html += `+ <div id="file-${index}" style="display: flex; align-items: center; padding: 0.75rem; background: white; border-radius: 6px; margin-bottom: 0.5rem; border: 1px solid #dee2e6;">+ <i class="fas fa-spinner fa-spin" style="color: #667eea; margin-right: 0.75rem; width: 16px;"></i>+ <div style="flex: 1;">+ <div style="font-weight: 500; color: #333; margin-bottom: 0.25rem;">${file.name}</div>+ <div style="font-size: 0.85rem; color: #6c757d;">${fileSize} MB</div>+ </div>+ <span style="font-size: 0.85rem; color: #667eea; font-weight: 500;">Uploading...</span>+ </div>+ `;+ });++ html += `+ </div>+ </div>+ `;++ progressDiv.innerHTML = html;+ progressDiv.style.display = 'block';+}++/**+ * Update progress to show completion+ */+function updateProgressComplete(data) {+ const progressBarFill = document.getElementById('progress-bar-fill');+ const progressSummary = document.getElementById('progress-summary');++ if (progressBarFill) {+ progressBarFill.style.width = '100%';+ }++ if (progressSummary) {+ const successCount = data.uploaded_files ? data.uploaded_files.length : 0;+ const failedCount = data.failed_files ? data.failed_files.length : 0;+ progressSummary.textContent = `✓ ${successCount} uploaded${failedCount > 0 ? `, ${failedCount} failed` : ''}`;+ progressSummary.style.color = failedCount > 0 ? '#f39c12' : '#27ae60';+ }++ // Update individual file status+ if (data.uploaded_files) {+ data.uploaded_files.forEach((file, index) => {+ const fileDiv = document.getElementById(`file-${index}`);+ if (fileDiv) {+ const icon = fileDiv.querySelector('i');+ const status = fileDiv.querySelector('span:last-child');+ icon.className = 'fas fa-check-circle';+ icon.style.color = '#27ae60';+ status.textContent = 'Complete';+ status.style.color = '#27ae60';+ fileDiv.style.borderColor = '#27ae60';+ fileDiv.style.background = '#f0fff4';+ }+ });+ }++ if (data.failed_files) {+ data.failed_files.forEach((file, index) => {+ const fileDiv = document.getElementById(`file-${index}`);+ if (fileDiv) {+ const icon = fileDiv.querySelector('i');+ const status = fileDiv.querySelector('span:last-child');+ icon.className = 'fas fa-exclamation-circle';+ icon.style.color = '#e74c3c';+ status.textContent = 'Failed';+ status.style.color = '#e74c3c';+ fileDiv.style.borderColor = '#e74c3c';+ fileDiv.style.background = '#fff5f5';+ }+ });+ }+}+/*** Show upload results*/function showUploadResults(data) {+ const progressDiv = document.getElementById('upload-progress');const resultsDiv = document.getElementById('upload-results');+ // Hide progress display+ progressDiv.style.display = 'none';+let html = '<div class="alert" style="background: #d4edda; color: #155724; border: 1px solid #c3e6cb; padding: 1rem; border-radius: 8px; margin-bottom: 1rem;">';html += '<h4 style="margin: 0 0 0.5rem 0;"><i class="fas fa-check-circle"></i> Upload Complete!</h4>';@@ -287,7 +396,14 @@ function showUploadResults(data) {* Show error message*/function showError(message) {+ const progressDiv = document.getElementById('upload-progress');const resultsDiv = document.getElementById('upload-results');++ // Hide progress display+ if (progressDiv) {+ progressDiv.style.display = 'none';+ }+const html = `<div class="alert" style="background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; padding: 1rem; border-radius: 8px; margin-bottom: 1rem;"><h4 style="margin: 0 0 0.5rem 0;"><i class="fas fa-exclamation-triangle"></i> Upload Error</h4>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.pyindex 1f4749d751..67e2c3ada8 100644--- 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@@ -66,7 +66,7 @@ class CollectionSearchEngine(LibraryRAGSearchEngine):returntry:- from ...database.models import LibraryCollection+ from ...database.models.library import Collection as LibraryCollectionfrom ...database.session_context import get_user_db_sessionwith get_user_db_session(self.username) as db_session: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.pyindex 90b34ac868..7498cbabc1 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@@ -206,7 +206,7 @@ class LibraryRAGSearchEngine(BaseSearchEngine):return relevant_itemstry:- from ...database.models.library import LibraryTextDocument+ from ...database.models.library import Documentfrom ...database.session_context import get_user_db_session# Retrieve full content for each document@@ -217,19 +217,19 @@ class LibraryRAGSearchEngine(BaseSearchEngine):# Get full document text from databasewith get_user_db_session(self.username) as db_session:- text_doc = (- db_session.query(LibraryTextDocument)+ document = (+ db_session.query(Document).filter_by(id=doc_id).first())- if text_doc and text_doc.content:+ if document and document.text_content:# Replace snippet with full content- item["content"] = text_doc.content+ item["content"] = document.text_contentitem["snippet"] = (- text_doc.content[:500] + "..."- if len(text_doc.content) > 500- else text_doc.content+ document.text_content[:500] + "..."+ if len(document.text_content) > 500+ else document.text_content)logger.debug(f"Retrieved full content for document {doc_id}"