
    Mi^                    
   % S SK Jr  S SKrS SKrS SKrS SKrS SKrS SKrS SKrS SK	r	S SK
r
S SKrS SKJrJr  S SKJr  S SKJrJrJrJrJrJrJrJrJrJr  S SKrS SKJrJr  S SK J!r!  \(       a  S SK"J#r#J$r$  \\%\%\%\%4   r&S	\'S
'   \\%\%4   r(S	\'S'   \\(S4   r)S	\'S'   Sr*\" S5      r+\" S5      r,        S+S jr-S,S jr.S-S jr/S.S jr0 S/     S0S jjr1\" SS9S1S j5       r2S2S jr3S3S jr4S4S jr5S5S jr6S5S jr7S r8S6S jr9        S7S  jr:      S8S! jr;S9S:S" jjr< S;       S<S# jjr= S=         S>S$ jjr>S?S% jr?  S@         SAS& jjr@  S@       SBS' jjrA SC     SDS( jjrB " S) S*5      rCg)E    )annotationsN)	lru_cachewraps)combinations)
TYPE_CHECKINGAnyCallableIterableIteratorListOptionalTupleTypeVarcast)	ParamSpec	TypeAlias)__version__)ElementTextr   BoxPoint.Points)z%Y-%m-%dz%Y-%m-%dT%H:%M:%Sz%Y-%m-%d+%H:%M:%Sz%Y-%m-%dT%H:%M:%S%z_T_Pc           
     R   [         R                  " U 5      n[        S0 [        [        UR                  U5      5      DUD6nUR                  R                  5        HH  nUR                  U;  d  M  UR                  UR                  Ld  M0  UR                  XER                  '   MJ     U$ )zMMap both explicit and default arguments of decorated func call by param name. )	inspect	signaturedictzip
parametersvaluesnamedefaultempty)funcargskwargssig	call_argsargs         l/var/www/eduai.edurigo.com/storigo/production/storigo_env/lib/python3.13/site-packages/unstructured/utils.pyget_call_args_applying_defaultsr-   /   s     

D
!C $ QtC,E'F Q& QI~~$$&889$CII)E"%++Ihh '     c                J    U R                  [        R                  " 5       5      $ )zTrue when file_path is in the Python-defined tempdir.

The Python-defined temp directory is platform dependent (macOS != Linux != Windows)
and can also be determined by an environment variable (TMPDIR, TEMP, or TMP).
)
startswithtempfile
gettempdir)	file_paths    r,   is_temp_file_pathr4   =   s      3 3 566r.   c                    [        US5       nUR                  S U  5       5        S S S 5        g ! , (       d  f       g = f)Nzw+c              3  T   #    U  H  n[         R                  " U5      S -   v   M      g7f)
N)jsondumps).0datums     r,   	<genexpr> save_as_jsonl.<locals>.<genexpr>H   s     JTEtzz%047Ts   &()open
writelines)datafilenameoutput_files      r,   save_as_jsonlrC   F   s.    	h	JTJJ 
		s   /
=c                    [        U 5       nU Vs/ s H  n[        R                  " U5      PM     snsS S S 5        $ s  snf ! , (       d  f       g = fN)r>   r8   loads)rA   
input_filelines      r,   read_from_jsonlrI   K   s8    	h:-78ZT

4 Z8 
8 
s   A =AA
Ac                L   ^ ^ [        T [        5      (       a  T /m SU U4S jjnU$ )Nc                   >^ ^ UU4S jm[        T 5      SU U4S jj5       n[        T 5      SU U4S jj5       n[        R                  " T 5      (       a  U$ U$ )Nc                   > / n T H&  n[        U5      (       a  M  U R                  U5        M(     [        U 5      S:  aG  [        SSR	                  U 5       S3T(       a  ST S3-   5      eSSR	                  U 5       S	3-   5      eg )
Nr   z$Following dependencies are missing: z, . z5Please install them using `pip install "unstructured[z]"`.z'Please install them using `pip install  z`.)dependency_existsappendlenImportErrorjoin)missing_depsdepdependenciesextrass     r,   	run_check;requires_dependencies.<locals>.decorator.<locals>.run_checkX   s    &(L#(-- '', $ < 1$!:499\;R:SSUV " RRXQYY]` 
  GsxxP\G]F^^`a	  %r.   c                 "   > T" 5         T" U 0 UD6$ rE   r   r'   r(   r&   rX   s     r,   wrapper9requires_dependencies.<locals>.decorator.<locals>.wrapperg   s    K(((r.   c                 >   >#    T" 5         T" U 0 UD6I S h  vN $  N7frE   r   r[   s     r,   wrapper_async?requires_dependencies.<locals>.decorator.<locals>.wrapper_asyncl   s!     Kt.v....s   )r'   _P.argsr(   	_P.kwargs)r   asyncioiscoroutinefunction)r&   r\   r_   rX   rV   rW   s   `  @r,   	decorator(requires_dependencies.<locals>.decoratorW   sV    	 
t	) 
	) 
t	/ 
	/ &&t,,  r.   )r&   Callable[_P, _T]returnrg   )
isinstancestr)rV   rW   re   s   `` r,   requires_dependenciesrk   P   s+     ,$$$~ < r.      )maxsizec                     [         R                  " U 5        g! [         a  nU [        U5      ;   a   S nAg S nAgS nAff = f)NFT)	importlibimport_modulerR   repr)
dependencyes     r,   rO   rO   x   sC    
+
 	  a  !	s    
A<Ac                h    [        U 5      n [        U5      nX!4$ ! [         a    [        S5      ef = f)NzYExpected at least 1 element in iterable from which to retrieve first, got empty iterable.)iternextStopIteration
ValueError)ititeratorouts      r,   _first_and_remaining_iteratorr|      sF    BxH
8n =  

 	

s    1c                     [        U 5      u  pU$ )zRReturns the first item from an iterable. Raises an error if the iterable is empty.)r|   )ry   r{   _s      r,   firstr      s    *2.FCJr.   c                d    [        U 5      u  p[        S U 5       5      (       a  [        S5      eU$ )ziReturns the only element from a singleton iterable.

Raises an error if the iterable is not a singleton.
c              3  &   #    U  H  nS v   M	     g7f)TNr   )r:   r~   s     r,   r<   only.<locals>.<genexpr>   s     
"A4s   zRExpected only 1 element in passed argument, instead there are at least 2 elements.)r|   anyrx   )ry   r{   rz   s      r,   onlyr      s8    
 2"5MC

"
"""`
 	
 Jr.   c                     [        [        R                  " S5      =(       d    SR                  5       5      =(       d6    [        [        R                  " S5      =(       d    SR                  5       5      $ )zTrue if telemetry should be disabled via env.

DO_NOT_TRACK and SCARF_NO_ANALYTICS both follow the same rule: any non-empty
value (after strip) opts out. See README/CHANGELOG for the public contract.
DO_NOT_TRACK SCARF_NO_ANALYTICS)boolosgetenvstripr   r.   r,   _telemetry_opt_outr      sO     >*0b779: d	'	(	.B557? r.   c                 ~    [         R                  " S5      =(       d    SR                  5       R                  5       S;   $ )zLTrue if telemetry is explicitly enabled via env. Only 'true' and '1' opt in.UNSTRUCTURED_TELEMETRY_ENABLEDr   )true1)r   r   r   lowerr   r.   r,   _telemetry_opt_inr      s6    II67=2DDFLLN S  r.   c                    [        5       (       d  [        5       (       d  g [        R                  " S/[        R                  S9  Sn SR                  [        R                  " 5       R                  S5      SS 5      n[        R                  " [        5         [        R                  " S[         [        R"                  " 5       U[        R$                  " 5       ['        U 5      ['        S	[         ;   5      R)                  5       S
.SS9  SSS5        g! [
        [        R                  4 a    Sn  Nf = f! , (       d  f       g= f)zSend a lightweight analytics ping. Off by default.

Set UNSTRUCTURED_TELEMETRY_ENABLED=true to opt in.
Opt-out env vars (DO_NOT_TRACK, SCARF_NO_ANALYTICS): any non-empty value opts out.
Nz
nvidia-smi)stderrTF.   z1https://packages.unstructured.io/python-telemetrydev)versionplatformpythonarchgpur   
   )paramstimeout)r   r   
subprocesscheck_outputDEVNULLOSErrorCalledProcessErrorrS   r   python_versionsplit
contextlibsuppress	Exceptionrequestsgetr   systemmachinerj   r   )gpu_presentr   s     r,   scarf_analyticsr      s     #4#6#6z7I7IJ XXh557==cB2AFGN			Y	'?&$OO-( ((*;'5K/0668 	
 
(	' Z223 
 
(	's   &D A/D1D.-D.1
D?c           	         US::  a  [        SU 35      e[        [        U 5      U-
  S-   5       Vs/ s H  n[        XX!-    5      PM     sn$ s  snf )zSGenerate n-grams from a list of strings where `n` (int) is the size of each n-gram.r   z!n must be positive, received n =    )rx   rangerQ   tuple)snis      r,   ngramsr      sT     	Av<QC@AA).s1vzA~)>?)>AE!,)>???s   Ac                   U(       d  S[        5       4$ [        U R                  5       U5      n[        UR                  5       U5      nU(       d  S[        5       4$ [        U5      [        U5      -  n[        U5      [        U5      -  S-  nXe4$ )zTCalculate the percentage of common_ngrams between string A and B with reference to Ar   d   )setr   r   rQ   )first_stringsecond_stringr   first_string_ngramssecond_string_ngramscommon_ngrams
percentages          r,   !calculate_shared_ngram_percentager      s     #%x !3!3!5q9!-"5"5"7;#%x+,s3G/HHMm$s+>'??3FJ$$r.   c                   [        5       n[        U R                  5       5      [        UR                  5       5      :  a  [        U R                  5       5      S-
  nO[        UR                  5       5      S-
  nXpSnU(       d$  [        U UU5      u  pBUS:X  a  OUS-  nU(       d  M$  [	        US5      U[        US-   5      4$ )a3  From two strings, calculate the shared ngram percentage.

Returns a tuple containing...
    - The largest n-gram percentage shared between the two strings.
    - A set containing the shared n-grams found during the calculation.
    - A string representation of the size of the largest shared n-grams found.
r   r   r   )r   rQ   r   r   roundrj   )r   r   shared_ngramsr   ngram_percentages        r,   "calculate_largest_ngram_percentager      s     +.%M
< 3}':':'<#==""$%)##%&*&3m*K+
'
 6FA  !1%}c!a%j@@r.   c                   [        U 5      S:w  a  g/ SQnU(       aN  [        U 5      S:X  a?  [        U 5      nUS==   U-  ss'   US==   U-  ss'   US==   U-  ss'   US==   U-  ss'   [        U5      S:X  a1  US   US   :  a%  US   US   :  a  US   US   ::  a  US   US   ::  a  g[        U5      S:H  =(       aC    US   US   s=:*  =(       a    US   :*  Os  =(       a    US   US   s=:*  =(       a    US   :*  $ s  $ )	zTrue if the child_target bounding box is nested in the parent_target.

Box format: [x_bottom_left, y_bottom_left, x_top_right, y_top_right].
The parameter 'add' is the pixel error tolerance for extra pixels outside the parent region
   Fr   r   r   r   r   r   r      T)rQ   list)parent_targetchild_targetaddparent_targetss       r,   is_parent_boxr     s)    =Q!N
s=!Q&m,qS qS qS qS  	LQ!_q 11l1oXYIZ6Z!_q 11l1oXYIZ6Z|! q\!_AAq0AA 	F1aEEN14EEEr.   c                   U S   u  p4U S   u  pVUS   u  pxUS   u  pXS-
  Xd-
  -  nX-
  X-
  -  n[        X75      n[        XH5      n[        XY5      n[        Xj5      n[        SX-
  5      [        SUU-
  5      -  n[        X5      n[        X5      nX-   nUS:X  a  US:X  a  gUU-  S-  nO,US:X  a  US:X  a  gUU-  S-  nOX-   S:X  a  gUX-   U-
  -  S-  n[        US5      UUU4$ )a#  Calculate the percentage of overlapped region.

Calculate the percentage with reference to
the biggest element-region (intersection_ratio_method="parent"),
the smallest element-region (intersection_ratio_method="partial"), or
the disjunctive union region (intersection_ratio_method="total")
r   r   parentr   r   partial)maxminr   )box1box2intersection_ratio_methodx1y1x2y2x3y3x4y4	area_box1	area_box2x_intersection1y_intersection1x_intersection2y_intersection2intersection_areamax_areamin_area
total_areaoverlap_percentages                         r,   calculate_overlap_percentager   +  s;    !WFB!WFB!WFB!WFBRW%IRW%I"kO"kO"kO"kOA@AC	/)E  9(H9(H&J H,q=/(:cA	"i	/q=/(:cA !a'/93HK\3\]add#Q'8ZGGr.   c                `   Su  pVpxU u  pUu  pUu  pUu  nn[        U	U
SS9u  nnnnXt:  a  U SU S3U SU S3/nSnOU(       d  U SU S3U SU S3/nSU 3nOU(       d  U SU S3U SU S3/nSU 3nOX;   d  X;   a  U SU S3U SU S3/nSnO[        X5      u  nnn[        US	5      nU(       d  U SU S3U SU S3/nS
nO\U SU S3U SU S3/n[        UR	                  5       5      [        UR	                  5       5      :  a  UOUnSU-   SU S3-   nSU SU 3nUUUUUUU4$ )au  Classifies the overlapping case for an element_pair input.

There are 5 cases of overlapping:
    'Small partial overlap'
    'Partial overlap with empty content'
    'Partial overlap with duplicate text (sharing 100% of the text)'
    'Partial overlap without sharing text'
    'Partial overlap sharing {calculate_largest_ngram_percentage(...)}% of the text'

Returns:
overlapping_elements: List[str] - List of element types with their `ix` value.
    Ex: ['Title(ix=0)']
overlapping_case: str - See list of cases above
overlap_percentage: float
largest_ngram_percentage: float
max_area: float
min_area: float
total_area: float
)NNNNr   r   (ix=)zSmall partial overlapz&partial overlap with empty content in z#partial overlap with duplicate textr   z$partial overlap without sharing textzof the text from(z-gram)zpartial overlap sharing z% )r   r   r   rQ   r   )box_pair
label_pair	text_pairix_pairsm_overlap_thresholdoverlapping_elementsoverlapping_caser   largest_ngram_percentager   r   type1type2text1text2ix_element1ix_element2r   r   r   r~   	largest_nref_types                          r,   identify_overlapping_caser  \  s5   4\X,> JDLELE&K9U"+:6(J
 0gT+a(gT+a( 
 3 'k]!,'k]!,$  "HwO'k]!,'k]!,$  "HwO^u~'k]!,'k]!,$   E 6X62$a (--Eq'I$+gT+a0gT+a0($ $J  gT+a0gT+a0($ %($6U[[]9K$K5QV-8Qyk;PP%=>V=WWYZbYc#d   r.   c                &    U S   u  pU S   u  p4XX44$ )zAccepts a set of Points and returns the lower-left and upper-right coordinates.

Expects four coordinates representing the corners of a rectangle, listed in this order:
bottom-left, top-left, top-right, bottom-right.
r   r   r   )coordinatesx_bottom_left_1y_bottom_left_1x_top_right_1y_top_right_1s        r,   _convert_coordinates_to_boxr
    s'     (31~$O#.q> M]IIr.   c           
        U u  pVUu  pxSR                  U V	s/ s H  oR                  5       (       d  M  U	PM     sn	5      n
SR                  U V	s/ s H  oR                  5       (       d  M  U	PM     sn	5      nUSS R                  5       nUSS R                  5       n[        U5      n[        U5      nUu  pnnUu  nnnnUU:  =(       a    UU:  nUU:  =(       a    UU:  nSu  nnnnnnSu  nnn U(       a  U(       a  [	        UUSS9u  n    n![	        UUSS9u  nnnn [        XUS	9(       a#  U S
U
 S3U S
U S3/nSU SU 3nSnU S
U
 S3nOH[        XUS	9(       a#  U S
U S3U S
U
 S3/nSU SU 3nSnU S
U S3nO[        U UUX4US9u  nnnnnnn UUUU=(       d    SU=(       d    SU=(       d    SU=(       d    SU=(       d    SU =(       d    S4	$ s  sn	f s  sn	f )a  Identify if overlapping or nesting elements exist and, if so, the type of overlapping case.

Returns:
overlapping_elements: List[str] - List of element types & their `ix` value. Ex: ['Title(ix=0)']
overlapping_case: str - See list of cases above
overlap_percentage: float
overlap_percentage_total: float
largest_ngram_percentage: float
max_area: float
min_area: float
total_area: float
r   r   N)NNNNNN)NNNtotalr   r   )r   r   r   znested z in r   )r   r   )rS   	isnumericr   r
  r   r   r  )"r   r   r   nested_error_tolerance_pxr   r   r   r   r   chr   r   box1_cornersbox2_cornersr  r  r  r	  x_bottom_left_2y_bottom_left_2x_top_right_2y_top_right_2horizontal_overlapvertical_overlapr   parent_elementr   r   overlap_percentage_totalr   r   r   r   r~   s"                                     r,   $identify_overlapping_or_nesting_caser    s   & JDLE''@"2@AK''@"2@AK!"IOOE!"IOOE.t4L.t4LEQBOm]EQBO_m](=8\]_=\&6Z=?;Z	   &6"Hh
.,H&--
) !Q
 >Z&.>
:Hh
 9RS'k]!,'k]!,$  ")tE7;!$ %wd;-q9N<;TU'k]!,'k]!,$  ")tE7;!$ %wd;-q9N **%9$ "( 	a %A %AAAa
 
U A@s   GGG!,G!c                   U S   R                   R                  =(       d    Sn[        U5       Vs/ s H  n/ PM     nn[        U5       Vs/ s H  n/ PM     nn[        U5       Vs/ s H  n/ PM     nn[        U 5       H  u  pU	R                   R                  =(       d    Sn
U
S-
  nU	R                   R                  (       aH  [        [        U	R                   R                  R                  5       S   5      nX[   R                  U5        Xk   R                  U SU	R                   35        X{   R                  U	R                  5        M     Sn/ n[        [        XVU5      SS9 H  u  n
u  nnn[        [        US5      5      n[        [        US5      5      n[        [        US5      5      n[        UUU5       Hu  u  nnn[        UUUUU5      u	  nnnnnnnnn U(       d  M)  UR                  UUUU S	3UU S	3[        US5       S
3[        US5       S
3[        U S5       S
3S.S.5        SnMw     M     X4$ s  snf s  snf s  snf )zLCatch overlapping and nested bounding boxes cases across a list of elements.r   r   pointsrM   F)startr   %u   pxˆ2)r   r  r   r   r   )r   r  r   r   metadataT)r   page_numberr   	enumerater  r   r   to_dictrP   categorytextr    r   r   r  r   )!elementsr  r   	num_pagesr~   pages_of_bboxestext_labelstext_contentixelementr!  n_page_to_ixboxdocument_with_overlapping_flagoverlapping_casespage_bboxespage_labels	page_textpage_bboxes_combinationspage_labels_combinationstext_content_combinationsr   r   r   r   r  r   r   r  r   r   r   r   s!                                    r,   #catch_overlapping_and_nested_bboxesr7  9  s~    %%116QI7<Y7G*H7G!27GO*H05i0@#A0@1B0@K#A16y1A$B1AAR1AL$B *&&227a"Q''vw//;;CCEhOPC)005!((B4r'2B2B1C)DE"))',,7 + &+".0>GO,7?::k;	 $([!(D#E #'[!(D#E $(i)C$D!/2$$%0
+Hj) 5)$
$ "((  !((0D*8,<1C0DA.F8P;S:TTU8V+01+=*>e(D+01+=*>e(D-2:q-A,B%*H% 26.O0
?b *<<C +I#A$Bs   H<I&Ic                    SSK Jn  U" [        5      nSnU  H?  n[        UR                  SS5      nUc
  U(       a  UnOUb  UnX6   R                  U5        MA     [        U5      $ )aP  Group elements by their parent_id metadata field.

Elements with the same parent_id are grouped together.

Args:
    elements: An iterable of Element objects to group.
    assign_orphans: If True, elements with no parent_id (None) will be assigned to
        the same group as the previous element. If False (default), elements with
        no parent are grouped under the None key.

Returns:
    A dictionary mapping parent_id values to lists of elements sharing that parent_id.

Example:
    >>> elements = partition("example.pdf")
    >>> grouped = group_elements_by_parent_id(elements)
    >>> for parent_id, children in grouped.items():
    ...     print(f"Parent {parent_id}: {len(children)} children")

    >>> # Assign orphan elements to previous element's group
    >>> grouped = group_elements_by_parent_id(elements, assign_orphans=True)
r   )defaultdictN	parent_id)collectionsr9  r   getattrr   rP   r   )r&  assign_orphansr9  groupslast_parent_idr,  r:  s          r,   group_elements_by_parent_idr@    si    4 (3>t3DF$(NG,,k4@	&I"&N  )  <r.   c                  4    \ rS rSrSS jrS rS	S jrS rSrg)
FileHandleri  c                D    Xl         [        R                  " 5       U l        g rE   )r3   	threadingLocklock)selfr3   s     r,   __init__FileHandler.__init__  s    "NN$	r.   c                    U R                      [        U R                  5       nUR                  5       nS S S 5        WsS S S 5        $ ! , (       d  f       N= f! , (       d  f       g = frE   )rF  r>   r3   read)rG  filer@   s      r,   	read_fileFileHandler.read_file  s@    YYdnn%yy{ & Y%% Ys!   AA	A
A	A
A&c                    U R                      [        U R                  S5       nUR                  U5        S S S 5        S S S 5        g ! , (       d  f       N= f! , (       d  f       g = f)Nw)rF  r>   r3   write)rG  r@   rL  s      r,   
write_fileFileHandler.write_file  s@    YYdnnc*d

4  + Y** Ys!   AAA
A	A
A&c                    U R                      [        R                  R                  U R                  5      (       a   [        R
                  " U R                  5        S S S 5        g ! , (       d  f       g = frE   )rF  r   pathexistsr3   remove)rG  s    r,   cleanup_fileFileHandler.cleanup_file  s:    YYww~~dnn--		$..) YYs   AA%%
A3)r3   rF  N)r3   rj   )r@   rj   rh   None)	__name__
__module____qualname____firstlineno__rH  rM  rR  rX  __static_attributes__r   r.   r,   rB  rB    s    %!
*r.   rB  )r&   zCallable[_P, List[Element]]r'   ra   r(   rb   rh   zdict[str, Any])r3   rj   rh   r   )r@   list[dict[str, Any]]rA   rj   rh   rZ  )rA   rj   rh   r`  rE   )rV   zstr | list[str]rW   zOptional[str]rh   z.Callable[[Callable[_P, _T]], Callable[_P, _T]])rr   rj   )ry   Iterable[_T]rh   zTuple[_T, Iterator[_T]])ry   ra  rh   r   )ry   zIterable[Any]rh   r   )rh   r   )r   z	list[str]r   intrh   zlist[tuple[str, ...]])r   rj   r   rj   r   rb  rh   z"tuple[float, set[tuple[str, ...]]])r   rj   r   rj   rh   z'tuple[float, set[tuple[str, ...]], str])g        )r   r   r   r   r   floatrh   r   )r  )r   r   r   r   r   rj   rh   z!tuple[float, float, float, float])      $@)
r   $list[Points] | tuple[Points, Points]r   list[str] | tuple[str, str]r   rf  r   rf  r   rc  )r  r   )   rd  )
r   re  r   rf  r   rf  r  rb  r   rc  )r&  zlist['Text']r  rb  r   rc  rh   z!tuple[bool, list[dict[str, Any]]])F)r&  zIterable['Element']r=  r   rh   z$dict[Optional[str], list['Element']])D
__future__r   rc   r   ro   r   r8   r   r   r   r1   rD  	functoolsr   r   	itertoolsr   typingr   r   r	   r
   r   r   r   r   r   r   r   typing_extensionsr   r   unstructured.__version__r   unstructured.documents.elementsr   r   rc  r   __annotations__r   r   DATE_FORMATSr   r   r-   r4   rC   rI   rk   rO   r|   r   r   r   r   r   r   r   r   r   r   r  r
  r  r7  r@  rB  r   r.   r,   <module>rq     s   "      	     & "    2 0= ueUE12Y 2&y &%*%	 %\T]t_
%  	7K
9 !%!%% 4%P 3 	

@@%%% % (	%&AA&)A,A>> &-.H
.H
.H  #.H '	.Hl #'b2b+b +b )	b
  bJJ  &'"&i2i+i +i  #	i
  i\ &'"&I=I="I=  I= '	I=\ !)!)) *)X* *r.   