mirror of
https://github.com/Mintplex-Labs/langchain-python.git
synced 2026-07-19 21:33:31 -04:00
e6c1c32aff
So, this is basically fixing the same things as #1517 but for GCS. ### Problem When loading GCS Objects with `/` in the object key (eg. folder/some-document.txt) using `GCSFileLoader`, the objects are downloaded into a temporary directory and saved as a file. This errors out when the parent directory does not exist within the temporary directory. ### What this pr does Creates parent directories based on object key. This also works with deeply nested keys: folder/subfolder/some-document.txt
37 lines
1.4 KiB
Python
37 lines
1.4 KiB
Python
"""Loading logic for loading documents from an GCS directory."""
|
|
from typing import List
|
|
|
|
from langchain.docstore.document import Document
|
|
from langchain.document_loaders.base import BaseLoader
|
|
from langchain.document_loaders.gcs_file import GCSFileLoader
|
|
|
|
|
|
class GCSDirectoryLoader(BaseLoader):
|
|
"""Loading logic for loading documents from GCS."""
|
|
|
|
def __init__(self, project_name: str, bucket: str, prefix: str = ""):
|
|
"""Initialize with bucket and key name."""
|
|
self.project_name = project_name
|
|
self.bucket = bucket
|
|
self.prefix = prefix
|
|
|
|
def load(self) -> List[Document]:
|
|
"""Load documents."""
|
|
try:
|
|
from google.cloud import storage
|
|
except ImportError:
|
|
raise ValueError(
|
|
"Could not import google-cloud-storage python package. "
|
|
"Please install it with `pip install google-cloud-storage`."
|
|
)
|
|
client = storage.Client(project=self.project_name)
|
|
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
|
|
loader = GCSFileLoader(self.project_name, self.bucket, blob.name)
|
|
docs.extend(loader.load())
|
|
return docs
|