U
    ½mœdL  ã                	   @   s:  d Z ddlmZmZmZ ddlmZmZmZ ddl	Z	ddl
ZddlmZ ddlmZmZmZmZ dd	lmZ e	 e¡Zed
ddd�Zedddd�Zedddd�edddd�edddd�fZd0dd„Zdd„ Zd1d d!„Zddd"dded#d$ƒed%d&ƒfddd'œd(d)„Zd2d*d+„Z d,ddd"ded#d$ƒed%d&ƒfdd-œd.d/„Z!dS )3zÞLabeled Faces in the Wild (LFW) dataset

This dataset is a collection of JPEG pictures of famous people collected
over the internet, all details are available on the official website:

    http://vis-www.cs.umass.edu/lfw/
é    )ÚlistdirÚmakedirsÚremove)ÚjoinÚexistsÚisdirN)ÚMemoryé   )Úget_data_homeÚ_fetch_remoteÚRemoteFileMetadataÚ
load_descré   )ÚBunchzlfw.tgzz.https://ndownloader.figshare.com/files/5976018Z@055f7d9c632d7370e6fb4afc7468d40f970c34a80d4c6f50ffec63f5a8d536c0)ÚfilenameÚurlZchecksumzlfw-funneled.tgzz.https://ndownloader.figshare.com/files/5976015Z@b47c8422c8cded889dc5a13418c4bc2abbda121092b3533a83306f90d900100aúpairsDevTrain.txtz.https://ndownloader.figshare.com/files/5976012Z@1d454dada7dfeca0e7eab6f65dc4e97a6312d44cf142207be28d688be92aabfaúpairsDevTest.txtz.https://ndownloader.figshare.com/files/5976009Z@7cb06600ea8b2814ac26e946201cdb304296262aad67d046a16a7ec85d0ff87cú	pairs.txtz.https://ndownloader.figshare.com/files/5976006Z@ea42330c62c92989f9d7c03237ed5d591365e89b3e649747777b70e692dc1592Tc           
      C   s  t | d�} t| dƒ}t|ƒs$t|ƒ tD ]D}t||jƒ}t|ƒs(|r`t d|j¡ t	||d� q(t
d| ƒ‚q(|r‚t|dƒ}t}nt|dƒ}t}t|ƒ�s
t||jƒ}t|ƒsÚ|rÎt d|j¡ t	||d� nt
d| ƒ‚d	d
l}	t d|¡ |	 |d¡j|d� t|ƒ ||fS )z0Helper function to download any missing LFW data)Ú	data_homeÚlfw_homezDownloading LFW metadata: %s)Údirnamez%s is missingZlfw_funneledZlfwz!Downloading LFW data (~200MB): %sr   Nz$Decompressing the data archive to %szr:gz)Úpath)r
   r   r   r   ÚTARGETSr   ÚloggerÚinfor   r   ÚIOErrorÚFUNNELED_ARCHIVEÚARCHIVEÚtarfileÚdebugÚopenÚ
extractallr   )
r   ÚfunneledÚdownload_if_missingr   ÚtargetZtarget_filepathÚdata_folder_pathÚarchiveÚarchive_pathr   © r)   úN/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/sklearn/datasets/_lfw.pyÚ_check_fetch_lfwJ   s8    




r+   c                 C   sÂ  zddl m} W n tk
r,   tdƒ‚Y nX tddƒtddƒf}|dkrP|}ntdd„ t||ƒD ƒƒ}|\}}|j|j |jp‚d }|j|j |jp˜d }	|dk	rÄt	|ƒ}t
|| ƒ}t
||	 ƒ}	t| ƒ}
|sètj|
||	ftjd	�}ntj|
||	d
ftjd	�}t| ƒD ]´\}}|d dk�r0t d|d |
¡ | |¡}| |j|j|j|jf¡}|dk	�rl| |	|f¡}tj|tjd	�}|jdk�r”td| ƒ‚|d }|�s®|jdd�}|||df< �q|S )zInternally used to load imagesr   )ÚImagez¨The Python Imaging Library (PIL) is required to load data from jpeg files. Please refer to https://pillow.readthedocs.io/en/stable/installation.html for installing PIL.éú   Nc                 s   s   | ]\}}|p|V  qd S )Nr)   )Ú.0ÚsZdsr)   r)   r*   Ú	<genexpr>‡   s     z_load_imgs.<locals>.<genexpr>r	   ©Zdtypeé   iè  zLoading face #%05d / %05dzLFailed to read the image file %s, Please make sure that libjpeg is installedg     ào@r   )Zaxis.)ZPILr,   ÚImportErrorÚsliceÚtupleÚzipÚstopÚstartÚstepÚfloatÚintÚlenÚnpÚzerosZfloat32Ú	enumerater   r    r!   ÚcropÚresizeZasarrayÚndimÚRuntimeErrorZmean)Ú
file_pathsÚslice_ÚcolorrA   r,   Zdefault_sliceZh_sliceZw_sliceÚhÚwÚn_facesÚfacesÚiÚ	file_pathZpil_imgZfacer)   r)   r*   Ú
_load_imgsu   sT    ÿ
	
ÿ
ÿÿrM   Fc                    sø   g g  }}t t| ƒƒD ]h}t| |ƒ‰ tˆ ƒs.q‡ fdd„t tˆ ƒƒD ƒ}t|ƒ}	|	|kr| dd¡}| |g|	 ¡ | |¡ qt|ƒ}
|
dkrœtd| ƒ‚t 	|¡}t 
||¡}t||||ƒ}t |
¡}tj d¡ |¡ || ||  }}|||fS )z~Perform the actual data loading for the lfw people dataset

    This operation is meant to be cached by a joblib wrapper.
    c                    s   g | ]}t ˆ |ƒ‘qS r)   )r   )r.   Úf©Zfolder_pathr)   r*   Ú
<listcomp>Í   s     z%_fetch_lfw_people.<locals>.<listcomp>Ú_ú r   z*min_faces_per_person=%d is too restrictiveé*   )Úsortedr   r   r   r<   ÚreplaceÚextendÚ
ValueErrorr=   ÚuniqueZsearchsortedrM   ZarangeÚrandomZRandomStateÚshuffle)r&   rE   rF   rA   Úmin_faces_per_personZperson_namesrD   Zperson_nameÚpathsZ
n_picturesrI   Útarget_namesr%   rJ   Úindicesr)   rO   r*   Ú_fetch_lfw_people¿   s.    	

ÿ

r_   g      à?éF   éÃ   éN   é¬   )r   r#   rA   r[   rF   rE   r$   Ú
return_X_yc                 C   s„   t | ||d�\}}	t d|¡ t|ddd�}
|
 t¡}||	||||d�\}}}| t|ƒd¡}tdƒ}|rr||fS t	|||||d	�S )
a¥  Load the Labeled Faces in the Wild (LFW) people dataset (classification).

    Download it if necessary.

    =================   =======================
    Classes                                5749
    Samples total                         13233
    Dimensionality                         5828
    Features            real, between 0 and 255
    =================   =======================

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

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

    funneled : bool, default=True
        Download and use the funneled variant of the dataset.

    resize : float or None, default=0.5
        Ratio used to resize the each face picture. If `None`, no resizing is
        performed.

    min_faces_per_person : int, default=None
        The extracted dataset will only retain pictures of people that have at
        least `min_faces_per_person` different pictures.

    color : bool, default=False
        Keep the 3 RGB channels instead of averaging them to a single
        gray level channel. If color is True the shape of the data has
        one more dimension than the shape with color = False.

    slice_ : tuple of slice, default=(slice(70, 195), slice(78, 172))
        Provide a custom 2D slice (height, width) to extract the
        'interesting' part of the jpeg files and avoid use statistical
        correlation from the background.

    download_if_missing : bool, default=True
        If False, raise a IOError if the data is not locally available
        instead of trying to download the data from the source site.

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

        .. versionadded:: 0.20

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

        data : numpy array of shape (13233, 2914)
            Each row corresponds to a ravelled face image
            of original size 62 x 47 pixels.
            Changing the ``slice_`` or resize parameters will change the
            shape of the output.
        images : numpy array of shape (13233, 62, 47)
            Each row is a face image corresponding to one of the 5749 people in
            the dataset. Changing the ``slice_``
            or resize parameters will change the shape of the output.
        target : numpy array of shape (13233,)
            Labels associated to each face image.
            Those labels range from 0-5748 and correspond to the person IDs.
        target_names : numpy array of shape (5749,)
            Names of all persons in the dataset.
            Position in array corresponds to the person ID in the target array.
        DESCR : str
            Description of the Labeled Faces in the Wild (LFW) dataset.

    (data, target) : tuple if ``return_X_y`` is True
        A tuple of two ndarray. The first containing a 2D array of
        shape (n_samples, n_features) with each row representing one
        sample and each column representing the features. The second
        ndarray of shape (n_samples,) containing the target samples.

        .. versionadded:: 0.20
    ©r   r#   r$   z Loading LFW people faces from %sé   r   ©ÚlocationÚcompressÚverbose)rA   r[   rF   rE   éÿÿÿÿúlfw.rst)ÚdataZimagesr%   r]   ÚDESCR)
r+   r   r    r   Úcacher_   Úreshaper<   r   r   )r   r#   rA   r[   rF   rE   r$   rd   r   r&   ÚmÚ	load_funcrJ   r%   r]   ÚXÚfdescrr)   r)   r*   Úfetch_lfw_peopleê   s4    ^  ÿ

û    ÿru   c              
   C   sÐ  t | dƒ�}dd„ |D ƒ}W 5 Q R X dd„ |D ƒ}t|ƒ}tj|td�}	tƒ }
t|ƒD �]\}}t|ƒdkr¦d|	|< |d t|d ƒd f|d t|d	 ƒd ff}nZt|ƒd
krìd|	|< |d t|d ƒd f|d	 t|d ƒd ff}ntd|d |f ƒ‚t|ƒD ]l\}\}}zt||ƒ}W n& t	k
�rH   t|t
|dƒƒ}Y nX ttt|ƒƒƒ}t||| ƒ}|
 |¡ �qqVt|
|||ƒ}t|jƒ}| d¡}| dd	¡ | d|d	 ¡ ||_||	t ddg¡fS )z}Perform the actual data loading for the LFW pairs dataset

    This operation is meant to be cached by a joblib wrapper.
    Úrbc                 S   s   g | ]}|  ¡  ¡  d ¡‘qS )ú	)ÚdecodeÚstripÚsplit)r.   Úlnr)   r)   r*   rP   w  s     z$_fetch_lfw_pairs.<locals>.<listcomp>c                 S   s   g | ]}t |ƒd kr|‘qS )r   )r<   )r.   Úslr)   r)   r*   rP   x  s      r1   r2   r	   r   r   é   zinvalid line %d: %rzUTF-8zDifferent personszSame person)r!   r<   r=   r>   r;   Úlistr?   rW   r   Ú	TypeErrorÚstrrT   r   ÚappendrM   ÚshapeÚpopÚinsertÚarray)Úindex_file_pathr&   rE   rF   rA   Z
index_fileÚsplit_linesZ
pair_specsZn_pairsr%   rD   rK   Ú
componentsÚpairÚjÚnameÚidxZperson_folderÚ	filenamesrL   Úpairsr‚   rI   r)   r)   r*   Ú_fetch_lfw_pairsm  sB    	þþ

r�   Útrain)Úsubsetr   r#   rA   rF   rE   r$   c                 C   s´   t |||d�\}}t d| |¡ t|ddd�}	|	 t¡}
dddd	œ}| |krhtd
| tt| 	¡ ƒƒf ƒ‚t
|||  ƒ}|
|||||d�\}}}tdƒ}t| t|ƒd¡||||d�S )a¸  Load the Labeled Faces in the Wild (LFW) pairs dataset (classification).

    Download it if necessary.

    =================   =======================
    Classes                                   2
    Samples total                         13233
    Dimensionality                         5828
    Features            real, between 0 and 255
    =================   =======================

    In the official `README.txt`_ this task is described as the
    "Restricted" task.  As I am not sure as to implement the
    "Unrestricted" variant correctly, I left it as unsupported for now.

      .. _`README.txt`: http://vis-www.cs.umass.edu/lfw/README.txt

    The original images are 250 x 250 pixels, but the default slice and resize
    arguments reduce them to 62 x 47.

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

    Parameters
    ----------
    subset : {'train', 'test', '10_folds'}, default='train'
        Select the dataset to load: 'train' for the development training
        set, 'test' for the development test set, and '10_folds' for the
        official evaluation set that is meant to be used with a 10-folds
        cross validation.

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

    funneled : bool, default=True
        Download and use the funneled variant of the dataset.

    resize : float, default=0.5
        Ratio used to resize the each face picture.

    color : bool, default=False
        Keep the 3 RGB channels instead of averaging them to a single
        gray level channel. If color is True the shape of the data has
        one more dimension than the shape with color = False.

    slice_ : tuple of slice, default=(slice(70, 195), slice(78, 172))
        Provide a custom 2D slice (height, width) to extract the
        'interesting' part of the jpeg files and avoid use statistical
        correlation from the background.

    download_if_missing : bool, default=True
        If False, raise a IOError if the data is not locally available
        instead of trying to download the data from the source site.

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

        data : ndarray of shape (2200, 5828). Shape depends on ``subset``.
            Each row corresponds to 2 ravel'd face images
            of original size 62 x 47 pixels.
            Changing the ``slice_``, ``resize`` or ``subset`` parameters
            will change the shape of the output.
        pairs : ndarray of shape (2200, 2, 62, 47). Shape depends on ``subset``
            Each row has 2 face images corresponding
            to same or different person from the dataset
            containing 5749 people. Changing the ``slice_``,
            ``resize`` or ``subset`` parameters will change the shape of the
            output.
        target : numpy array of shape (2200,). Shape depends on ``subset``.
            Labels associated to each pair of images.
            The two label values being different persons or the same person.
        target_names : numpy array of shape (2,)
            Explains the target values of the target array.
            0 corresponds to "Different person", 1 corresponds to "same person".
        DESCR : str
            Description of the Labeled Faces in the Wild (LFW) dataset.
    re   zLoading %s LFW pairs from %srf   r   rg   r   r   r   )r�   ÚtestZ10_foldsz+subset='%s' is invalid: should be one of %r)rA   rF   rE   rl   rk   )rm   rŽ   r%   r]   rn   )r+   r   r    r   ro   r�   rW   r~   rT   Úkeysr   r   r   rp   r<   )r‘   r   r#   rA   rF   rE   r$   r   r&   rq   rr   Zlabel_filenamesr†   rŽ   r%   r]   rt   r)   r)   r*   Úfetch_lfw_pairs¡  sD    Z  ÿ

ýÿÿ    ÿûr”   )NTT)NFNr   )NFN)"Ú__doc__Úosr   r   r   Úos.pathr   r   r   ÚloggingÚnumpyr=   Zjoblibr   Ú_baser
   r   r   r   Úutilsr   Ú	getLoggerÚ__name__r   r   r   r   r+   rM   r_   r4   ru   r�   r”   r)   r)   r)   r*   Ú<module>   s~   

ýýýýýõ
+K       ÿ
-÷      ÿ
6ø