a
    ¡˜ëjD  ã                   @  s¤  U d Z ddlmZ ddlZddlZddlZddlmZmZm	Z	m
Z
 ddlZddlmZ ddlmZmZ ddlmZmZ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  ddl!m"Z" e	de#e f Z$de%d< d0ddddi dde j&g d¢ddddddddddddddœddddddddddddddddddddddd d!d"d#œd$d%„Z'di ddfdddddd&d'œd(d)„Z(d*dddd+œd,d-„Z)G d.d/„ d/ƒZ*dS )1z9Provides partitioning with automatic file-type detection.é    )ÚannotationsN)ÚIOÚAnyÚCallableÚOptional)Ú	TypeAlias)ÚDataSourceMetadataÚElement)Údetect_filetypeÚis_json_processableÚis_ndjson_processable)ÚFileType)Úlogger)ÚUnsupportedFileFormatError)Úexactly_one)Úcheck_language_args)ÚPartitionStrategy)Údependency_exists.r   ÚPartitionerT)ÚpdfZjpgZpngZheicFé   )ÚfileÚencodingÚcontent_typeÚurlÚheadersÚ
ssl_verifyÚrequest_timeoutÚstrategyÚskip_infer_table_typesÚocr_languagesÚ	languagesÚdetect_language_per_elementÚpdf_infer_table_structureÚextract_images_in_pdfÚextract_image_block_typesÚextract_image_block_output_dirÚextract_image_block_to_payloadÚdata_source_metadataÚmetadata_filenameÚhi_res_model_nameÚ
model_nameÚstarting_page_numberzOptional[str]zOptional[IO[bytes]]zdict[str, str]ÚboolzOptional[int]Ústrz	list[str]zOptional[list[str]]zOptional[DataSourceMetadata]Úintr   úlist[Element])Úfilenamer   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   ÚkwargsÚreturnc          #        s~  t || ˆd� | d|¡ |r(t d¡ t|p0g |
ƒ}ˆdurVtˆˆ |||d�\}‰n$|i krht d¡ t| ||ˆ |d�‰|durŒ| d¡ | d	d¡}|dur¤|n
t	ˆ|	|ƒ}t
ƒ }d
d
dœ‡ ‡‡‡fdd„}ˆtjk�r| ˆ¡}|f | |d||||pü||||||dœ|¤Ž}||ƒS ˆj�rnˆjdk�rn| ˆ¡}|f | |d||||�pP||||||dœ|¤Ž}||ƒS ˆtjk�r¶t| |d��s�tdƒ‚| ˆ¡}|f | |dœ|¤Ž}||ƒS ˆtjk�rþt| |d��sØtdƒ‚| ˆ¡} | f | |dœ|¤Ž}||ƒS ˆtjk�rg S t |¡}!||!d< ||!d< ||!d	< ||!d< ||!d< ||!d< ||!d< ||!d< | ˆ¡}"|"f | |dœ|!¤Ž}||ƒS )aC  Partitions a document into its constituent elements.

    Uses libmagic to determine the file's type and route it to the appropriate partitioning
    function. Applies the default parameters for each partitioning function. Use the document-type
    specific partitioning functions if you need access to additional kwarg options.

    Parameters
    ----------
    filename
        A string defining the target filename path.
    file
        A file-like object using "rb" mode --> open(filename, "rb").
    encoding
        The character-encoding used to decode the input bytes when drawn from `filename` or `file`.
        Defaults to "utf-8".
    url
        The url for a remote document. Pass in content_type if you want partition to treat
        the document as a specific content_type.
    headers
        The headers to be used in conjunction with the HTTP request if URL is set.
    ssl_verify
        If the URL parameter is set, determines whether or not partition uses SSL verification
        in the HTTP request.
    request_timeout
        The timeout for the HTTP request if URL is set. Defaults to None meaning no timeout and
        requests will block indefinitely.
    content_type
        A string defining the file content in MIME type
    metadata_filename
        When file is not None, the filename (string) to store in element metadata. E.g. "foo.txt"
    strategy
        The strategy to use for partitioning PDF/image. Uses a layout detection model if set
        to 'hi_res', otherwise partition simply extracts the text from the document
        and processes it.
    skip_infer_table_types
        The document types that you want to skip table extraction with.
    languages
        The languages present in the document, for use in partitioning and/or OCR. For partitioning
        image or pdf documents with Tesseract, you'll first need to install the appropriate
        Tesseract language pack. For other partitions, language is detected using naive Bayesian
        filter via `langdetect`. Multiple languages indicates text could be in either language.
        Additional Parameters:
            detect_language_per_element
                Detect language per element instead of at the document level.
    pdf_infer_table_structure
        Deprecated! Use `skip_infer_table_types` to opt out of table extraction for any document
        type.
        If True and strategy=hi_res, any Table Elements extracted from a PDF will include an
        additional metadata field, "text_as_html," where the value (string) is a just a
        transformation of the data into an HTML <table>.
        The "text" field for a partitioned Table Element is always present, whether True or False.
    extract_images_in_pdf
        Only applicable if `strategy=hi_res`.
        If True, any detected images will be saved in the path specified by
        'extract_image_block_output_dir' or stored as base64 encoded data within metadata fields.
        Deprecation Note: This parameter is marked for deprecation. Future versions will use
        'extract_image_block_types' for broader extraction capabilities.
    extract_image_block_types
        Only applicable if `strategy=hi_res`.
        Images of the element type(s) specified in this list (e.g., ["Image", "Table"]) will be
        saved in the path specified by 'extract_image_block_output_dir' or stored as base64
        encoded data within metadata fields.
    extract_image_block_to_payload
        Only applicable if `strategy=hi_res`.
        If True, images of the element type(s) defined in 'extract_image_block_types' will be
        encoded as base64 data and stored in two metadata fields: 'image_base64' and
        'image_mime_type'.
        This parameter facilitates the inclusion of element data directly within the payload,
        especially for web-based applications or APIs.
    extract_image_block_output_dir
        Only applicable if `strategy=hi_res` and `extract_image_block_to_payload=False`.
        The filesystem path for saving images of the element type(s)
        specified in 'extract_image_block_types'.
    hi_res_model_name
        The layout detection model used when partitioning strategy is set to `hi_res`.
    model_name
        The layout detection model used when partitioning strategy is set to `hi_res`. To be
        deprecated in favor of `hi_res_model_name`.
    starting_page_number
        Indicates what page number should be assigned to the first page in the document.
        This information will be reflected in elements' metadata and can be be especially
        useful when partitioning a document that is part of a larger document.
    )r   r1   r   r)   z]The pdf_infer_table_structure kwarg is deprecated. Please use skip_infer_table_types instead.N)r   r   r   r   r   zUThe headers kwarg is set but the url kwarg is not. The headers kwarg will be ignored.)Ú	file_pathr   r   r   Zmetadata_file_pathr   Úinfer_table_structurer0   )Úelementsr3   c                   sN   | D ]D}ˆ|j _ˆ|j _ˆ dur>t ˆ ¡}|r4|jnd|j _qˆj|j _q| S )z)Add some metadata fields to each element.N)Úmetadatar   Zdata_sourcer   Zfrom_mime_typeZ	mime_typeÚfiletype)r6   ÚelementZout_filetype©r   r(   Ú	file_typer   © úZ/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/unstructured/partition/auto.pyÚaugment_metadataÃ   s    
z#partition.<locals>.augment_metadata)r1   r   r   r5   r   r!   r*   r$   r%   r&   r'   r,   Úimage)r1   r   zŽDetected a JSON file that does not conform to the Unstructured schema. partition_json currently only processes serialized Unstructured output.z‘Detected an NDJSON file that does not conform to the Unstructured schema. partition_json currently only processes serialized Unstructured output.r"   r   r!   r,   r   r%   r'   )r   Ú
setdefaultr   Úwarningr   Úfile_and_type_from_urlr
   ÚseekÚpopÚdecide_table_extractionÚ_PartitionerLoaderr   ZPDFÚgetZpartitioner_shortnameZJSONr   Ú
ValueErrorZNDJSONr   ZEMPTYÚcopyÚdeepcopy)#r1   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r2   Zkwargs_infer_table_structurer5   Zpartitioner_loaderr>   Zpartition_pdfr6   Zpartition_imageZpartition_jsonZpartition_ndjsonZpartitioning_kwargsÚ	partitionr<   r:   r=   rK      sÖ    nÿûÿû
ÿýý

ôó
ôóÿ
ÿ


rK   ztuple[io.BytesIO, FileType])r   r   r   r   r   r3   c           	      C  sf   t j| |||d�}t |j¡}|p.|j dd ¡ }rJ| d¡d  ¡  ¡ }|j	}t
|||d�}||fS )N)r   ÚverifyÚtimeoutzContent-Typeú;r   )r   r   r   )ÚrequestsrG   ÚioÚBytesIOÚcontentr   ÚsplitÚstripÚlowerr   r
   )	r   r   r   r   r   Úresponser   r   r8   r<   r<   r=   rB   &  s    rB   zOptional[FileType])r8   r   r#   r3   c                 C  s.   | r| j  ¡ nd }|dkr&|p$||vS ||vS )Nr   )ÚnamerU   )r8   r   r#   Zdoc_typer<   r<   r=   rE   :  s    rE   c                   @  s>   e Zd ZU dZi Zded< dddœdd„Zdddœd	d
„ZdS )rF   a°  Provides uniform helpful error when a partitioner dependency is not installed.

    Used by `partition()` to encapsulate coping with the possibility the Python environment it is
    executing in may not have all dependencies installed for a particular partitioner.

    Provides `.get()` to access partitioners by file-type, which raises when one or more
    dependencies for that partitioner are not installed.

    The error message indicates what extra needs to be installed to enable that partitioner. This
    avoids an inconsistent variety of possibly puzzling exceptions arising from much deeper in the
    partitioner when access to the missing dependency is first attempted.
    zdict[FileType, Partitioner]Ú_partitionersr   r   )r;   r3   c                 C  s:   |j std|› d�ƒ‚|| jvr0|  |¡| j|< | j| S )zËReturn partitioner for `file_type`.

        Raises when one or more package dependencies for that file-type have not been
        installed. Also raises when the file-type is not partitionable.
        z&Partitioning is not supported for the z file type.)Úis_partitionabler   rX   Ú_load_partitioner)Úselfr;   r<   r<   r=   rG   \  s    
ÿ
z_PartitionerLoader.getc                 C  sN   |j D ]$}t|ƒst|j› d|j› d�ƒ‚q|js6J ‚t |j¡}t	||jƒS )zBLoad the partitioner for `file_type` after verifying dependencies.zg() is not available because one or more dependencies are not installed. Use: pip install "unstructured[z:]" (including quotes) to install the required dependencies)
Zimportable_package_dependenciesr   ÚImportErrorZpartitioner_function_nameZ
extra_namerY   Ú	importlibÚimport_moduleZpartitioner_module_qnameÚgetattr)r[   r;   Úpkg_nameZpartitioner_moduler<   r<   r=   rZ   n  s    
þÿ
z$_PartitionerLoader._load_partitionerN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rX   Ú__annotations__rG   rZ   r<   r<   r<   r=   rF   K  s   
rF   )N)+rd   Ú
__future__r   rI   r]   rP   Útypingr   r   r   r   rO   Ztyping_extensionsr   Zunstructured.documents.elementsr   r	   Z unstructured.file_utils.filetyper
   r   r   Zunstructured.file_utils.modelr   Zunstructured.loggerr   Zunstructured.partition.commonr   Z$unstructured.partition.common.commonr   Z"unstructured.partition.common.langr   Z&unstructured.partition.utils.constantsr   Zunstructured.utilsr   Úlistr   re   ZAUTOrK   rB   rE   rF   r<   r<   r<   r=   Ú<module>   sf    ÿèB  û