Source code for langchain_community.document_loaders.gcs_directory

import logging
from typing import Callable, List, Optional

from langchain_core._api.deprecation import deprecated
from langchain_core.documents import Document

from langchain_community.document_loaders.base import BaseLoader
from langchain_community.document_loaders.gcs_file import GCSFileLoader
from langchain_community.utilities.vertexai import get_client_info

logger = logging.getLogger(__name__)


[docs]@deprecated( since="0.0.32", removal="0.3.0", alternative_import="langchain_google_community.GCSDirectoryLoader", ) class GCSDirectoryLoader(BaseLoader): """从GCS目录加载。"""
[docs] def __init__( self, project_name: str, bucket: str, prefix: str = "", loader_func: Optional[Callable[[str], BaseLoader]] = None, continue_on_failure: bool = False, ): """初始化使用存储桶和键名。 参数: project_name:GCS存储桶所属项目的ID。 bucket:GCS存储桶的名称。 prefix:GCS存储桶的前缀。 loader_func:一个加载器函数,根据file_path参数实例化一个加载器。如果未提供任何内容,GCSFileLoader将使用其默认加载器。 continue_on_failure:对GCS目录中的每个文件使用try-except块。如果设置为`True`,则无法处理文件不会导致错误。 """ self.project_name = project_name self.bucket = bucket self.prefix = prefix self._loader_func = loader_func self.continue_on_failure = continue_on_failure
[docs] def load(self) -> List[Document]: """加载文档。""" try: from google.cloud import storage except ImportError: raise ImportError( "Could not import google-cloud-storage python package. " "Please install it with `pip install google-cloud-storage`." ) client = storage.Client( project=self.project_name, client_info=get_client_info(module="google-cloud-storage"), ) docs = [] for blob in client.list_blobs(self.bucket, prefix=self.prefix): # we shall just skip directories since GCSFileLoader creates # intermediate directories on the fly if blob.name.endswith("/"): continue # Use the try-except block here try: loader = GCSFileLoader( self.project_name, self.bucket, blob.name, loader_func=self._loader_func, ) docs.extend(loader.load()) except Exception as e: if self.continue_on_failure: logger.warning(f"Problem processing blob {blob.name}, message: {e}") continue else: raise e return docs