
    +gdXm                     l   d Z ddlZddlZddlZddl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 ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZmZ ddl m!Z! ddl"m#Z# ddl$m%Z%m&Z&m'Z' ddl(m)Z) ddl*m+Z+m,Z,  e)e-          Z. G d de%          Z/d Z0 G d d          Z1 G d de1          Z2dS )z Metrics base class.    N)AnyDictListOptionalTupleUnion   )config)Dataset)ArrowReader)ArrowWriter)DownloadConfig)DownloadManager)Features)DatasetInfo
MetricInfo)camelcase_to_snakecase)
deprecated)BaseFileLockFileLockTimeout)
get_logger)copyfunc	temp_seedc                   .     e Zd ZdZ fdZd Zd Z xZS )FileFreeLockz-Thread lock until a file **cannot** be lockedc                 j    t          |          | _         t                      j        |g|R i | d S N)r   filelocksuper__init__)self	lock_fileargskwargs	__class__s       /lib/python3.11/site-packages/datasets/metric.pyr!   zFileFreeLock.__init__.   s?     ++4T444V44444    c                     	 | j                             dd           | j                                          d | _        d S # t          $ r | j         j        | _        Y d S w xY w)Ng{Gz?g{Gz?)timeoutpoll_intervall)r   acquirerelease_lock_file_fdr   r#   r"   s    r'   _acquirezFileFreeLock._acquire2   sy    	&M!!$t!DDD M!!###!%D  	9 	9 	9!%!8D	9s   A   AAc                     d | _         d S r   )r.   r/   s    r'   _releasezFileFreeLock._release=   s    !r(   )__name__
__module____qualname____doc__r!   r0   r2   __classcell__)r&   s   @r'   r   r   +   s\        775 5 5 5 5	& 	& 	&" " " " " " "r(   r   c                     t          |           t          k    rt          |           dk    r|  S d }d || d d                    d || dd                     dS )N   c                 @    d                     d | D                       S )Nz, c              3   4   K   | ]}t          |          V  d S r   )repr).0xs     r'   	<genexpr>z?summarize_if_long_list.<locals>.format_chunk.<locals>.<genexpr>H   s(      00Qa000000r(   )join)chunks    r'   format_chunkz,summarize_if_long_list.<locals>.format_chunkG   s#    yy00%000000r(   [   z, ..., ])typelistlen)objrB   s     r'   summarize_if_long_listrK   C   sw    99CAx1 1 1 G||CG$$FF\\#bcc(-C-CFFFFr(   c                      e Zd ZdZdefdZed             Zedefd            Z	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defd            Zede
e         fd            Zedefd            Zede
ee                  fd            Zede
ee                  fd            Zedefd            Zede
e         fd            ZdS )MetricInfoMixinu   This base class exposes some attributes of MetricInfo
    at the base level of the Metric for easy access.

    <Deprecated version="2.5.0">

    Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate

    </Deprecated>

    infoc                     || _         d S r   _metric_info)r"   rN   s     r'   r!   zMetricInfoMixin.__init__Y   s     r(   c                     | j         S )zN:class:`datasets.MetricInfo` object containing all the metadata in the metric.rP   r/   s    r'   rN   zMetricInfoMixin.info\   s       r(   returnc                     | j         j        S r   )rQ   metric_namer/   s    r'   namezMetricInfoMixin.namea        ,,r(   c                     | j         j        S r   )rQ   experiment_idr/   s    r'   rY   zMetricInfoMixin.experiment_ide        ..r(   c                     | j         j        S r   )rQ   descriptionr/   s    r'   r\   zMetricInfoMixin.descriptioni   rW   r(   c                     | j         j        S r   )rQ   citationr/   s    r'   r^   zMetricInfoMixin.citationm        ))r(   c                     | j         j        S r   )rQ   featuresr/   s    r'   ra   zMetricInfoMixin.featuresq   r_   r(   c                     | j         j        S r   )rQ   inputs_descriptionr/   s    r'   rc   z"MetricInfoMixin.inputs_descriptionu   s     33r(   c                     | j         j        S r   )rQ   homepager/   s    r'   re   zMetricInfoMixin.homepagey   r_   r(   c                     | j         j        S r   )rQ   licenser/   s    r'   rg   zMetricInfoMixin.license}   s     ((r(   c                     | j         j        S r   )rQ   codebase_urlsr/   s    r'   ri   zMetricInfoMixin.codebase_urls   rZ   r(   c                     | j         j        S r   )rQ   reference_urlsr/   s    r'   rk   zMetricInfoMixin.reference_urls   s     //r(   c                     | j         j        S r   )rQ   
streamabler/   s    r'   rm   zMetricInfoMixin.streamable   s     ++r(   c                     | j         j        S r   )rQ   formatr/   s    r'   ro   zMetricInfoMixin.format   s     ''r(   N)r3   r4   r5   r6   r   r!   propertyrN   strrV   r   rY   r\   r^   r   ra   rc   re   rg   r   ri   rk   boolrm   ro    r(   r'   rM   rM   M   sF       	 	!Z ! ! ! ! ! ! X! -c - - - X- /x} / / / X/ -S - - - X- *# * * * X* *( * * * X* 4C 4 4 4 X4 *(3- * * * X* ) ) ) ) X) /xS	2 / / / X/ 0c 3 0 0 0 X0 ,D , , , X, ( ( ( ( X( ( (r(   rM   c                      e Zd ZdZ ed          	 	 	 	 	 	 	 	 	 d)d	ee         d
edee         dededee         dee         dede	ee
f         fd            Zd Zd Zd Zd*deeef         fdZdeee         ee         f         fdZd Zd Zd Zddddee         fdZddddZdddd Zd*d!Zdefd"Z	 	 d+d#ee         d$ee         fd%Z d& Z!dddde"ee#f         fd'Z$d( Z%dS ),Metricu  A Metric is the base class and common API for all metrics.

    <Deprecated version="2.5.0">

    Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate

    </Deprecated>

    Args:
        config_name (``str``): This is used to define a hash specific to a metrics computation script and prevents the metric's data
            to be overridden when the metric loading script is modified.
        keep_in_memory (:obj:`bool`): keep all predictions and references in memory. Not possible in distributed settings.
        cache_dir (``str``): Path to a directory in which temporary prediction/references data will be stored.
            The data directory should be located on a shared file-system in distributed setups.
        num_process (``int``): specify the total number of nodes in a distributed settings.
            This is useful to compute metrics in distributed setups (in particular non-additive metrics like F1).
        process_id (``int``): specify the id of the current process in a distributed setup (between 0 and num_process-1)
            This is useful to compute metrics in distributed setups (in particular non-additive metrics like F1).
        seed (:obj:`int`, optional): If specified, this will temporarily set numpy's random seed when :func:`datasets.Metric.compute` is run.
        experiment_id (``str``): A specific experiment id. This is used if several distributed evaluations share the same file system.
            This is useful to compute metrics in distributed setups (in particular non-additive metrics like F1).
        max_concurrent_cache_files (``int``): Max number of concurrent metrics cache files (default 10000).
        timeout (``Union[int, float]``): Timeout in second for distributed setting synchronization.
    uO   Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluateNFr	   r   '  d   config_namekeep_in_memory	cache_dirnum_process
process_idseedrY   max_concurrent_cache_filesr*   c
                 v   |pd| _         |                                 }t          | j        j                  |_        | j         |_         |pd|_        t                              | |           t          |t                    r|dk     rt          d          t          |t                    r||k    rt          d          |r|dk    rt          d          || _        || _        || _        || _        t           j                            |pt&          j                  | _        |                                 | _        |>t0          j                                        ^}}}}|dk     r||         n|d         | _        n|| _        |	| _        t;          j        t?          | j                   |           | _         t;          j        t?          | j!                  |           | _!        t;          j        t?          | j"                  |           | _"        | j         j#        xj$        | j%        j&        z  c_$        | j!        j#        xj$        | j%        j&        z  c_$        | j"        j#        xj$        | j%        j&        z  c_$        d | _'        d | _(        d | _)        d | _*        d | _+        d | _,        d | _-        d | _.        d | _/        d S )	Ndefaultdefault_experimentr   z.'process_id' should be a number greater than 0z8'num_process' should be a number greater than process_idr	   zPUsing 'keep_in_memory' is not possible in distributed setting (num_process > 1).ip  )0rx   _infor   r&   r3   rU   rY   rM   r!   
isinstanceint
ValueErrorr{   r|   r~   ry   ospath
expanduserr
   HF_METRICS_CACHE_data_dir_root_build_data_dirdata_dirnprandom	get_stater}   r*   types
MethodTyper   compute	add_batchadd__func__r6   rN   rc   
buf_writerwriterwriter_batch_sizedatacache_file_namer   rendez_vous_lock
file_paths	filelocks)r"   rx   ry   rz   r{   r|   r}   rY   r~   r*   r%   rN   _poss                 r'   r!   zMetric.__init__   s|    '3)zz||1$.2IJJ+*B.B  t,,, *c** 	Oj1nnMNNN+s++ 	Y{j/H/HWXXX 	qkQ..oppp&$*D', g001Uf>UVV,,..<!y2244AtS1*-))T#YYaDII!DI*1 '(>(>EE)(4>*B*BDII#HTX$6$6==%%)EE%%''49+GG''!!TY%AA!! !%	  $ $ r(   c                 <    | j         dnt          | j                   S )zReturn the number of examples (predictions or predictions/references pair)
        currently stored in the metric's cache.
        Nr   )r   rI   r/   s    r'   __len__zMetric.__len__   s     K'qqS-=-==r(   c           
      X    d| j          d| j         d| j         dt          |            d	S )NzMetric(name: "z", features: z, usage: """z""", stored examples: ))rV   ra   rc   rI   r/   s    r'   __repr__zMetric.__repr__   sP    -TY - -T] - -0- - #D		- - -	
r(   c                     | j         }t          j                            || j        | j                  }t          j        |d           |S )a  Path of this metric in cache_dir:
        Will be:
            self._data_dir_root/self.name/self.config_name/self.hash (if not none)/
        If any of these element is missing or if ``with_version=False`` the corresponding subfolders are dropped.
        T)exist_ok)r   r   r   r@   rV   rx   makedirs)r"   builder_data_dirs     r'   r   zMetric._build_data_dir   sG      .7<<(8$)TEUVV
$t4444r(   rS   c                    t           j                            | j        | j         d| j         d| j         d          }d}t          | j                  D ]}t          |dz             }	 |
                    |            n# t          $ r | j        dk    rt          d| d| j         d	          d|| j        dz
  k    rt          d
| j         d          dt          t          j                              }t           j                            | j        | j         d| d| j         d| j         d          }Y w xY w||fS )zTCreate a new cache file. If the default cache file is used, we generated a new hash.-.arrowN.lockr*   r	   z^Error in _create_cache_file: another metric instance is already using the local cache file at .. Please specify an experiment_id (currently: :) to avoid collision between distributed metric instances.zCannot acquire lock, too many metric instance are operating concurrently on this file system.You should set a larger value of max_concurrent_cache_files when creating the metric (current value is z).)r   r   r@   r   rY   r{   r|   ranger~   r   r,   r   r   rq   uuiduuid4)r"   r*   	file_pathr   i	file_uuids         r'   _create_cache_filezMetric._create_cache_file	  s   GLL43E0r0rHX0r0r[_[j0r0r0rss	t677 	 	A	G 344H   111, +     #q(($A  zC A AGKGYA A A   	 
 7!;;;$Q-1-LQ Q Q   	   
--	GLLMd&8#q#q9#q#qtGW#q#qZ^Zi#q#q#q 			#. (""s   )BB8D<;D<c           	           j         dk    r j        t          d           j        g}n  fdt           j                   D             }g }t	          |          D ]\  }}|dk    r|                     j                   &t          |dz             }	 |                     j	                   |                    |           j# t          $ r t          d| d	| d
          dw xY w||fS )zGet a lock on all the cache files in a distributed setup.
        We wait for timeout second to let all the distributed node finish their tasks (default is 100 seconds).
        r	   Nz|Metric cache file doesn't exist. Please make sure that you call `add` or `add_batch` at least once before calling `compute`.c                     g | ]:}t           j                            j        j         d j         d | d          ;S )r   r   r   r   r@   r   rY   r{   r=   r|   r"   s     r'   
<listcomp>z/Metric._get_all_cache_files.<locals>.<listcomp>6  s[        T]t/A,i,iDDT,i,iWa,i,i,ijj  r(   r   r   r   z#Cannot acquire lock on cached file z for process .)r{   r   r   r   	enumerateappendr   r   r,   r*   r   )r"   r   r   r|   r   r   s   `     r'   _get_all_cache_fileszMetric._get_all_cache_files*  sY    q  #+ >   ./JJ   "'(8"9"9  J 	%.z%:%: 	/ 	/!J	Q  ////#I$788/$$T\$::: $$X....       $ciccV`ccc    9$$s   C"C)c           	      $     fdt           j                  D             }|D ]k}t          |          }	 |                     j                   |                                 B# t          $ r t          d| d j         d          d w xY wd S )Nc                     g | ]:}t           j                            j        j         d j         d | d          ;S )r   z.arrow.lockr   r   s     r'   r   z5Metric._check_all_processes_locks.<locals>.<listcomp>N  s[     $
 $
 $
 GLL4+=(j(j@P(j(jS](j(j(jkk$
 $
 $
r(   r   Expected to find locked file  from process  but it doesn't exist.)	r   r{   r   r,   r*   r-   r   r   r|   )r"   expected_lock_file_namesexpected_lock_file_name
nofilelocks   `   r'   _check_all_processes_locksz!Metric._check_all_processes_locksM  s    $
 $
 $
 $
#D$455$
 $
 $
  (@ 		% 		%#%&=>>J%""4<"888 ""$$$$      C4K  C  C[_[j  C  C  C 			% 		%s   A&&'Bc                    t           j                            | j        | j         d| j         d          }t          |          }	 |                    | j                   |	                                 n*# t          $ r t          d| d| j         d          d w xY wt           j                            | j        | j         d| j         d          }t          |          }	 |                    | j                   |	                                 d S # t          $ r t          d| d| j         d	          d w xY w)
Nr   z-0.arrow.lockr   r   r   r   	-rdv.lockzCouldn't acquire lock on r   )r   r   r@   r   rY   r{   r   r,   r*   r-   r   r   r|   r   )r"   r   r   lock_file_namer   s        r'   _check_rendez_vouszMetric._check_rendez_vous]  s   "$',,t}AS>u>uVZVf>u>u>u"v"v!"9::
	!t|444       	 	 	~0G~~W[Wf~~~ 	 dm8J5h5hTM]5h5h5hii#N33	'$$T\$::: $$&&&&&  	u 	u 	uiiiW[Wfiiijjptt	us   A6 6'B%D 'D=c                    | j         | j                                          d| _         | j        $| j        dk    r| j                                         | j        r[t          | j        t          | j	                            }t          j        | j                                                  | _        dS | j        dk    r|                                 \  }}	 t          dt          | j	                            }t          di |                    d |D                       | _        n# t"          $ r t%          d          dw xY w|| _        || _        dS dS )	zClose all the writing process and load/gather the data
        from all the nodes if main node or all_process is True.
        Nr   ra   )r   rN    c                     g | ]}d |iS )filenamers   )r=   fs     r'   r   z$Metric._finalize.<locals>.<listcomp>  s    8]8]8]Q*a8]8]8]r(   zError in finalize: another metric instance is already using the local cache file. Please specify an experiment_id to avoid collision between distributed metric instances.rs   )r   finalizer   r|   r-   ry   r   r   r   ra   r   from_bufferr   getvaluer   r   
read_filesFileNotFoundErrorr   r   r   )r"   readerr   r   s       r'   	_finalizezMetric._finalizeq  so    ;"K  """=$1)<)<M!!### 	' dm+t}:]:]:]^^^F+DO,D,D,F,FGGDIII_!!$($=$=$?$?!J	$";3V3V3VWWW#__f&7&78]8]R\8]8]8]&^&^__		$    o   )DO&DNNN! "!s   AD+ +Epredictions
referencesc                8    ||d|+|)fd j         D             }                    |           n<fd j         D             }|r't          d| dt           j                              fd j         D             } fdD             }t	          d	 |                                D                       r  j        di |                                   d _        d _	         j
        d
k    r j                             j        j                    fd j         D             }t           j                  5    j        di ||}ddd           n# 1 swxY w Y    j        d _         `d _        nt'          t          t)           j         j                                      D ]\\  }	}
t.                              d|
             `d _         `d _        t3          j        |
           |	                                 ]|S dS )ai  Compute the metrics.

        Usage of positional arguments is not allowed to prevent mistakes.

        Args:
            predictions (list/array/tensor, optional): Predictions.
            references (list/array/tensor, optional): References.
            **kwargs (optional): Keyword arguments that will be forwarded to the metrics :meth:`_compute`
                method (see details in the docstring).

        Return:
            dict or None

            - Dictionary with the metrics if this metric is run on the main process (``process_id == 0``).
            - None if the metric is not run on the main process (``process_id != 0``).

        Example:

        ```py
        >>> from datasets import load_metric
        >>> metric = load_metric("accuracy")
        >>> accuracy = metric.compute(predictions=model_prediction, references=labels)
        ```
        r   Nc                     i | ]	}|v|d 
S r   rs   r=   k
all_kwargss     r'   
<dictcomp>z"Metric.compute.<locals>.<dictcomp>  s%    TTT!@S@Sa@S@S@Sr(   c                     g | ]}|v|	S rs   rs   r   s     r'   r   z"Metric.compute.<locals>.<listcomp>  s#    NNNA!::M:Ma:M:M:Mr(   zMetric inputs are missing: . All required inputs are c                 "    i | ]}||         S rs   rs   )r=   
input_namer   s     r'   r   z"Metric.compute.<locals>.<dictcomp>  s     UUU*j4UUUr(   c                 4    i | ]}|j         v||         S rs   r   )r=   r   r%   r"   s     r'   r   z"Metric.compute.<locals>.<dictcomp>  s+    QQQ1!4=:P:P!VAY:P:P:Pr(   c              3      K   | ]}|d uV  	d S r   rs   )r=   vs     r'   r?   z!Metric.compute.<locals>.<genexpr>  s&      66q}666666r(   r   )rG   c                 ,    i | ]}|j         |         S rs   )r   r=   r   r"   s     r'   r   z"Metric.compute.<locals>.<dictcomp>  s"    XXXJj$)J"7XXXr(   z	Removing rs   )ra   updater   rH   anyvaluesr   r   r   r   r|   r   
set_formatrN   ro   r   r}   _computer   reversedzipr   r   loggerr   r   remover-   )r"   r   r   r%   missing_kwargsmissing_inputsinputscompute_kwargsoutputr   r   r   s   `  `       @r'   r   zMetric.compute  s   2 &1
UUfU
:#5TTTTt}TTTNn----NNNNNNNN  q.qq\`aean\o\oqq   VUUUt}UUUQQQQQQQQ66fmmoo66666 	%DN$$V$$$#?aI  di&6 777XXXX$-XXXF49%% C C&BBB>BBC C C C C C C C C C C C C C C *"&I 		 ,4DT^T_9]9]4^4^+_+_ ' ''HiKK 7I 7 7888	 $DI"&DKIi((($$&&&&M4s   E$$E(+E(c                   	  fd|D             }|r't          d| dt           j                             ||d|fd j        D              j        j                                       j                                          	  j                                       dS # t          j	        $ r t          fdD                       rgt          t                              		fdD             d	         }d
	 dt          	                    d| dt          |                    d	}n{t           j                  ddgk    r7d j         d}d                    fd j        D                       }||z  }n*d j         dt!          |           dt!          |           }t          |          dw xY w)a  Add a batch of predictions and references for the metric's stack.

        Args:
            predictions (list/array/tensor, optional): Predictions.
            references (list/array/tensor, optional): References.

        Example:

        ```py
        >>> from datasets import load_metric
        >>> metric = load_metric("accuracy")
        >>> metric.add_batch(predictions=model_prediction, references=labels)
        ```
        c                 &    g | ]}|j         v|S rs   r   r   s     r'   r   z$Metric.add_batch.<locals>.<listcomp>  %    ]]]ZZt}=\=\j=\=\=\r(   Bad inputs for metric: r   r   c                 "    i | ]}||         S rs   rs   )r=   intput_namebatchs     r'   r   z$Metric.add_batch.<locals>.<dictcomp>  s     RRR[eK0RRRr(   Nc           
   3      K   | ]V}t          |                   t          t          t                                                                        k    V  Wd S r   )rI   nextiterr   )r=   cr   s     r'   r?   z#Metric.add_batch.<locals>.<genexpr>  sR      SS3uQx==CT%,,..-A-A(B(B$C$CCSSSSSSr(   c                 l    g | ]0}t          |                   t                             k    .|1S rs   )rI   )r=   r  r   col0s     r'   r   z$Metric.add_batch.<locals>.<listcomp>  s9    QQQs58}}E$K@P@P/P/P1/P/P/Pr(   r   zMismatch in the number of z (z) and r   r   r   @Metric inputs don't match the expected format.
Expected format: ,
c              3   N   K   | ]}d | dt          |                    V   dS zInput z: NrK   )r=   r   r   s     r'   r?   z#Metric.add_batch.<locals>.<genexpr>  sS       . .[eVZVV+A%
BS+T+TVV. . . . . .r(   zPPredictions and/or references don't match the expected format.
Expected format: z,
Input predictions: z,
Input references: )r   rH   ra   rN   encode_batchr   _init_writerwrite_batchpaArrowInvalidr   r  r  rI   sortedr@   rK   )
r"   r   r   r%   
bad_inputsbad_col	error_msgerror_msg_inputsr   r  s
   `       @@r'   r   zMetric.add_batch  sr    ^]]]6]]]
 	trzrr]abfbo]p]prrsss +:PPPRRRRDMRRR	"//66;	2K##E***** 	2 	2 	2SSSSUSSSSS DKK((QQQQQeQQQRSTrrrU4[9I9IrrQXrr\_`efm`n\o\orrr 	 &&<*GGGvdhdqvvv	#(:: . . . .imiv. . . $ $  --		N(,N N*@*M*MN N *@
)K)KN N  Y''T1)	2s   B, ,DG
)
prediction	referencec                     fd|D             }|r't          d| dt           j                             ||d|fd j        D              j        j                                       j                                          	  j                                       dS # t          j	        $ rG d j         d}d
                    fd	 j        D                       }||z  }t          |          dw xY w)
a  Add one prediction and reference for the metric's stack.

        Args:
            prediction (list/array/tensor, optional): Predictions.
            reference (list/array/tensor, optional): References.

        Example:

        ```py
        >>> from datasets import load_metric
        >>> metric = load_metric("accuracy")
        >>> metric.add(predictions=model_predictions, references=labels)
        ```
        c                 &    g | ]}|j         v|S rs   r   r   s     r'   r   zMetric.add.<locals>.<listcomp>  r   r(   r   r   r   c                 "    i | ]}||         S rs   rs   )r=   r   examples     r'   r   zMetric.add.<locals>.<dictcomp>  s     VVV; 4VVVr(   Nr  r  c              3   N   K   | ]}d | dt          |                    V   dS r
  r  )r=   r   r  s     r'   r?   zMetric.add.<locals>.<genexpr>$  sS       * *YcTTT'=gj>Q'R'RTT* * * * * *r(   )r   rH   ra   rN   encode_exampler   r  writer  r  r@   )r"   r  r  r%   r  r  r  r  s   `      @r'   r   z
Metric.add	  s`    ^]]]6]]]
 	trzrr]abfbo]p]prrsss",IPPPVVVVVVV)$33G<<;	2Kg&&&&& 	2 	2 	2r`d`mrrrI$zz * * * *gkgt* * *     ))IY''T1	2s   B+ +ADc                 h   | j         dk    r| j        dk    rt          j                            | j        | j         d| j          d          }t          |          | _        	 | j        	                    |           n*# t          $ r t          d| d| j         d          d w xY w| j        rDt          j                    | _        t!          | j        j        | j        | j        	          | _        ned | _        | j        | j        %|                                 \  }}|| _        || _        t!          | j        j        | j        | j        
          | _        | j         dk    rP| j        dk    r/|                                  | j                                         d S |                                  d S d S )Nr	   r   r   r   r   zXError in _init_writer: another metric instance is already using the local cache file at r   r   )ra   streamr   )ra   r   r   )r{   r|   r   r   r@   r   rY   r   r   r,   TimeoutErrorr   ry   r  BufferOutputStreamr   r   rN   ra   r   r   r   r   r   r   r-   r   )r"   r*   r   r   r   s        r'   r  zMetric._init_writer*  s   a!##GLL4;M8k8kPTP`8k8k8kll	(0(;(;% )11'1BBBB#      $As| A AGKGYA A A   	    	 355DO%+DOW[Wm  DKK #DO #+t}/D,0,C,C,E,E)'6$ (%+$2FZ^Zp  DK a!##//111%--/////'')))))  s   !A= ='B$c                     t           )a  Construct the MetricInfo object. See `MetricInfo` for details.

        Warning: This function is only called once and the result is cached for all
        following .info() calls.

        Returns:
            info: (MetricInfo) The metrics information
        NotImplementedErrorr/   s    r'   r   zMetric._infoQ  s
     "!r(   download_config
dl_managerc                     |]|?t                      }t          j                            | j        d          |_        d|_        t          | j        || j                  }| 	                    |           dS )a  Downloads and prepares dataset for reading.

        Args:
            download_config (:class:`DownloadConfig`, optional): Specific download configuration parameters.
            dl_manager (:class:`DownloadManager`, optional): Specific download manager to use.
        N	downloadsF)dataset_namer&  r   )
r   r   r   r@   r   rz   force_downloadr   rV   _download_and_prepare)r"   r&  r'  s      r'   download_and_preparezMetric.download_and_prepare\  sz     &"0"2"2,.GLL,T,T)16.(!YRVR_  J 	"":.....r(   c                     dS )aY  Downloads and prepares resources for the metric.

        This is the internal implementation to overwrite called when user calls
        `download_and_prepare`. It should download all required resources for the metric.

        Args:
            dl_manager (:class:`DownloadManager`): `DownloadManager` used to download and cache data.
        Nrs   )r"   r'  s     r'   r,  zMetric._download_and_prepares  s	     tr(   c                    t           )zEThis method defines the common API for all the metrics in the libraryr$  )r"   r   r   r%   s       r'   r   zMetric._compute~  s    !!r(   c                    t          | d          r | j        | j                                         t          | d          r | j        | j                                         t          | d          r| `t          | d          r| `d S d S )Nr   r   r   r   )hasattrr   r-   r   r   r   r/   s    r'   __del__zMetric.__del__  s    4$$ 	$)BM!!###4+,, 	,1F1R!))+++4"" 	4   					 	r(   )	NFNr	   r   NNrv   rw   )r	   )NN)&r3   r4   r5   r6   r   r   rq   rr   r   r   floatr!   r   r   r   r   r   r   r   r   r   r   r   dictr   r   r   r  r   r   r   r   r-  r,  r   r   r   r2  rs   r(   r'   ru   ru      s        2 Zabb &*$#'"'+*/%(B Bc]B B C=	B
 B B smB  }B %(B sEz"B B B cbBH> > >
 
 
	  	  	 # #uS(]/C # # # #B!%eDItH~,E&F !% !% !% !%F% % % ' ' '( '  '  'D &*d E E ERV E E E EN (, -2 -2 -2 -2 -2^ !% 2 2 2 2 2B%* %* %* %*N	"z 	" 	" 	" 	" 5904/ /!.1/ _-/ / / /.	 	 	 '+t " " "$sTWx. " " " "    r(   ru   )3r6   r   r   r   typingr   r   r   r   r   r   numpyr   pyarrowr  r   r
   arrow_datasetr   arrow_readerr   arrow_writerr   download.download_configr   download.download_managerr   ra   r   rN   r   r   namingr   utils.deprecation_utilsr   utils.filelockr   r   r   utils.loggingr   utils.py_utilsr   r   r3   r   r   rK   rM   ru   rs   r(   r'   <module>rB     s.      				   : : : : : : : : : : : : : : : :               " " " " " " % % % % % % % % % % % % 4 4 4 4 4 4 6 6 6 6 6 6       ) ) ) ) ) ) ) ) * * * * * * / / / / / / ; ; ; ; ; ; ; ; ; ; % % % % % % / / / / / / / / 
H		" " " " "< " " "0G G GB( B( B( B( B( B( B( B(Jx x x x x_ x x x x xr(   