dropbox.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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(
  17. 'Dropbox requires extra dependencies. Install with `pip install --upgrade "embedchain[dropbox]"`'
  18. )
  19. try:
  20. dbx = Dropbox(access_token)
  21. dbx.users_get_current_account()
  22. self.dbx = dbx
  23. except exceptions.AuthError as ex:
  24. raise ValueError("Invalid Dropbox access token. Please verify your token and try again.") from ex
  25. def _download_folder(self, path: str, local_root: str) -> list[FileMetadata]:
  26. """Download a folder from Dropbox and save it preserving the directory structure."""
  27. entries = self.dbx.files_list_folder(path).entries
  28. for entry in entries:
  29. local_path = os.path.join(local_root, entry.name)
  30. if isinstance(entry, FileMetadata):
  31. self.dbx.files_download_to_file(local_path, f"{path}/{entry.name}")
  32. else:
  33. os.makedirs(local_path, exist_ok=True)
  34. self._download_folder(f"{path}/{entry.name}", local_path)
  35. return entries
  36. def _generate_dir_id_from_all_paths(self, path: str) -> str:
  37. """Generate a unique ID for a directory based on all of its paths."""
  38. entries = self.dbx.files_list_folder(path).entries
  39. paths = [f"{path}/{entry.name}" for entry in entries]
  40. return hashlib.sha256("".join(paths).encode()).hexdigest()
  41. def load_data(self, path: str):
  42. """Load data from a Dropbox URL, preserving the folder structure."""
  43. root_dir = f"dropbox_{self._generate_dir_id_from_all_paths(path)}"
  44. os.makedirs(root_dir, exist_ok=True)
  45. for entry in self.dbx.files_list_folder(path).entries:
  46. local_path = os.path.join(root_dir, entry.name)
  47. if isinstance(entry, FileMetadata):
  48. self.dbx.files_download_to_file(local_path, f"{path}/{entry.name}")
  49. else:
  50. os.makedirs(local_path, exist_ok=True)
  51. self._download_folder(f"{path}/{entry.name}", local_path)
  52. dir_loader = DirectoryLoader()
  53. data = dir_loader.load_data(root_dir)["data"]
  54. # Clean up
  55. self._clean_directory(root_dir)
  56. return {
  57. "doc_id": hashlib.sha256(path.encode()).hexdigest(),
  58. "data": data,
  59. }
  60. def _clean_directory(self, dir_path):
  61. """Recursively delete a directory and its contents."""
  62. for item in os.listdir(dir_path):
  63. item_path = os.path.join(dir_path, item)
  64. if os.path.isdir(item_path):
  65. self._clean_directory(item_path)
  66. else:
  67. os.remove(item_path)
  68. os.rmdir(dir_path)