-
Notifications
You must be signed in to change notification settings - Fork 170
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
44b0653
commit 77fef0e
Showing
10 changed files
with
358 additions
and
200 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
from __future__ import annotations | ||
from abc import ABC, abstractmethod | ||
from typing import Optional | ||
from attr import Factory, define, field | ||
from griptape.artifacts import BaseArtifact, ErrorArtifact, TextArtifact, InfoArtifact | ||
from griptape.loaders import BaseLoader, CsvLoader, ImageLoader, PdfLoader, TextLoader | ||
|
||
|
||
@define | ||
class BaseFileManagerDriver(ABC): | ||
""" | ||
BaseFileManagerDriver can be used to list, load, and save files. | ||
Attributes: | ||
default_loader: The default loader to use for loading file contents into artifacts. | ||
loaders: Dictionary of file extension specifc loaders to use for loading file contents into artifacts. | ||
""" | ||
|
||
default_loader: Optional[BaseLoader] = field(default=None, kw_only=True) | ||
loaders: dict[str, BaseLoader] = field( | ||
default=Factory( | ||
lambda: { | ||
"pdf": PdfLoader(), | ||
"csv": CsvLoader(), | ||
"txt": TextLoader(), | ||
"html": TextLoader(), | ||
"json": TextLoader(), | ||
"yaml": TextLoader(), | ||
"xml": TextLoader(), | ||
"png": ImageLoader(), | ||
"jpg": ImageLoader(), | ||
"jpeg": ImageLoader(), | ||
"webp": ImageLoader(), | ||
"gif": ImageLoader(), | ||
"bmp": ImageLoader(), | ||
"tiff": ImageLoader(), | ||
} | ||
), | ||
kw_only=True, | ||
) | ||
|
||
@abstractmethod | ||
def list_files(self, path: str) -> TextArtifact | ErrorArtifact: | ||
... | ||
|
||
@abstractmethod | ||
def load_file(self, path: str) -> BaseArtifact: | ||
... | ||
|
||
@abstractmethod | ||
def save_file(self, path: str, value: bytes | str) -> InfoArtifact | ErrorArtifact: | ||
... |
74 changes: 74 additions & 0 deletions
74
griptape/drivers/file_manager/local_file_manager_driver.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
from __future__ import annotations | ||
import os | ||
from pathlib import Path | ||
from attr import define, field, Factory | ||
from griptape.artifacts import ErrorArtifact, InfoArtifact, ListArtifact, BaseArtifact, TextArtifact | ||
from .base_file_manager_driver import BaseFileManagerDriver | ||
|
||
|
||
@define | ||
class LocalFileManagerDriver(BaseFileManagerDriver): | ||
""" | ||
LocalFileManagerDriver can be used to list, load, and save files on the local file system. | ||
Attributes: | ||
workdir: The absolute working directory. List, load, and save operations will be performed relative to this directory. | ||
""" | ||
|
||
workdir: str = field(default=Factory(lambda: os.getcwd()), kw_only=True) | ||
|
||
@workdir.validator # pyright: ignore | ||
def validate_workdir(self, _, workdir: str) -> None: | ||
if not Path(workdir).is_absolute(): | ||
raise ValueError("Workdir must be an absolute path") | ||
|
||
def list_files(self, path: str) -> TextArtifact | ErrorArtifact: | ||
path = path.lstrip("/") | ||
full_path = Path(os.path.join(self.workdir, path)) | ||
|
||
if os.path.exists(full_path): | ||
entries = os.listdir(full_path) | ||
|
||
return TextArtifact("\n".join([e for e in entries])) | ||
else: | ||
return ErrorArtifact("Path not found") | ||
|
||
def load_file(self, path: str) -> BaseArtifact: | ||
path = path.lstrip("/") | ||
full_path = Path(os.path.join(self.workdir, path)) | ||
extension = path.split(".")[-1] | ||
loader = self.loaders.get(extension) or self.default_loader | ||
try: | ||
result = loader.load(full_path) | ||
except Exception as e: | ||
return ErrorArtifact(f"Failed to load file: {str(e)}") | ||
|
||
if isinstance(result, BaseArtifact): | ||
return result | ||
else: | ||
return ListArtifact(result) | ||
|
||
def save_file(self, path: str, value: bytes | str) -> InfoArtifact | ErrorArtifact: | ||
path = path.lstrip("/") | ||
full_path = Path(os.path.join(self.workdir, path)) | ||
extension = path.split(".")[-1] | ||
loader = self.loaders.get(extension) or self.default_loader | ||
encoding = None if loader is None else loader.encoding | ||
|
||
os.makedirs(os.path.dirname(full_path), exist_ok=True) | ||
|
||
try: | ||
if isinstance(value, str): | ||
if encoding is None: | ||
value = value.encode() | ||
else: | ||
value = value.encode(encoding=encoding) | ||
elif isinstance(value, bytearray) or isinstance(value, memoryview): | ||
raise ValueError(f"Unsupported type: {type(value)}") | ||
|
||
with open(full_path, "wb") as file: | ||
file.write(value) | ||
except Exception as e: | ||
return ErrorArtifact(f"Failed to save file: {str(e)}") | ||
|
||
return InfoArtifact("Successfully saved file") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
Oops, something went wrong.