U
    DAf;                  	   @   s   d dl Z d dlmZ d dlmZmZmZmZmZ d dl	m
Z
mZmZ d dlmZmZ d dlmZ d dlmZ ed"Zd d	lmZ d d
lmZmZ W 5 Q R X eeZeG dd dZdS )    N)Path)AnyDictListOptionalUnion)Document	componentlogging)get_bytestream_from_sourcenormalize_metadata)
ByteStream)
LazyImportzRun 'pip install pdfminer.six')extract_pages)LAParamsLTTextContainerc                
   @   s   e Zd ZdZdeeeeee eeddd	d
ZedddZ	e
jee ddeeeeef  eeeeef eeeef  f  dddZdS )PDFMinerToDocumenta  
    Converts PDF files to Documents.

    Uses `pdfminer` compatible converters to convert PDF files to Documents. https://pdfminersix.readthedocs.io/en/latest/

    Usage example:
    ```python
    from haystack.components.converters.pdfminer import PDFMinerToDocument

    converter = PDFMinerToDocument()
    results = converter.run(sources=["sample.pdf"], meta={"date_added": datetime.now().isoformat()})
    documents = results["documents"]
    print(documents[0].content)
    # 'This is a text from the PDF file.'
    ```
          ?       @皙?TFN)line_overlapchar_marginline_marginword_margin
boxes_flowdetect_vertical	all_textsreturnc              	   C   s$   t   t|||||||d| _dS )ai  
        Create a PDFMinerToDocument component.

        :param line_overlap:
            This parameter determines whether two characters are considered to be on
            the same line based on the amount of overlap between them.
            The overlap is calculated relative to the minimum height of both characters.
        :param char_margin:
            Determines whether two characters are part of the same line based on the distance between them.
            If the distance is less than the margin specified, the characters are considered to be on the same line.
            The margin is calculated relative to the width of the character.
        :param word_margin:
            Determines whether two characters on the same line are part of the same word
            based on the distance between them. If the distance is greater than the margin specified,
            an intermediate space will be added between them to make the text more readable.
            The margin is calculated relative to the width of the character.
        :param line_margin:
            This parameter determines whether two lines are part of the same paragraph based on
            the distance between them. If the distance is less than the margin specified,
            the lines are considered to be part of the same paragraph.
            The margin is calculated relative to the height of a line.
        :param boxes_flow:
            This parameter determines the importance of horizontal and vertical position when
            determining the order of text boxes. A value between -1.0 and +1.0 can be set,
            with -1.0 indicating that only horizontal position matters and +1.0 indicating
            that only vertical position matters. Setting the value to 'None' will disable advanced
            layout analysis, and text boxes will be ordered based on the position of their bottom left corner.
        :param detect_vertical:
            This parameter determines whether vertical text should be considered during layout analysis.
        :param all_texts:
            If layout analysis should be performed on text in figures.
        )r   r   r   r   r   r   r   N)pdfminer_importcheckr   layout_params)selfr   r   r   r   r   r   r    r"   K/tmp/pip-unpacked-wheel-z752163x/haystack/components/converters/pdfminer.py__init__(   s    +zPDFMinerToDocument.__init__)r   c                 C   sP   g }|D ]2}d}|D ]}t |tr|| 7 }q|| qd|}t|dS )z
        Extracts text from PDF pages then convert the text into Documents

        :param extractor:
            Python generator that yields PDF pages.

        :returns:
            PDF text converted to Haystack Document
         )content)
isinstancer   Zget_textappendjoinr   )r!   Z	extractorZpagespagetext	containerconcatr"   r"   r#   Z__converter_   s    


zPDFMinerToDocument.__converter)	documents)sourcesmetac                 C   s   g }t |t|d}t||D ]\}}zt|}W n: tk
rl } ztjd||d W Y qW 5 d}~X Y nX z$tt	|j
| jd}	| |	}
W n: tk
r } ztjd||d W Y qW 5 d}~X Y nX |j|}||
_||
 qd|iS )a  
        Converts PDF files to Documents.

        :param sources:
            List of PDF file paths or ByteStream objects.
        :param meta:
            Optional metadata to attach to the Documents.
            This value can be either a list of dictionaries or a single dictionary.
            If it's a single dictionary, its content is added to the metadata of all produced Documents.
            If it's a list, the length of the list must match the number of sources, because the two lists will
            be zipped.
            If `sources` contains ByteStream objects, their `meta` will be added to the output Documents.

        :returns:
            A dictionary with the following keys:
            - `documents`: Created Documents
        )Zsources_countz4Could not read {source}. Skipping it. Error: {error})sourceerrorN)ZlaparamszECould not read {source} and convert it to Document, skipping. {error}r/   )r   lenzipr   	Exceptionloggerwarningr   ioBytesIOdatar    _PDFMinerToDocument__converterr1   r)   )r!   r0   r1   r/   Z	meta_listr2   metadataZ
bytestreameZ
pdf_readerdocumentZmerged_metadatar"   r"   r#   runw   s,      
zPDFMinerToDocument.run)r   r   r   r   r   TF)N)__name__
__module____qualname____doc__floatr   boolr$   r   r<   r	   Zoutput_typesr   r   strr   r   r   r   r@   r"   r"   r"   r#   r      s2          7 "r   )r9   pathlibr   typingr   r   r   r   r   Zhaystackr   r	   r
   Z$haystack.components.converters.utilsr   r   Zhaystack.dataclassesr   Zhaystack.lazy_importsr   r   Zpdfminer.high_levelr   Zpdfminer.layoutr   r   	getLoggerrA   r7   r   r"   r"   r"   r#   <module>   s   

