
    Mib#                        S r SSKJr  SSKJr  SSKJrJrJr  SSK	J
r
JrJrJrJrJrJr  SSKJr  SSSSSSSSSSSSS.                           SS	 jjrSS jr " S S
\5      rg)zdImplementation of chunking by title.

Main entry point is the `@add_chunking_strategy()` decorator.
    )annotations)cached_property)IterableIteratorOptional)CHUNK_MULTI_PAGE_DEFAULTBoundaryPredicateChunkingOptionsPreChunkCombiner
PreChunkeris_on_next_pageis_title)ElementNcombine_text_under_n_charsinclude_orig_elementsmax_characters
max_tokensmultipage_sectionsnew_after_n_charsnew_after_n_tokensoverlapoverlap_all	tokenizerrepeat_table_headersskip_table_chunkingc               T    [         R                  UUUUUUUUU	U
UUS9n[        X5      $ )a  Uses title elements to identify sections within the document for chunking.

Splits off into a new CompositeElement when a title is detected or if metadata changes, which
happens when page numbers or sections change. Cuts off sections once they have exceeded a
character length of max_characters (or token count of max_tokens).

Parameters
----------
elements
    A list of unstructured elements. Usually the output of a partition function.
combine_text_under_n_chars
    Combines elements (for example a series of titles) until a section reaches a length of
    n characters. 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.
include_orig_elements
    When `True` (default), add elements from pre-chunk to the `.metadata.orig_elements` field
    of the chunk(s) formed from that pre-chunk. Among other things, this allows access to
    original-element metadata that cannot be consolidated and is dropped in the course of
    chunking.
max_characters
    Chunks elements text and text_as_html (if present) into chunks of length
    n characters (hard max). Mutually exclusive with `max_tokens`.
max_tokens
    Chunks elements into chunks of n tokens (hard max). Requires `tokenizer` to be specified.
    Mutually exclusive with `max_characters`.
multipage_sections
    If True, sections can span multiple pages. Defaults to True.
new_after_n_chars
    Cuts off new sections once they reach a length of n characters (soft max). Defaults to
    `max_characters` when not specified, which effectively disables any soft window.
    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).
new_after_n_tokens
    Token-based equivalent of `new_after_n_chars`. Cuts off new sections once they reach
    n tokens (soft max). Requires `max_tokens` and `tokenizer` to be specified.
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.
tokenizer
    The tokenizer to use for token-based chunking. Can be either an encoding name (e.g.,
    "cl100k_base") or a model name (e.g., "gpt-4"). Required when using `max_tokens`.
repeat_table_headers
    Default: `True`. When `True`, repeated table-header behavior is enabled for chunked table
    continuations. Specify `False` to opt out and preserve legacy table-chunk behavior.
skip_table_chunking
    Default: `False`. When `True`, `Table` elements are passed through unchanged without
    being split into `TableChunk` elements, regardless of their size.
r   )_ByTitleChunkingOptionsnew_chunk_by_title)elementsr   r   r   r   r   r   r   r   r   r   r   r   optss                 u/var/www/eduai.edurigo.com/storigo/production/storigo_env/lib/python3.13/site-packages/unstructured/chunking/title.pychunk_by_titler$      sK    P #&&#=3%-+-1/ ' D 8**    r   c                    [        [        R                  " X5      US9R                  5       nU VVs/ s H  o3R	                  5         H  oDPM     M     snn$ s  snnf )z-Implementation of actual "by-title" chunking.)r"   )r   r   iter_pre_chunksiter_combined_pre_chunksiter_chunks)r!   r"   
pre_chunks	pre_chunkchunks        r#   r    r    p   sT     """82   $.S:i;P;P;R%E;RE:SSSs   "Ac                  l   ^  \ rS rSrSr\SS j5       r\S	S j5       r\S
S j5       rSU 4S jjr	Sr
U =r$ )r   {   a  Adds the by-title-specific chunking options to the base case.

`by_title`-specific options:

combine_text_under_n_chars
    A remedy to over-chunking caused by elements mis-identified as Title elements.
    Every Title element would start a new chunk and this setting mitigates that, at the
    expense of sometimes violating legitimate semantic boundaries.
multipage_sections
    Indicates that page-boundaries should not be respected while chunking, i.e. elements
    appearing on two different pages can appear in the same chunk.
c                4   ^  SU 4S jjn[        U" 5       5      $ )a  The semantic-boundary detectors to be applied to break pre-chunks.

For the `by_title` strategy these are sections indicated by a title (section-heading), an
explicit section metadata item (only present for certain document types), and optionally
page boundaries.
c               3  Z   >#    [         v   T R                  (       d  [        5       v   g g 7f)N)r   r   r   )selfs   r#   iter_boundary_predicatesM_ByTitleChunkingOptions.boundary_predicates.<locals>.iter_boundary_predicates   s"     N**%'' +s   (+)returnzIterator[BoundaryPredicate])tuple)r1   r2   s   ` r#   boundary_predicates+_ByTitleChunkingOptions.boundary_predicates   s    	(
 -/00r%   c                Z    U R                   R                  S5      nUc  U R                  $ U$ )a  Combine consecutive text pre-chunks if former is smaller than this and both will fit.

- Does not combine text chunks if together they would exceed the chunking window.
- Defaults to `max_characters` when not specified.
- Is reduced to `new_after_n_chars` when it exceeds that value.
r   )_kwargsgethard_maxr1   	arg_values     r#   r   2_ByTitleChunkingOptions.combine_text_under_n_chars   s-     LL$$%AB	 ) 1t}}@y@r%   c                `    U R                   R                  S5      nUc  [        $ [        U5      $ )z0When False, break pre-chunks on page-boundaries.r   )r9   r:   r   boolr<   s     r#   r   *_ByTitleChunkingOptions.multipage_sections   s.     LL$$%9:	+4+<'Q$y/Qr%   c                   > [         TU ]  5         U R                  S:  a  [        SU R                   35      eU R                  U R                  :  a%  [        SU R                   SU R                   35      eg)z2Raise ValueError if request option-set is invalid.r   z8'combine_text_under_n_chars' argument must be >= 0, got zR'combine_text_under_n_chars' argument must not exceed `max_characters` value, got z > N)super	_validater   
ValueErrorr;   )r1   	__class__s    r#   rD   !_ByTitleChunkingOptions._validate   s     	 **Q.778:  **T]]:#>>?s4==/S  ;r%    )r4   ztuple[BoundaryPredicate, ...])r4   int)r4   r@   )r4   None)__name__
__module____qualname____firstlineno____doc__r   r6   r   r   rD   __static_attributes____classcell__)rF   s   @r#   r   r   {   sR     1 1 	A 	A R R
 r%   )r!   Iterable[Element]r   Optional[int]r   Optional[bool]r   rS   r   rS   r   rT   r   rS   r   rS   r   rS   r   rT   r   zOptional[str]r   rT   r   rT   r4   list[Element])r!   rR   r"   r   r4   rU   )rO   
__future__r   	functoolsr   typingr   r   r   unstructured.chunking.baser   r	   r
   r   r   r   r   unstructured.documents.elementsr   r$   r    r   rH   r%   r#   <module>r[      s  
 # % / /   4 15,0$( $)-'+(,!"&#+/*.V+V+ !.V+ *	V+
 "V+ V+ 'V+ %V+ &V+ V+  V+ V+ )V+ (V+ V+rTEo Er%   