images.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import hashlib
  2. from typing import Optional
  3. from langchain.text_splitter import RecursiveCharacterTextSplitter
  4. from embedchain.chunkers.base_chunker import BaseChunker
  5. from embedchain.config.add_config import ChunkerConfig
  6. class ImagesChunker(BaseChunker):
  7. """Chunker for an Image."""
  8. def __init__(self, config: Optional[ChunkerConfig] = None):
  9. if config is None:
  10. config = ChunkerConfig(chunk_size=300, chunk_overlap=0, length_function=len)
  11. image_splitter = RecursiveCharacterTextSplitter(
  12. chunk_size=config.chunk_size,
  13. chunk_overlap=config.chunk_overlap,
  14. length_function=config.length_function,
  15. )
  16. super().__init__(image_splitter)
  17. def create_chunks(self, loader, src):
  18. """
  19. Loads the image(s), and creates their corresponding embedding. This creates one chunk for each image
  20. :param loader: The loader whose `load_data` method is used to create
  21. the raw data.
  22. :param src: The data to be handled by the loader. Can be a URL for
  23. remote sources or local content for local loaders.
  24. """
  25. documents = []
  26. embeddings = []
  27. ids = []
  28. data_result = loader.load_data(src)
  29. data_records = data_result["data"]
  30. doc_id = data_result["doc_id"]
  31. metadatas = []
  32. for data in data_records:
  33. meta_data = data["meta_data"]
  34. # add data type to meta data to allow query using data type
  35. meta_data["data_type"] = self.data_type.value
  36. chunk_id = hashlib.sha256(meta_data["url"].encode()).hexdigest()
  37. ids.append(chunk_id)
  38. documents.append(data["content"])
  39. embeddings.append(data["embedding"])
  40. meta_data["doc_id"] = doc_id
  41. metadatas.append(meta_data)
  42. return {
  43. "documents": documents,
  44. "embeddings": embeddings,
  45. "ids": ids,
  46. "metadatas": metadatas,
  47. "doc_id": doc_id,
  48. }
  49. def get_word_count(self, documents):
  50. """
  51. The number of chunks and the corresponding word count for an image is fixed to 1, as 1 embedding is created for
  52. each image
  53. """
  54. return 1