base_chunker.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import hashlib
  2. from embedchain.helper.json_serializable import JSONSerializable
  3. from embedchain.models.data_type import DataType
  4. class BaseChunker(JSONSerializable):
  5. def __init__(self, text_splitter):
  6. """Initialize the chunker."""
  7. self.text_splitter = text_splitter
  8. self.data_type = None
  9. def create_chunks(self, loader, src):
  10. """
  11. Loads data and chunks it.
  12. :param loader: The loader which's `load_data` method is used to create
  13. the raw data.
  14. :param src: The data to be handled by the loader. Can be a URL for
  15. remote sources or local content for local loaders.
  16. """
  17. documents = []
  18. ids = []
  19. idMap = {}
  20. data_result = loader.load_data(src)
  21. data_records = data_result["data"]
  22. doc_id = data_result["doc_id"]
  23. metadatas = []
  24. for data in data_records:
  25. content = data["content"]
  26. meta_data = data["meta_data"]
  27. # add data type to meta data to allow query using data type
  28. meta_data["data_type"] = self.data_type.value
  29. meta_data["doc_id"] = doc_id
  30. url = meta_data["url"]
  31. chunks = self.get_chunks(content)
  32. for chunk in chunks:
  33. chunk_id = hashlib.sha256((chunk + url).encode()).hexdigest()
  34. if idMap.get(chunk_id) is None:
  35. idMap[chunk_id] = True
  36. ids.append(chunk_id)
  37. documents.append(chunk)
  38. metadatas.append(meta_data)
  39. return {
  40. "documents": documents,
  41. "ids": ids,
  42. "metadatas": metadatas,
  43. "doc_id": doc_id,
  44. }
  45. def get_chunks(self, content):
  46. """
  47. Returns chunks using text splitter instance.
  48. Override in child class if custom logic.
  49. """
  50. return self.text_splitter.split_text(content)
  51. def set_data_type(self, data_type: DataType):
  52. """
  53. set the data type of chunker
  54. """
  55. self.data_type = data_type
  56. # TODO: This should be done during initialization. This means it has to be done in the child classes.
  57. def get_word_count(self, documents):
  58. return sum([len(document.split(" ")) for document in documents])