|
| 1 | +import logging |
| 2 | +import os |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +from botocore.exceptions import NoCredentialsError |
| 6 | +from haystack import Pipeline |
| 7 | +from haystack.components.converters import MultiFileConverter |
| 8 | +from haystack.components.embedders import SentenceTransformersDocumentEmbedder |
| 9 | +from haystack.components.preprocessors import DocumentPreprocessor |
| 10 | +from haystack.components.writers import DocumentWriter |
| 11 | +from haystack_integrations.document_stores.chroma import ChromaDocumentStore |
| 12 | + |
| 13 | +from src.app_config import config |
| 14 | +from src.util import file_util |
| 15 | + |
| 16 | +logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | + |
| 19 | +def populate_vector_db() -> None: |
| 20 | + logging.basicConfig(format="%(levelname)s - %(name)s - %(message)s", level=logging.INFO) |
| 21 | + |
| 22 | + chroma_client = config.chroma_client() |
| 23 | + logger.info("ChromaDB collections: %s", chroma_client.list_collections()) |
| 24 | + doc_store = config.chroma_document_store() |
| 25 | + collection_name = doc_store._collection_name |
| 26 | + |
| 27 | + # Clear existing collection if any |
| 28 | + if doc_store.count_documents() > 0: |
| 29 | + logger.info("Deleting existing vector DB collection=%r", collection_name) |
| 30 | + chroma_client.delete_collection(collection_name) |
| 31 | + # Re-create the document store after deletion |
| 32 | + doc_store = config.chroma_document_store() |
| 33 | + |
| 34 | + # Download files from S3 |
| 35 | + local_folder = download_s3_folder_to_local() |
| 36 | + files_to_ingest = [str(p) for p in Path(local_folder).rglob("*") if p.is_file()] |
| 37 | + logger.info("Files to ingest: %s", files_to_ingest) |
| 38 | + |
| 39 | + # Ingest documents into ChromaDB |
| 40 | + logger.info("Ingesting documents into collection=%r", collection_name) |
| 41 | + # Run the pipeline to index documents |
| 42 | + pipeline = _create_ingest_pipeline(doc_store) |
| 43 | + pipeline.run({"converter": {"sources": files_to_ingest}}) |
| 44 | + logger.info("Ingested documents doc_count=%d", doc_store.count_documents()) |
| 45 | + |
| 46 | + logger.info("ChromaDB collections: %s", chroma_client.list_collections()) |
| 47 | + |
| 48 | + |
| 49 | +def download_s3_folder_to_local(s3_folder: str = "files_to_ingest_into_vector_db") -> str: |
| 50 | + """Download the contents of a folder directory from S3 to a local folder.""" |
| 51 | + bucket = os.environ.get("BUCKET_NAME", f"labs-referral-pilot-app-{config.environment}") |
| 52 | + try: |
| 53 | + local_folder = s3_folder |
| 54 | + os.makedirs(local_folder, exist_ok=True) |
| 55 | + except PermissionError as e: |
| 56 | + logger.error("Error creating directories for %s: %s", s3_folder, e) |
| 57 | + local_folder = f"/tmp/{s3_folder}" # nosec B108 |
| 58 | + logger.info("Downloading s3://%s/%s to local folder %s", bucket, s3_folder, local_folder) |
| 59 | + |
| 60 | + if config.environment == "local": |
| 61 | + assert os.path.exists( |
| 62 | + local_folder |
| 63 | + ), f"Local folder {local_folder} should exist with manually downloaded files from S3" |
| 64 | + return local_folder |
| 65 | + |
| 66 | + s3 = file_util.get_s3_client() |
| 67 | + paginator = s3.get_paginator("list_objects_v2") |
| 68 | + try: |
| 69 | + for result in paginator.paginate(Bucket=bucket, Prefix=s3_folder): |
| 70 | + for obj in result.get("Contents", []): |
| 71 | + s3_key = obj["Key"] |
| 72 | + if s3_key.endswith("/"): |
| 73 | + continue # Skip folders |
| 74 | + local_file_path = os.path.join(local_folder, os.path.relpath(s3_key, s3_folder)) |
| 75 | + os.makedirs(os.path.dirname(local_file_path), exist_ok=True) |
| 76 | + s3.download_file(bucket, s3_key, local_file_path) |
| 77 | + logger.info("Downloaded %s to %s", s3_key, local_file_path) |
| 78 | + return local_folder |
| 79 | + except NoCredentialsError: |
| 80 | + logger.error("AWS credentials not found. Please configure your AWS credentials.") |
| 81 | + raise |
| 82 | + |
| 83 | + |
| 84 | +def _create_ingest_pipeline(doc_store: ChromaDocumentStore) -> Pipeline: |
| 85 | + pipeline = Pipeline() |
| 86 | + pipeline.add_component("converter", MultiFileConverter()) |
| 87 | + pipeline.add_component( |
| 88 | + "preprocessor", |
| 89 | + DocumentPreprocessor( |
| 90 | + split_length=config.rag_chunk_split_length, |
| 91 | + split_overlap=config.rag_chunk_split_overlap, |
| 92 | + remove_empty_lines=False, |
| 93 | + remove_extra_whitespaces=False, |
| 94 | + ), |
| 95 | + ) |
| 96 | + pipeline.add_component( |
| 97 | + "embedder", SentenceTransformersDocumentEmbedder(model=config.rag_embedding_model) |
| 98 | + ) |
| 99 | + pipeline.add_component("writer", DocumentWriter(document_store=doc_store)) |
| 100 | + |
| 101 | + # Connect the components |
| 102 | + pipeline.connect("converter.documents", "preprocessor.documents") |
| 103 | + pipeline.connect("preprocessor.documents", "embedder.documents") |
| 104 | + pipeline.connect("embedder.documents", "writer.documents") |
| 105 | + return pipeline |
0 commit comments