a
    bgؾ                     @   s.  d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZ d dlm	Z	 d dl
mZmZ d dlmZmZmZmZmZmZmZmZmZmZ d dlm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$ d dl%m&Z& d dl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ d dl0m1Z1 er*d dl2m3Z3 e4e5Z6G dd de1Z7G dd de eZ8G dd de8Z9G dd de8Z:G dd de8Z;G dd de Z<G dd de8Z=G dd de8Z>G d d! d!e8Z?G d"d# d#e8Z@G d$d% d%e8ZAG d&d' d'e8ZBG d(d) d)e$ZCG d*d+ d+e8ZDG d,d- d-e8ZEe:ZFdS ).    N)ABC)StringIO)PathPurePath)
TYPE_CHECKINGAnyBinaryIOIteratorLiteralMappingOptionalSequenceUnioncast)urlparse)Document)get_from_dict_or_env)
BaseLoader)Blob)DedocBaseLoader)BaseImageBlobParser)_DEFAULT_PAGES_DELIMITERAmazonTextractPDFParserDocumentIntelligenceParserPDFMinerParserPDFPlumberParserPyMuPDFParserPyPDFium2ParserPyPDFParser)UnstructuredFileLoader)TextLinearizationConfigc                       sB   e Zd ZdZd	eeef eed fddZe	dddZ
  ZS )
UnstructuredPDFLoadera  Load `PDF` files using `Unstructured`.

    You can run the loader in one of two modes: "single" and "elements".
    If you use "single" mode, the document will be returned as a single
    langchain Document object. If you use "elements" mode, the unstructured
    library will split the document into elements such as Title and NarrativeText.
    You can pass in additional unstructured kwargs after mode to apply
    different unstructured settings.

    Examples
    --------
    from langchain_community.document_loaders import UnstructuredPDFLoader

    loader = UnstructuredPDFLoader(
        "example.pdf", mode="elements", strategy="fast",
    )
    docs = loader.load()

    References
    ----------
    https://unstructured-io.github.io/unstructured/bricks.html#partition-pdf
    single)	file_pathmodeunstructured_kwargsc                    s$   t |}t jf ||d| dS )a%  

        Args:
            file_path: The path to the PDF file to load.
            mode: The mode to use when loading the file. Can be one of "single",
                "multi", or "all". Default is "single".
            **unstructured_kwargs: Any kwargs to pass to the unstructured.
        )r#   r$   N)strsuper__init__)selfr#   r$   r%   	__class__ v/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_community/document_loaders/pdf.pyr(   J   s    zUnstructuredPDFLoader.__init__returnc                 C   s"   ddl m} |f d| ji| jS )Nr   )partition_pdffilename)Zunstructured.partition.pdfr0   r#   r%   )r)   r0   r,   r,   r-   _get_elements[   s    z#UnstructuredPDFLoader._get_elements)r"   )__name__
__module____qualname____doc__r   r&   r   r   r(   listr2   __classcell__r,   r,   r*   r-   r!   2   s    
r!   c                   @   s   e Zd ZdZddeeef ee dddZ	dddd	Z
eeed
ddZeeed
ddZeeed
ddZeedddZdS )BasePDFLoaderzBase Loader class for `PDF` files.

    If the file is a web path, it will download it to a temporary file, use it, then
        clean up the temporary file after completion.
    Nheadersr#   r;   c                C   sL  t || _d| _|| _d| jv r0tj| j| _tj| js*| | jr*t	
 | _tj| j\}}| | jrt| jjdd }tj| jjd| }| j| _| | jsHtj| j| jd}|jdkrtd|j t|d	d
}||j W d   n1 s0    Y  t || _ntj| jsHtd| j dS )zInitialize with a file path.

        Args:
            file_path: Either a local, S3 or web path to a PDF file.
            headers: Headers to use for GET request to download a file from a web path.
        N~/tmpr:      z3Check the url of your file; returned status code %swb)r$   z'File path %s is not a valid file or url)r&   r#   web_pathr;   ospath
expanduserisfile_is_valid_urltempfileTemporaryDirectorytemp_dirsplitext_is_s3_presigned_urlr   splitjoinname
_is_s3_urlrequestsgetstatus_code
ValueErroropenwritecontent)r)   r#   r;   _suffixZtemp_pdfrfr,   r,   r-   r(   h   s2    	



,zBasePDFLoader.__init__r.   c                 C   s   t | dr| j  d S )NrK   )hasattrrK   cleanupr)   r,   r,   r-   __del__   s    
zBasePDFLoader.__del__)urlr/   c                 C   s   t | }t|jot|jS )zCheck if the url is valid.)r   boolnetlocscheme)ra   parsedr,   r,   r-   rH      s    zBasePDFLoader._is_valid_urlc                 C   s>   z$t | }|jdkr |jr W dS W dS  ty8   Y dS 0 dS )zcheck if the url is S3Zs3TFN)r   rd   rc   rU   ra   resultr,   r,   r-   rQ      s    zBasePDFLoader._is_s3_urlc                 C   s6   zt | }ttd|jW S  ty0   Y dS 0 dS )z'Check if the url is a presigned S3 url.z\.s3\.amazonaws\.com$FN)r   rb   researchrc   rU   rf   r,   r,   r-   rM      s
    z"BasePDFLoader._is_s3_presigned_urlc                 C   s   | j d ur| j S | jS N)rC   r#   r_   r,   r,   r-   source   s    zBasePDFLoader.source)r3   r4   r5   r6   r   r&   r   r   dictr(   r`   staticmethodrb   rH   rQ   rM   propertyrk   r,   r,   r,   r-   r9   a   s   &
r9   c                   @   s"   e Zd ZdZee dddZdS )OnlinePDFLoaderzLoad online `PDF`.r.   c                 C   s   t t| j}| S )zLoad documents.)r!   r&   r#   load)r)   loaderr,   r,   r-   rp      s    zOnlinePDFLoader.loadN)r3   r4   r5   r6   r7   r   rp   r,   r,   r,   r-   ro      s   ro   c                       s   e Zd ZdZddddedddeeef eeee	f  ee
 eed ee ed	 eed
 ee
 dd fddZee dddZ  ZS )PyPDFLoadera  Load and parse a PDF file using 'pypdf' library.

    This class provides methods to load and parse PDF documents, supporting various
    configurations such as handling password-protected files, extracting images, and
    defining extraction mode. It integrates the `pypdf` library for PDF processing and
    offers both synchronous and asynchronous document loading.

    Examples:
        Setup:

        .. code-block:: bash

            pip install -U langchain-community pypdf

        Instantiate the loader:

        .. code-block:: python

            from langchain_community.document_loaders import PyPDFLoader

            loader = PyPDFLoader(
                file_path = "./example_data/layout-parser-paper.pdf",
                # headers = None
                # password = None,
                mode = "single",
                pages_delimiter = "
",
                # extract_images = True,
                # images_parser = RapidOCRBlobParser(),
            )

        Lazy load documents:

        .. code-block:: python

            docs = []
            docs_lazy = loader.lazy_load()

            for doc in docs_lazy:
                docs.append(doc)
            print(docs[0].page_content[:100])
            print(docs[0].metadata)

        Load documents asynchronously:

        .. code-block:: python

            docs = await loader.aload()
            print(docs[0].page_content[:100])
            print(docs[0].metadata)
    NFpagetextplain)r$   images_parserimages_inner_formatpages_delimiterextraction_modeextraction_kwargsr"   rs   rt   zmarkdown-imgzhtml-imgru   Zlayout)r#   passwordr;   extract_imagesr$   rv   rw   rx   ry   rz   r/   c             
      s.   t  j||d t|||||||	|
d| _dS )u  Initialize with a file path.

        Args:
            file_path: The path to the PDF file to be loaded.
            headers: Optional headers to use for GET request to download a file from a
              web path.
            password: Optional password for opening encrypted PDFs.
            mode: The extraction mode, either "single" for the entire document or "page"
                for page-wise extraction.
            pages_delimiter: A string delimiter to separate pages in single-mode
                extraction.
            extract_images: Whether to extract images from the PDF.
            images_parser: Optional image blob parser.
            images_inner_format: The format for the parsed output.
                - "text" = return the content as is
                - "markdown-img" = wrap the content into an image markdown link, w/ link
                pointing to (`![body)(#)`]
                - "html-img" = wrap the content as the `alt` text of an tag and link to
                (`<img alt="{body}" src="#"/>`)
            extraction_mode: “plain” for legacy functionality, “layout” extract text
                in a fixed width format that closely adheres to the rendered layout in
                the source pdf
            extraction_kwargs: Optional additional parameters for the extraction
                process.

        Returns:
            This method does not directly return data. Use the `load`, `lazy_load` or
            `aload` methods to retrieve parsed documents with content and metadata.
        r:   )r~   r$   r   rv   rw   rx   ry   rz   N)r'   r(   r   parser)r)   r#   r~   r;   r   r$   rv   rw   rx   ry   rz   r*   r,   r-   r(      s    +zPyPDFLoader.__init__r.   c                 c   sF   | j r$tjt| jd | j d}nt| j}| j|E dH  dS z
        Lazy load given path as pages.
        Insert image, if possible, between two paragraphs.
        In this way, a paragraph can be continued on the next page.
        rbrE   N	rC   r   	from_datarV   r#   read	from_pathr   Z
lazy_parser)   blobr,   r,   r-   	lazy_load%  s    zPyPDFLoader.lazy_load)NNF)r3   r4   r5   r6   r   r   r&   r   r   bytesrl   rb   r
   r   r(   r	   r   r   r8   r,   r,   r*   r-   rr      s4   6   
9rr   c                       sP   e Zd ZdZdddeeef ee e	d fddZ
ee dd	d
Z  ZS )PyPDFium2Loaderz;Load `PDF` using `pypdfium2` and chunks at character level.NF)r;   r   )r#   r;   r   c                   s    t  j||d t|d| _dS )Initialize with a file path.r:   )r   N)r'   r(   r   r   )r)   r#   r;   r   r*   r,   r-   r(   9  s    zPyPDFium2Loader.__init__r.   c                 c   sF   | j r$tjt| jd | j d}nt| j}| j|E dH  dS )Lazy load given path as pages.r   r   N)	rC   r   r   rV   r#   r   r   r   parser   r,   r,   r-   r   D  s    zPyPDFium2Loader.lazy_load)r3   r4   r5   r6   r   r&   r   r   rl   rb   r(   r	   r   r   r8   r,   r,   r*   r-   r   6  s   
r   c                   @   s   e Zd ZdZddddddddeeef eeeeeee e	d ee
 ee e	d	 ee d
ddZeeedddZee dddZdS )PyPDFDirectoryLoadera  Load and parse a directory of PDF files using 'pypdf' library.

    This class provides methods to load and parse multiple PDF documents in a directory,
    supporting options for recursive search, handling password-protected files,
    extracting images, and defining extraction modes. It integrates the `pypdf` library
    for PDF processing and offers synchronous document loading.

    Examples:
        Setup:

        .. code-block:: bash

            pip install -U langchain-community pypdf

        Instantiate the loader:

        .. code-block:: python

            from langchain_community.document_loaders import PyPDFDirectoryLoader

            loader = PyPDFDirectoryLoader(
                path = "./example_data/",
                glob = "**/[!.]*.pdf",
                silent_errors = False,
                load_hidden = False,
                recursive = False,
                extract_images = False,
                password = None,
                mode = "page",
                images_to_text = None,
                headers = None,
                extraction_mode = "plain",
                # extraction_kwargs = None,
            )

        Load documents:

        .. code-block:: python

            docs = loader.load()
            print(docs[0].page_content[:100])
            print(docs[0].metadata)

        Load documents asynchronously:

        .. code-block:: python

            docs = await loader.aload()
            print(docs[0].page_content[:100])
            print(docs[0].metadata)
    **/[!.]*.pdfFNrs   ru   )r~   r$   rv   r;   ry   rz   r{   r}   )rE   globsilent_errorsload_hidden	recursiver   r~   r$   rv   r;   ry   rz   c                C   sL   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	|| _
|| _dS )u  Initialize with a directory path.

        Args:
            path: The path to the directory containing PDF files to be loaded.
            glob: The glob pattern to match files in the directory.
            silent_errors: Whether to log errors instead of raising them.
            load_hidden: Whether to include hidden files in the search.
            recursive: Whether to search subdirectories recursively.
            extract_images: Whether to extract images from PDFs.
            password: Optional password for opening encrypted PDFs.
            mode: The extraction mode, either "single" for extracting the entire
                document or "page" for page-wise extraction.
            images_parser: Optional image blob parser..
            headers: Optional headers to use for GET request to download a file from a
              web path.
            extraction_mode: “plain” for legacy functionality, “layout” for
              experimental layout mode functionality
            extraction_kwargs: Optional additional parameters for the extraction
              process.

        Returns:
            This method does not directly return data. Use the `load` method to
            retrieve parsed documents with content and metadata.
        N)r~   r$   rE   r   r   r   r   r   rv   r;   ry   rz   )r)   rE   r   r   r   r   r   r~   r$   rv   r;   ry   rz   r,   r,   r-   r(     s    (zPyPDFDirectoryLoader.__init__)rE   r/   c                 C   s   t dd | jD  S )Nc                 s   s   | ]}| d V  qdS ).N
startswith).0partr,   r,   r-   	<genexpr>      z3PyPDFDirectoryLoader._is_visible.<locals>.<genexpr>)anypartsr   r,   r,   r-   _is_visible  s    z PyPDFDirectoryLoader._is_visibler.   c           	      C   s   t | j}g }| jr || jn
|| j}|D ]}| r0| ||sR| jr0zXt	t
|| j| j| j| j| j| j| jd}| }|D ]}t
||jd< q|| W q0 ty } z"| jrt| n|W Y d }~q0d }~0 0 q0|S )N)r~   r$   r   rv   r;   ry   rz   rk   )r   rE   r   rglobr   is_filer   relative_tor   rr   r&   r~   r$   r   rv   r;   ry   rz   rp   metadataextend	Exceptionr   loggerwarning)	r)   pdocsitemsirq   Zsub_docsdocer,   r,   r-   rp     s4    

zPyPDFDirectoryLoader.load)r   FFFF)r3   r4   r5   r6   r   r&   r   rb   r   r
   r   rl   r(   rm   r   r7   r   rp   r,   r,   r,   r-   r   O  s<   7     	
5r   c                       s~   e Zd ZdZddeddddddeeef ee e	d ee
ee e	d ee ee
 dd	
 fd
dZee dddZ  ZS )PDFMinerLoadera  Load and parse a PDF file using 'pdfminer.six' library.

    This class provides methods to load and parse PDF documents, supporting various
    configurations such as handling password-protected files, extracting images, and
    defining extraction mode. It integrates the `pdfminer.six` library for PDF
    processing and offers both synchronous and asynchronous document loading.

    Examples:
        Setup:

        .. code-block:: bash

            pip install -U langchain-community pdfminer.six

        Instantiate the loader:

        .. code-block:: python

            from langchain_community.document_loaders import PDFMinerLoader

            loader = PDFMinerLoader(
                file_path = "./example_data/layout-parser-paper.pdf",
                # headers = None
                # password = None,
                mode = "single",
                pages_delimiter = "
",
                # extract_images = True,
                # images_to_text = convert_images_to_text_with_tesseract(),
            )

        Lazy load documents:

        .. code-block:: python

            docs = []
            docs_lazy = loader.lazy_load()

            for doc in docs_lazy:
                docs.append(doc)
            print(docs[0].page_content[:100])
            print(docs[0].metadata)

        Load documents asynchronously:

        .. code-block:: python

            docs = await loader.aload()
            print(docs[0].page_content[:100])
            print(docs[0].metadata)
    Nr"   Frt   )r~   r$   rx   r   rv   rw   r;   concatenate_pagesr{   r|   )
r#   r~   r$   rx   r   rv   rw   r;   r   r/   c          
   	      s,   t  j||d t||||	|||d| _dS )ar  Initialize with a file path.

        Args:
            file_path: The path to the PDF file to be loaded.
            headers: Optional headers to use for GET request to download a file from a
              web path.
            password: Optional password for opening encrypted PDFs.
            mode: The extraction mode, either "single" for the entire document or "page"
                for page-wise extraction.
            pages_delimiter: A string delimiter to separate pages in single-mode
                extraction.
            extract_images: Whether to extract images from the PDF.
            images_parser: Optional image blob parser.
            images_inner_format: The format for the parsed output.
                - "text" = return the content as is
                - "markdown-img" = wrap the content into an image markdown link, w/ link
                pointing to (`![body)(#)`]
                - "html-img" = wrap the content as the `alt` text of an tag and link to
                (`<img alt="{body}" src="#"/>`)
            concatenate_pages: Deprecated. If True, concatenate all PDF pages into one
                a single document. Otherwise, return one document per page.

        Returns:
            This method does not directly return data. Use the `load`, `lazy_load` or
            `aload` methods to retrieve parsed documents with content and metadata.
        r:   )r~   r   rv   r   r$   rx   rw   N)r'   r(   r   r   )
r)   r#   r~   r$   rx   r   rv   rw   r;   r   r*   r,   r-   r(     s    'zPDFMinerLoader.__init__r.   c                 c   sF   | j r$tjt| jd | j d}nt| j}| j|E dH  dS r   r   r   r,   r,   r-   r   A  s    zPDFMinerLoader.lazy_load)r3   r4   r5   r6   r   r   r&   r   r   r
   rb   r   rl   r(   r	   r   r   r8   r,   r,   r*   r-   r     s.   7
4r   c                       sL   e Zd ZdZddeeef ee d fddZ	e
e ddd	Z  ZS )
PDFMinerPDFasHTMLLoaderz2Load `PDF` files as HTML content using `PDFMiner`.Nr:   r<   c                   s@   zddl m} W n ty*   tdY n0 t j||d dS )r   r   extract_text_to_fpzO`pdfminer` package not found, please install it with `pip install pdfminer.six`r:   N)pdfminer.high_levelr   ImportErrorr'   r(   )r)   r#   r;   r   r*   r,   r-   r(   U  s    
z PDFMinerPDFasHTMLLoader.__init__r.   c                 c   s   ddl m} ddlm} ddlm} t }|| jd*}|tt	||d| dd W d	   n1 sf0    Y  d
| j
d	u rt| jn| j
i}t| |dV  d	S )
Load file.r   r   )LAParams)open_filenamer    html)codecZlaparamsoutput_typeNrk   Zpage_contentr   )r   r   Zpdfminer.layoutr   Zpdfminer.utilsr   r   r#   r   r   rC   r&   r   getvalue)r)   r   r   r   Zoutput_stringfpr   r,   r,   r-   r   c  s    $z!PDFMinerPDFasHTMLLoader.lazy_load)r3   r4   r5   r6   r   r&   r   r   rl   r(   r	   r   r   r8   r,   r,   r*   r-   r   R  s   r   c                       s   e Zd ZdZddeddddddd	eeef ee e	d ee
ee e	d ee	d	 df ee eeeef  edd
 fddZeee dddZeee dddZee dddZ  ZS )PyMuPDFLoadera3  Load and parse a PDF file using 'PyMuPDF' library.

    This class provides methods to load and parse PDF documents, supporting various
    configurations such as handling password-protected files, extracting tables,
    extracting images, and defining extraction mode. It integrates the `PyMuPDF`
    library for PDF processing and offers both synchronous and asynchronous document
    loading.

    Examples:
        Setup:

        .. code-block:: bash

            pip install -U langchain-community pymupdf

        Instantiate the loader:

        .. code-block:: python

            from langchain_community.document_loaders import PyMuPDFLoader

            loader = PyMuPDFLoader(
                file_path = "./example_data/layout-parser-paper.pdf",
                # headers = None
                # password = None,
                mode = "single",
                pages_delimiter = "
",
                # extract_images = True,
                # images_parser = TesseractBlobParser(),
                # extract_tables = "markdown",
                # extract_tables_settings = None,
            )

        Lazy load documents:

        .. code-block:: python

            docs = []
            docs_lazy = loader.lazy_load()

            for doc in docs_lazy:
                docs.append(doc)
            print(docs[0].page_content[:100])
            print(docs[0].metadata)

        Load documents asynchronously:

        .. code-block:: python

            docs = await loader.aload()
            print(docs[0].page_content[:100])
            print(docs[0].metadata)
    Nrs   Frt   )	r~   r$   rx   r   rv   rw   extract_tablesr;   extract_tables_settingsr{   r|   )csvmarkdownr   )r#   r~   r$   rx   r   rv   rw   r   r;   r   kwargsr/   c       	            s@   |dvrt dt j||	d t|||||||||
d	| _dS )a  Initialize with a file path.

        Args:
            file_path: The path to the PDF file to be loaded.
            headers: Optional headers to use for GET request to download a file from a
              web path.
            password: Optional password for opening encrypted PDFs.
            mode: The extraction mode, either "single" for the entire document or "page"
                for page-wise extraction.
            pages_delimiter: A string delimiter to separate pages in single-mode
                extraction.
            extract_images: Whether to extract images from the PDF.
            images_parser: Optional image blob parser.
            images_inner_format: The format for the parsed output.
                - "text" = return the content as is
                - "markdown-img" = wrap the content into an image markdown link, w/ link
                pointing to (`![body)(#)`]
                - "html-img" = wrap the content as the `alt` text of an tag and link to
                (`<img alt="{body}" src="#"/>`)
            extract_tables: Whether to extract tables in a specific format, such as
                "csv", "markdown", or "html".
            extract_tables_settings: Optional dictionary of settings for customizing
                table extraction.
            **kwargs: Additional keyword arguments for customizing text extraction
                behavior.

        Returns:
            This method does not directly return data. Use the `load`, `lazy_load`, or
            `aload` methods to retrieve parsed documents with content and metadata.

        Raises:
            ValueError: If the `mode` argument is not one of "single" or "page".
        r{   zmode must be single or pager:   )	r~   r$   rx   text_kwargsr   rv   rw   r   r   N)rU   r'   r(   r   r   )r)   r#   r~   r$   rx   r   rv   rw   r   r;   r   r   r*   r,   r-   r(     s    0zPyMuPDFLoader.__init__)r   r/   c                 k   sd   |rt d| d | j}| jr@tjt| jd | jd}nt	| j}|j
||dE dH  dS )zLazy load given path as pages or single document (see `mode`).
        Insert image, if possible, between two paragraphs.
        In this way, a paragraph can be continued on the next page.
        zReceived runtime arguments zd. Passing runtime args to `load` is deprecated. Please pass arguments during initialization instead.r   r   )r   N)r   r   r   rC   r   r   rV   r#   r   r   Z_lazy_parse)r)   r   r   r   r,   r,   r-   
_lazy_load  s    
zPyMuPDFLoader._lazy_loadc                 K   s   t | jf i |S rj   )r7   r   )r)   r   r,   r,   r-   rp     s    zPyMuPDFLoader.loadr.   c                 c   s   |   E d H  d S rj   )r   r_   r,   r,   r-   r     s    zPyMuPDFLoader.lazy_load)r3   r4   r5   r6   r   r   r&   r   r   r
   rb   r   rl   r   r(   r	   r   r   r7   rp   r   r8   r,   r,   r*   r-   r   x  s6   :
?r   c                	       s   e Zd ZdZdeeef eeee	e
eef  edd fddZee
eef d	d
dZeed	ddZee
d	ddZed	ddZeddddZeedddZeedddZee d	ddZ  ZS )MathpixPDFLoaderz)Load `PDF` files using `Mathpix` service.md  FN)r#   processed_file_formatmax_wait_time_secondsshould_clean_pdfextra_request_datar   r/   c                    sp   t |dd| _t |dd| _|dd |dd t j|fi | || _|durZ|ni | _|| _|| _	dS )a  Initialize with a file path.

        Args:
            file_path: a file for loading.
            processed_file_format: a format of the processed file. Default is "md".
            max_wait_time_seconds: a maximum time to wait for the response from
             the server. Default is 500.
            should_clean_pdf: a flag to clean the PDF file. Default is False.
            extra_request_data: Additional request data.
            **kwargs: additional keyword arguments.
        mathpix_api_keyZMATHPIX_API_KEYmathpix_api_idZMATHPIX_API_IDN)
r   r   r   popr'   r(   r   r   r   r   )r)   r#   r   r   r   r   r   r*   r,   r-   r(     s    zMathpixPDFLoader.__init__r.   c                 C   s   | j | jdS )N)Zapp_idZapp_key)r   r   r_   r,   r,   r-   _mathpix_headers2  s    z!MathpixPDFLoader._mathpix_headersc                 C   s   dS )Nzhttps://api.mathpix.com/v3/pdfr,   r_   r,   r,   r-   ra   6  s    zMathpixPDFLoader.urlc                 C   s"   d| j dii| j}dt|iS )NZconversion_formatsTZoptions_json)r   r   jsondumps)r)   optionsr,   r,   r-   data:  s
    
zMathpixPDFLoader.datac                 C   s   t t| jd0}d|i}tj| j| j|| jd}W d    n1 sF0    Y  | }d|v rrt	d|d  d|v r|d }|S t	dd S )Nr   file)r;   filesr   errorzMathpix request failed: pdf_idzUnable to send PDF to Mathpix.)
rV   r&   r#   rR   postra   r   r   r   rU   )r)   r\   r   responseresponse_datar   r,   r,   r-   send_pdfB  s    $zMathpixPDFLoader.send_pdf)r   r/   c           
      C   s   | j d | }td| jdD ]}tj|| jd}| }|dd}|dd}|durd| }|dur~|d	|d
  d7 }t||dd}	|	dkr dS |	dkrtdqt	d|	 t
d qtdS )zmWait for processing to complete.

        Args:
            pdf_id: a PDF id.

        Returns: None
        r>   r      r:   r   N
error_infoz%Unable to retrieve PDF from Mathpix: z (id)status	completedz#Unable to retrieve PDF from Mathpixz.Status: %s, waiting for processing to complete)ra   ranger   rR   rS   r   r   rU   r   infotimesleepTimeoutError)
r)   r   ra   rY   r   r   r   r   	error_msgr   r,   r,   r-   wait_for_processingQ  s&    

z$MathpixPDFLoader.wait_for_processingc                 C   s>   |  | | j d| d| j }tj|| jd}|jdS )Nr>   r   r:   zutf-8)r   ra   r   rR   rS   r   rX   decode)r)   r   ra   r   r,   r,   r-   get_processed_pdfv  s    
z"MathpixPDFLoader.get_processed_pdf)contentsr/   c                 C   sV   d dd |dD }|dddd}|dd	d
ddddd}|S )ziClean the PDF file.

        Args:
            contents: a PDF file contents.

        Returns:

        
c                 S   s   g | ]}| d s|qS )z![]r   )r   liner,   r,   r-   
<listcomp>  r   z.MathpixPDFLoader.clean_pdf.<locals>.<listcomp>z	\section{z# }r   z\$$z\%%z\((z\)r   )rO   rN   replace)r)   r   r,   r,   r-   	clean_pdf|  s    	zMathpixPDFLoader.clean_pdfc                 C   s@   |   }| |}| jr"| |}| j| j|d}t||dgS )N)rk   r#   r   r   )r   r   r   r   rk   r   )r)   r   r   r   r,   r,   r-   rp     s    

zMathpixPDFLoader.load)r   r   FN)r3   r4   r5   r6   r   r&   r   intrb   r   rl   r   r(   rn   r   ra   r   r   r   r   r   r7   r   rp   r8   r,   r,   r*   r-   r     s2       
'%r   c                       s\   e Zd ZdZd
eeef eeee	f  e
ee e
dd fddZee ddd	Z  ZS )PDFPlumberLoaderz$Load `PDF` files using `pdfplumber`.NF)r#   r   deduper;   r   r/   c                    sR   zddl }W n ty&   tdY n0 t j||d |p>i | _|| _|| _dS )r   r   NzMpdfplumber package not found, please install it with `pip install pdfplumber`r:   )
pdfplumberr   r'   r(   r   r   r   )r)   r#   r   r   r;   r   r   r*   r,   r-   r(     s    	

zPDFPlumberLoader.__init__r.   c                 C   sN   t | j| j| jd}| jr8tjt| jd	 | jd}nt
| j}||S )r   )r   r   r   r   r   )r   r   r   r   rC   r   r   rV   r#   r   r   r   )r)   r   r   r,   r,   r-   rp     s    zPDFPlumberLoader.load)NFNF)r3   r4   r5   r6   r   r&   r   r   r   r   rb   rl   r(   r7   r   rp   r8   r,   r,   r*   r-   r     s       
r   c                       s   e Zd ZdZdddeeef eee  ee	 ee ee ee ee
 ed dd	 fddZee dd	d
Zee dddZeeedddZ  ZS )AmazonTextractPDFLoadera  Load `PDF` files from a local file system, HTTP or S3.

    To authenticate, the AWS client uses the following methods to
    automatically load credentials:
    https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html

    If a specific credential profile should be used, you must pass
    the name of the profile from the ~/.aws/credentials file that is to be used.

    Make sure the credentials / roles used have the required policies to
    access the Amazon Textract service.

    Example:
        .. code-block:: python
            from langchain_community.document_loaders import AmazonTextractPDFLoader
            loader = AmazonTextractPDFLoader(
                file_path="s3://pdfs/myfile.pdf"
            )
            document = loader.load()
    N)linearization_configr    )	r#   textract_featuresclientcredentials_profile_nameregion_nameendpoint_urlr;   r   r/   c             
      s  t  j||d zddl W n ty6   tdY n0 |rP fdd|D }	ng }	|sb|sb|rzVddl}
|dur|
j|d}n|
 }i }|r||d< |r||d	< |jdi |}W nN ty   tdY n6 ty } ztd| |W Y d}~n
d}~0 0 t	|	||d| _
dS )aU  Initialize the loader.

        Args:
            file_path: A file, url or s3 path for input file
            textract_features: Features to be used for extraction, each feature
                               should be passed as a str that conforms to the enum
                               `Textract_Features`, see `amazon-textract-caller` pkg
            client: boto3 textract client (Optional)
            credentials_profile_name: AWS profile name, if not default (Optional)
            region_name: AWS region, eg us-east-1 (Optional)
            endpoint_url: endpoint url for the textract service (Optional)
            linearization_config: Config to be used for linearization of the output
                                  should be an instance of TextLinearizationConfig from
                                  the `textractor` pkg
        r:   r   NztCould not import amazon-textract-caller python package. Please install it with `pip install amazon-textract-caller`.c                    s   g | ]} j | qS r,   )ZTextract_Features)r   xZtcr,   r-   r     r   z4AmazonTextractPDFLoader.__init__.<locals>.<listcomp>)Zprofile_namer   r  textractzRCould not import boto3 python package. Please install it with `pip install boto3`.zCould not load credentials to authenticate with AWS client. Please check that credentials in the specified profile name are valid. )r   r   r   )r  )r'   r(   Ztextractcallerr   boto3Sessionr   r   rU   r   r   )r)   r#   r   r   r   r   r  r;   r   featuresr  sessionZclient_paramsr   r*   r  r-   r(     sN    
z AmazonTextractPDFLoader.__init__r.   c                 C   s   t |  S zLoad given path as pages.r7   r   r_   r,   r,   r-   rp   &  s    zAmazonTextractPDFLoader.loadc                 c   sb   | j r | | j r t| j d}n,t| j}t|dkrLtd|j d| j	
|E dH  dS )zLazy load documentsr      z	the file z is a multi-page document,                     but not stored on S3.                     Textract requires multi-page documents to be on S3.N)rC   rQ   r   r   r#   r   _get_number_of_pagesrU   rE   r   r   r   r,   r,   r-   r   *  s    z!AmazonTextractPDFLoader.lazy_load)r   r/   c           	      C   s   zdd l }ddlm}m} W n ty6   tdY n0 | jdkr|  $}||}t|j	W  d    S 1 st0    Y  n^| jdkrd}|
|  }t||D ]\}}|d7 }q|S | jdv rdS td| j d S )	Nr   )ImageImageSequencezcCould not import pypdf or Pilloe python package. Please install it with `pip install pypdf Pillow`.zapplication/pdfz
image/tiffr  )z	image/pngz
image/jpegzunsupported mime type: )pypdfZPILr  r  r   mimetypeZas_bytes_ioZ	PdfReaderlenpagesrV   as_bytes	enumerater	   rU   )	r   r  r  r  Zinput_pdf_fileZ
pdf_reader	num_pagesZimgrY   r,   r,   r-   r  ?  s,    



*



z,AmazonTextractPDFLoader._get_number_of_pages)NNNNNN)r3   r4   r5   r6   r   r&   r   r   r   r   rl   r(   r7   r   rp   r	   r   rm   r   r   r  r8   r,   r,   r*   r-   r     s2         


Lr   c                   @   s   e Zd ZdZedddZdS )DedocPDFLoadera  DedocPDFLoader document loader integration to load PDF files using `dedoc`.
    The file loader can automatically detect the correctness of a textual layer in the
        PDF document.
    Note that `__init__` method supports parameters that differ from ones of
        DedocBaseLoader.

    Setup:
        Install ``dedoc`` package.

        .. code-block:: bash

            pip install -U dedoc

    Instantiate:
        .. code-block:: python

            from langchain_community.document_loaders import DedocPDFLoader

            loader = DedocPDFLoader(
                file_path="example.pdf",
                # split=...,
                # with_tables=...,
                # pdf_with_text_layer=...,
                # pages=...,
                # ...
            )

    Load:
        .. code-block:: python

            docs = loader.load()
            print(docs[0].page_content[:100])
            print(docs[0].metadata)

        .. code-block:: python

            Some text
            {
                'file_name': 'example.pdf',
                'file_type': 'application/pdf',
                # ...
            }

    Lazy load:
        .. code-block:: python

            docs = []
            docs_lazy = loader.lazy_load()

            for doc in docs_lazy:
                docs.append(doc)
            print(docs[0].page_content[:100])
            print(docs[0].metadata)

        .. code-block:: python

            Some text
            {
                'file_name': 'example.pdf',
                'file_type': 'application/pdf',
                # ...
            }

    Parameters used for document parsing via `dedoc`
        (https://dedoc.readthedocs.io/en/latest/parameters/pdf_handling.html):

        with_attachments: enable attached files extraction
        recursion_deep_attachments: recursion level for attached files extraction,
            works only when with_attachments==True
        pdf_with_text_layer: type of handler for parsing, available options
            ["true", "false", "tabby", "auto", "auto_tabby" (default)]
        language: language of the document for PDF without a textual layer,
            available options ["eng", "rus", "rus+eng" (default)], the list of
            languages can be extended, please see
            https://dedoc.readthedocs.io/en/latest/tutorials/add_new_language.html
        pages: page slice to define the reading range for parsing
        is_one_column_document: detect number of columns for PDF without a textual
            layer, available options ["true", "false", "auto" (default)]
        document_orientation: fix document orientation (90, 180, 270 degrees) for PDF
            without a textual layer, available options ["auto" (default), "no_change"]
        need_header_footer_analysis: remove headers and footers from the output result
        need_binarization: clean pages background (binarize) for PDF without a textual
            layer
        need_pdf_table_analysis: parse tables for PDF without a textual layer
    r.   c                 C   s$   ddl m} |t| j| j| jdS )Nr   )make_manager_pdf_config)r#   Zparsing_paramsrN   )Zdedoc.utils.langchainr  r&   r#   Zparsing_parametersrN   )r)   r  r,   r,   r-   _make_config  s    zDedocPDFLoader._make_configN)r3   r4   r5   r6   rl   r  r,   r,   r,   r-   r  \  s   Vr  c                       s`   e Zd ZdZdeeef eeee	 dd fddZ
ee ddd	Zee dd
dZ  ZS )DocumentIntelligenceLoaderz+Load a PDF with Azure Document Intelligenceprebuilt-documentN)r#   r   modelr;   r/   c                    s"   t  j||d t||d| _dS )a  Initialize the object for file processing with Azure Document Intelligence
        (formerly Form Recognizer).

        This constructor initializes a DocumentIntelligenceParser object to be used
        for parsing files using the Azure Document Intelligence API. The load method
        generates a Document node including metadata (source blob and page number)
        for each page.

        Parameters:
        -----------
        file_path : str
            The path to the file that needs to be parsed.
        client: Any
            A DocumentAnalysisClient to perform the analysis of the blob
        model : str
            The model name or ID to be used for form recognition in Azure.

        Examples:
        ---------
        >>> obj = DocumentIntelligenceLoader(
        ...     file_path="path/to/file",
        ...     client=client,
        ...     model="prebuilt-document"
        ... )
        r:   )r   r  N)r'   r(   r   r   )r)   r#   r   r  r;   r*   r,   r-   r(     s    !z#DocumentIntelligenceLoader.__init__r.   c                 C   s   t |  S r	  r
  r_   r,   r,   r-   rp     s    zDocumentIntelligenceLoader.loadc                 c   s"   t | j}| j|E dH  dS )r   N)r   r   r#   r   r   r   r,   r,   r-   r     s    z$DocumentIntelligenceLoader.lazy_load)r  N)r3   r4   r5   r6   r   r&   r   r   r   rl   r(   r7   r   rp   r	   r   r8   r,   r,   r*   r-   r    s     
$r  c                       sH   e Zd ZdZd
eeef eedd fddZe	e
 ddd	Z  ZS )ZeroxPDFLoadera  Document loader utilizing Zerox library:
    https://github.com/getomni-ai/zerox

    Zerox converts PDF document to series of images (page-wise) and
    uses vision-capable LLM model to generate Markdown representation.

    Zerox utilizes anyc operations. Therefore when using this loader
    inside Jupyter Notebook (or any environment running async)
    you will need to:
    ```python
        import nest_asyncio
        nest_asyncio.apply()
    ```
    gpt-4o-miniN)r#   r  zerox_kwargsr/   c                    s   t  j|d || _|| _d S )N)r#   )r'   r(   r  r  )r)   r#   r  r  r*   r,   r-   r(      s    zZeroxPDFLoader.__init__r.   c                 c   s~   ddl }ddlm} ||f t| j| jd| j}t|j	dkrz|j	d j
}|j	D ] }t|j| j|j
|ddV  qXdS )zLazily load pages.r   N)zerox)r#   r  r?   )rk   rs   r  r   )asyncioZpyzeroxr  runr&   r#   r  r  r  r  rs   r   rX   rk   )r)   r   r  Zzerox_outputr  rs   r,   r,   r-   r     s    
zZeroxPDFLoader.lazy_load)r  )r3   r4   r5   r6   r   r&   r   r   r(   r	   r   r   r8   r,   r,   r*   r-   r    s    
r  )Gr   loggingrD   rh   rI   r   abcr   ior   pathlibr   r   typingr   r   r   r	   r
   r   r   r   r   r   urllib.parser   rR   Zlangchain_core.documentsr   Zlangchain_core.utilsr   Z)langchain_community.document_loaders.baser   Z1langchain_community.document_loaders.blob_loadersr   Z*langchain_community.document_loaders.dedocr   Z3langchain_community.document_loaders.parsers.imagesr   Z0langchain_community.document_loaders.parsers.pdfr   r   r   r   r   r   r   r   Z1langchain_community.document_loaders.unstructuredr   Z)textractor.data.text_linearization_configr    	getLogger__file__r   r!   r9   ro   rr   r   r   r   r   r   r   r   r   r  r  r  ZPagedPDFSplitterr,   r,   r,   r-   <module>   sT   0(

/P	| w&  ( a3F