a
    ¡˜ëjôá  ã                   @  sª  U d Z ddlmZ ddlZddlZddlmZmZmZm	Z	m
Z
mZ ddlZddlmZmZ ddlmZmZmZ ddlmZmZmZmZmZmZmZ ddlmZ d	Zd
ed< dZ ded< eege!f Z"ded< e#e$e$f Z%ded< G dd„ dƒZ&G dd„ dƒZ'G dd„ dƒZ(G dd„ dƒZ)G dd„ dƒZ*G dd„ dƒZ+G dd„ dƒZ,G d d!„ d!ƒZ-G d"d#„ d#ƒZ.G d$d%„ d%ƒZ/G d&d'„ d'ƒZ0G d(d)„ d)ƒZ1dd*œd+d,„Z2d-dd.œd/d0„Z3dS )1z@Chunking objects not specific to a particular chunking strategy.é    )ÚannotationsN)ÚAnyÚCallableÚDefaultDictÚIterableÚIteratorÚcast)ÚSelfÚ	TypeAlias)ÚHtmlCellÚHtmlRowÚ	HtmlTable)ÚCompositeElementÚConsolidationStrategyÚElementÚElementMetadataÚTableÚ
TableChunkÚTitle)Úlazypropertyiô  ÚintÚCHUNK_MAX_CHARS_DEFAULTTÚboolÚCHUNK_MULTI_PAGE_DEFAULTr
   ÚBoundaryPredicateÚTextAndHtmlc                   @  sô   e Zd ZdZddœdd„Zedddœdd	„ƒZed
dœdd„ƒZeddœdd„ƒZ	eddœdd„ƒZ
eddœdd„ƒZeddœdd„ƒZeddœdd„ƒZeddœdd„ƒZeddœdd„ƒZeddœd d!„ƒZed"dœd#d$„ƒZd%dœd&d'„Zd(S ))ÚChunkingOptionsaY  Specifies parameters of optional chunking behaviors.

    Parameters
    ----------
    max_characters
        Hard-maximum text-length of chunk. A chunk longer than this will be split mid-text and be
        emitted as two or more chunks.
    new_after_n_chars
        Preferred approximate chunk size. A chunk composed of elements totalling this size or
        greater is considered "full" and will not be enlarged by adding another element, even if it
        will fit within the remaining `max_characters` for that chunk. Defaults to `max_characters`
        when not specified, which effectively disables this behavior. Specifying 0 for this
        argument causes each element to appear in a chunk by itself (although an element with text
        longer than `max_characters` will be still be split into two or more chunks).
    combine_text_under_n_chars
        Provides a way to "recombine" small chunks formed by breaking on a semantic boundary. Only
        relevant for a chunking strategy that specifies higher-level semantic boundaries to be
        respected, like "section" or "page". Recursively combines two adjacent pre-chunks when the
        first pre-chunk is smaller than this threshold. "Recursively" here means the resulting
        pre-chunk can be combined with the next pre-chunk if it is still under the length threshold.
        Defaults to `max_characters` which combines chunks whenever space allows. Specifying 0 for
        this argument suppresses combining of small chunks. Note this value is "capped" at the
        `new_after_n_chars` value since a value higher than that would not change this parameter's
        effect.
    overlap
        Specifies the length of a string ("tail") to be drawn from each chunk and prefixed to the
        next chunk as a context-preserving mechanism. By default, this only applies to split-chunks
        where an oversized element is divided into multiple chunks by text-splitting.
    overlap_all
        Default: `False`. When `True`, apply overlap between "normal" chunks formed from whole
        elements and not subject to text-splitting. Use this with caution as it entails a certain
        level of "pollution" of otherwise clean semantic chunk boundaries.
    text_splitting_separators
        A sequence of strings like `("
", " ")` to be used as target separators during
        text-splitting. Text-splitting only applies to splitting an oversized element into two or
        more chunks. These separators are tried in the specified order until one is found in the
        string to be split. The default separator is `""` which matches between any two characters.
        This separator should not be specified in this sequence because it is always the separator
        of last-resort. Note that because the separator is removed during text-splitting, only
        whitespace character sequences are suitable.
    r   )Úkwargsc                 K  s
   || _ d S ©N)Ú_kwargs)Úselfr   © r!   úY/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/unstructured/chunking/base.pyÚ__init__a   s    zChunkingOptions.__init__r	   )r   Úreturnc                 K  s   | f i |¤Ž}|  ¡  |S )zUReturn instance or raises `ValueError` on invalid arguments like overlap > max_chars.)Ú	_validate)Úclsr   r    r!   r!   r"   Únewd   s    zChunkingOptions.newútuple[BoundaryPredicate, ...]©r$   c                 C  s   dS )z�The semantic-boundary detectors to be applied to break pre-chunks.

        Overridden by sub-typs to provide semantic-boundary isolation behaviors.
        r!   r!   ©r    r!   r!   r"   Úboundary_predicatesk   s    z#ChunkingOptions.boundary_predicatesr   c                 C  s   | j  d¡}|dur|S dS )a   Combine two consecutive text pre-chunks if first is smaller than this and both will fit.

        Default applied here is `0` which essentially disables chunk combining. Must be overridden
        by subclass where combining behavior is supported.
        Úcombine_text_under_n_charsNr   ©r   Úget©r    Ú	arg_valuer!   r!   r"   r,   s   s    z*ChunkingOptions.combine_text_under_n_charsc                 C  s   | j  d¡}|dur|S tS )zÿThe maximum size for a chunk.

        A pre-chunk will only exceed this size when it contains exactly one element which by itself
        exceeds this size. Such a pre-chunk is subject to mid-text splitting later in the chunking
        process.
        Úmax_charactersN)r   r.   r   r/   r!   r!   r"   Úhard_max}   s    zChunkingOptions.hard_maxr   c                 C  s    | j  d¡}|du rdS t|ƒS )z�When True, add original elements from pre-chunk to `.metadata.orig_elements` of chunk.

        Default value is `True`.
        Úinclude_orig_elementsNT)r   r.   r   r/   r!   r!   r"   r3   ˆ   s    z%ChunkingOptions.include_orig_elementsc                 C  s   | j  d¡}|r| jS dS )zåCharacters of overlap to add between chunks.

        This applies only to boundaries between chunks formed from whole elements and not to
        text-splitting boundaries that arise from splitting an oversized element.
        Zoverlap_allr   )r   r.   Úoverlap)r    Zoverlap_all_argr!   r!   r"   Úinter_chunk_overlap‘   s    z#ChunkingOptions.inter_chunk_overlapc                 C  s   | j  d¡}|pdS )zæThe number of characters to overlap text when splitting chunks mid-text.

        The actual overlap will not exceed this number of characters but may be less as required to
        respect splitting-character boundaries.
        r4   r   r-   )r    Zoverlap_argr!   r!   r"   r4   ›   s    zChunkingOptions.overlapc                 C  s.   | j }| j d¡}|du r|S ||kr*|S |S )zÇA pre-chunk of this size or greater is considered full.

        Note that while a value of `0` is valid, it essentially disables chunking by putting
        each element into its own chunk.
        Únew_after_n_charsN)r2   r   r.   )r    r2   Znew_after_n_chars_argr!   r!   r"   Úsoft_max¥   s    zChunkingOptions.soft_maxz Callable[[str], tuple[str, str]]c                 C  s   t | ƒS )a  A text-splitting function suitable for splitting the text of an oversized pre-chunk.

        The function is pre-configured with the chosen chunking window size and any other applicable
        options specified by the caller as part of this chunking-options instance.
        )Ú_TextSplitterr*   r!   r!   r"   Úsplitº   s    zChunkingOptions.splitÚstrc                 C  s   dS )a;  The string to insert between elements when concatenating their text for a chunk.

        Right now this is just "

" (a blank line in plain text), but having this here rather
        than as a module-level constant provides a way for us to easily make it user-configurable
        in future if we want to.
        z

r!   r*   r!   r!   r"   Útext_separatorÃ   s    zChunkingOptions.text_separatorztuple[str, ...]c                 C  s    | j  d¡}|du rdS t|ƒS )zLSequence of text-splitting target strings to be used in order of preference.Útext_splitting_separatorsN)Ú
ú )r   r.   Útuple)r    Ztext_splitting_separators_argr!   r!   r"   r<   Í   s
    ÿýz)ChunkingOptions.text_splitting_separatorsÚNonec                 C  sj   | j }|dkrtd|› �ƒ‚| j d¡}|durF|dk rFtd|› �ƒ‚| j|krftd| j› d|› �ƒ‚dS )z5Raise ValueError if requestion option-set is invalid.r   z+'max_characters' argument must be > 0, got r6   Nz/'new_after_n_chars' argument must be >= 0, got z;'overlap' argument must be less than `max_characters`, got z >= )r2   Ú
ValueErrorr   r.   r4   )r    r1   r6   r!   r!   r"   r%   ×   s     ÿ
ÿÿÿzChunkingOptions._validateN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r#   Úclassmethodr'   r   r+   r,   r2   r3   r5   r4   r7   r9   r;   r<   r%   r!   r!   r!   r"   r   6   s2   *	
				r   c                   @  sf   e Zd ZdZdddœdd„Zeddddœd	d
„ƒZddœdd„Zeddœdd„ƒZ	dddœdd„Z
dS )Ú
PreChunkeraq  Gathers sequential elements into pre-chunks as length constraints allow.

    The pre-chunker's responsibilities are:

    - **Segregate semantic units.** Identify semantic unit boundaries and segregate elements on
      either side of those boundaries into different sections. In this case, the primary indicator
      of a semantic boundary is a `Title` element. A page-break (change in page-number) is also a
      semantic boundary when `multipage_sections` is `False`.

    - **Minimize chunk count for each semantic unit.** Group the elements within a semantic unit
      into sections as big as possible without exceeding the chunk window size.

    - **Minimize chunks that must be split mid-text.** Precompute the text length of each section
      and only produce a section that exceeds the chunk window size when there is a single element
      with text longer than that window.

    A Table element is placed into a section by itself. CheckBox elements are dropped.

    The "by-title" strategy specifies breaking on section boundaries; a `Title` element indicates
    a new "section", hence the "by-title" designation.
    úIterable[Element]r   )ÚelementsÚoptsc                 C  s   || _ || _d S r   )Ú	_elementsÚ_opts)r    rI   rJ   r!   r!   r"   r#   
  s    zPreChunker.__init__úIterator[PreChunk])rI   rJ   r$   c                 C  s   | ||ƒ  ¡ S )zEGenerate pre-chunks from the element-stream provided on construction.)Ú_iter_pre_chunks)r&   rI   rJ   r!   r!   r"   Úiter_pre_chunks  s    zPreChunker.iter_pre_chunksr)   c                 c  sT   t | jƒ}| jD ]0}|  |¡s(| |¡s6| ¡ E dH  | |¡ q| ¡ E dH  dS )aÅ  Generate pre-chunks from the element-stream provided on construction.

        A *pre-chunk* is the largest sub-sequence of elements that will both fit within the
        chunking window and respects the semantic boundary rules of the chunking strategy. When a
        single element exceeds the chunking window size it is placed in a pre-chunk by itself and
        is subject to mid-text splitting in the second phase of the chunking process.
        N)ÚPreChunkBuilderrL   rK   Ú_is_in_new_semantic_unitÚwill_fitÚflushÚadd_element)r    Zpre_chunk_builderÚelementr!   r!   r"   rN     s    

þüzPreChunker._iter_pre_chunksr(   c                 C  s   | j jS )zBThe semantic-boundary detectors to be applied to break pre-chunks.)rL   r+   r*   r!   r!   r"   Ú_boundary_predicates0  s    zPreChunker._boundary_predicatesr   r   ©rU   r$   c                   s   ‡ fdd„| j D ƒ}t|ƒS )zITrue when `element` begins a new semantic unit such as a section or page.c                   s   g | ]}|ˆ ƒ‘qS r!   r!   )Ú.0Úpred©rU   r!   r"   Ú
<listcomp>:  ó    z7PreChunker._is_in_new_semantic_unit.<locals>.<listcomp>)rV   Úany)r    rU   Zsemantic_boundariesr!   rZ   r"   rQ   5  s    z#PreChunker._is_in_new_semantic_unitN)rB   rC   rD   rE   r#   rF   rO   rN   r   rV   rQ   r!   r!   r!   r"   rG   ó   s   rG   c                   @  s‚   e Zd ZdZdddœdd„Zdddœd	d
„Zddœdd„Zdddœdd„Zeddœdd„ƒZ	dddœdd„Z
eddœdd„ƒZdS )rP   an  An element accumulator suitable for incrementally forming a pre-chunk.

    Provides the trial method `.will_fit()` a pre-chunker can use to determine whether it should add
    the next element in the element stream.

    `.flush()` is used to build a PreChunk object from the accumulated elements. This method
    returns an iterator that generates zero-or-one `PreChunk` object and is used like so:

        yield from builder.flush()

    If no elements have been accumulated, no `PreChunk` instance is generated. Flushing the builder
    clears the elements it contains so it is ready to build the next pre-chunk.
    r   r@   ©rJ   r$   c                 C  s.   || _ t|jƒ| _g | _d| _g | _d| _d S )NÚ r   )rL   Úlenr;   Ú_separator_lenrK   Ú_overlap_prefixÚ_text_segmentsÚ	_text_len©r    rJ   r!   r!   r"   r#   M  s    zPreChunkBuilder.__init__r   rW   c                 C  s8   | j  |¡ |jr4| j |j¡ |  jt|jƒ7  _dS )zAdd `element` to this section.N)rK   ÚappendÚtextrc   rd   r`   ©r    rU   r!   r!   r"   rT   Y  s    zPreChunkBuilder.add_elementrM   r)   c                 c  s4   | j }|sdS t|| j| jƒ}|  |j¡ |V  dS )a  Generate zero-or-one `PreChunk` object and clear the accumulator.

        Suitable for use to emit a PreChunk when the maximum size has been reached or a semantic
        boundary has been reached. Also to clear out a terminal pre-chunk at the end of an element
        stream.
        N)rK   ÚPreChunkrb   rL   Ú_reset_stateÚoverlap_tail)r    rI   Ú	pre_chunkr!   r!   r"   rS   `  s    zPreChunkBuilder.flushr   c                 C  s:   t | jƒdkrdS | j| jjkr$dS | jt |jp2dƒk  S )aU  True when `element` can be added to this prechunk without violating its limits.

        There are several limits:
        - A `Table` element will never fit with any other element. It will only fit in an empty
          pre-chunk.
        - No element will fit in a pre-chunk that already contains a `Table` element.
        - A text-element will not fit in a pre-chunk that already exceeds the soft-max
          (aka. new_after_n_chars).
        - A text-element will not fit when together with the elements already present it would
          exceed the hard-max (aka. max_characters).
        r   TFr_   )r`   rK   Ú_text_lengthrL   r7   Ú_remaining_spacerg   rh   r!   r!   r"   rR   s  s
    zPreChunkBuilder.will_fitr   c                 C  s"   | j t| jƒ }| jj| j | S )zMMaximum text-length of an element that can be added without exceeding maxlen.)ra   r`   rc   rL   r2   rd   ©r    Zseparators_lenr!   r!   r"   rn   ˆ  s    z PreChunkBuilder._remaining_spacer:   )Úoverlap_prefixr$   c                 C  s.   || _ | j ¡  |r|gng | _t|ƒ| _dS )zMSet working-state values back to "empty", ready to accumulate next pre-chunk.N)rb   rK   Úclearrc   r`   rd   )r    rp   r!   r!   r"   rj   �  s    
zPreChunkBuilder._reset_statec                 C  s*   t | jƒ}|r|d nd}| j|| j  S )a•  Length of the text in this pre-chunk.

        This value represents the chunk-size that would result if this pre-chunk was flushed in its
        current state. In particular, it does not include the length of a trailing separator (since
        that would only appear if an additional element was added).

        Not suitable for judging remaining space, use `.remaining_space` for that value.
        é   r   )r`   rc   rd   ra   )r    ÚnZseparator_countr!   r!   r"   rm   –  s    
zPreChunkBuilder._text_lengthN)rB   rC   rD   rE   r#   rT   rS   rR   Úpropertyrn   rj   rm   r!   r!   r!   r"   rP   >  s   rP   c                   @  s”   e Zd ZdZdddddœdd„Zd	d
dœdd„Zd d
dœdd„Zd d dœdd„Zddœdd„Ze	ddœdd„ƒZ
ddœdd„Ze	ddœdd„ƒZdS ) ri   zaSequence of elements staged to form a single chunk.

    This object is purposely immutable.
    rH   r:   r   r@   )rI   rp   rJ   r$   c                 C  s   t |ƒ| _|| _|| _d S r   )ÚlistrK   rb   rL   )r    rI   rp   rJ   r!   r!   r"   r#   ³  s    
zPreChunk.__init__r   r   )Úotherr$   c                 C  s&   t |tƒsdS | j|jko$| j|jkS )NF)Ú
isinstanceri   rb   rK   )r    rv   r!   r!   r"   Ú__eq__º  s    
zPreChunk.__eq__©rl   r$   c                 C  s2   t | jƒ| jjkrdS t |  |¡jƒ}|| jjkS )zRTrue when `pre_chunk` can be combined with this one without exceeding size limits.F)r`   Ú_textrL   r,   Úcombiner2   )r    rl   Zcombined_lenr!   r!   r"   Úcan_combine¿  s    zPreChunk.can_combine)Úother_pre_chunkr$   c                 C  s   t | j|j | j| jd�S )z?Return new `PreChunk` that combines this and `other_pre_chunk`.)rp   rJ   )ri   rK   rb   rL   )r    r}   r!   r!   r"   r{   Ë  s
    
ýzPreChunk.combinez/Iterator[CompositeElement | Table | TableChunk]r)   c                 c  s\   t | jƒdkr>t| jd tƒr>t | jd | j| j¡E dH  nt | j| j	| j¡E dH  dS )aT  Form this pre-chunk into one or more chunk elements maxlen or smaller.

        When the total size of the pre-chunk will fit in the chunking window, a single chunk it
        emitted. When this prechunk contains an oversized element (always isolated), it is split
        into two or more chunks that each fit the chunking window.
        rr   r   N)
r`   rK   rw   r   Ú_TableChunkerÚiter_chunksrb   rL   Ú_Chunkerrz   r*   r!   r!   r"   r   Õ  s
    ÿzPreChunk.iter_chunksc                 C  s$   | j j}|r | j| d…  ¡ S dS )a6  The portion of this chunk's text to be repeated as a prefix in the next chunk.

        This value is the empty-string ("") when either the `.overlap` length option is `0` or
        `.overlap_all` is `False`. When there is a text value, it is stripped of both leading and
        trailing whitespace.
        Nr_   )rL   r5   rz   Ústrip)r    r4   r!   r!   r"   rk   ç  s    zPreChunk.overlap_tailúIterator[str]c                 c  sL   | j r| j V  | jD ]2}|jrt|jƒrd |j ¡  ¡ ¡}|r|V  qdS )zuGenerate overlap text and each element text segment in order.

        Empty text segments are not included.
        r>   N)rb   rK   rg   r`   Újoinr�   r9   )r    Úerg   r!   r!   r"   Ú_iter_text_segmentsò  s    
zPreChunk._iter_text_segmentsc                 C  s   | j j |  ¡ ¡S )zéThe concatenated text of all elements in this pre-chunk, including any overlap.

        Whitespace is normalized to a single space. The text of each element is separated from
        that of the next by a blank line ("

").
        )rL   r;   rƒ   r…   r*   r!   r!   r"   rz   ÿ  s    zPreChunk._textN)rB   rC   rD   rE   r#   rx   r|   r{   r   r   rk   r…   rz   r!   r!   r!   r"   ri   ­  s   

ri   c                   @  s¤   e Zd ZdZdddddœdd„Zedddd	dœd
d„ƒZd	dœdd„Zeddœdd„ƒZ	eddœdd„ƒZ
eddœdd„ƒZeddœdd„ƒZeddœdd„ƒZdS )r€   zƒForms chunks from a pre-chunk other than one containing only a `Table`.

    Produces zero-or-more `CompositeElement` objects.
    rH   r:   r   r@   )rI   rg   rJ   r$   c                 C  s   t |ƒ| _|| _|| _d S r   )ru   rK   rz   rL   )r    rI   rg   rJ   r!   r!   r"   r#     s    
z_Chunker.__init__zIterator[CompositeElement]c                 C  s   | |||ƒ  ¡ S )zÛForm zero or more chunks from `elements`.

        One `CompositeElement` is produced when all `elements` will fit. Otherwise there is a
        single `Text`-subtype element and chunks are formed by splitting.
        ©Ú_iter_chunks)r&   rI   rg   rJ   r!   r!   r"   r     s    	z_Chunker.iter_chunksr)   c                 c  sV   | j s
dS | jj}|| j ƒ\}}t|| jd�V  |rR||ƒ\}}t|| jd�V  q0dS )z)Form zero or more chunks from `elements`.N©rg   Úmetadata)rz   rL   r9   r   Ú_consolidated_metadataÚ_continuation_metadata)r    r9   ÚsÚ	remainderr!   r!   r"   r‡   $  s    z_Chunker._iter_chunkszdict[str, list[Any]]c                 C  sP   dddœdd„}t  t¡}| jD ]&}||jƒD ]\}}||  |¡ q.q t|ƒS )a¤  Collection of all populated metadata values across elements.

        The resulting dict has one key for each `ElementMetadata` field that had a non-None value in
        at least one of the elements in this pre-chunk. The value of that key is a list of all those
        populated values, in element order, for example:

            {
                "filename": ["sample.docx", "sample.docx"],
                "languages": [["lat"], ["lat", "eng"]]
                ...
            }

        This preprocessing step provides the input for a specified consolidation strategy that will
        resolve the list of values for each field to a single consolidated value.
        r   úIterator[tuple[str, Any]])r‰   r$   c                 S  s   dd„ | j  ¡ D ƒS )zM(field_name, value) pair for each non-None field in single `ElementMetadata`.c                 s  s"   | ]\}}|d ur||fV  qd S r   r!   )rX   Ú
field_nameÚvaluer!   r!   r"   Ú	<genexpr>L  s   þzO_Chunker._all_metadata_values.<locals>.iter_populated_fields.<locals>.<genexpr>)Zknown_fieldsÚitems)r‰   r!   r!   r"   Úiter_populated_fieldsJ  s    þz<_Chunker._all_metadata_values.<locals>.iter_populated_fields)ÚcollectionsÚdefaultdictru   rK   r‰   rf   Údict)r    r“   Zfield_valuesr„   r�   r�   r!   r!   r"   Ú_all_metadata_values8  s    

z_Chunker._all_metadata_valuesr   c                 C  s$   t f i | j¤Ž}| jjr | j|_|S )a“  Metadata applicable to this pre-chunk as a single chunk.

        Formed by applying consolidation rules to all metadata fields across the elements of this
        pre-chunk.

        For the sake of consistency, the same rules are applied (for example, for dropping values)
        to a single-element pre-chunk too, even though metadata for such a pre-chunk is already
        "consolidated".
        )r   Ú_meta_kwargsrL   r3   Ú_orig_elementsÚorig_elements)r    Zconsolidated_metadatar!   r!   r"   rŠ   [  s    z_Chunker._consolidated_metadatac                 C  s   t   | j¡}d|_|S )a  Metadata applicable to the second and later text-split chunks of the pre-chunk.

        The same metadata as the first text-split chunk but includes `.is_continuation = True`.
        Unused for non-oversized pre-chunks since those are not subject to text-splitting.
        T)ÚcopyrŠ   Úis_continuation)r    Zcontinuation_metadatar!   r!   r"   r‹   k  s    
z_Chunker._continuation_metadatazdict[str, Any]c                   s,   t ‰ t  ¡ ‰ddœ‡ ‡‡fdd„}t|ƒ ƒS )a$  The consolidated metadata values as a dict suitable for constructing ElementMetadata.

        This is where consolidation strategies are actually applied. The output is suitable for use
        in constructing an `ElementMetadata` object like `ElementMetadata(**self._meta_kwargs)`.
        rŽ   r)   c                  3  sÒ   ˆj  ¡ D ]Â\} }ˆ | ¡}|ˆ ju r6| |d fV  q
|ˆ ju rX| t|tdg ƒƒfV  q
|ˆ ju r„dd„ |D ƒ}| t| 	¡ ƒfV  q
|ˆ j
u rª| d dd„ |D ƒ¡fV  q
|ˆ ju r¸q
q
tdt| ƒ› d	�ƒ‚q
d
S )zKGenerate (field-name, value) pairs for each field in consolidated metadata.r   z	list[Any]c                 S  s   i | ]}|D ]
}|d “qqS r   r!   )rX   Úval_listÚkeyr!   r!   r"   Ú
<dictcomp>�  r\   zC_Chunker._meta_kwargs.<locals>.iter_kwarg_pairs.<locals>.<dictcomp>r>   c                 s  s   | ]}|  ¡ V  qd S r   )r�   )rX   Úvalr!   r!   r"   r‘   ’  r\   zB_Chunker._meta_kwargs.<locals>.iter_kwarg_pairs.<locals>.<genexpr>zmetadata field z& has no defined consolidation strategyN)r—   r’   r.   ZFIRSTZLIST_CONCATENATEÚsumr   ZLIST_UNIQUEru   ÚkeysZSTRING_CONCATENATErƒ   ÚDROPÚNotImplementedErrorÚrepr)r�   ÚvaluesÚstrategyZordered_unique_keys©ÚCSÚfield_consolidation_strategiesr    r!   r"   Úiter_kwarg_pairsƒ  s     





ÿz/_Chunker._meta_kwargs.<locals>.iter_kwarg_pairs)r   rª   r–   )r    r«   r!   r¨   r"   r˜   y  s    z_Chunker._meta_kwargsúlist[Element]c                   s   ‡ fdd„}t |ƒ ƒS )zJThe `.metadata.orig_elements` value for chunks formed from this pre-chunk.c                  3  s<   ˆ j D ]0} | jjd u r| V  qt | ¡}d |j_|V  qd S r   )rK   r‰   rš   r›   )r„   Zorig_elementr*   r!   r"   Úiter_orig_elements¢  s    

z3_Chunker._orig_elements.<locals>.iter_orig_elements)ru   )r    r­   r!   r*   r"   r™   ž  s    z_Chunker._orig_elementsN)rB   rC   rD   rE   r#   rF   r   r‡   r   r—   rŠ   r‹   r˜   r™   r!   r!   r!   r"   r€     s   
"$r€   c                   @  sÒ   e Zd ZdZdddddœdd„Zedddd	dœd
d„ƒZd	dœdd„Zeddœdd„ƒZ	eddœdd„ƒZ
ddœdd„Zddœdd„Zeddœdd„ƒZeddœdd„ƒZeddœdd „ƒZeddœd!d"„ƒZd#S )$r~   zçResponsible for forming chunks, especially splits, from a single-table pre-chunk.

    Table splitting is specialized because we recursively split on an even row, cell, text
    boundary. This object encapsulate those details.
    r   r:   r   r@   )Útablerp   rJ   r$   c                 C  s   || _ || _|| _d S r   )Ú_tablerb   rL   )r    r®   rp   rJ   r!   r!   r"   r#   ¹  s    z_TableChunker.__init__zIterator[Table | TableChunk]c                 C  s   | |||ƒ  ¡ S )úLSplit this pre-chunk into `Table` or `TableChunk` objects maxlen or smaller.r†   )r&   r®   rp   rJ   r!   r!   r"   r   ¾  s    z_TableChunker.iter_chunksr)   c                 c  sŠ   | j s
dS | jj}t| jƒ|krTt| jƒ|krT| j}| jp<d|_t| j|d�V  dS | jrf| jjdk rx|  	¡ E dH  dS |  
¡ E dH  dS )r°   Nrˆ   é2   )Ú_table_textrL   r2   r`   Ú_text_with_overlapÚ_htmlÚ	_metadataÚtext_as_htmlr   Ú_iter_text_only_table_chunksÚ _iter_text_and_html_table_chunks)r    Úmaxlenr‰   r!   r!   r"   r‡   Å  s    z_TableChunker._iter_chunksc                 C  s   | j  }sdS |jS )zçThe compactified HTML for this table when it has text-as-HTML.

        The empty string when table-structure has not been captured, perhaps because
        `infer_table_structure` was set `False` in the partitioning call.
        r_   )Ú_html_tableÚhtml)r    Ú
html_tabler!   r!   r"   r´   á  s    
z_TableChunker._htmlzHtmlTable | Nonec                 C  s0   | j jj }du rdS | ¡ }|s&dS t |¡S )z�The `lxml` HTML element object for this table.

        `None` when the `Table` element has no `.metadata.text_as_html`.
        N)r¯   r‰   r¶   r�   r   Zfrom_html_text)r    r¶   r!   r!   r"   rº   í  s    z_TableChunker._html_tablezIterator[TableChunk]c                 c  s^   | j  }du rtdƒ‚d}t || j¡D ]0\}}| j}||_|pBd|_d}t||d�V  q(dS )z Split table into chunks where HTML corresponds exactly to text.

        `.metadata.text_as_html` for each chunk is a parsable `<table>` HTML fragment.
        Nz<this method is undefined for a table having no .text_as_htmlFTrˆ   )	rº   rA   Ú_HtmlTableSplitterÚiter_subtablesrL   rµ   r¶   rœ   r   )r    r¼   rœ   rg   r»   r‰   r!   r!   r"   r¸   ü  s    
z._TableChunker._iter_text_and_html_table_chunksc                 c  sJ   | j }| jj}d}|rF||ƒ\}}| j}|p.d|_d}t||d�V  qdS )z´Split oversized text-only table (no text-as-html) into chunks.

        `.metadata.text_as_html` is optional, not included when `infer_table_structure` is
        `False`.
        FNTrˆ   )r³   rL   r9   rµ   rœ   r   )r    Ztext_remainderr9   rœ   Z
chunk_textr‰   r!   r!   r"   r·     s    
z*_TableChunker._iter_text_only_table_chunksr   c                   sV   t ‰ t | jj¡}‡ fdd„ˆ  ¡  ¡ D ƒ}|D ]}t||dƒ q0| jj	rR| j
|_|S )a
  The base `.metadata` value for chunks formed from this pre-chunk.

        The term "base" here means that other metadata fields will be added, depending on the
        chunk. In particular, `.metadata.text_as_html` will be different for each text-split chunk
        and `.metadata.is_continuation` must be added for second-and-later text-split chunks.

        Note this is a fresh copy of the metadata on each call since it will need to be mutated
        differently for each chunk formed from this pre-chunk.
        c                   s   g | ]\}}|ˆ j u r|‘qS r!   )r£   )rX   r�   r§   ©r©   r!   r"   r[   3  s   
þz+_TableChunker._metadata.<locals>.<listcomp>N)r   r›   Údeepcopyr¯   r‰   rª   r’   ÚsetattrrL   r3   r™   rš   )r    r‰   Zdrop_field_namesr�   r!   r¿   r"   rµ   #  s    

þz_TableChunker._metadatar¬   c                 C  s   t  | j¡}d|j_|gS )a,  The `.metadata.orig_elements` value for chunks formed from this pre-chunk.

        Note this is not just the `Table` element, it must be adjusted to strip out any
        `.metadata.orig_elements` value it may have when it is itself a chunk and not a direct
        product of partitioning.
        N)r›   rÀ   r¯   r‰   rš   )r    Z
orig_tabler!   r!   r"   r™   ?  s    
z_TableChunker._orig_elementsc                 C  s   | j jsdS d | j j ¡ ¡S )zMThe text in this table, not including any overlap-prefix or extra whitespace.r_   r>   )r¯   rg   rƒ   r9   r*   r!   r!   r"   r²   N  s    z_TableChunker._table_textc                 C  s2   | j }| jjsdn
| jj ¡ }|r.|d | S |S )zCThe text for this chunk, including the overlap-prefix when present.r_   r=   )rb   r¯   rg   r�   )r    rp   Z
table_textr!   r!   r"   r³   U  s    z _TableChunker._text_with_overlapN)rB   rC   rD   rE   r#   rF   r   r‡   r   r´   rº   r¸   r·   rt   rµ   r™   r²   r³   r!   r!   r!   r"   r~   ²  s&   r~   c                   @  sd   e Zd ZdZdddœdd„Zeddddœd	d
„ƒZddœdd„Zdddœdd„Zdddœdd„Z	dS )r½   ap  Produces (text, html) pairs for a `<table>` HtmlElement.

    Each chunk contains a whole number of rows whenever possible. An oversized row is split on an
    even cell boundary and a single cell that is by itself too big to fit in the chunking window
    is divided by text-splitting.

    The returned `html` value is always a parseable HTML `<table>` subtree.
    r   r   )Útable_elementrJ   c                 C  s   || _ || _d S r   )Ú_table_elementrL   )r    rÂ   rJ   r!   r!   r"   r#   m  s    z_HtmlTableSplitter.__init__úIterator[TextAndHtml])rÂ   rJ   r$   c                 C  s   | ||ƒ  ¡ S )a  Generate (text, html) pair for each split of this table pre-chunk.

        Each split is on an even row boundary whenever possible, falling back to even cell and even
        word boundaries when a row or cell is by itself oversized, respectively.
        )Ú_iter_subtables)r&   rÂ   rJ   r!   r!   r"   r¾   q  s    	z!_HtmlTableSplitter.iter_subtablesr)   c                 c  sn   t | jjd�}| j ¡ D ]B}| |¡s4| ¡ E dH  | |¡rJ| |¡ q|  |¡E dH  q| ¡ E dH  dS )zÞGenerate (text, html) pairs containing as many whole rows as will fit in window.

        Falls back to splitting rows into whole cells when a single row is by itself too big to
        fit in the chunking window.
        ©r¹   N)	Ú_RowAccumulatorrL   r2   rÃ   Z	iter_rowsrR   rS   Úadd_rowÚ_iter_row_splits)r    ÚaccumÚrowr!   r!   r"   rÅ   |  s    

z"_HtmlTableSplitter._iter_subtablesr   ©rË   r$   c                 c  sl   t | jjd�}| ¡ D ]B}| |¡s2| ¡ E dH  | |¡rH| |¡ q|  |¡E dH  q| ¡ E dH  dS )zQSplit oversized row into (text, html) pairs containing as many cells as will fit.rÆ   N)Ú_CellAccumulatorrL   r2   Z
iter_cellsrR   rS   Úadd_cellÚ_iter_cell_splits)r    rË   rÊ   Úcellr!   r!   r"   rÉ   �  s    

z#_HtmlTableSplitter._iter_row_splitsr   ©rÐ   r$   c                 c  sb   t | jjd d�}t|ƒ}||jƒ\}}|d|› d�fV  |r^||ƒ\}}|d|› d�fV  q:dS )zDSplit a single oversized cell into sub-sub-sub-table HTML fragments.é!   )r1   z<table><tr><td>z</td></tr></table>N)r   rL   r2   r8   rg   )r    rÐ   rJ   r9   rg   r�   r!   r!   r"   rÏ      s    z$_HtmlTableSplitter._iter_cell_splitsN)
rB   rC   rD   rE   r#   rF   r¾   rÅ   rÉ   rÏ   r!   r!   r!   r"   r½   c  s   	
r½   c                   @  sT   e Zd ZdZddœdd„Zdddœd	d
„Zeddœdd„ƒZdddddœdd„ZdS )r8   aó  Provides a text-splitting function configured on construction.

    Text is split on the best-available separator, falling-back from the preferred separator
    through a sequence of alternate separators.

    - The separator is removed by splitting so only whitespace strings are suitable separators.
    - A "blank-line" ("

") is unlikely to occur in an element as it would have been used as an
      element boundary during partitioning.

    This is a *callable* object. Constructing it essentially produces a function:

        split = _TextSplitter(opts)
        fragment, remainder = split(s)

    This allows it to be configured with length-options etc. on construction and used throughout a
    chunking operation on a given element-stream.
    r   )rJ   c                 C  s
   || _ d S r   )rL   re   r!   r!   r"   r#   Â  s    z_TextSplitter.__init__r:   ztuple[str, str])rŒ   r$   c                 C  sŽ   | j j}t|ƒ|kr|dfS | jD ]B\}}|  |||¡\}}|r"t|ƒt|ƒkrRq"| ¡ | ¡ f  S |d|…  ¡ ||| j j d…  ¡ fS )aÕ  Return pair of strings split from `s` on the best match of configured patterns.

        The first string is the split, the second is the remainder of the string. The split string
        will never be longer than `maxlen`. The separators are tried in order until a match is
        found. The last separator is "" which matches between any two characters so there will
        always be a split.

        The separator is removed and does not appear in the split or remainder.

        An `s` that is already less than the maximum length is returned unchanged with no remainder.
        This allows this function to be called repeatedly with the remainder until it is consumed
        and returns a remainder of "".
        r_   N)rL   r2   r`   Ú	_patternsÚ_split_from_maxlenÚrstripÚlstripr4   )r    rŒ   r¹   ÚpÚsep_lenÚfragmentr�   r!   r!   r"   Ú__call__Å  s    þüz_TextSplitter.__call__z*tuple[tuple[regex.Pattern[str], int], ...]r)   c                 C  s   | j j}tdd„ |D ƒƒS )aÕ  Sequence of (pattern, len) pairs to match against.

        Patterns appear in order of preference, those following are "fall-back" patterns to be used
        if no match of a prior pattern is found.

        NOTE these regexes search *from the end of the string*, which is what the "(?r)" bit
        specifies. This is much more efficient than starting at the beginning of the string which
        could result in hundreds of matches before the desired one.
        c                 s  s&   | ]}t  d |› �¡t|ƒfV  qdS )z(?r)N)ÚregexÚcompiler`   )rX   Úsepr!   r!   r"   r‘   ö  r\   z*_TextSplitter._patterns.<locals>.<genexpr>)rL   r<   r?   )r    Ú
separatorsr!   r!   r"   rÓ   ê  s    z_TextSplitter._patternszregex.Pattern[str]r   )ÚpatternrØ   rŒ   r$   c                 C  s°   | j j| j j }}|j||d || d�}|du r:d|fS | ¡ \}}d}	|d|…  ¡ }
||d…  ¡ }|t|	ƒkr~|
|fS |t|	ƒ }|
| d…  ¡ }||	 | }|
|fS )a  Return (split, remainder) pair split from `s` on the right-most match before `maxlen`.

        Returns `"", s` if no suitable match was found. Also returns `"", s` if splitting on this
        separator produces a split shorter than the required overlap (which would produce an
        infinite loop).

        `split` will never be longer than `maxlen` and there is no longer split available using
        `pattern`.

        The separator is removed and does not appear in either the split or remainder.
        rr   )ÚposÚendposNr_   r>   )rL   r2   r4   ÚsearchÚspanrÕ   rÖ   r`   )r    rß   rØ   rŒ   r¹   r4   ÚmatchZmatch_startZ	match_endÚ	separatorrÙ   Zraw_remainderZtail_lenÚtailZoverlapped_remainderr!   r!   r"   rÔ   ø  s    z _TextSplitter._split_from_maxlenN)	rB   rC   rD   rE   r#   rÚ   r   rÓ   rÔ   r!   r!   r!   r"   r8   ¯  s   %r8   c                   @  sl   e Zd ZdZddœdd„Zdddœd	d
„Zddœdd„Zdddœdd„Zddœdd„Ze	ddœdd„ƒZ
dS )rÍ   zúIncrementally build `<table>` fragment cell-by-cell to maximally fill chunking window.

    Accumulate cells until chunking window is filled, then generate the text and HTML for the
    subtable composed of all those rows that fit in the window.
    r   rÆ   c                 C  s   || _ g | _d S r   )Ú_maxlenÚ_cells©r    r¹   r!   r!   r"   r#   *  s    z_CellAccumulator.__init__r   r@   rÑ   c                 C  s   | j  |¡ dS )zPAdd `cell` to this accumulation. Caller is responsible for ensuring it will fit.N)rè   rf   ©r    rÐ   r!   r!   r"   rÎ   .  s    z_CellAccumulator.add_cellrÄ   r)   c                 c  sR   | j s
dS d |  ¡ ¡}d dd„ | j D ƒ¡}d|› d�}| j  ¡  ||fV  dS )zFGenerate zero-or-one (text, html) pairs for accumulated sub-sub-table.Nr>   r_   c                 s  s   | ]}|j V  qd S r   ©r»   ©rX   Úcr!   r!   r"   r‘   7  r\   z)_CellAccumulator.flush.<locals>.<genexpr>z<table><tr>z</tr></table>)rè   rƒ   Ú_iter_cell_textsrq   )r    rg   Ztds_strr»   r!   r!   r"   rS   2  s    
z_CellAccumulator.flushr   c                 C  s   | j t|jƒkS )zLTrue when `cell` will fit within remaining space left by accummulated cells.)rn   r`   rg   rê   r!   r!   r"   rR   <  s    z_CellAccumulator.will_fitr‚   c                 c  s"   | j D ]}|j }sq|V  qdS )zŸGenerate contents of each accumulated cell as a separate string.

        A cell that is empty or contains only whitespace does not generate a string.
        N)rè   rg   )r    rÐ   rg   r!   r!   r"   rî   @  s    

z!_CellAccumulator._iter_cell_textsc                 C  s(   t | jƒ}| j| tdd„ | jD ƒƒ S )zHNumber of characters remaining when text of accumulated cells is joined.c                 s  s   | ]}t |jƒV  qd S r   )r`   rg   rì   r!   r!   r"   r‘   P  r\   z4_CellAccumulator._remaining_space.<locals>.<genexpr>)r`   rè   rç   r¡   ro   r!   r!   r"   rn   J  s    
z!_CellAccumulator._remaining_spaceN)rB   rC   rD   rE   r#   rÎ   rS   rR   rî   rt   rn   r!   r!   r!   r"   rÍ   #  s   

rÍ   c                   @  sl   e Zd ZdZddœdd„Zdddœd	d
„Zddœdd„Zdddœdd„Zddœdd„Ze	ddœdd„ƒZ
dS )rÇ   z¿Maybe `SubtableAccumulator`.

    Accumulate rows until chunking window is filled, then generate the text and HTML for the
    subtable composed of all those rows that fit in the window.
    r   rÆ   c                 C  s   || _ g | _d S r   )rç   Ú_rowsré   r!   r!   r"   r#   Z  s    z_RowAccumulator.__init__r   r@   rÌ   c                 C  s   | j  |¡ dS )zOAdd `row` to this accumulation. Caller is responsible for ensuring it will fit.N)rï   rf   ©r    rË   r!   r!   r"   rÈ   ^  s    z_RowAccumulator.add_rowrÄ   r)   c                 c  sR   | j s
dS d |  ¡ ¡}d dd„ | j D ƒ¡}d|› d�}| j  ¡  ||fV  dS )zBGenerate zero-or-one (text, html) pairs for accumulated sub-table.Nr>   r_   c                 s  s   | ]}|j V  qd S r   rë   ©rX   Úrr!   r!   r"   r‘   g  r\   z(_RowAccumulator.flush.<locals>.<genexpr>z<table>z</table>)rï   rƒ   rî   rq   )r    rg   Ztrs_strr»   r!   r!   r"   rS   b  s    
z_RowAccumulator.flushr   c                 C  s   | j |jkS )zJTrue when `row` will fit within remaining space left by accummulated rows.)rn   Útext_lenrð   r!   r!   r"   rR   l  s    z_RowAccumulator.will_fitr‚   c                 c  s   | j D ]}| ¡ E dH  qdS )z—Generate contents of each row cell as a separate string.

        A cell that is empty or contains only whitespace does not generate a string.
        N)rï   Ziter_cell_texts)r    rò   r!   r!   r"   rî   p  s    
z _RowAccumulator._iter_cell_textsc                 C  s(   t | jƒ}| j| tdd„ | jD ƒƒ S )zJNumber of characters remaining when accumulated rows are formed into HTML.c                 s  s   | ]}|j V  qd S r   )ró   rñ   r!   r!   r"   r‘   ~  r\   z3_RowAccumulator._remaining_space.<locals>.<genexpr>)r`   rï   rç   r¡   ro   r!   r!   r"   rn   x  s    
z _RowAccumulator._remaining_spaceN)rB   rC   rD   rE   r#   rÈ   rS   rR   rî   rt   rn   r!   r!   r!   r"   rÇ   S  s   
rÇ   c                   @  s.   e Zd ZdZdddœdd„Zddœd	d
„ZdS )ÚPreChunkCombinerzDFilters pre-chunk stream to combine small pre-chunks where possible.zIterable[PreChunk]r   )Ú
pre_chunksrJ   c                 C  s   || _ || _d S r   )Ú_pre_chunksrL   )r    rõ   rJ   r!   r!   r"   r#   ‰  s    zPreChunkCombiner.__init__rM   r)   c                 c  sJ   t | jƒ}| jD ]&}| |¡s,| ¡ E dH  | |¡ q| ¡ E dH  dS )zTGenerate pre-chunk objects, combining `PreChunk` objects when they'll fit in window.N)Ú_PreChunkAccumulatorrL   rö   rR   rS   Úadd_pre_chunk)r    rÊ   rl   r!   r!   r"   Úiter_combined_pre_chunks�  s    


z)PreChunkCombiner.iter_combined_pre_chunksN)rB   rC   rD   rE   r#   rù   r!   r!   r!   r"   rô   †  s   rô   c                   @  sN   e Zd ZdZdddœdd„Zdddœd	d
„Zddœdd„Zdddœdd„ZdS )r÷   a[  Accumulates, measures, and combines pre-chunks.

    Used for combining pre-chunks for chunking strategies like "by-title" that can potentially
    produce undersized chunks and offer the `combine_text_under_n_chars` option.

    Provides `.add_pre_chunk()` allowing a pre-chunk to be added to the chunk and provides
    monitoring properties `.remaining_space` and `.text_length` suitable for deciding whether to add
    another pre-chunk.

    `.flush()` is used to combine the accumulated pre-chunks into a single `PreChunk` object.
    This method returns an interator that generates zero-or-one `PreChunk` objects and is used
    like so:

        yield from accum.flush()

    If no pre-chunks have been accumulated, no `PreChunk` is generated. Flushing the builder
    clears the pre-chunks it contains so it is ready to accept the next pre-chunk.
    r   r@   r^   c                 C  s   || _ d | _d S r   )rL   Ú
_pre_chunkre   r!   r!   r"   r#   ¯  s    z_PreChunkAccumulator.__init__ri   ry   c                 C  s    | j du r|n
| j  |¡| _ dS )zPAdd a pre-chunk to the accumulator for possible combination with next pre-chunk.N)rú   r{   ©r    rl   r!   r!   r"   rø   ³  s    ÿz"_PreChunkAccumulator.add_pre_chunkrM   r)   c                 c  s   | j s
dS | j V  d| _ dS )zŽGenerate accumulated pre-chunk as a single combined pre-chunk.

        Does not generate a pre-chunk when none has been accumulated.
        N)rú   r*   r!   r!   r"   rS   ¹  s    z_PreChunkAccumulator.flushr   c                 C  s   | j du rdS | j  |¡S )a3  True when there is room for `pre_chunk` in accumulator.

        An empty accumulator always has room. Otherwise there is only room when `pre_chunk` can be
        combined with any other pre-chunks in the accumulator without exceeding the combination
        limits specified for the chunking run.
        NT)rú   r|   rû   r!   r!   r"   rR   Æ  s    
z_PreChunkAccumulator.will_fitN)rB   rC   rD   rE   r#   rø   rS   rR   r!   r!   r!   r"   r÷   ›  s
   r÷   r)   c                    s"   d‰ d‰dddœ‡ ‡fdd„} | S )a”  Not a predicate itself, calling this returns a predicate that triggers on each new page.

    The lifetime of the returned callable cannot extend beyond a single element-stream because it
    stores current state (current page-number) that is particular to that element stream.

    The returned predicate tracks the "current" page-number, starting at 1. An element with a
    greater page number returns True, indicating the element starts a new page boundary, and
    updates the enclosed page-number ready for the next transition.

    An element with `page_number == None` or a page-number lower than the stored value is ignored
    and returns False.
    rr   Tr   r   rW   c                   s<   | j j}ˆr|pd‰ d‰dS |d u r(dS |ˆ kr4dS |‰ dS )Nrr   FT)r‰   Úpage_number)rU   rü   ©Zcurrent_page_numberZis_firstr!   r"   Úpage_number_incremented÷  s    z0is_on_next_page.<locals>.page_number_incrementedr!   )rþ   r!   rý   r"   Úis_on_next_pageç  s    rÿ   r   rW   c                 C  s
   t | tƒS )z:True when `element` is a `Title` element, False otherwise.)rw   r   rZ   r!   r!   r"   Úis_title  s    r   )4rE   Ú
__future__r   r”   r›   Útypingr   r   r   r   r   r   rÛ   Ztyping_extensionsr	   r
   Zunstructured.common.html_tabler   r   r   Zunstructured.documents.elementsr   r   r   r   r   r   r   Zunstructured.utilsr   r   Ú__annotations__r   r   r   r?   r:   r   r   rG   rP   ri   r€   r~   r½   r8   rÍ   rÇ   rô   r÷   rÿ   r   r!   r!   r!   r"   Ú<module>   s<    $		 >Koa % 2Lt03L.