o
    tBht                     @   s  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 d dlZd dl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mZ d dlmZ d dlmZmZ d d	lmZm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gZ(dZ)dZ*dZ+dZ,dZ-dZ.eee/e/f  Z0eee/e/f  Z1de/de/de/fddZ2de/dee/ defddZ3	 dYd!e4d"e5d#e/defd$d%Z6	dZde/dee/ d!e4d"e5fd&d'Z7G d(d) d)e8Z9		dZd#e/d*ee/ dee/ d!e4d"e5defd+d,Z:		dZd-e/d.ee4e/f dee/ d!e4d"e5f
d/d0Z;		dZd1e4dee/ d!e4d"e5dee/ef f
d2d3Z<		dZd1e4dee/ d!e4d"e5de1f
d4d5Z=		dZd1e4dee/ d!e4d"e5de0f
d6d7Z>d8e0de4fd9d:Z?		dZd#e/dee/ d;e/d<ed=ed>ed?ed@edAedBe/d!e4d"e5defdCdDZ@dddEd#e/dFeAdee/ dGeAdHed=ee4 d>edAeee4e4f  dBe/d!e4d"e5fdIdJZBdKdL ZCdMdN ZD	d[dOdddPdQdRdSdddT	d-ee/ d.ee/e4f d1ee4 dee/ dUeee/ef  dVeAdWeAdGee/eAf d!e4d"e5fdXdZEdS )\    N)join)warn)closingwraps)CallableOptionalDictTupleListAnyUnion)TemporaryDirectory)urlopenRequest)	HTTPErrorURLError   )_arff   )get_data_home)_liac_arff_parser)Bunchfetch_openmlzhttps://openml.org/z*api/v1/json/data/list/data_name/{}/limit/2zapi/v1/json/data/{}zapi/v1/json/data/features/{}zapi/v1/json/data/qualities/{}zdata/v1/download/{}openml_path	data_homereturnc                 C   s   t j|d| d S )Nz
openml.orgz.gz)ospathr   )r   r    r   o/var/www/html/riverr-enterprise-integrations-main/venv/lib/python3.10/site-packages/sklearn/datasets/_openml.py_get_local_path$      r!   c                    s    fdd}|S )zIf the first call to the decorated function fails, the local cached
    file is removed, and the function is called again. If ``data_home`` is
    ``None``, then the function is called once.
    c                    s   t   fdd}|S )Nc                     s    d u r| i |S z| i |W S  t y     ty?   tdt t }tj|r6t| | i | Y S w )Nz!Invalid cache, redownloading file)	r   	Exceptionr   RuntimeWarningr!   r   r   existsunlink)argskw
local_path)r   fr   r   r    wrapper/   s   


z;_retry_with_clean_cache.<locals>.decorator.<locals>.wrapperr   r*   r+   r   r   r*   r    	decorator.   s   z*_retry_with_clean_cache.<locals>.decoratorr   )r   r   r/   r   r-   r    _retry_with_clean_cache(   s   r0            ? 	n_retriesdelayurlc                    s    fdd}|S )aU  If the function call results in a network error, call the function again
    up to ``n_retries`` times with a ``delay`` between each call. If the error
    has a 412 status code, don't call the function again as this is a specific
    OpenML error.
    The url parameter is used to give more information to the user about the
    error.
    c                    s   t   fdd}|S )Nc               
      s   }	 z| i |W S  t tfy@ } z't|tr |jdkr  |dkr% td d |d8 }t  W Y d }~nd }~ww q)NT  r   z+A network error occurred while downloading z. Retrying...r   )r   TimeoutError
isinstancer   coder   timesleep)r'   kwargsretry_countere)r5   r*   r4   r6   r   r    r+   O   s"   
z;_retry_on_network_error.<locals>.decorator.<locals>.wrapperr   r,   r5   r4   r6   r.   r    r/   N   s   z*_retry_on_network_error.<locals>.decoratorr   )r4   r5   r6   r/   r   r@   r    _retry_on_network_errorC   s   rA   c              
   C   s  dd }t t|  }|dd |du r,t|||jt|}||r*tj|ddS |S t| |}t	j
|\}}	t	j
|st	j|dd	 zet|d
V}
tt|||jt|2}||rbt}ntj}|t	j
|
|	d}t|| W d   n1 sw   Y  W d   n1 sw   Y  t|j| W d   n1 sw   Y  W n ty   t	j
|rt	|  w t|dS )a  
    Returns a resource from OpenML.org. Caches it to data_home if required.

    Parameters
    ----------
    openml_path : str
        OpenML URL that will be accessed. This will be prefixes with
        _OPENML_PREFIX.

    data_home : str
        Directory to which the files will be cached. If None, no caching will
        be applied.

    n_retries : int, default=3
        Number of retries when HTTP errors are encountered. Error with status
        code 412 won't be retried as they represent OpenML generic errors.

    delay : float, default=1.0
        Number of seconds between retries.

    Returns
    -------
    result : stream
        A stream to the OpenML resource.
    c                 S   s   |   dddkS )NzContent-Encodingr3   gzip)infoget)_fsrcr   r   r    is_gzip_encoded   r"   z)_open_openml_url.<locals>.is_gzip_encodedzAccept-encodingrB   Nrb)fileobjmodeT)exist_ok)dirwb)r   _OPENML_PREFIX
add_headerrA   full_urlr   rB   GzipFiler!   r   r   splitr%   makedirsr   r   openr   shutilcopyfileobjmovenamer#   r&   )r   r   r4   r5   rF   reqfsrcr)   dir_name	file_nametmpdiropenerfdstr   r   r    _open_openml_urlf   sJ   

r_   c                   @   s   e Zd ZdZdS )OpenMLErrorzDHTTP 412 is a specific OpenML error code, indicating a generic errorN)__name__
__module____qualname____doc__r   r   r   r    r`      s    r`   error_messagec              
      s^   t   fdd}z| W S  ty. } z|jdkr!|W Y d}~t|d}~ww )a  
    Loads json data from the openml api

    Parameters
    ----------
    url : str
        The URL to load from. Should be an official OpenML endpoint.

    error_message : str or None
        The error message to raise if an acceptable OpenML error is thrown
        (acceptable error is, e.g., data id not found. Other errors, like 404's
        will throw the native error message).

    data_home : str or None
        Location to cache the response. None if no cache is required.

    n_retries : int, default=3
        Number of retries when HTTP errors are encountered. Error with status
        code 412 won't be retried as they represent OpenML generic errors.

    delay : float, default=1.0
        Number of seconds between retries.

    Returns
    -------
    json_data : json
        the json result from the OpenML server if the call was successful.
        An exception otherwise.
    c                     sL   t t d} t|  dW  d    S 1 sw   Y  d S )Nr4   r5   utf-8)r   r_   jsonloadsreaddecode)responser   r5   r4   r6   r   r    
_load_json   s   $z5_get_json_content_from_openml_api.<locals>._load_jsonr7   N)r0   r   r:   r`   )r6   re   r   r4   r5   rn   errorr   rm   r    !_get_json_content_from_openml_api   s   %

rp   rW   versionc           	   
   C   s   |dkr6t | d }d| }t|||||d}|d d }t|dkr2tdj| |d	 d
 d |d	 S t d | |}zt|d|||d}W n tye   |d7 }d| |}t|||||d}Y nw |d d d	 S )a?  
    Utilizes the openml dataset listing api to find a dataset by
    name/version
    OpenML api function:
    https://www.openml.org/api_docs#!/data/get_data_list_data_name_data_name

    Parameters
    ----------
    name : str
        name of the dataset

    version : int or str
        If version is an integer, the exact name/version will be obtained from
        OpenML. If version is a string (value: "active") it will take the first
        version from OpenML that is annotated as active. Any other string
        values except "active" are treated as integer.

    data_home : str or None
        Location to cache the response. None if no cache is required.

    n_retries : int, default=3
        Number of retries when HTTP errors are encountered. Error with status
        code 412 won't be retried as they represent OpenML generic errors.

    delay : float, default=1.0
        Number of seconds between retries.

    Returns
    -------
    first_dataset : json
        json representation of the first dataset object that adhired to the
        search criteria

    activez/status/active/zNo active dataset {} found.r   r4   r5   datadatasetr   zMultiple active versions of the dataset matching the name {name} exist. Versions may be fundamentally different, returning version {version}.r   rq   )rW   rq   z/data_version/{}N)re   r   r4   r5   z/status/deactivatedz%Dataset {} with version {} not found.)_SEARCH_NAMEformatrp   lenr   r`   )	rW   rq   r   r4   r5   r6   	error_msg	json_dataresr   r   r    _get_data_info_by_name   sN   )


r|   data_idc                 C   s.   t | }d| }t|||||d}|d S )N"Dataset with data_id {} not found.rs   data_set_description)
_DATA_INFOrw   rp   r}   r   r4   r5   r6   re   rz   r   r   r    _get_data_description_by_idH  s   

r   c                 C   s2   t | }d| }t|||||d}|d d S )Nr~   rs   data_featuresfeature)_DATA_FEATURESrw   rp   r   r   r   r    _get_data_features[  s   

r   c                 C   s:   t | }d| }t|||||d}|di dg S )Nr~   rs   data_qualitiesquality)_DATA_QUALITIESrw   rp   rD   r   r   r   r    _get_data_qualitieso  s   

	r   r   c                 C   s&   d}dd | D }t t|d|S )aJ  Get the number of samples from data qualities.

    Parameters
    ----------
    data_qualities : list of dict
        Used to retrieve the number of instances (samples) in the dataset.

    Returns
    -------
    n_samples : int
        The number of samples in the dataset or -1 if data qualities are
        unavailable.
    c                 S   s   i | ]	}|d  |d qS )rW   valuer   ).0dr   r   r    
<dictcomp>  s    z$_get_num_samples.<locals>.<dictcomp>NumberOfInstances)intfloatrD   )r   default_n_samples	qualitiesr   r   r    _get_num_samples  s   r   output_arrays_typefeatures_dictdata_columnstarget_columnscol_slice_xcol_slice_yshapemd5_checksumc              
      s   t | ||
|d}t|U t   fdd}||}|dk }|dkr'tjntj}tj|||d}t||||||||\}}}}|D ]}qC 	 |	krTt
d|  d ||||fW  d	   S 1 sdw   Y  d	S )
z@Load arff data with url and parses arff response with parse_arffrf   c                 3   s&    | D ]}  | |dV  qd S )Nrg   )updaterk   )rl   lineactual_md5_checksumr   r    _stream_checksum_generator  s
   
z7_load_arff_response.<locals>._stream_checksum_generatorpandassparse)return_typeencode_nominalzmd5 checksum of local file for zk does not match description. Downloaded file could have been modified / corrupted, clean cache and retry...N)r_   r   hashlibmd5r   COO	DENSE_GENloadr   	hexdigest
ValueError)r6   r   r   r   r   r   r   r   r   r   r4   r5   rl   r   streamr   r   arffXyframenominal_attributes_r   r   r    _load_arff_response  s@   


$r   rf   r   as_framefeatures_listc                   s   dd |D  t  |  fdd|D } fdd|D }|D ]}|| }t|d }|dkr:td|d	 |q |r@d
}n|rEd}nd}t| |t| || |||||||	|
d\}}}}t||||||dS )z1Download OpenML ARFF and convert to Bunch of datac                 S   s   i | ]}|d  |qS )rW   r   r   r   r   r   r    r     s    z+_download_data_to_bunch.<locals>.<dictcomp>c                       g | ]
}t  | d  qS indexr   r   col_namer   r   r    
<listcomp>      z+_download_data_to_bunch.<locals>.<listcomp>c                    r   r   r   r   r   r   r    r     r   number_of_missing_valuesr   z]Target column {} has {} missing values. Missing values are not supported for target columns. rW   r   r   numpy)r   r4   r5   )rt   targetr   
categoriesfeature_namestarget_names)_verify_target_data_typer   r   rw   r0   r   r   )r6   r   r   r   r   r   r   r   r   r4   r5   r   r   col_idxfeat
nr_missingr   r   r   r   r   r   r   r    _download_data_to_bunch  sT   

r   c                 C   s   t |tstdt| t }|D ]<}|| vrtd| | d dkr+|tj n|t	 | | d dkr?t
d| | | d dkrNt
d	| qt|d
krYtdd S )Nz%target_column should be list, got: %szCould not find target_column={}	data_typenumeric	is_ignoretruez$target_column={} has flag is_ignore.is_row_identifierz,target_column={} has flag is_row_identifier.r   zgCan only handle homogeneous multi-target datasets, i.e., all targets are either numeric or categorical.)r9   listr   typesetKeyErroraddnpfloat64objectr   rw   rx   )r   r   found_typestarget_columnr   r   r    r   #  s&   

r   c                 C   sD   g }| D ]}|d |vr|d dkr|d dkr| |d  q|S )NrW   r   r   r   )append)r   r   valid_data_column_namesr   r   r   r    _valid_data_column_names>  s   r   rr   default-targetTFauto)	rq   r}   r   r   cache
return_X_yr   r4   r5   r   r   r   c       	         C   sh  |du rd}n
t |d}t|d}| dur3|  } |dur%td|| t| ||||	d}
|
d }n|durD|dkrCtd	||ntd
t||}|d dkrbtd|d |d |d  d|v rotd|d  d|v r|td|d  d}|d  dkrd}|dkr| }|r|rtdt||}|s|D ]}d|d |d fv rq|d dkrtdq|dkrd d! |D }n!t	|t
r|g}n|du rg }nt	|tr|}n	td"t|t||}|st||}t|t|f}nd}t|d# }t|||t||||||d$ ||	d%}|r|j|jfS d&|d'}|j||d(|d) |S )*a)  Fetch dataset from openml by name or dataset id.

    Datasets are uniquely identified by either an integer ID or by a
    combination of name and version (i.e. there might be multiple
    versions of the 'iris' dataset). Please give either name or data_id
    (not both). In case a name is given, a version can also be
    provided.

    Read more in the :ref:`User Guide <openml>`.

    .. versionadded:: 0.20

    .. note:: EXPERIMENTAL

        The API is experimental (particularly the return value structure),
        and might have small backward-incompatible changes without notice
        or warning in future releases.

    Parameters
    ----------
    name : str, default=None
        String identifier of the dataset. Note that OpenML can have multiple
        datasets with the same name.

    version : int or 'active', default='active'
        Version of the dataset. Can only be provided if also ``name`` is given.
        If 'active' the oldest version that's still active is used. Since
        there may be more than one active version of a dataset, and those
        versions may fundamentally be different from one another, setting an
        exact version is highly recommended.

    data_id : int, default=None
        OpenML ID of the dataset. The most specific way of retrieving a
        dataset. If data_id is not given, name (and potential version) are
        used to obtain a dataset.

    data_home : str, default=None
        Specify another download and cache folder for the data sets. By default
        all scikit-learn data is stored in '~/scikit_learn_data' subfolders.

    target_column : str, list or None, default='default-target'
        Specify the column name in the data to use as target. If
        'default-target', the standard target column a stored on the server
        is used. If ``None``, all columns are returned as data and the
        target is ``None``. If list (of strings), all columns with these names
        are returned as multi-target (Note: not all scikit-learn classifiers
        can handle all types of multi-output combinations).

    cache : bool, default=True
        Whether to cache the downloaded datasets into `data_home`.

    return_X_y : bool, default=False
        If True, returns ``(data, target)`` instead of a Bunch object. See
        below for more information about the `data` and `target` objects.

    as_frame : bool or 'auto', default='auto'
        If True, the data is a pandas DataFrame including columns with
        appropriate dtypes (numeric, string or categorical). The target is
        a pandas DataFrame or Series depending on the number of target_columns.
        The Bunch will contain a ``frame`` attribute with the target and the
        data. If ``return_X_y`` is True, then ``(data, target)`` will be pandas
        DataFrames or Series as describe above.

        If as_frame is 'auto', the data and target will be converted to
        DataFrame or Series as if as_frame is set to True, unless the dataset
        is stored in sparse format.

        .. versionchanged:: 0.24
           The default value of `as_frame` changed from `False` to `'auto'`
           in 0.24.

    n_retries : int, default=3
        Number of retries when HTTP errors or network timeouts are encountered.
        Error with status code 412 won't be retried as they represent OpenML
        generic errors.

    delay : float, default=1.0
        Number of seconds between retries.

    Returns
    -------

    data : :class:`~sklearn.utils.Bunch`
        Dictionary-like object, with the following attributes.

        data : np.array, scipy.sparse.csr_matrix of floats, or pandas DataFrame
            The feature matrix. Categorical features are encoded as ordinals.
        target : np.array, pandas Series or DataFrame
            The regression target or classification labels, if applicable.
            Dtype is float if numeric, and object if categorical. If
            ``as_frame`` is True, ``target`` is a pandas object.
        DESCR : str
            The full description of the dataset.
        feature_names : list
            The names of the dataset columns.
        target_names: list
            The names of the target columns.

        .. versionadded:: 0.22

        categories : dict or None
            Maps each categorical feature name to a list of values, such
            that the value encoded as i is ith in the list. If ``as_frame``
            is True, this is None.
        details : dict
            More metadata from OpenML.
        frame : pandas DataFrame
            Only present when `as_frame=True`. DataFrame with ``data`` and
            ``target``.

    (data, target) : tuple if ``return_X_y`` is True

        .. note:: EXPERIMENTAL

            This interface is **experimental** and subsequent releases may
            change attributes without notice (although there should only be
            minor changes to ``data`` and ``target``).

        Missing values in the 'data' are represented as NaN's. Missing values
        in 'target' are represented as NaN's (numerical target) or None
        (categorical target).
    FN)r   openmlzfDataset data_id={} and name={} passed, but you can only specify a numeric data_id or a name, not both.rf   didrr   zlDataset data_id={} and version={} passed, but you can only specify a numeric data_id or a version, not both.zFNeither name nor data_id are provided. Please provide name or data_id.statuszVersion {} of dataset {} is inactive, meaning that issues have been found in the dataset. Try using a newer version from this URL: {}rq   rW   r6   ro   zMOpenML registered a problem with the dataset. It might be unusable. Error: {}warningzIOpenML raised a warning on the dataset. It might be unusable. Warning: {}rw   sparse_arffTr   z(Cannot return dataframe with sparse datar   r   r   r   stringzOSTRING attributes are not supported for array representation. Try as_frame=Truer   c                 S   s    g | ]}|d  dkr|d qS )	is_targetr   rW   r   r   r   r   r    r   *  s
    z fetch_openml.<locals>.<listcomp>zKDid not recognize type of target_columnShould be str, list or None. Got: {}file_idr   )r   r   r   r   r   r   r4   r5   z{}

Downloaded from openml.org.descriptionzhttps://www.openml.org/d/{})DESCRdetailsr6   )r   r   lowerr   rw   r|   r   r   r   r9   strr   	TypeErrorr   r   r   r   rx   
_DATA_FILEr   boolrt   r   popr   )rW   rq   r}   r   r   r   r   r   r4   r5   	data_infodata_descriptionreturn_sparser   r   r   r   r   r   r6   bunchr   r   r   r    r   N  s    




	







)r1   r2   r3   )r1   r2   )N)FrB   rh   r   rT   r   os.pathr   r;   warningsr   
contextlibr   	functoolsr   typingr   r   r	   r
   r   r   r   tempfiler   urllib.requestr   r   urllib.errorr   r   r   r   	externalsr   r3   r   _arff_parserr   utilsr   __all__rM   rv   r   r   r   r   r   OpenmlQualitiesTypeOpenmlFeaturesTyper!   r0   r   r   rA   r_   r   r`   rp   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   r    <module>   s   $
$
J

<

]



 	

J	

J

	
