data_formatter.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. from importlib import import_module
  2. from typing import Any, Dict
  3. from embedchain.chunkers.base_chunker import BaseChunker
  4. from embedchain.config import AddConfig
  5. from embedchain.config.add_config import ChunkerConfig, LoaderConfig
  6. from embedchain.helper.json_serializable import JSONSerializable
  7. from embedchain.loaders.base_loader import BaseLoader
  8. from embedchain.models.data_type import DataType
  9. class DataFormatter(JSONSerializable):
  10. """
  11. DataFormatter is an internal utility class which abstracts the mapping for
  12. loaders and chunkers to the data_type entered by the user in their
  13. .add or .add_local method call
  14. """
  15. def __init__(self, data_type: DataType, config: AddConfig, kwargs: Dict[str, Any]):
  16. """
  17. Initialize a dataformatter, set data type and chunker based on datatype.
  18. :param data_type: The type of the data to load and chunk.
  19. :type data_type: DataType
  20. :param config: AddConfig instance with nested loader and chunker config attributes.
  21. :type config: AddConfig
  22. """
  23. self.loader = self._get_loader(data_type=data_type, config=config.loader, kwargs=kwargs)
  24. self.chunker = self._get_chunker(data_type=data_type, config=config.chunker, kwargs=kwargs)
  25. def _lazy_load(self, module_path: str):
  26. module_path, class_name = module_path.rsplit(".", 1)
  27. module = import_module(module_path)
  28. return getattr(module, class_name)
  29. def _get_loader(self, data_type: DataType, config: LoaderConfig, kwargs: Dict[str, Any]) -> BaseLoader:
  30. """
  31. Returns the appropriate data loader for the given data type.
  32. :param data_type: The type of the data to load.
  33. :type data_type: DataType
  34. :param config: Config to initialize the loader with.
  35. :type config: LoaderConfig
  36. :raises ValueError: If an unsupported data type is provided.
  37. :return: The loader for the given data type.
  38. :rtype: BaseLoader
  39. """
  40. loaders = {
  41. DataType.YOUTUBE_VIDEO: "embedchain.loaders.youtube_video.YoutubeVideoLoader",
  42. DataType.PDF_FILE: "embedchain.loaders.pdf_file.PdfFileLoader",
  43. DataType.WEB_PAGE: "embedchain.loaders.web_page.WebPageLoader",
  44. DataType.QNA_PAIR: "embedchain.loaders.local_qna_pair.LocalQnaPairLoader",
  45. DataType.TEXT: "embedchain.loaders.local_text.LocalTextLoader",
  46. DataType.DOCX: "embedchain.loaders.docx_file.DocxFileLoader",
  47. DataType.SITEMAP: "embedchain.loaders.sitemap.SitemapLoader",
  48. DataType.XML: "embedchain.loaders.xml.XmlLoader",
  49. DataType.DOCS_SITE: "embedchain.loaders.docs_site_loader.DocsSiteLoader",
  50. DataType.CSV: "embedchain.loaders.csv.CsvLoader",
  51. DataType.MDX: "embedchain.loaders.mdx.MdxLoader",
  52. DataType.IMAGES: "embedchain.loaders.images.ImagesLoader",
  53. DataType.UNSTRUCTURED: "embedchain.loaders.unstructured_file.UnstructuredLoader",
  54. DataType.JSON: "embedchain.loaders.json.JSONLoader",
  55. DataType.OPENAPI: "embedchain.loaders.openapi.OpenAPILoader",
  56. DataType.GMAIL: "embedchain.loaders.gmail.GmailLoader",
  57. DataType.NOTION: "embedchain.loaders.notion.NotionLoader",
  58. }
  59. custom_loaders = set(
  60. [
  61. DataType.POSTGRES,
  62. DataType.MYSQL,
  63. DataType.SLACK,
  64. ]
  65. )
  66. if data_type in loaders:
  67. loader_class: type = self._lazy_load(loaders[data_type])
  68. return loader_class()
  69. elif data_type in custom_loaders:
  70. loader_class: type = kwargs.get("loader", None)
  71. if loader_class is not None:
  72. return loader_class
  73. raise ValueError(
  74. f"Cant find the loader for {data_type}.\
  75. We recommend to pass the loader to use data_type: {data_type},\
  76. check `https://docs.embedchain.ai/data-sources/overview`."
  77. )
  78. def _get_chunker(self, data_type: DataType, config: ChunkerConfig, kwargs: Dict[str, Any]) -> BaseChunker:
  79. """Returns the appropriate chunker for the given data type (updated for lazy loading)."""
  80. chunker_classes = {
  81. DataType.YOUTUBE_VIDEO: "embedchain.chunkers.youtube_video.YoutubeVideoChunker",
  82. DataType.PDF_FILE: "embedchain.chunkers.pdf_file.PdfFileChunker",
  83. DataType.WEB_PAGE: "embedchain.chunkers.web_page.WebPageChunker",
  84. DataType.QNA_PAIR: "embedchain.chunkers.qna_pair.QnaPairChunker",
  85. DataType.TEXT: "embedchain.chunkers.text.TextChunker",
  86. DataType.DOCX: "embedchain.chunkers.docx_file.DocxFileChunker",
  87. DataType.SITEMAP: "embedchain.chunkers.sitemap.SitemapChunker",
  88. DataType.XML: "embedchain.chunkers.xml.XmlChunker",
  89. DataType.DOCS_SITE: "embedchain.chunkers.docs_site.DocsSiteChunker",
  90. DataType.CSV: "embedchain.chunkers.table.TableChunker",
  91. DataType.MDX: "embedchain.chunkers.mdx.MdxChunker",
  92. DataType.IMAGES: "embedchain.chunkers.images.ImagesChunker",
  93. DataType.UNSTRUCTURED: "embedchain.chunkers.unstructured_file.UnstructuredFileChunker",
  94. DataType.JSON: "embedchain.chunkers.json.JSONChunker",
  95. DataType.OPENAPI: "embedchain.chunkers.openapi.OpenAPIChunker",
  96. DataType.GMAIL: "embedchain.chunkers.gmail.GmailChunker",
  97. DataType.NOTION: "embedchain.chunkers.notion.NotionChunker",
  98. DataType.POSTGRES: "embedchain.chunkers.postgres.PostgresChunker",
  99. DataType.MYSQL: "embedchain.chunkers.mysql.MySQLChunker",
  100. DataType.SLACK: "embedchain.chunkers.slack.SlackChunker",
  101. }
  102. if data_type in chunker_classes:
  103. if "chunker" in kwargs:
  104. chunker_class = kwargs.get("chunker")
  105. else:
  106. chunker_class = self._lazy_load(chunker_classes[data_type])
  107. chunker = chunker_class(config)
  108. chunker.set_data_type(data_type)
  109. return chunker
  110. else:
  111. raise ValueError(
  112. f"Cant find the chunker for {data_type}.\
  113. We recommend to pass the chunker to use data_type: {data_type},\
  114. check `https://docs.embedchain.ai/data-sources/overview`."
  115. )