dropbox.py 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import hashlib
  2. import os
  3. from dropbox.files import FileMetadata
  4. from embedchain.helpers.json_serializable import register_deserializable
  5. from embedchain.loaders.base_loader import BaseLoader
  6. from embedchain.loaders.directory_loader import DirectoryLoader
  7. @register_deserializable
  8. class DropboxLoader(BaseLoader):
  9. def __init__(self):
  10. access_token = os.environ.get("DROPBOX_ACCESS_TOKEN")
  11. if not access_token:
  12. raise ValueError("Please set the `DROPBOX_ACCESS_TOKEN` environment variable.")
  13. try:
  14. from dropbox import Dropbox, exceptions
  15. except ImportError:
  16. raise ImportError("Dropbox requires extra dependencies. Install with `pip install dropbox==11.36.2`")
  17. try:
  18. dbx = Dropbox(access_token)
  19. dbx.users_get_current_account()
  20. self.dbx = dbx
  21. except exceptions.AuthError as ex:
  22. raise ValueError("Invalid Dropbox access token. Please verify your token and try again.") from ex
  23. def _download_folder(self, path: str, local_root: str) -> list[FileMetadata]:
  24. """Download a folder from Dropbox and save it preserving the directory structure."""
  25. entries = self.dbx.files_list_folder(path).entries
  26. for entry in entries:
  27. local_path = os.path.join(local_root, entry.name)
  28. if isinstance(entry, FileMetadata):
  29. self.dbx.files_download_to_file(local_path, f"{path}/{entry.name}")
  30. else:
  31. os.makedirs(local_path, exist_ok=True)
  32. self._download_folder(f"{path}/{entry.name}", local_path)
  33. return entries
  34. def _generate_dir_id_from_all_paths(self, path: str) -> str:
  35. """Generate a unique ID for a directory based on all of its paths."""
  36. entries = self.dbx.files_list_folder(path).entries
  37. paths = [f"{path}/{entry.name}" for entry in entries]
  38. return hashlib.sha256("".join(paths).encode()).hexdigest()
  39. def load_data(self, path: str):
  40. """Load data from a Dropbox URL, preserving the folder structure."""
  41. root_dir = f"dropbox_{self._generate_dir_id_from_all_paths(path)}"
  42. os.makedirs(root_dir, exist_ok=True)
  43. for entry in self.dbx.files_list_folder(path).entries:
  44. local_path = os.path.join(root_dir, entry.name)
  45. if isinstance(entry, FileMetadata):
  46. self.dbx.files_download_to_file(local_path, f"{path}/{entry.name}")
  47. else:
  48. os.makedirs(local_path, exist_ok=True)
  49. self._download_folder(f"{path}/{entry.name}", local_path)
  50. dir_loader = DirectoryLoader()
  51. data = dir_loader.load_data(root_dir)["data"]
  52. # Clean up
  53. self._clean_directory(root_dir)
  54. return {
  55. "doc_id": hashlib.sha256(path.encode()).hexdigest(),
  56. "data": data,
  57. }
  58. def _clean_directory(self, dir_path):
  59. """Recursively delete a directory and its contents."""
  60. for item in os.listdir(dir_path):
  61. item_path = os.path.join(dir_path, item)
  62. if os.path.isdir(item_path):
  63. self._clean_directory(item_path)
  64. else:
  65. os.remove(item_path)
  66. os.rmdir(dir_path)