base_chunker.py 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import hashlib
  2. import logging
  3. from typing import Optional
  4. from embedchain.config.add_config import ChunkerConfig
  5. from embedchain.helpers.json_serializable import JSONSerializable
  6. from embedchain.models.data_type import DataType
  7. class BaseChunker(JSONSerializable):
  8. def __init__(self, text_splitter):
  9. """Initialize the chunker."""
  10. self.text_splitter = text_splitter
  11. self.data_type = None
  12. def create_chunks(self, loader, src, app_id=None, config: Optional[ChunkerConfig] = None):
  13. """
  14. Loads data and chunks it.
  15. :param loader: The loader whose `load_data` method is used to create
  16. the raw data.
  17. :param src: The data to be handled by the loader. Can be a URL for
  18. remote sources or local content for local loaders.
  19. :param app_id: App id used to generate the doc_id.
  20. """
  21. documents = []
  22. chunk_ids = []
  23. id_map = {}
  24. min_chunk_size = config.min_chunk_size if config is not None else 1
  25. logging.info(f"Skipping chunks smaller than {min_chunk_size} characters")
  26. data_result = loader.load_data(src)
  27. data_records = data_result["data"]
  28. doc_id = data_result["doc_id"]
  29. # Prefix app_id in the document id if app_id is not None to
  30. # distinguish between different documents stored in the same
  31. # elasticsearch or opensearch index
  32. doc_id = f"{app_id}--{doc_id}" if app_id is not None else doc_id
  33. metadatas = []
  34. for data in data_records:
  35. content = data["content"]
  36. metadata = data["meta_data"]
  37. # add data type to meta data to allow query using data type
  38. metadata["data_type"] = self.data_type.value
  39. metadata["doc_id"] = doc_id
  40. # TODO: Currently defaulting to the src as the url. This is done intentianally since some
  41. # of the data types like 'gmail' loader doesn't have the url in the meta data.
  42. url = metadata.get("url", src)
  43. chunks = self.get_chunks(content)
  44. for chunk in chunks:
  45. chunk_id = hashlib.sha256((chunk + url).encode()).hexdigest()
  46. chunk_id = f"{app_id}--{chunk_id}" if app_id is not None else chunk_id
  47. if id_map.get(chunk_id) is None and len(chunk) >= min_chunk_size:
  48. id_map[chunk_id] = True
  49. chunk_ids.append(chunk_id)
  50. documents.append(chunk)
  51. metadatas.append(metadata)
  52. return {
  53. "documents": documents,
  54. "ids": chunk_ids,
  55. "metadatas": metadatas,
  56. "doc_id": doc_id,
  57. }
  58. def get_chunks(self, content):
  59. """
  60. Returns chunks using text splitter instance.
  61. Override in child class if custom logic.
  62. """
  63. return self.text_splitter.split_text(content)
  64. def set_data_type(self, data_type: DataType):
  65. """
  66. set the data type of chunker
  67. """
  68. self.data_type = data_type
  69. # TODO: This should be done during initialization. This means it has to be done in the child classes.
  70. @staticmethod
  71. def get_word_count(documents) -> int:
  72. return sum([len(document.split(" ")) for document in documents])