
    Mi                          S SK r S SKrS SKrS SKrS SKJr  S SKJrJrJ	r	  S SK
r
S SKrS SKJrJr  \ R                   " S5      rS\S\S\4S	 jrS
\S\\   4S jrS rS rS r SS\S\S\R0                  S\S\4
S jjrS rS\4S jrS\4S jrS S\	\R<                  \\   4   S\\    S\	\S4   4S jjr!S S\\\      S\\    S\	\S4   4S jjr"S S\\\      S\\    S\	\S4   4S jjr#S\\\      S\4S jr$S r%g)!    N)Path)ListOptionalUnion)elements_from_jsonelements_to_textzunstructured.evaldocpathoutput_typereturnc                      US:X  a  [        [        U 5      5      nU$ US:X  a  [        U 5      nU$ [        SU S35      e! [         a  n[        R                  SU  35        UeSnAff = f)zu
Convert given input document (path) into cct-ready. The function only support conversion
from `json` or `txt` file.
jsontxtzZFile type not supported. Expects one of `json` or `txt`,                     but received z	 instead.zCould not read the file N)r   r   _read_text_file
ValueErrorloggererror)r	   r
   
output_cctes       t/var/www/eduai.edurigo.com/storigo/production/storigo_env/lib/python3.13/site-packages/unstructured/metrics/utils.py_prepare_output_cctr      s    
& )*<W*EFJ  E!(1J  ""-i9   /y9:s!   A  A  A   
A)
A$$A)dirc                 (   / n[         R                  " U 5       Hu  u  p#nU Hi  n[         R                  R                  X 5      nUS:X  a  UR	                  U5        M;  UR	                  [         R                  R                  Xe5      5        Mk     Mw     U$ )z
Recursively lists all files in the given directory and its subdirectories.
Returns a list of all files found, with each file's path relative to the
initial directory.
.)oswalkpathrelpathappendjoin)r   listdirdirpath_	filenamesfilenamerelative_paths          r   _listdir_recursiver&   %   sp     G!#I!HGGOOG9M#x(rww||MDE " ". N    c                 .    SSSSS.nU R                  US9$ )z
Renames aggregated columns in a DataFrame based on a predefined mapping.

Parameters:
df (pandas.DataFrame): The DataFrame with aggregated columns to rename.

Returns:
pandas.DataFrame: A new DataFrame with renamed aggregated columns.
meanstdevpstdevcount)_mean_stdev_pstdev_count)columns)rename)df
rename_maps     r   _rename_aggregated_columnsr5   7   s$     "WU\]J99Z9((r'   c                  H    [         R                  " U SS9R                  5       $ )zg
Concatenates multiple pandas DataFrame objects along the columns (side-by-side)
and resets the index.
   )axis)pdconcatreset_index)r3   s    r   _format_grouping_outputr<   E   s    
 99Ra ,,..r'   c                   ^^ [        U 5      S:X  a  gU R                  R                  5       nU Vs/ s H*  n[        [        U5      [        S X    5       5      5      PM,     snm[        R
                  " SR                  U4S j[        U5       5       5      5        [        R
                  " S[        T5      -  S[        U5      S-
  -  -   5        U R                  5        H  u  p4/ mU HG  n[        U[        5      (       a  TR                  US 5        M-  TR                  [        U5      5        MI     [        R
                  " SR                  UU4S	 j[        [        T5      5       5       5      5        M     gs  snf )
z<
Displays the evaluation metrics in a formatted text table.
r   Nc              3   J   #    U  H  n[        [        U5      5      v   M     g 7fN)lenstr).0items     r   	<genexpr>_display.<locals>.<genexpr>U   s     C
ST^^
s   !# c              3   P   >#    U  H  u  pUR                  TU   5      v   M     g 7fr?   ljust)rB   iheader
col_widthss      r   rD   rE   W   s%     XEW	Z]33EWs   #&-r7   z.3fc              3   R   >#    U  H  nTU   R                  TU   5      v   M     g 7fr?   rH   )rB   rJ   rL   formatted_rows     r   rD   rE   a   s*     ^D]q]1%++JqM::D]s   $')r@   r1   tolistmaxclickechor   	enumeratesumiterrows
isinstancefloatr   rA   range)r3   headersrK   r"   rowrC   rL   rO   s         @@r   _displayr\   M   s"    2w!|jj!GSZSZCKC
CCDSZJ 
JJsxxXYwEWXXY	JJsS_$sc'lQ.>'??@++-D$&&$$Sz3$$SY/	 
 	

HH^E#mJ\D]^^	
  s   1E<	directoryr$   r3   mode	overwritec                    US;  a  [        S5      eU (       a  [        U 5      R                  SS9  UR                  5       nSUR                  ;   a  US   R                  [        5      US'   SUR                  ;   a!  SUR                  ;   a  UR                  SS/S9nU(       d  [        X5      nUR                  [        R                  R                  X5      S	US
US:H  S9  g)z
Save the metrics report to tsv file. The function allows an option 1) to choose `mode`
as `w` (write) or `a` (append) and 2) to `overwrite` the file if filename existed or not.
)waz/Mode not supported. Mode must be one of [w, a].T)exist_okr,   r$   	connector)by	Fra   )sepr^   indexrK   N)r   r   mkdircopyr1   astypeintsort_values_get_non_duplicated_filenameto_csvr   r   r   )r]   r$   r3   r^   r_   s        r   _write_to_filerp   e   s     :JKKYt,	B"**k((-7RZZK2::$=^^Z8^9/	DII
Y)t$eUY]`U`  r'   c                 \    [         R                  " SU 5      nU(       a  [        US   5      $ g)z
A function that defines the sorting method for duplicated file names. For example,
with filename.ext filename (1).ext filename (2).ext filename (10).ext - this function
extracts the integer in the bracket and sort those numbers ascendingly.
z(\d+)r   )refindallrl   )r$   numberss     r   _sorting_keyrv   }   s+     jj8,G72; r'   c           	      2   UR                  SS5      u  p#S[        R                  " U5       S[        R                  " U5       S3n[        U  Vs/ s H"  n[        R                  " XE5      (       d  M   UPM$     sn[
        S9n/ nU HL  n[        R                  " SU5      n	U	(       d  M#  UR                  [        U	R                  S5      5      5        MN     UR                  5         Sn
U H  nX:X  a  U
S-  n
M    O   US-   [        U
5      -   S	-   U-   $ s  snf )
z
Checks the duplicity of the file name from the list and run the numerical check
of the minimum number needed as extension to not overwrite the exising file.
Returns a string of file name in the format of `filename (<min number>).ext`.
r   r7   ^z(?: \((\d+)\))?\.$)keyz	\((\d+)\)z (z).)rsplitrs   escapesortedmatchrv   searchr   rl   groupsortrA   )	file_listtarget_filenameoriginal_filename	extensionpatternfduplicated_filesru   filer~   counternumbers               r   _uniquity_filer      s     $3#9#9#q#A 299./00A"))IBVAWWXYG)L)Qrxx7Kq)LR^_G 		,-5NN3u{{1~./ !
 LLNGqLG	  t#c'l2T9IEE# Ms   D2Dc                 F    [        [        R                  " U 5      U5      nU$ )zg
Helper function to calls the `_uniquity_file` function. Takes in directory and file name
to check on.
)r   r   r    )r   r$   s     r   rn   rn      s    
 bjjox8HOr'   scoresroundingc                 v    [        U 5      S:X  a  g[        R                  " U 5      nU(       d  U$ [        X!5      $ )z
Find mean from the list. Returns None if no element in the list.

Args:
    rounding (int): optional argument that allows user to define decimal points. Default at 3.
r   N)r@   
statisticsr)   round)r   r   r)   s      r   r-   r-      s4     6{a??6"D  r'   c                     U  Vs/ s H	  o"c  M  UPM     n n[        U 5      S::  a  gU(       d  [        R                  " U 5      $ [        [        R                  " U 5      U5      $ s  snf )z
Find standard deviation from the list.
Returns None if only 0 or 1 element in the list.

Args:
    rounding (int): optional argument that allows user to define decimal points. Default at 3.
Nr7   )r@   r   r*   r   r   r   scores      r   r.   r.      sX     "(=eF=
6{a''!!&)844 >
   A$A$c                     U  Vs/ s H	  o"c  M  UPM     n n[        U 5      S::  a  gU(       d  [        R                  " U 5      $ [        [        R                  " U 5      U5      $ s  snf )z
Find population standard deviation from the list.
Returns None if only 0 or 1 element in the list.

Args:
    rounding (int): optional argument that allows user to define decimal points. Default at 3.
Nr7   )r@   r   r+   r   r   s      r   r/   r/      sX     "(=eF=
6{a  ((""6*H55 >r   c                     [        U 5      $ )z$
Returns the row count of the list.
)r@   )r   s    r   r0   r0      s     v;r'   c                    [         R                  R                  U 5      (       d  [        SU  S35      e [	        U SS9 nUR                  5       nSSS5        U$ ! , (       d  f       W$ = f! [         a  n[        SU  SU 35      eSnAff = f)z?
Reads the contents of a text file and returns it as a string.
zThe file at z does not exist.ignore)errorsNz+An error occurred when reading the file at z: )r   r   existsFileNotFoundErroropenreadOSErrorIOError)r   r   textr   s       r   r   r      s    
 77>>$,tf4D EFFQ$x(A668D ) )( QCD6A3OPPQs4   
A, A	A, 
A)$A, )A, ,
B6BB)ra   T)   )&loggingr   rs   r   pathlibr   typingr   r   r   rR   pandasr9   unstructured.staging.baser   r   	getLoggerr   rA   r   r&   r5   r<   r\   	DataFrameboolrp   rv   r   rn   SeriesrX   rl   r-   r.   r/   r0   r    r'   r   <module>r      s    	 	   ( (   J			.	/ 3 3 *C DI $)/
2 Y]!')||;>QU0 F# F83 !%		4;./ !8C= !QVW\^bWbQc !54( 5HSM 5%PUW[P[J\ 5$6D%) 6Xc] 65QVX\Q\K] 6 4( U Qr'   