a
    bg                     @   s   U d dl Z d dlZd dlZd dlmZ d dlmZmZmZ d dl	Z	d dl	Z
d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ erd d	lmZ eeZG d
d deZG dd deZG dd deZdZeed< G dd deZ dS )    N)abstractmethod)TYPE_CHECKINGIterableIterator)Document)BaseChatModel)HumanMessage)BaseBlobParser)BlobImagec                   @   s8   e Zd ZdZededddZeee	 dddZ
d	S )
BaseImageBlobParserz6Abstract base class for parsing image blobs into text.r   imgreturnc                 C   s   dS )zAbstract method to analyze an image and extract textual content.

        Args:
            img: The image to be analyzed.

        Returns:
          The extracted text content.
        N )selfr   r   r   /var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_community/document_loaders/parsers/images.py_analyze_image   s    z"BaseImageBlobParser._analyze_image)blobr   c                 c   s   zddl m} | r}|jdkr4|t|}n
||}| |}t	
d|dd t|i |jd|jidV  W d	   n1 s0    Y  W n ty   td
Y n0 d	S )zLazily parse a blob and yields Documents containing the parsed content.

        Args:
            blob (Blob): The blob to be parsed.

        Yields:
            Document:
              A document containing the parsed content and metadata.
        r   r   zapplication/x-npyzImage text: %s
z\nsource)Zpage_contentmetadataNzG`Pillow` package not found, please install it with `pip install Pillow`)ZPILr   Zas_bytes_iomimetypeZ	fromarraynumpyloadopenr   loggerdebugreplacer   r   r   ImportError)r   r   ZImgbufr   contentr   r   r   
lazy_parse$   s     




*zBaseImageBlobParser.lazy_parseN)__name__
__module____qualname____doc__r   strr   r
   r   r   r#   r   r   r   r   r      s   
r   c                       s6   e Zd ZdZdd fddZdeddd	Z  ZS )
RapidOCRBlobParserzParser for extracting text from images using the RapidOCR library.

    Attributes:
        ocr:
          The RapidOCR instance for performing OCR.
    N)r   c                    s   t    d| _dS )z5
        Initializes the RapidOCRBlobParser.
        N)super__init__ocr)r   	__class__r   r   r+   K   s    
zRapidOCRBlobParser.__init__r   r   c                 C   sr   | j s:zddlm} | | _ W n ty8   tdY n0 |  t|\}}d}|rnddd |D  }|S )z
        Analyzes an image and extracts text using RapidOCR.

        Args:
            img (Image):
              The image to be analyzed.

        Returns:
            str:
              The extracted text content.
        r   )RapidOCRzc`rapidocr-onnxruntime` package not found, please install it with `pip install rapidocr-onnxruntime` r   c                 S   s   g | ]}|d  qS )   r   ).0textr   r   r   
<listcomp>m       z5RapidOCRBlobParser._analyze_image.<locals>.<listcomp>)r,   Zrapidocr_onnxruntimer/   r    nparrayjoinstrip)r   r   r/   Z
ocr_result_r"   r   r   r   r   T   s    
z!RapidOCRBlobParser._analyze_image)r$   r%   r&   r'   r+   r(   r   __classcell__r   r   r-   r   r)   C   s   		r)   c                       s@   e Zd ZdZddee d fddZdeddd	Z  ZS )
TesseractBlobParserzFParse for extracting text from images using the Tesseract OCR library.)Zeng)langsc                   s   t    t|| _dS )zInitialize the TesseractBlobParser.

        Args:
            langs (list[str]):
              The languages to use for OCR.
        N)r*   r+   listr=   )r   r=   r-   r   r   r+   t   s    
zTesseractBlobParser.__init__r   r   c                 C   sB   zddl }W n ty&   tdY n0 |j|d| jd S )zAnalyze an image and extracts text using Tesseract OCR.

        Args:
            img: The image to be analyzed.

        Returns:
            str: The extracted text content.
        r   NzQ`pytesseract` package not found, please install it with `pip install pytesseract`+)lang)pytesseractr    Zimage_to_stringr8   r=   r9   )r   r   rA   r   r   r   r      s    	
z"TesseractBlobParser._analyze_image)	r$   r%   r&   r'   r   r(   r+   r   r;   r   r   r-   r   r<   q   s   r<   a  You are an assistant tasked with summarizing images for retrieval. 1. These summaries will be embedded and used to retrieve the raw image. Give a concise summary of the image that is well optimized for retrieval
2. extract all the text from the image. Do not exclude any content from the page.
Format answer in markdown without explanatory text and without markdown delimiter ``` at the beginning. _PROMPT_IMAGES_TO_DESCRIPTIONc                       s>   e Zd ZdZedeed fddZdeddd	Z  Z	S )
LLMImageBlobParserzParser for analyzing images using a language model (LLM).

    Attributes:
        model (BaseChatModel):
          The language model to use for analysis.
        prompt (str):
          The prompt to provide to the language model.
    )prompt)modelrD   c                   s   t    || _|| _dS )zInitializes the LLMImageBlobParser.

        Args:
            model (BaseChatModel):
              The language model to use for analysis.
            prompt (str):
              The prompt to provide to the language model.
        N)r*   r+   rE   rD   )r   rE   rD   r-   r   r   r+      s    
zLLMImageBlobParser.__init__r   r   c                 C   sz   t  }|j|dd t| d}| jt	d| j
jtddddd| id	gd
g}|j}t|tsvJ |S )zAnalyze an image using the provided language model.

        Args:
            img: The image to be analyzed.

        Returns:
            The extracted textual content.
        ZPNG)formatzutf-8r3   )typer3   	image_urlurlzdata:image/jpeg;base64,)rG   rH   )r"   )ioBytesIOsavebase64	b64encodegetvaluedecoderE   Zinvoker   rD   rF   r"   
isinstancer(   )r   r   Zimage_bytesZ
img_base64msgresultr   r   r   r      s&    	
z!LLMImageBlobParser._analyze_image)
r$   r%   r&   r'   rB   r   r(   r+   r   r;   r   r   r-   r   rC      s   rC   )!rM   rJ   loggingabcr   typingr   r   r   r   r6   Zlangchain_core.documentsr   Zlangchain_core.language_modelsr   Zlangchain_core.messagesr   Z)langchain_community.document_loaders.baser	   Z1langchain_community.document_loaders.blob_loadersr
   Z	PIL.Imager   	getLoggerr$   r   r   r)   r<   rB   r(   __annotations__rC   r   r   r   r   <module>   s(   

-.%
