
    ;3hE                    d   d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZmZmZ ddlmZ ddlmZ ddl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mZm Z mZm!Z! ddl"m#Z#m$Z$m%Z% ddl&m'Z'm(Z( ddl)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1 ddl2m3Z3 erddl4m5Z5 dZ6	 	 	 	 	 	 	 	 	 	 	 	 	 d+ddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d,dZ7 e        G d d             Z8	 	 	 	 	 	 d-dZ9 G d d      Z: edd       G d de             Z;d.d Z<d! Z=	 	 	 d/	 	 	 	 	 	 	 	 	 d0d"Z>	 	 	 d/	 	 	 	 	 	 	 	 	 d1d#Z? e       d2d$       Z@	 	 	 d3	 	 	 	 	 	 	 	 	 d4d%ZA ed&'      	 	 	 	 d5	 	 	 	 	 	 	 d6d(       ZB ed&'      	 	 	 	 d7	 	 	 	 	 	 	 d6d)       ZC ed&'      	 	 	 	 d8	 	 	 	 	 	 	 d6d*       ZDy)9zK
Defines helper methods useful for loading and caching Interface examples.
    )annotationsN)CallableIterableSequence)partial)Path)TYPE_CHECKINGAnyLiteralOptional)utils)document)
componentsoauthprocessing_utilsroutesr   
wasm_utils)ContextLocalContextget_blocks_context)GradioModelGradioRootModel)
Dependency	EventData)Error)	CSVLogger)I18nData)UnhashableKeyDict)	Componentlog.csvT)example_labelsvisiblec                   t        di d| d|d|d|d|d|d|d|d	|d
|	d|
d|d|d|d|d|d|dd}|j                          |S )zTop-level synchronous function that creates Examples. Provided for backwards compatibility, i.e. so that gr.Examples(...) can be used to create the Examples component.examplesinputsoutputsfncache_examples
cache_modeexamples_per_page	_api_modelabelelem_idrun_on_click
preprocesspostprocessapi_namebatchr!   r"   _initiated_directlyF )Examplescreate)r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r!   r"   examples_objs                     N/var/www/html/audio-gradio/venv/lib/python3.12/site-packages/gradio/helpers.pycreate_examplesr9   %   s    *    	
 &  ,    "       &!" #$ "%L(     c                      e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 ddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZd ZddZddZdd	Zd
 Z	dddZ
ddZy)r5   aK  
    This class is a wrapper over the Dataset component and can be used to create Examples
    for Blocks / Interfaces. Populates the Dataset component with examples and
    assigns event listener so that clicking on an example populates the input/output
    components. Optionally handles example caching for fast inference.

    Demos: calculator_blocks
    Guides: more-on-examples-and-flagging, using-hugging-face-integrations, image-classification-in-pytorch, image-classification-in-tensorflow, image-classification-with-vision-transformers, create-your-own-friends-with-a-gan
    NT)r!   r"   r3   c                  |rt        j                  d       d| _        |2t        j                  dd      j                         dv rH|F|Dd| _        n<|dk(  rt        j                  d	       d| _        n|d
v r|| _        nt        d|       | j                  r||t        d      t        j                  d      x}rE|C|j                         dk(  rd}n-|j                         dk(  rd}nd}t        j                  d       | j                  r|dk(  rd| _        t        |t              s|g}|rt        |t              s|g}t               j                         }|t        d      t        |t              r#t        |      dk(  st        |d   t              rnMt        |t              r t        |      dk(  r|D cg c]  }|g }}nt        |t              rt        |      j                         st        d|       |}t        |      t         z  j                         sDt        |      dk(  r$t        j"                  |      D cg c]  }|g }}nt        dt         z         t%        t        |      t         z        5 }t        t'        j(                  |            }t+        dt        |            D cg c]  }||   dt        |        }}ddd       nt        d      dgt        |      z  }|D ]  }t-        |      D ]  \  }}|		 d||<      t1        ||d      D cg c]
  \  }}|s	| }}}|D cg c]%  }t1        ||d      D cg c]	  \  }}|r| c}}' } }}}|"t        |      t        |      k7  rt        d      || _        | | _        || _        || _        || _        |xs g | _        || _        || _         || _!        || _"        || _#        || _$        || _%        || _&        ddl'm(}! tS        jT                  |      5   |!jV                  |tY        jZ                  |       d|	||
||      | _.        ddd       t_        ddd      | _0        tS        jb                         t        | j\                  jd                        z  | _3        t        jh                  jk                  d      dk(  r9| jf                  j                         rtm        jn                  | jf                         t        | jf                        dz  | _8        t        | jf                        dz  | _9        || _:        d| _;        ty               | _=        | j\                  j|                  rRt-        | j4                        D ]:  \  }"}| j                  |      | jz                  | j\                  j|                  |"   <   < | j                  dk(  rht        d tS        j                  | jf                         d!d"       t        | jp                        j                         rt        d#       t        d$       yyc c}w c c}w c c}w # 1 sw Y   `xY w# t.        $ r Y Pw xY wc c}}w c c}}w c c}}}w # 1 sw Y   'xY w)%aS  
        Parameters:
            examples: example inputs that can be clicked to populate specific components. Should be nested list, in which the outer list consists of samples and each inner list consists of an input corresponding to each input component. A string path to a directory of examples can also be provided but it should be within the directory with the python file running the gradio app. If there are multiple input components and a directory is provided, a log.csv file must be present in the directory to link corresponding inputs.
            inputs: the component or list of components corresponding to the examples
            outputs: optionally, provide the component or list of components corresponding to the output of the examples. Required if `cache_examples` is not False.
            fn: optionally, provide the function to run to generate the outputs corresponding to the examples. Required if `cache_examples` is not False. Also required if `run_on_click` is True.
            cache_examples: If True, caches examples in the server for fast runtime in examples. If "lazy", then examples are cached (for all users of the app) after their first use (by any user of the app). If None, will use the GRADIO_CACHE_EXAMPLES environment variable, which should be either "true" or "false". In HuggingFace Spaces, this parameter is True (as long as `fn` and `outputs` are also provided). The default option otherwise is False.
            cache_mode: if "lazy", examples are cached after their first use. If "eager", all examples are cached at app launch. If None, will use the GRADIO_CACHE_MODE environment variable if defined, or default to "eager".
            examples_per_page: how many examples to show per page.
            label: the label to use for the examples component (by default, "Examples")
            elem_id: an optional string that is assigned as the id of this component in the HTML DOM.
            run_on_click: if cache_examples is False, clicking on an example does not run the function when an example is clicked. Set this to True to run the function when an example is clicked. Has no effect if cache_examples is True.
            preprocess: if True, preprocesses the example input before running the prediction function and caching the output. Only applies if `cache_examples` is not False.
            postprocess: if True, postprocesses the example output after running the prediction function and before caching. Only applies if `cache_examples` is not False.
            api_name: Defines how the event associated with clicking on the examples appears in the API docs. Can be a string or False. If set to a string, the endpoint will be exposed in the API docs with the given name. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use the example function.
            batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. Used only if cache_examples is not False.
            example_labels: A list of labels for each example. If provided, the length of this list should be the same as the number of examples, and these labels will be used in the UI instead of rendering the example values.
            visible: If False, the examples component will be hidden in the UI.
        zXPlease use gr.Examples(...) instead of gr.examples.Examples(...) to create the Examples.FNGRADIO_CACHE_EXAMPLES )truelazyTr@   zIn future versions of Gradio, the `cache_examples` parameter will no longer accept a value of 'lazy'. To enable lazy caching in Gradio, you should set `cache_examples=True`, and `cache_mode='lazy'` instead.)TFzCThe `cache_examples` parameter should be either True or False, not z8If caching examples, `fn` and `outputs` must be providedGRADIO_CACHE_MODEeagerzeThe `GRADIO_CACHE_MODE` environment variable must be either 'eager' or 'lazy'. Defaulting to 'eager'.z'The parameter `examples` cannot be Noner      z#Could not find examples directory: z8Could not find log file (required for multiple inputs): zThe parameter `examples` must either be a string directory or a list(if there is only 1 input component) or (more generally), a nested list, where each sublist represents a set of inputs.strictzlIf `example_labels` are provided, the length of `example_labels` must be the same as the number of examples.)r   tuple)r   samplestyper,   samples_per_pager-   r"   sample_labelsr    )simplify_file_dataverbosedataset_file_nameGRADIO_RESET_EXAMPLES_CACHETruezindices.csvzWill cache examples in 'z' directory at first use.)endzYIf method or examples have changed since last caching, delete this folder to reset cache.
)Bwarningswarnr(   osgetenvlower
ValueError
isinstancer   r   absolutelistlenstrexistsFileNotFoundErrorLOG_FILElistdiropencsvreaderrange	enumerate
IndexErrorzipr$   non_none_examplesr%   input_has_examplesinputs_with_examplesr&   r'   r+   r/   r0   r1   r2   r!   working_directorygradior   r   set_directoryDatasetcopydeepcopydatasetr   cache_loggerget_cache_folder_idcached_folderenvirongetshutilrmtreecached_filecached_indices_filer.   cache_eventr   non_none_processed_examplesrG   _get_processed_exampleprintabspath)#selfr$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r!   r"   r3   cache_mode_envrk   elogsiri   exampleidxexample_for_inputinpkeeprj   exrh   r   indexs#                                      r8   __init__zExamples.__init__^   s^   R MMj $!		126<<>BRRN'&*#v%MMa #)D},"0DUVdUef  BJ'/WXX ii(;<<N<*BT##%0$
%%'61#
$
-
 :#7"(D&(+XF:gx8iG FOO-FGG$'MQ*Xa[$"?x&3v;!+;%-..H.#&>((*'9(D  !)NX-557v;!#-/ZZ-ABBHB+R"# 
 $x.834 #CJJt$45H<A!S]<S 78Mc&k2 H    G  $Ws6{2 	G*3G*< &&$026*3/	 $'v/A%#P 
S$TXC 
  
 $
 
  #&g/A%"PR 
 
 %#n*=X*N~  !!2"4$8!}""$&.6
,!2%  !23 
	-:--/&78!2,	DL
	 &$ey
 #335DLL<L<L8MMJJNN89VC""))+MM$,,- 2 23i?#'(:(:#;m#K (.2+<+>(<<"+D,B,B"C w//8 001E1Ee1LM
 &(*5==9K9K+L*MMfg D$$%,,.o $K )Q /  C  & &  

<
	 
	sl    
X2
X76Y=X<YY.
Y9YY*Y$*Y*3Y1<YY	YY$Y*1Y;c                   || j                   v r| j                   |   S t        j                  | j                        5  g }t	        | j
                  |d      D ]e  \  }}|j                  |      }t        |t        t        f      r|j                         }t        j                  ||d      }|j                  |       g 	 ddd       |S # 1 sw Y   S xY w)a  
        This function is used to get the post-processed example values, ready to be used
        in the frontend for each input component. For example, if the input components are
        image components, the post-processed example values will be the a list of ImageData dictionaries
        with the path, url, size, mime_type, orig_name, and is_stream keys. For any input components
        that should be skipped (b/c they are None for all samples), they will simply be absent
        from the returned list

        Parameters:
            example: a list of example values for each input component, excluding those components
            that have all None values
        FrD   T)r0   N)r}   r   rm   rk   rg   rj   r0   rX   r   r   
model_dumpr   move_files_to_cacheappend)r   r   sub	componentsampleprediction_values         r8   r~   zExamples._get_processed_example5  s     d66633G<<  !7!78 	-C%())75& -!	6 $-#8#8#@ .+0NO'7'B'B'D$#3#G#G$ $$ 
 

+,-	- 
	- 
s   BCCc           
         t               }t        j                  xs |r|j                  nd _        |rw j                  r/ j                  j                  j	                   j
                          j                  r fd} fd} j                  j                  | j                  g j                  dddd      j                  | j                  g j                  d j                  d      x _         _        y fd} j                  j                  | j                  g j                  ddd j                  d	       _         j                   rU j"                  t%        d
       j                  j                   j"                   j                   j                  d       yyt'        j(                  d j                  rdnd d       y)z2Creates the Dataset component to hold the examplesNc                Z    | \  }}j                  |      }t        j                  |      S N)r~   r   resolve_singleton)example_tuple_example_valueprocessed_exampler   s       r8   load_example_inputz+Examples.create.<locals>.load_example_input`  s0    '4$A}(,(C(CM(R% 223DEEr:   c                Z    | \  }}j                  |      }t        j                  |      S r   )load_from_cacher   r   )r   
example_idr   cached_outputsr   s       r8   load_example_outputz,Examples.create.<locals>.load_example_outpute  s-    $1MJ%)%9%9*%EN 22>BBr:   hiddenF)r%   r&   show_progressr0   queueshow_api)r%   r&   r0   r1   r   c           	     Z   | \  }}j                  |      }t        j                        dk(  r't        dd|d   ij                  j
                  d   S t        t        j                              D cg c])  }t        dd||   ij                  j
                  |   + c}S c c}w )NrC   valuer   r4   )r~   r[   rj   updaterq   component_propsrd   )r   r   r   r   r   r   s        r8   load_examplez%Examples.create.<locals>.load_example|  s    '4$A}(,(C(CM(R%4445:%  "3A"6 "ll::1=   "'s4+D+D'E!F
 	  "3A"6"ll::1=  s   7.B()r%   r&   r   r0   r   r1   r   z.Cannot run_on_click if no function is provided)r%   r&   r   zhIf an Examples object is created outside a Blocks Context, make sure to call `examples.dataset.render()`zand `examples.create()`r>   z) to render the examples in the interface.)r   r   
root_blockextra_startup_eventsr   _start_cachingr(   rq   clickr%   thenr&   r1   r|   load_input_eventrj   r.   r'   rW   rR   rS   )r   blocks_configr   r   r   s   `    r8   r6   zExamples.createT  s   *,!,, 
(5M$$4 	 44;;D<O<OP""F
C
 <@<<;M;M& LL> KK"* %" <N < $' LL> LL %!]]"   4#8$  )-(:(:  LL> 55"* %!]]" ); 	)% $$ww(L  ))..#{{ $!&	 /  % MMz  Y]  Yl  Yl  |U  rt  {u  u^  _r:   c                  K   ddl }|j                         5 }| j                  D cg c]  }|j                          c} |j	                  | j
                  | j                  | j                         ddd       j                          |j                  |j                  j                  d   d       d{   S c c}w # 1 sw Y   PxY w7 w)a  
        This is a way that we can postprocess the data manually, since we set postprocess=False in the lazy_cache
        event handler. The reason we did that is because we don't want to postprocess data if we are loading from
        the cache, since that has already been postprocessed. We postprocess this data manually if we are calling
        the function using the _handle_callable_as_generator() method.
        r   N)rl   Blocksr&   renderloadr'   r%   unrenderpostprocess_datadefault_configfns)r   outputgrdemos       r8   _postprocess_outputzExamples._postprocess_output  s      	YY[ 	:D+/<<8V]]_8IIdggt{{DLL9	: 	**4+>+>+B+B1+EvtTTT 9	: 	: Us9   CC B;4C 1AC6C7C;C  C	Cc                "   t        | j                        j                         r[t        | j                        5 }|D cg c]  }t	        |j                                }}d d d        |v r|j                  |      }|S y c c}w # 1 sw Y   &xY wr   )r   r{   r]   ra   intstripr   )r   example_indexflinecached_indicescached_indexs         r8   _get_cached_index_if_cachedz$Examples._get_cached_index_if_cached  s    (()002d../ C1@A!B#djjl"3!B!BC.-33MB##	 "CC Cs   B B B BBc                  K   | j                   rZ| j                  D ]K  }t        |D cg c]  }||	 c}      t        | j                        k7  s6t	        j
                  d        n | j                   du r?t        j                  rt	        j
                  d       y | j                          d {    y y c c}w 7 w)NaQ  Examples will be cached but not all input components have example values. This may result in an exception being thrown by your function. If you do get an error while caching examples, make sure all of your inputs have example values for all of your examples or you provide default values for those particular parameters in your function.TzSetting `cache_examples=True` is not supported in the Wasm mode. You can set `cache_examples='lazy'` to cache examples after first use.)	r(   r$   r[   r%   rR   rS   r   IS_WASMcache)r   r   r   s      r8   r   zExamples._start_caching  s     == 	W?r?@CDTTMMj 	 $&!!  ^ jjl"" ' @( #s'   %B>B7
B7
B>AB>0B<1B>c           	        K    j                   t        d      t         j                        j	                         r/|-t        dt        j                   j                         d       yt        dt        j                   j                         d        j                  j                   j                   j                         g t        j                   j                        r	 fd}|}n4t        j                   j                        r	 fd}|}n j                  }d	d
lm}  j                   j$                  j'                   |t(        j                   d      g| j*                   j                   j,                  xr  j.                    j0                  xr  j.                    j2                        \  }} j                  t5        d      t7         j8                        D ]0  \  }}|||k7  r j;                  |      }	t7         j<                        D ]  \  }
}|r	|	j?                  |
d         j2                  r|	D cg c]  }|g }	}t        j@                         5   j                   jC                   j                   j$                  jD                  |   |	d       d{   }ddd       d   }rtG         j                  |       d{   } j2                  r|D cg c]  }|d	   	 }} j                  jI                  |       3  j                   j$                  jD                  jK                  |       yc c}w 7 # 1 sw Y   xY w7 c c}w w)z
        Caches examples so that their predictions can be shown immediately.
        Parameters:
            example_id: The id of the example to process (zero-indexed). If None, all examples are cached.
        Nz1Cannot cache examples if not in a Blocks context.zUsing cache from 'zg' directory. If method or examples have changed since last caching, delete this folder to clear cache.
zCaching examples at: ''c                 v    d }j                           j                  |  D ]  }j                  |        |S r   clearr'   r   argsxgenerated_valuesr   s     r8   get_final_itemz&Examples.cache.<locals>.get_final_item  s@    A$**,$TWWd^ 3(//23Hr:   c                    K   d }j                           j                  |  2 3 d {   }j                  |       7 6 |S wr   r   r   s     r8   r   z&Examples.cache.<locals>.get_final_item  sL     A$**,#*477D> 3 3a(//23>Hs%   "AAA AA AAr   )EventListenerMethodr   )r'   r%   r&   r/   r0   r2   self.outputs is missing)block_fnr%   requestdata)&r   r   r   rz   r]   r   r   r   ru   rr   setupr&   inspectisgeneratorfunctionr'   isasyncgenfunctiongradio.eventsr   r   set_event_triggerr   r%   r/   r+   r0   r2   rW   re   rh   r~   ri   insertMatplotlibBackendManangerprocess_apir   "merge_generated_values_into_outputflagpop)r   r   r   r'   r   r   fn_indexr   r   processed_inputr   r   r   
predictionr   r   s   `              @r8   r   zExamples.cache  s     ??"KLL  !((*z/A$U]]43E3E%F$G  Hp  q *5==9K9K+L*MQOP##DLL$2D2DE!**4773 $++DGG4 $WW ://88JJ$W%7%7@A{{??A4>>/A ,,CT^^1Cjj K KAx ||# !:;;'(>(>? /
7)a:o"&"="=g"F#,T-D-D#E <KE4'..ud;< ::<K&L5w&LO&L446 '+'B'B!%!?!?!C!CH!M. $ (C ( "J $F+##E&6$ F ::4:;5eAh;F;!!&&v.-/0 OO**..228<! 'M"  <sb   H(M--$M-
MM-1AM4M5M9)M-"M&#M-7M(AM-MM#	M-(M-c                   | j                   dk(  r| j                  |      x}t        j                  | j                  |       t        | j                  d      5 }|j                  | d       ddd       t        | j                        5 }t        |j                               dz
  }ddd       n|}t        | j                  d      5 }t        t        j                  |            }ddd       |dz      }g }| j                  t        d      t!        | j                  |d	
      D ]z  \  }}	|	}
	 t#        j$                  |	      }t'        |t              rt'        |t(        j*                        r|}
t-        j.                  |      st1        d      |j3                  |       | |S # 1 sw Y   =xY w# 1 sw Y   xY w# 1 sw Y   xY w# t        t0        t4        f$ r# |j3                  |j7                  |
             Y w xY w)zLoads a particular cached example for the interface.
        Parameters:
            example_id: The id of the example to process (zero-indexed).
        r@   NarQ   rC   zutf-8)encodingr   FrD   zvalue wasn't an update)r(   r   client_utilssynchronize_asyncr   ra   r{   writer[   	readlinesrz   rZ   rb   rc   r&   rW   rg   astliteral_evalrX   r   Filer   is_prop_update	TypeErrorr   SyntaxErrorread_from_flag)r   r   r   r   r   r$   r   r   r   r   value_to_usevalue_as_dicts               r8   r   zExamples.load_from_cache(  s   
 &( $ @ @ LLU..tzz:F$22C8 /AGGzl"-./$223 8q!$Q[[]!3a!7J8 8 *
$""W5 	/CJJu-.H	/ :>*<<677 #DLL'% H 	FIu LF # 0 0 7 mT2zz8 $1L++M:#$<==m,	F  =/ /8 8
	/ 	/* 	;7 Fi66|DEFs7   F)F6
G3A2G)F36G G4HH)NNNN
   Fr5   NFTTr   F)$r$   !list[Any] | list[list[Any]] | strr%   Component | Sequence[Component]r&   &Component | Sequence[Component] | Noner'   Callable | Noner(   bool | Noner)   Literal['eager', 'lazy'] | Noner*   r   r+   boolr,   str | I18nData | Noner-   
str | Noner.   r  r/   r  r0   r  r1   str | Literal[False]r2   r  r!   list[str] | Noner"   r  r3   r  returnNone)r  rZ   )r  
int | Noner   )r   r
  r  r	  )r   r   r  z	list[Any])__name__
__module____qualname____doc__r   r~   r6   r   r   r   r   r   r4   r:   r8   r5   r5   R   s4    ;?"&*6:!#'1"" )7!U$ ,0$()U3U 0U 8	U
 U $U 4U U U %U U U U U 'U  !U$ )%U& 'U( ")Un>QfU#2N=`&r:   r5   c                z  K   ddl m} t        |       D ]  \  }}t        ||      s|j                  s!g }d }t        |      D ]  \  }}	t        |       dkD  r|	|   }	|j                  |	      }
t        |
t        t        f      r|
j                         }
|j                  |
d|dk(         d {   }|dk(  r.|d   j                  d      x}rt        |      j                  dd  }|d   s|j                  |d   d           |j                  ||       d {   }|j                         ||<     |S 7 7 w)Nr   )StreamingOutputrC   r>   	orig_namer   )desired_output_format)gradio.components.baser  re   rX   	streamingr[   r0   r   r   r   stream_outputrw   r   suffixr   combine_stream)r   r   r   r  output_indexoutput_componentbinary_chunksr  r   chunkprocessed_chunkstream_chunkr  combined_outputs                 r8   r   r   Q  se     7*3J*? @&&&8=M=W=WM$(!%&67 B5z?Q&!,/E"2">">u"Eo_/MN&5&@&@&BO%5%C%C#Ra&   6LO,?,?,LLyL,0O,B,B12,F)?!((a)@AB %5$C$C5J %D % O $3#=#=#?F< )@, M s4   %D;D;A8D;-D7.<D;+/D;D9D;9D;c                  4    e Zd Z	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 ddZy)TrackedIterableNc                f    || _         || _        || _        || _        || _        || _        || _        y r   )iterabler   lengthdescunit_tqdmprogress)r   r"  r   r#  r$  r%  r&  r'  s           r8   r   zTrackedIterable.__init__p  s5     !
		
 r:   )NN)r"  Iterable | Noner   r
  r#  r
  r$  r  r%  r  r'  float | Noner  r	  )r  r  r  r   r4   r:   r8   r   r   o  sS     !%!!! ! 	!
 ! ! ! 
!r:   r   __call__tqdmc                      e Zd ZdZ	 d	 ddZd Zd Zd Z	 	 	 	 d	 	 	 	 	 	 	 ddZ	 	 	 	 d	 	 	 	 	 	 	 ddZ	dd	Z
d
 Zed        Zy)ProgressaD  
    The Progress class provides a custom progress tracker that is used in a function signature.
    To attach a Progress tracker to a function, simply add a parameter right after the input parameters that has a default value set to a `gradio.Progress()` instance.
    The Progress tracker can then be updated in the function by calling the Progress object or using the `tqdm` method on an Iterable.
    The Progress tracker is currently only available with `queue()`.
    Example:
        import gradio as gr
        import time
        def my_function(x, progress=gr.Progress()):
            progress(0, desc="Starting...")
            time.sleep(1)
            for i in progress.tqdm(range(100)):
                time.sleep(0.1)
            return x
        gr.Interface(my_function, gr.Textbox(), gr.Textbox()).queue().launch()
    c                8    |r
t                || _        g | _        y)z
        Parameters:
            track_tqdm: If True, the Progress object will track any tqdm.tqdm iterations with the tqdm library in the function.
        N)
patch_tqdm
track_tqdm	iterables)r   r0  s     r8   r   zProgress.__init__  s     L$02r:   c                4    | j                   d   j                  S )N)r1  r#  r   s    r8   __len__zProgress.__len__  s    ~~b!(((r:   c                    | S r   r4   r4  s    r8   __iter__zProgress.__iter__  s    r:   c                .   | j                         }|r| j                  d   }t        |j                  d      sat	        | j                        dkD  rI| j                  j                         }t        |j                  d      st	        | j                        dkD  rI || j                         |j                  t        d      |xj                  dz  c_        	 t        |j                        S | S # t        $ r | j                  j                           w xY w)zF
        Updates progress tracker with next item in iterable.
        r3  __next__r   Index not set.rC   )
_progress_callbackr1  hasattrr"  r[   r   r   rf   nextStopIteration)r   callbackcurrent_iterables      r8   r9  zProgress.__next__  s     **,#~~b1,55zB'!+#'>>#5#5#7  ,55zB'!+ T^^$%%- !122""a'",5566
 K	 ! ""$s   C/ /%DNc                    | j                         }|r@t        |t              r|\  }}d}nd} || j                  t	        d||||||      gz          y|S )a  
        Updates progress tracker with progress and message text.
        Parameters:
            progress: If float, should be between 0 and 1 representing completion. If Tuple, first number represents steps completed, and second value represents total steps or None if unknown. If None, hides progress bar.
            desc: description to display.
            total: estimated total number of steps.
            unit: unit of iterations.
        N)r;  rX   rF   r1  r   )r   r'  r$  totalr%  r&  r?  r   s           r8   r*  zProgress.__call__  se      **,(E*'u"4tT5(STU
 Or:   c           
     B   | j                         }|r|?t        dd||||      }| j                  j                  |        || j                         | S t	        |d      rt        |      n|}| j                  j                  t        t        |      d||||             | S )a  
        Attaches progress tracker to iterable, like tqdm.
        Parameters:
            iterable: iterable to attach progress tracker to.
            desc: description to display.
            total: estimated total number of steps.
            unit: unit of iterations.
        Nr   r5  )r;  r   r1  r   r<  r[   iter)	r   r"  r$  rB  r%  r&  r?  new_iterabler#  s	            r8   r+  zProgress.tqdm  s      **,.tQtT5Q%%l3(&-h	&BS]FNN!!X64uM r:   c                    | j                         }|rft        | j                        dkD  rN| j                  d   }|j                  t	        d      |xj                  |z  c_         || j                         yy)z
        Increases latest iterable with specified number of steps.
        Parameters:
            n: number of steps completed.
        r   r3  Nr:  )r;  r[   r1  r   rf   )r   nr?  r@  s       r8   r   zProgress.update  sl     **,DNN+a/#~~b1%%- !122""a'"T^^$r:   c                *   | j                         }|rt        t        | j                              D ]M  }t	        | j                  |   j
                        t	        |      k(  s2| j                  j                  |        n  || j                         yy)z4
        Removes iterable with given _tqdm.
        N)r;  rd   r[   r1  idr&  r   )r   r&  r?  r   s       r8   closezProgress.close  sx     **,3t~~./ dnnQ'--."U);NN&&q) T^^$r:   c                     t         j                  j                         } t         j                  j                         }| r|sy t	        | j
                  j                  |      S r   )r   blocksrw   event_idr   _queueset_progress)rL  rM  s     r8   r;  zProgress._progress_callback  sI    $$((*((,,.8v}}118<<r:   )F)r0  r  )NNstepsN)r'  z%float | tuple[int, int | None] | Noner$  r  rB  r
  r%  r\   )r"  r(  r$  r  rB  r
  r%  r\   rC   )r  r  r  r  r   r5  r7  r9  r*  r+  r   rJ  staticmethodr;  r4   r:   r8   r-  r-    s    & !33)6   7  	
 B   !  	
 :  = =r:   r-  c                    	 t        d      } 	 dd}d }dd}d }d }t        | j                  d      s%| j                  j                  | j                  _        t        | j                  d      s%| j                  j                  | j                  _        t        | j                  d	      s%| j                  j                  | j                  _	        t        | j                  d
      s%| j                  j                  | j                  _        t        | j                  d      s%| j                  j                  | j                  _        || j                  _        || j                  _        || j                  _        || j                  _
        || j                  _        t        | d      r3t        | j                  d      r| j                  | j                  _        y y y # t        $ r Y y w xY w)Nr+  c                   t         j                  j                         | _        | j                  =| j                  j	                  |||||        t        t        j                  d      |d<    | j                  |||g|d|i| y )N)r&  wfiler%  )	r   r'  rw   	_progressr+  ra   rT   devnull__init__orig__)r   r"  r$  rB  r%  r   kwargss          r8   	init_tqdmzpatch_tqdm.<locals>.init_tqdm)  sx     &..224>>%NN$t4H!"**c2F6NHdENDNtNvNr:   c                R    | j                   | j                   S | j                         S r   )rW  __iter__orig__r4  s    r8   	iter_tqdmzpatch_tqdm.<locals>.iter_tqdm2  s%    >>%>>!""$$r:   c                r    | j                   | j                   j                  |       | j                  |      S r   )rW  r   __update__orig__)r   rG  s     r8   update_tqdmzpatch_tqdm.<locals>.update_tqdm7  s/    >>%NN!!!$$$Q''r:   c                p    | j                   | j                   j                  |        | j                         S r   )rW  rJ  __close__orig__r4  s    r8   
close_tqdmzpatch_tqdm.<locals>.close_tqdm<  s-    >>%NN  &##%%r:   c                v    | j                   | j                   j                  |        | j                  |||      S r   )rW  rJ  __exit__orig__)r   exc_type	exc_value	tracebacks       r8   	exit_tqdmzpatch_tqdm.<locals>.exit_tqdmA  s3    >>%NN  &""8Y	BBr:   rY  r`  rc  rf  r]  auto)NNNrP  rQ  )
__import__ModuleNotFoundErrorr<  r+  r   rY  r   r`  rJ  rc  __exit__rf  r7  r]  rk  )r&  r[  r^  ra  rd  rj  s         r8   r/  r/  #  sn   6"
 :AO%
(
&
C 5::/0$)JJ$7$7

!5::12&+jj&7&7

#5::01%*ZZ%5%5

"5::/0$)JJ$7$7

!5::/0$)JJ$7$7

! $EJJ#EJJ!EJJ#EJJ#EJJuf'%**f"=**

 #>g  s   G 	G'&G'c                    t        |      }|s|| fS |t        j                  | t        j                  j
                  |ft        j                  j
                  d      fS )N)r0  r   )r   	before_fnbefore_argsafter_fn
after_args)r-  r   function_wrapperr   r'  set)r'   r0  r'  s      r8   create_trackerrv  ]  s\    :.H|U++
''++K&&**  r:   c                   	 t        j                  |       }t        j                  |       }g }|j
                  j                         D ]9  }|j                  |j                  |j                  fvr n|j                  |       ; d}d}	t        |      D ]  \  }
}|j                  |j                        }t        |j                  t               r"|
}|A|j#                  |
|j                         ^|t$        j&                  t(        t$        j&                     fv r||j#                  |
|       |t*        j,                  dz  t*        j.                  dz  t*        j,                  t*        j.                  fv rA|t1        |di       xs t1        t1        |dd      di       }|t(        t*        j,                     t*        j,                  fv rXd|v r|d   d   nd}|t+        j,                  |      }n|t*        j,                  k(  rt3        d      |j#                  |
|       |t(        t*        j.                     t*        j.                  fv s|j                  dd      }|!t+        j.                  |d   |d   |d	   
      nd}||t*        j.                  k(  rt3        d      |j#                  |
|       %|r}t        j4                  |      rht7        |t8              rX|
}	|R|Vt;        j<                  |j>                         |j#                  |
 ||j@                  |j>                               |j                  |jB                  us|tE        |      |
k  s|j#                  |
|j                          |tE        |      tE        |      k  rtE        |      }
||
   }|j                  |jB                  k(  r'tG        jH                  d       |j                  d       n|j                  |j                         tE        |      tE        |      k  r|xs g ||	fS # t        $ r |xs g ddfcY S w xY w)a  
    Checks if function has special arguments Request or EventData (via annotation) or Progress (via default value).
    If inputs is provided, these values will be loaded into the inputs array.
    Parameters:
        fn: function to check.
        inputs: array to load special arguments into.
        request: request to load into inputs.
        event_data: event-related data to load into inputs.
    Returns:
        updated inputs, progress index, event data index.
    Nsessionr   
oauth_infouserinfoz@This action requires a logged in user. Please sign in and retry.access_tokenscope
expires_at)tokenr|  r}  z'Unexpected argument. Filling with None.)%r   	signaturerW   r   get_type_hints
parametersvalueskindPOSITIONAL_ONLYPOSITIONAL_OR_KEYWORDr   re   rw   namerX   defaultr-  r   r   Requestr   r   OAuthProfile
OAuthTokengetattrr   isclass
issubclassr   r   check_all_files_in_cache_datatargetemptyr[   rR   rS   )r'   r%   r   
event_datar  
type_hintspositional_argsparamprogress_indexevent_data_indexr   	type_hintrx  oauth_profilery  oauth_tokens                   r8   special_argsr  j  s   "(%%b)	 %%b)JO%%,,. &::e33U5P5PQQu%& No. E,5NN5::.	emmX.N!a/6>>8FNN+CDD!a)%t#	
 
 ! GY3 N GGY=y"M  %*<*<!=u?Q?Q RR (72  -j9! "
 %0(-(:(:=(I"e&8&88#^  MM!]3 8E,<,<#=u?O?O"PP!(\4!@J &1 ((",^"<",W"5'1,'? "   #*yE<L<L/L#^  MM![1	*9i0 !j&< 99*:J:JKa:+<+<j>N>N!OPMM,1CFWXHXMM!U]]+KE,L &kC00FA#A&E}}+GHd#emm, &kC00 <R)999s  (|T4''(s   P) )P>=P>c                :    d|d<   | | |d<   |||d<   |||d<   |S )aV  
    Updates a component's properties. When a function passed into a Gradio Interface or a Blocks
    events returns a value, it typically updates the value of the output component. But it is also possible
    to update the *properties* of an output component (such as the number of lines of a `Textbox` or
    the visibility of an `Row`) by returning a component and passing in the parameters to update in
    the constructor of the component. Alternatively, you can return `gr.update(...)` with any arbitrary
    parameters to update. (This is useful as a shorthand or if the same function can be called with different
    components to update.) This method does not work with the `gr.State` component.

    Parameters:
        elem_id: Use this to update the id of the component in the HTML DOM
        elem_classes: Use this to update the classes of the component in the HTML DOM
        visible: Use this to update the visibility of the component
        kwargs: Any other keyword arguments to update the component's properties.
    Example:
        import gradio as gr
        with gr.Blocks() as demo:
            radio = gr.Radio([1, 2, 4], label="Set the value of the number")
            number = gr.Number(value=2, interactive=True)
            radio.change(fn=lambda value: gr.update(value=value), inputs=radio, outputs=number)
        demo.launch()
    r   __type__r-   elem_classesr"   r4   )r-   r  r"   rZ  s       r8   r   r     sC    8 "F:#y!-~#yMr:   c                 
    ddiS )a  
    A special function that can be returned from a Gradio function to skip updating the output component. This may be useful when
    you want to update the output component conditionally, and in some cases, you want to skip updating the output component.
    If you have multiple output components, you can return `gr.skip()` as part of a tuple to skip updating a specific output component,
    or you can return a single `gr.skip()` to skip updating all output components.
    r  r   r4   r4   r:   r8   skipr    s     !!r:   c                   ddl m} |j                  j                         }|j                  j                         }||+|dv rt        |        y |dk(  rt        j                  |        y |j                  j                  || ||||       y )Nr   )r   )infosuccesswarning)rM  logtitleleveldurationr"   )
gradio.contextr   rL  rw   rM  r   rR   rS   rN  log_message)messager  r  r  r"   r   rL  rM  s           r8   r  r  
  s     ,  $$&F$$((*H~) '''N 	 iMM'"
MM  r:   modals)documentation_groupc                $    t        | |d||       y)a  
    This function allows you to pass custom warning messages to the user. You can do so simply by writing `gr.Warning('message here')` in your function, and when that line is executed the custom message will appear in a modal on the demo. The modal is yellow by default and has the heading: "Warning." Queue must be enabled for this behavior; otherwise, the warning will be printed to the console using the `warnings` library.
    Demos: blocks_chained_events
    Parameters:
        message: The warning message to be displayed to the user. Can be HTML, which will be rendered in the modal.
        duration: The duration in seconds that the warning message should be displayed for. If None or 0, the message will be displayed indefinitely until the user closes it.
        visible: Whether the error message should be displayed in the UI.
        title: The title to be displayed to the user at the top of the modal.
    Example:
        import gradio as gr
        def hello_world():
            gr.Warning('This is a warning message.')
            return "hello world"
        with gr.Blocks() as demo:
            md = gr.Markdown()
            demo.load(hello_world, inputs=None, outputs=[md])
        demo.launch()
    r  r  r  r  r"   Nr  r  r  r"   r  s       r8   Warningr  '  s    2 uI'r:   c                $    t        | |d||       y)a  
    This function allows you to pass custom info messages to the user. You can do so simply by writing `gr.Info('message here')` in your function, and when that line is executed the custom message will appear in a modal on the demo. The modal is gray by default and has the heading: "Info." Queue must be enabled for this behavior; otherwise, the message will be printed to the console.
    Demos: blocks_chained_events
    Parameters:
        message: The info message to be displayed to the user. Can be HTML, which will be rendered in the modal.
        duration: The duration in seconds that the info message should be displayed for. If None or 0, the message will be displayed indefinitely until the user closes it.
        visible: Whether the error message should be displayed in the UI.
        title: The title to be displayed to the user at the top of the modal.
    Example:
        import gradio as gr
        def hello_world():
            gr.Info('This is some info.')
            return "hello world"
        with gr.Blocks() as demo:
            md = gr.Markdown()
            demo.load(hello_world, inputs=None, outputs=[md])
        demo.launch()
    r  r  Nr  r  s       r8   Infor  E  s    2 uFXwWr:   c                $    t        | |d||       y)aw  
    This function allows you to pass custom success messages to the user. You can do so simply by writing `gr.Success('message here')` in your function, and when that line is executed the custom message will appear in a modal on the demo. The modal is green by default and has the heading: "Success." Queue must be enabled for this behavior; otherwise, the message will be printed to the console.
    Parameters:
        message: The success message to be displayed to the user. Can be HTML, which will be rendered in the modal.
        duration: The duration in seconds that the success message should be displayed for. If None or 0, the message will be displayed indefinitely until the user closes it.
        visible: Whether the error message should be displayed in the UI.
        title: The title to be displayed to the user at the top of the modal.
    Example:
        def hello_world():
            gr.Success('Operation completed successfully!')
            return "hello world"
        with gr.Blocks() as demo:
            md = gr.Markdown()
            demo.load(hello_world, inputs=None, outputs=[md])
        demo.launch()
    r  r  Nr  r  s       r8   Successr  a  s    . uI'r:   )NNNNr   FNNFTTr   F)"r$   r   r%   r   r&   r   r'   r   r(   r   r)   r  r*   r   r+   r  r,   r  r-   r  r.   r  r/   r  r0   r  r1   r  r2   r  r!   r  r"   r  )r   zSequence[Component]r   rZ   r   rZ   r  )NNN)
r'   r   r%   zlist[Any] | Noner   zroutes.Request | Noner  zEventData | Noner  z#tuple[list, int | None, int | None])
r-   r  r  zlist[str] | str | Noner"   r   rZ  r
   r  zdict[str, Any])r  dict)r  r   T)
r  r\   r  r\   r  z%Literal['info', 'warning', 'success']r  r)  r"   r  )zWarning issued.r   Tr  )r  r\   r  r)  r"   r  r  r\   )zInfo issued.r   Tr  )zSuccess.r   Tr  )Er  
__future__r   r   ro   rb   r   rT   rx   rR   collections.abcr   r   r   	functoolsr   pathlibr   typingr	   r
   r   r   gradio_clientr   r   gradio_client.documentationr   rl   r   r   r   r   r   r  r   r   r   gradio.data_classesr   r   r   r   r   gradio.exceptionsr   gradio.flaggingr   gradio.i18nr   gradio.utilsr   gradio.componentsr   r_   r9   r5   r   r   r-  r/  rv  r  r   r  r  r  r  r  r4   r:   r8   <module>r     sw   # 
  
  	   8 8   8 8 / 0 Q Q D D < / # %   *+ 7;"&26#'%3*" (,%*/*+* 4* 		*
  * 0* * * !* * * * * #* *" %#*$ %*Z 
{ { {|#7;EI<! !( 
*f\=x \= \=~7%t
  $%)#'	l:l:l: #l: !	l:
 )l:` +/##(# # 	#
 #L 
" " 4: 1 	
 : 
h'$	  	 (: 
h'!	XXX X 	X (X6 
h'	  	 (r:   