
    Jiv                     x   d dl Z d dlZd dlZd dlZd dlmZmZ d dlmZ d dl	m
Z
mZmZmZmZmZmZ d dlZd dlZd dlmZ d dlmZmZmZmZ d dlmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z% d dl&m'Z' d d	l(m)Z) d d
l*m+Z+m,Z, d dl-m.Z.m/Z/m0Z0 d dl1m2Z2 d dl3m4Z4 d dl5m6Z6 d dl7m8Z8m9Z9 d dl:m;Z; d dl<m=Z=  ed      Z>ee+ee   f   Z? ee$j                  e"j                        ZBdeCdeDfdZEde'de?de+fdZF	 	 	 	 dFde'deGdeHdeIdeIdeIdefdZJ	 	 	 	 	 	 dGde'deGd eeG   d!eeG   deHdeIdeIdeIdefd"ZK	 	 	 	 	 	 	 	 	 	 	 dHde'deGd#eHd$eHd%eDd eeG   d!eeG   d&eHd'eId(eId)eHd*eId+eIdee   fd,ZLd-eeee>f   d.e=d/eDd0eId1ede>fd2ZMd3eddfd4ZN G d5 d6      ZO G d7 d8e4      ZPeQd9k(  rd d:lRmSZS  eS         eeT      j                  j                  d;z  d<z  ZV eP       ZW	 eWj                  d=>      ZYeYj                  eVdDz  dEz        Z]eWj                  eYj                          e`e]       yy# eZ$ r eWj                  d=d?d@dAid@dAidBdC      ZYY _w xY w)I    N)BufferedIOBaseTextIOWrapper)Path)ListOptionalTypeUnion	CoroutineAnyTypeVar)	BaseModel)retry_if_exceptionstop_after_attemptwait_exponential_jitterAsyncRetrying)
ExtractAgentExtractConfig
ExtractJob
ExtractRunFileFileDataExtractMode
StatusEnumExtractTargetPaginatedExtractRunsResponse)AsyncLlamaCloud)ApiError)JSONObjectTypeExperimentalWarning)augment_async_errors
SourceText	FileInput)
FileClient)BaseComponent)run_jobs)FieldPrivateAttr)DEFAULT_BASE_URL)ThreadPoolExecutorT)extraction_targetextraction_mode	exceptionreturnc                     t        | t              r| j                  dv S t        | t        j                  t        j
                  t        j                  f      ryy)z#Check if an exception is retryable.)i  i  i  i  i  TF)
isinstancer   status_codehttpxHTTPStatusErrorRequestErrorTimeoutException)r-   s    v/var/www/html/BankruptcyAI-uat/bankruptcy-ai/venv/lib/python3.12/site-packages/llama_cloud_services/extract/extract.py_is_retryable_errorr7   6   sL    )X&$$(AAA	E))5+=+=u?U?UV
     clientdata_schemac                   K   t        |t              r|}n<t        |t              r!t        |t              r|j                         }nt        d      | j                  j                  |       d{   }|j                  S 7 w)z:Convert SchemaInput to a validated JSON schema dictionary.;data_schema must be either a dictionary or a Pydantic model)r:   N)
r0   dicttype
issubclassr   model_json_schema
ValueErrorllama_extractvalidate_extraction_schemar:   )r9   r:   processed_schemavalidated_schemas       r6   _validate_schemarF   A   s     
 +t$&	K	&:k9+M&88:VWW $11LL$ M   '''s   A/B1B2Bjob_idmax_attemptsinitial_waitmax_waitjitterc           	        K   t        t        t              t        |      t	        |||      d      2 3 d{   }|5  | j
                  j                  |       d{   cddd       c S 7 67 # 1 sw Y   HxY w6 yw)z$Get extraction job with retry logic.initialmaxrK   TretrystopwaitreraiseNrG   )r   r   r7   r   r   rB   get_job)r9   rG   rH   rI   rJ   rK   attempts          r6   _get_job_with_retryrX   U   s      ' !45-$\xPVW	 E Eg  	E--55V5DD	E 	EE E	E 	EsH   2BA?A/A?B A3A1 A3#B/A?1A33A<	8	B
project_idorganization_idc           	      
  K   t        t        t              t        |      t	        |||      d      2 3 d{   }|5  | j
                  j                  |||       d{   cddd       c S 7 87 # 1 sw Y   JxY w6 yw)z$Get extraction run with retry logic.rM   TrP   N)rG   rY   rZ   )r   r   r7   r   r   rB   get_run_by_job_id)	r9   rG   rY   rZ   rH   rI   rJ   rK   rW   s	            r6   _get_run_with_retryr]   h   s      ' !45-$\xPVW	  g  	--??% / @  	 		 	sH   2BBA1BB"A5!A3"A5%B1B3A55A>	:	Bcheck_intervalmax_timeoutverbosejob_retry_attemptsjob_max_wait
job_jitterrun_retry_attemptsrun_max_wait
run_jitterc           	        K   t        j                         }d}	 t        j                  |       d{    |dz  }t	        | ||||	       d{   }|j
                  t        j                  k(  rt        | ||||
||       d{   S |j
                  t        j                  k(  rCt        j                         }||z
  |kD  rt        d|       |r|dz  dk(  rt        dd	d
       t        j                  d| d|j
                   d|j                          t        | ||||
||       d{   S 7 7 7 7 w)5Wait for and return the results of an extraction job.r   TN   )rH   rJ   rK   z#Timeout while extracting the file: 
   . )endflushzFailure in job: z
, status: z	, error: )timeperf_counterasynciosleeprX   statusr   SUCCESSr]   PENDING	Exceptionprintwarningswarnerror)r9   rG   r^   r_   r`   rY   rZ   ra   rb   rc   rd   re   rf   start
poll_countjobrm   s                    r6   _wait_for_job_resultr~      sZ      EJ
mmN+++a
'+!
 
 ::+++,/%!   ZZ:---##%CU{[("EfX NOO:?a/cr.MM"6(*SZZL	#))U -/%!  ? 	,
(sF   0E D7E D:6E D<B+E 2D>3E :E <E >E corothread_poolverifyhttpx_timeoutclient_wrapperc                      dt         f fddt         ffd}|j                  |      j                         S )z8Run coroutine in a thread with proper client management.r.   c                  2  K   t        j                  t        j                  dd            } j                  }	 | _         d {   |_        | j	                          d {    S 7 #7 # |_        | j	                          d {  7   w xY ww)Nd   )max_keepalive_connectionsmax_connections)r   timeoutlimits)r2   AsyncClientLimitshttpx_clientaclose)r9   original_clientr   r   r   r   s     r6   wrapped_coroz#run_in_thread.<locals>.wrapped_coro   s     ""!<<#sS

 )55	"*0N':*9N'--/!!  " +:N'--/!!sL   :BA2 
A.A2 B(A0)B.A2 0B2BBBBc                      	 t        j                                S # t        j                  $ r} t	        dt        |              | d } ~ wt        j                  $ r} t        dt        |              | d } ~ ww xY w)NzRequest timed out: zNetwork error: )rq   runr2   r5   TimeoutErrorstrNetworkErrorConnectionError)er   s    r6   run_corozrun_in_thread.<locals>.run_coro   ss    	E;;|~..%% 	F!4SVH=>AE!! 	E!OCF8"<=1D	Es     A;AA;A66A;)r*   submitresult)r   r   r   r   r   r   r   s   ` ``` @r6   run_in_threadr      s>    " " "Ea E h'..00r8   configc                 X   | j                   s| j                  rt        j                  dt               | j
                  r(| j                  t        j                  k(  rt        d      | j                   r8| j                  t        j                  t        j                  fv rt        d      y y )Nz`cite_sources`/`confidence_scores` could greatly increase the size of the response, and slow down the extraction. Results will be available in the `extraction_metadata` field for the extraction run.zU`reasoning` is only supported with BALANCED, MULTIMODAL, or PREMIUM extraction modes.zM`cite_sources` is only supported with MULTIMODAL or PREMIUM extraction modes.)cite_sourcesconfidence_scoresrx   ry   r   use_reasoningr,   r   FASTrA   BALANCED)r   s    r6   _extraction_config_warningr      s    f66S  		
 !![%5%55g  !!k&6&68L8L%MM_  N r8   c                   j   e Zd ZdZ	 	 	 	 	 	 	 	 	 d-dededee   dee   deded	ed
e	de	dee	   dee
   fdZedefd       Zedefd       Zedefd       Zej"                  deddfd       Zedefd       Zej"                  deddfd       Zdeeeef   defdZdedefdZdedefdZdedee   fdZd.dZ d e!ee"e   f   de!e#e"e#   f   fd!Z$d e!ee"e   f   de!ee"e   f   fd"Z%d e!ee"e   f   de!ee"e   f   fd#Z&dede#fd$Z'dedefd%Z(d&eddfd'Z)	 d/d(ed)ede*fd*Z+defd+Z,d.d,Z-y)0ExtractionAgentzTClass representing a single extraction agent with methods for extraction operations.Nr9   agentrY   rZ   r^   r_   num_workersshow_progressr`   r   r   c                 F   || _         || _        || _        || _        || _        || _        || _        || _        |
| _        || _	        |	| _
        d | _        d | _        t        t        dt        j                          xs ddz               | _        t%        |||      | _        y )Nrj   ri      max_workers)_client_agent_project_id_organization_idr^   r_   r   r   r   r   _verbose_data_schema_configr)   minos	cpu_count_thread_poolr#   _file_client)selfr9   r   rY   rZ   r^   r_   r   r   r`   r   r   s               r6   __init__zExtractionAgent.__init__   s     % /,&&**9=37.B!41 9:
 'vz?Kr8   r.   c                 .    | j                   j                  S N)r   idr   s    r6   r   zExtractionAgent.id  s    {{~~r8   c                 .    | j                   j                  S r   )r   namer   s    r6   r   zExtractionAgent.name  s    {{r8   c                 ^    | j                   s| j                  j                  S | j                   S r   )r   r   r:   r   s    r6   r:   zExtractionAgent.data_schema   s%    .2.?.?t{{&&VTEVEVVr8   r:   c                 X    | j                  t        | j                  |            | _        y r   )_run_in_threadrF   r   r   )r   r:   s     r6   r:   zExtractionAgent.data_schema$  s%     !//T\\;7
r8   c                 ^    | j                   s| j                  j                  S | j                   S r   )r   r   r   r   s    r6   r   zExtractionAgent.config+  s!    )-t{{!!G4<<Gr8   r   c                 (    t        |       || _        y r   )r   r   )r   r   s     r6   r   zExtractionAgent.config/  s    "6*r8   r   c                     t        || j                  | j                  | j                  | j                  j
                        S z=Run coroutine in a separate thread to avoid event loop issues)r   r   r   r   r   _client_wrapperr   r   s     r6   r   zExtractionAgent._run_in_thread4  s8    KKLL((
 	
r8   
file_inputc                 T   K   | j                   j                  |       d{   S 7 w)a"  Upload a file for extraction.

        Args:
            file_input: The file to upload (path, bytes, or file-like object)

        Raises:
            ValueError: If filename is not provided for bytes input or for file-like objects
                       without a name attribute.
        Nr   upload_contentr   r   s     r6   upload_filezExtractionAgent.upload_file>  s%      &&55jAAAA   (&(c                 T   K   | j                   j                  |       d{   S 7 w)z8Upload a file from various input types using FileClient.Nr   r   s     r6   _upload_filezExtractionAgent._upload_fileJ  s#     &&55jAAAAr   rG   c                    K   t        | j                  || j                  | j                  | j                  | j
                  | j                  dddddd       d{   S 7 w)rh      <         r9   rG   r^   r_   r`   rY   rZ   ra   rb   rc   rd   re   rf   N)r~   r   r^   r_   r   r   r   r   rG   s     r6   r~   z$ExtractionAgent._wait_for_job_resultN  sd     )<<..((MM'' 11  
 
 	
 
   AA!AA!c                     | j                  | j                  j                  j                  | j                  | j
                  | j                              | _        y)zPersist the extraction agent's schema and config to the database.

        Returns:
            ExtractionAgent: The updated extraction agent
        )extraction_agent_idr:   r   N)r   r   rB   update_extraction_agentr   r:   r   r   r   s    r6   savezExtractionAgent.save`  sJ     ))LL&&>>$(GG ,,{{ ? 
r8   filesc           	      J  K   	 t        |t              s|g}d}nd}|D cg c]  }| j                  |       }}t               5  t	        || j
                  d| j                         d{   }ddd       D cg c]S  }| j                  j                  j                  | j                  |j                  | j                  | j                        U }}t               5  t	        || j
                  d| j                         d{   }ddd       | j                  rRt        |      D ]C  \  }}t        |t        t         f      rt        |      nd}	t#        d	|	 d
|j                          E |rd   S S c c}w 7 # 1 sw Y   xY wc c}w 7 # 1 sw Y   xY ww)z
        Queue multiple files for extraction.

        Args:
            files (Union[FileInput, List[FileInput]]): The files to extract

        Returns:
            Union[ExtractJob, List[ExtractJob]]: The queued extraction jobs
        TFzUploading filesworkersdescr   N)r   file_iddata_schema_overrideconfig_overridezCreating extraction jobsz<bytes/buffer>z Queued file extraction for file z under job_id r   )r0   listr   r    r%   r   r   r   rB   run_jobr   r:   r   r   zipr   r   rw   )
r   r   single_filefileupload_tasksuploaded_files	job_tasksextract_jobsr}   	file_reprs
             r6   queue_extractionz ExtractionAgent.queue_extractionn  s     	C%&GEKK<ABD))$/BB!# 	/7((&"00	0 *N	 '
  LL&&..$(GG%)%5%5 $	 / 
	 
 "# 	!)((/"00	" L	 == 5 	c!+D3+!>CIDT  6ykPSPVPVxX	 #.|A?<?G C*	 	
	 	sq   F#E;F#'F+F ,F0F#<AFF# 'FFFA4F# FFF#FF F#c                 t  K   t        |t              s|g}d}nd}| j                  |       d{   }|D cg c]  }| j                  |j                         }}t               5  t        || j                  d| j                         d{   }ddd       |rd   S S 7 sc c}w 7 # 1 sw Y   xY ww)a  Asynchronously extract data from one or more files using this agent.

        Args:
            files (Union[FileInput, List[FileInput]]): The files to extract

        Returns:
            Union[ExtractRun, List[ExtractRun]]: The extraction results
        TFNzExtracting filesr   r   )	r0   r   r   r~   r   r    r%   r   r   )r   r   r   jobsr}   result_tasksresultss          r6   aextractzExtractionAgent.aextract  s      %&GEKK **511EIJc11#&&9JJ!# 	$(('"00	 G	 )wqz5g5 2J	 	sJ   -B8B#B8"B%B8&'B,B*B,B8%B8*B,,B51B8c                 B    | j                  | j                  |            S )a  Synchronously extract data from one or more files using this agent.

        Args:
            files (Union[FileInput, List[FileInput]]): The files to extract

        Returns:
            Union[ExtractRun, List[ExtractRun]]: The extraction results
        r   r   )r   r   s     r6   extractzExtractionAgent.extract  s     ""4==#788r8   c                 l    | j                  | j                  j                  j                  |            S )z
        Get the extraction job for a given job_id.

        Args:
            job_id (str): The job_id to get the extraction job for

        Returns:
            ExtractJob: The extraction job
        rU   )r   r   rB   rV   r   s     r6   get_extraction_jobz"ExtractionAgent.get_extraction_job  s-     ""4<<#=#=#E#EV#E#TUUr8   c                 l    | j                  | j                  j                  j                  |            S )z
        Get the extraction run for a given job_id.

        Args:
            job_id (str): The job_id to get the extraction run for

        Returns:
            ExtractRun: The extraction run
        rU   )r   r   rB   r\   r   s     r6   get_extraction_run_for_jobz*ExtractionAgent.get_extraction_run_for_job  s7     ""LL&&88 9 
 	
r8   run_idc                 n    | j                  | j                  j                  j                  |             y)zxDelete an extraction run by ID.

        Args:
            run_id (str): The ID of the extraction run to delete
        )r   N)r   r   rB   delete_extraction_run)r   r   s     r6   r   z%ExtractionAgent.delete_extraction_run  s-     	LL&&<<F<K	
r8   pagelimitc                     | j                  | j                  j                  j                  | j                  ||z  |            S )zList extraction runs for the extraction agent.

        Returns:
            PaginatedExtractRunsResponse: Paginated list of extraction runs
        )r   skipr  )r   r   rB   list_extract_runsr   )r   r  r  s      r6   list_extraction_runsz$ExtractionAgent.list_extraction_runs  sE     ""LL&&88$(GGE\ 9 
 	
r8   c                 <    d| j                    d| j                   dS )NzExtractionAgent(id=z, name=))r   r   r   s    r6   __repr__zExtractionAgent.__repr__	  s    $TWWIWTYYKqAAr8   c                 v    	 t        | d      r| j                  j                  d       yy# t        $ r Y yw xY wzCleanup resources properly.r   T)rS   Nhasattrr   shutdownrv   r   s    r6   __del__zExtractionAgent.__del__  ?    	t^,!!***5 - 		   (, 	88)	NNri     r   TFTr   r.   N)r   r   ).__name__
__module____qualname____doc__r   CloudExtractAgentr   r   intboolfloatr   propertyr   r   r=   r:   setterSchemaInputr   r   r
   r   r*   r   r!   r   r   r"   r   r   r~   r   r	   r   r   r   r   r   r   r   r   r   r  r	  r   r8   r6   r   r      s   ^ %))-"!%)+LL !L SM	L
 "#L L L L L L L  L@ C    c     WT W W 
{ 
t 
 
 H H H ]]] t  
9S#q[#9 
a 

BJ 
B4 
BBY B4 B
 
*9M 
$
7@YY/07@ 
z4
++	,7@r69d9o566	z4
++	,6>99d9o569	z4
++	,9
V 
V 
V
 
 
 
C 
D 
 +.

$'
	%
 B# Br8   r   c                       e Zd ZU dZ ed      Zeed<    ed      Zeed<    edd	      Z	e
ed
<    edd	      Ze
ed<    edddd      Ze
ed<    edd	      Zeed<    edd	      Zeed<    edd	      Zee   ed<    edd	      Zee   ed<    e       Zeed<    e       Zeed <    e       Zee   ed!<    e       Zee   ed"<   	 	 	 	 	 	 	 	 	 	 	 d?dee   dee   d
e
de
de
ded$ee   d%ee   dee   dee   def fd&Zd'eeeef   d(efd)Z	 d@d*ed+e d,ee!   d(e"fd-Z#	 	 dAd*ee   d.ee   d(e"fd/Z$d(e%e"   fd0Z&d1ed(d#fd2Z'd3ed(ee(   fd4Z)	 	 dAd5ee   d6ee*ee+f      d(efd7Z,d8e-d(e*e.ee/f   fd9Z0d+e d,e!d:e*e-e%e-   f   d(e*e1e%e1   f   fd;Z2d+e d,e!d:e*e-e%e-   f   d(e*e(e%e(   f   fd<Z3d+e d,e!d:e*e-e%e-   f   d(e*e(e%e(   f   fd=Z4dBd>Z5 xZ6S )CLlamaExtractz:Factory class for creating and managing extraction agents.z%The API key for the LlamaExtract API.)descriptionapi_keyz%The base URL of the LlamaExtract API.base_urlri   z;The interval in seconds to check if the extraction is done.)defaultr"  r^   r  zDThe maximum timeout in seconds to wait for the extraction to finish.r_   r   r   rj   zAThe number of workers to use sending API requests for extraction.)r%  gtltr"  r   Tz-Show progress when extracting multiple files.r   Fz*Show verbose output when extracting files.r`   zSimple SSL verification option.r   r   zTimeout for the httpx client.r   _async_clientr   r   r   NrY   rZ   c                 .   |s#t        j                  dd       }|t        d      |st        j                  dd       xs t        }t        |   |||||||||	|
|       t        j                  |	|
      | _        |	| _	        |
| _
        t        | j                  | j                  | j                        | _        t        t!        dt        j"                         xs dd	z         
      | _        |st        j                  dd       }|| _        || _        y )NLLAMA_CLOUD_API_KEYzThe API key is required.LLAMA_CLOUD_BASE_URL)r#  r$  r^   r_   r   r   rY   rZ   r   r   r`   )r   r   )tokenr$  r   rj   ri   r   r   LLAMA_CLOUD_PROJECT_ID)r   getenvrA   r(   superr   r2   r   _httpx_clientr   r   r   r#  r$  r(  r)   r   r   r   r   r   )r   r#  r$  r^   r_   r   r   rY   rZ   r   r   r`   	__class__s               r6   r   zLlamaExtract.__init__9  s    ii 5t<G !;<<yy!7>RBRH)##'!+' 	 	
 #..fmT*,,,]]++

 /B!41 9:
 #;TBJ% /r8   r   r.   c                     t        || j                  | j                  | j                  | j                  j
                        S r   )r   r   r   r   r(  r   r   s     r6   r   zLlamaExtract._run_in_threadm  s:    KK..
 	
r8   r   r:   r   c                 2   |t        |       nt        }t        |t              rn,t	        |t
              r|j                         }nt        d      | j                  | j                  j                  j                  | j                  | j                  |||            }t        | j                  || j                  | j                  | j                  | j                   | j"                  | j$                  | j&                  | j(                  | j*                        S )a]  Create a new extraction agent.

        Args:
            name (str): The name of the extraction agent
            data_schema (SchemaInput): The data schema for the extraction agent
            config (Optional[ExtractConfig]): The extraction config for the agent

        Returns:
            ExtractionAgent: The created extraction agent
        r<   )rY   rZ   r   r:   r   r9   r   rY   rZ   r^   r_   r   r   r`   r   r   )r   DEFAULT_EXTRACT_CONFIGr0   r=   r?   r   r@   rA   r   r(  rB   create_extraction_agentr   r   r   r^   r_   r   r   r`   r   r   )r   r   r:   r   r   s        r6   create_agentzLlamaExtract.create_agentw  s     &v.+Fk4(Y/%779KM  ##,,DD++ $ 5 5' E 
 %%'' 11..((((,,LL;;,,
 	
r8   r   c                 4   ||t        j                  d       |r6| j                  | j                  j                  j                  |            }nN|rA| j                  | j                  j                  j                  || j                              }nt        d      t        | j                  || j                  | j                  | j                  | j                  | j                  | j                  | j                  | j                   | j"                        S )a  Get extraction agents by name or extraction agent ID.

        Args:
            name (Optional[str]): Filter by name
            extraction_agent_id (Optional[str]): Filter by extraction agent ID

        Returns:
            ExtractionAgent: The extraction agent
        zJBoth name and extraction_agent_id are provided. Using extraction_agent_id.r   )r   rY   z4Either name or extraction_agent_id must be provided.r4  )rx   ry   r   r(  rB   get_extraction_agentget_extraction_agent_by_namer   rA   r   r   r^   r_   r   r   r`   r   r   )r   r   r   r   s       r6   	get_agentzLlamaExtract.get_agent  s
    >d.MM\ ''""00EE(* F E ''""00MM#// N E STT%%'' 11..((((,,LL;;,,
 	
r8   c                    | j                  | j                  j                  j                  | j                              }|D cg c]|  }t        | j                  || j                  | j                  | j                  | j                  | j                  | j                  | j                  | j                  | j                        ~ c}S c c}w )z%List all available extraction agents.)rY   r4  )r   r(  rB   list_extraction_agentsr   r   r   r^   r_   r   r   r`   r   r   )r   agentsr   s      r6   list_agentszLlamaExtract.list_agents  s    $$,,CC++ D 
(  
  ))++ $ 5 5#22 ,, ,,"00{{"00
 	
 
s   BCagent_idc                 n    | j                  | j                  j                  j                  |             y)zzDelete an extraction agent by ID.

        Args:
            agent_id (str): ID of the extraction agent to delete
        r9  N)r   r(  rB   delete_extraction_agent)r   rA  s     r6   delete_agentzLlamaExtract.delete_agent  s5     	,,DD$, E 	
r8   rG   c                    K   t        | j                  || j                  | j                  | j                  | j
                  | j                  dddddd       d{   S 7 w)rh   r   r   r   r   N)r~   r(  r^   r_   r`   r   r   r   s     r6   r~   z!LlamaExtract._wait_for_job_result  sf     )%%..((LL'' 11  
 
 	
 
r   filename	file_pathc                    dddddddddd	d	d
}d}|r$t        |      j                  j                         }n%|r#t        |      j                  j                         }|r	||v r||   S |j                         D cg c]  }|dd 	 }}dj	                  t        |            }|r|dd }t        d| d|       t        d|       c c}w )z9Determine MIME type for a file based on filename or path.z
text/plainztext/csvzapplication/jsonz	text/htmlztext/markdownzapplication/pdfzGapplication/vnd.openxmlformats-officedocument.wordprocessingml.documentz	image/pngz
image/jpeg)z.txtz.csvz.jsonz.htmlz.htmz.mdz.pdfz.docxz.pngz.jpgz.jpegNri   z, zUnsupported file type: 'z'. Supported formats are: zaCould not determine file type. Please provide a filename with one of these supported extensions: )r   suffixlowerkeysjoinsortedrA   )	r   rF  rG  MIME_TYPE_MAP	extensionextsupported_extensionssupported_listext_without_dots	            r6   _get_mime_typezLlamaExtract._get_mime_type  s    !' "%^ !
$ 	X--335IY..446I m3 ++ 4A3E3E3GHCABHH6*>#?@'mO*?*; <**8)9; 
 s  uC  tD  E   Is   9Cr   c                     t        |t              r|S t        |t              r|j                  |j                  S |j                  t        |j                  t
              r|j                  }|j                  }n:t        |j                  t        t        f      rSt        |j                  d      5 }|j                         }ddd       |j                  xs t        |j                        }nt        |j                  t        t        f      rt        |j                  d      r?|j                  j                         }t        |t              r|j                  d      }n|}nt        d      |j                  xs t!        |j                  dd      }n!t        dt#        |j                               t%        j&                        j)                  d      }| j+                  |      }t-        ||	      S t        d
      t        |t        t        f      rht        |d      5 }|j                         }ddd       t%        j&                        j)                  d      }| j+                  |      }t-        ||	      S t        |t
              rt        d      t        |t        t        f      rt        |d      r|j                         }t        |t              r|j                  d      }n|}t%        j&                  |      j)                  d      }t!        |dd      }| j+                  |      }t-        ||	      S t        d      t        dt#        |             # 1 sw Y   xY w# 1 sw Y   =xY w)zFConvert FileInput to FileData or text string for stateless extraction.Nrbreadzutf-8z#File object must have a read methodr   zUnsupported file type: )rF  )data	mime_typez0SourceText must have either text_content or file)rG  ziCannot determine file type from raw bytes. Please use SourceText with a filename, or provide a file path.zUnsupported file input type: )r0   r   r!   text_contentr   bytesrF  r   r   openrW  r   r   r  encoderA   getattrr>   base64	b64encodedecoderT  r   )r   r   rX  rF  fcontentencoded_datarY  s           r6   _convert_file_to_file_dataz'LlamaExtract._convert_file_to_file_dataH  s    j$'j*-&&2!...,joou5%??D)22H
#t=joot4 ( vvx()22Jc*//6JH
.-1PQz7",//"6"6"8%gs3#*>>'#:D#*D()NOO)22  g"7H %'>tJOO?T>U%VWW  &//5<<WE !///B	\YGG !STT
S$K0j$'  1vvx !++D188AL++j+AICC
E*{  
^]$CDz6*$//+gs+">>'2D"D%//5<<WE #:vt< ///B	\YGG !FGG <T*=M<NOPPw( (:   s   3M&'M3&M03M=r   c           	        K   t        |       t        | j                  |       d{   }t        |t              s|g}g }|D ]  }| j                  |      }t        |t              rd|j                  i}nt        |t              rd|i}nd|i} | j                  j                  j                  d| j                  | j                  ||d| d{   }	|j                  |	        t        |      dk(  r|d   S |S 7 7 .w)	a;  Queue extraction jobs using stateless extraction (no agent required).

        Args:
            data_schema: The schema defining what data to extract
            config: The extraction configuration
            files: File(s) to extract from

        Returns:
            ExtractJob or list of ExtractJobs
        Nr   textr   )rY   rZ   r:   r   ri   r   r  )r   rF   r(  r0   r   re  r   r   r   rB   extract_statelessr   r   appendlen)
r   r:   r   r   rD   r   r   file_data_or_text	file_argsr}   s
             r6   r   zLlamaExtract.queue_extraction  s      	#6*!1$2D2Dk!RR%&GE 	J $ ? ?
 K+T2&(9(<(<=	-s3#%67	 $%67	J**88JJ ++ $ 5 5,	
  C KK)	, d)q.tAw2d29 S&s"   %DC>B)DD -D Dc                   K   | j                  |||       d{   }t        |t              rYg }|D ]P  }| j                  |j                         d{   }|t        d|j                         |j                  |       R |S | j                  |j                         d{   }|t        d|j                         |S 7 7 t7 $w)a@  Run stateless extraction and wait for results.

        Args:
            data_schema: The schema defining what data to extract
            config: The extraction configuration
            files: File(s) to extract from

        Returns:
            ExtractRun or list of ExtractRuns with the extraction results
        Nz(Failed to get extraction result for job )r   r0   r   r~   r   RuntimeErrorri  )r   r:   r   r   r   runsr}   r   s           r6   r   zLlamaExtract.aextract  s       **;FFdD!D ! 55cff==;&B366(K  C ! K11$''::C{"%MdggY#WXXJ! G
 > ;s4   CC9CCAC%C
&!CC
Cc                 F    | j                  | j                  |||            S )aV  Run stateless extraction and wait for results (synchronous version).

        Args:
            data_schema: The schema defining what data to extract
            config: The extraction configuration
            files: File(s) to extract from

        Returns:
            ExtractRun or list of ExtractRuns with the extraction results
        r   )r   r:   r   r   s       r6   r   zLlamaExtract.extract  s"      ""4==fe#LMMr8   c                 v    	 t        | d      r| j                  j                  d       yy# t        $ r Y yw xY wr  r  r   s    r6   r  zLlamaExtract.__del__  r  r  )NNri   r  r   TNNTr   Fr   )NNr  )7r  r  r  r  r&   r#  r   __annotations__r$  r^   r  r_   r   r   r  r`   r   r   r   r  r'   r(  r   r   r)   r   r   r   r
   r   r*   r   r  r   r   r7  r<  r   r@  rD  r   r~   r	   r   rT  r"   r   r   re  r   r   r   r   r  __classcell__)r1  s   @r6   r!  r!    s   D%LMGSM&MNHcNQNC  ZK  W	K   "QM4  #OGT  #"CFHTN  &+ ?&M8E?  &1]M?2'2}L$4!,K#.&1mhsm3 "&"&"$()-!%)+20#20 3-20 	20
 20 20 20 SM20 "#20 20  20 20h
9S#q[#9 
a 
 +/	4
4
 !4
 '	4

 
4
p # 0
sm0
 SM0
 
	0
d
T/2 
2

S 

T 


 
*9M 
( #'0403-0 E#t),-0 
	0dJQ#JQ	xd"	#JQX-3 -3 -3 YY/0	-3
 
z4
++	,-3^      YY/0	 
 
z4
++	, DN N N YY/0	N
 
z4
++	,N$r8   r!  __main__)load_dotenvtestsrX  z
test-agent)r   objectr>   string)titlesummary)r>   
propertiesslidezconocophilips.pdf)r   ri   r   r   )NNr   ri   r   r   )ri   r  FNNr   r   r   r   r   r   )arq   r_  r   ro   ior   r   pathlibr   typingr   r   r   r	   r
   r   r   rx   r2   pydanticr   tenacityr   r   r   r   llama_cloudr   r  r   r   r   r   r   r   r   r   r   llama_cloud.clientr   llama_cloud.core.api_errorr   "llama_cloud_services.extract.utilsr   r   llama_cloud_services.utilsr    r!   r"   !llama_cloud_services.files.clientr#   llama_index.core.schemar$   llama_index.core.async_utilsr%    llama_index.core.bridge.pydanticr&   r'   llama_index.core.constantsr(   concurrent.futuresr)   r*   r  PER_DOC
MULTIMODALr5  BaseExceptionr  r7   rF   r   r  r  rX   r]   r~   r   r   r   r!  r  dotenvru  __file__parentdata_dir	extractorr<  r   rv   r7  r   r   rD  r   rw   r  r8   r6   <module>r     s     	  ,  G G G       / / S R 8 1 1 ? 7 1CL NDO34&#++** = T ((*5((. EEE E 	E
 E E E, !%%)  c]	
     8  $%);;; ; 	;
 ; ; c]; ; ; ; ; ; ; j;|1
CaK
 1#1 1 	1
 1 1D}  (] ]@	h= hV z"M  H~$$++g5>HI
###6 mmHw.1DDEG588$	'NI .  

&& $h/ &1	


s   H !H98H9