U
    -e$j                  	   @   sV  d dl Z d dlZd dlmZ d dlmZ d dlmZmZ d dl	m
Z
mZmZmZmZ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
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$ d
dl%m&Z&m'Z' d
dl(m)Z)m*Z* e+e"j,Z-e$.e/Z0G dd de+Z1G dd de2Z3dZ4e"j,ddge"j5ddddge"j6dddd giZ7d!Z8d"d#gZ9d$d%gZ:e"j,e"j5e"j6gZ;d&d' e;D Z<d(d' e;D Z=e"j,d)giZ>e4gZ?e=e<e>gZ@d*d+d,d-gZAd.ZBd/d0d1d2d3gZCe+eDd4d5d6ZEeeee+f ee+eee+ d7f f d8d9d:ZFe+e+eDd;d<d=ZGe+e+eDd;d>d?ZHe
e+gee+ f ee+ee+ f d@dAdBZIe
e+gee+ f ee+ d@dCdDZJdWe+e+eee+  ee ee+ dEdFdGZKdXe+ee ee+ee+ f dHdIdJZLdYe+ee ee+ dHdKdLZMdZe+ee ee+ dMdNdOZNd[ee+ ee ee+ dQdRdSZOG dTd7 d7ee+ ZPG dUdV dVee+ePf ZQdS )\    N)partial)	has_magic)PathPurePath)CallableDictListOptionalSetTupleUnion)get_fs_token_paths)HTTPFileSystem)HfFileSystem)
thread_map   )config)DownloadConfig)!_prepare_path_and_storage_options	xbasenamexjoin)Split)logging)is_local_pathis_relative_path)glob_pattern_to_regexstring_to_dictc                   @   s   e Zd ZdS )UrlN__name__
__module____qualname__ r"   r"   T/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/datasets/data_files.pyr      s   r   c                   @   s   e Zd ZdS )EmptyDatasetErrorNr   r"   r"   r"   r#   r$   !   s   r$   zFdata/{split}-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9]*.*trainZtrainingZ
validationZvaliddevvaltesttestingevalZ
evaluationz-._ 0-9z**[{sep}/]{keyword}[{sep}]*z{keyword}[{sep}]*z{keyword}[{sep}/]**z**[{sep}/]{keyword}[{sep}/]**c                 C   s    i | ]}|d d t | D qS )c                 S   s$   g | ]}t D ]}|j|td qqS )keywordsep)"KEYWORDS_IN_FILENAME_BASE_PATTERNSformatNON_WORDS_CHARS.0r,   patternr"   r"   r#   
<listcomp>2   s    <dictcomp>.<listcomp>SPLIT_KEYWORDSr2   splitr"   r"   r#   
<dictcomp>1   s
    r:   c                 C   s    i | ]}|d d t | D qS )c                 S   s$   g | ]}t D ]}|j|td qqS r+   )"KEYWORDS_IN_DIR_NAME_BASE_PATTERNSr/   r0   r1   r"   r"   r#   r4   :   s    r5   r6   r8   r"   r"   r#   r:   9   s
    z**zmetadata.csvz**/metadata.csvzmetadata.jsonlz**/metadata.jsonlz*[]z	README.mdzconfig.jsonzdataset_infos.jsonzdummy_data.zipzdataset_dict.json)r3   returnc                    s   t  fddtD S )Nc                 3   s   | ]}| kV  qd S Nr"   )r2   Zwilcard_characterr3   r"   r#   	<genexpr>W   s     z%contains_wildcards.<locals>.<genexpr>)anyWILDCARD_CHARACTERSr>   r"   r>   r#   contains_wildcardsV   s    rB   DataFilesList)patternsr<   c                 C   s   t | trdd |  D S t | tr0t| giS t | trtdd | D r| D ]D}t |trt|dkrd|krt |dttfsPt	d| qPd	d
 | D }tt
|t|krt	d| dd | D S t| iS ntt| S dS )a/  
    Take the data_files patterns from the user, and format them into a dictionary.
    Each key is the name of the split, and each value is a list of data files patterns (paths or urls).
    The default split is "train".

    Returns:
        patterns: dictionary of split_name -> list of patterns
    c                 S   s*   i | ]"\}}t |t|tr |n|gqS r"   str
isinstancelist)r2   keyvaluer"   r"   r#   r:   d   s      z%sanitize_patterns.<locals>.<dictcomp>c                 s   s   | ]}t |tV  qd S r=   )rG   dictr2   r3   r"   r"   r#   r?   h   s     z$sanitize_patterns.<locals>.<genexpr>   r9   pathz]Expected each split to have a 'path' key which can be a string or a list of strings, but got c                 S   s   g | ]}|d  qS r9   r"   rL   r"   r"   r#   r4   s   s     z%sanitize_patterns.<locals>.<listcomp>z*Some splits are duplicated in data_files: c                 S   s6   i | ].}t |d  t|d tr(|d n|d gqS )r9   rN   rE   rL   r"   r"   r#   r:   v   s   
 N)rG   rK   itemsrF   SANITIZED_DEFAULT_SPLITrH   r@   lenget
ValueErrorsetsanitize_patterns)rD   r3   splitsr"   r"   r#   rV   Z   s4    	





rV   )matched_rel_pathr3   r<   c                 C   s<   dd t | jjD }dd t |jjD }t|t|kS )u  
    When a path matches a pattern, we additionnally check if it's inside a special directory
    we ignore by default (if it starts with a double underscore).

    Users can still explicitly request a filepath inside such a directory if "__pycache__" is
    mentioned explicitly in the requested pattern.

    Some examples:

    base directory:

        ./
        └── __pycache__
            └── b.txt

    >>> _is_inside_unrequested_special_dir("__pycache__/b.txt", "**")
    True
    >>> _is_inside_unrequested_special_dir("__pycache__/b.txt", "*/b.txt")
    True
    >>> _is_inside_unrequested_special_dir("__pycache__/b.txt", "__pycache__/*")
    False
    >>> _is_inside_unrequested_special_dir("__pycache__/b.txt", "__*/*")
    False
    c                 S   s   g | ]}| d r|qS __
startswithr2   partr"   r"   r#   r4      s     
 z6_is_inside_unrequested_special_dir.<locals>.<listcomp>c                 S   s   g | ]}| d r|qS rY   r[   r]   r"   r"   r#   r4      s     
 )r   parentpartsrR   )rX   r3   Zdata_dirs_to_ignore_in_pathZdata_dirs_to_ignore_in_patternr"   r"   r#   "_is_inside_unrequested_special_dir   s    ra   c                 C   s8   dd t | jD }dd t |jD }t|t|kS )u:  
    When a path matches a pattern, we additionnally check if it's a hidden file or if it's inside
    a hidden directory we ignore by default, i.e. if the file name or a parent directory name starts with a dot.

    Users can still explicitly request a filepath that is hidden or is inside a hidden directory
    if the hidden part is mentioned explicitly in the requested pattern.

    Some examples:

    base directory:

        ./
        └── .hidden_file.txt

    >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_file.txt", "**")
    True
    >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_file.txt", ".*")
    False

    base directory:

        ./
        └── .hidden_dir
            └── a.txt

    >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/a.txt", "**")
    True
    >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/a.txt", ".*/*")
    False
    >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/a.txt", ".hidden_dir/*")
    False

    base directory:

        ./
        └── .hidden_dir
            └── .hidden_file.txt

    >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/.hidden_file.txt", "**")
    True
    >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/.hidden_file.txt", ".*/*")
    True
    >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/.hidden_file.txt", ".*/.*")
    False
    >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/.hidden_file.txt", ".hidden_dir/*")
    True
    >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/.hidden_file.txt", ".hidden_dir/.*")
    False
    c                 S   s(   g | ] }| d rt|d hks|qS .r\   rU   r]   r"   r"   r#   r4      s    
  zS_is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir.<locals>.<listcomp>c                 S   s(   g | ] }| d rt|d hks|qS rb   rd   r]   r"   r"   r#   r4      s    
  )r   r`   rR   )rX   r3   Zhidden_directories_in_pathZhidden_directories_in_patternr"   r"   r#   ?_is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir   s    5re   )pattern_resolverr<   c                    s.  t D ]dd}z| |}W n tk
r8   Y qY nX t|dkrfdd|D fddtD ttt  }fdd	|D   S qtD ]~ g }  D ]R\}}|D ]D}z| |}W n tk
r   Y qY nX t|dkr|	|  qqq|r fd
d	|D   S qtd| d|  dS )a+  
    Get the default pattern from a directory or repository by testing all the supported patterns.
    The first patterns to return a non-empty list of data files is returned.

    In order, it first tests if SPLIT_PATTERN_SHARDED works, otherwise it tests the patterns in ALL_DEFAULT_PATTERNS.
    z{split}*r   c                    s   h | ]}t |t d  qS rO   )r   r   )r2   psplit_patternr"   r#   	<setcomp>   s     z+_get_data_files_patterns.<locals>.<setcomp>c                    s   g | ]}| krt |qS r"   )rF   r8   )rW   r"   r#   r4      s      z,_get_data_files_patterns.<locals>.<listcomp>c                    s   i | ]}| j |d gqS )rO   )r/   r8   ri   r"   r#   r:      s      z,_get_data_files_patterns.<locals>.<dictcomp>c                    s   i | ]}| | qS r"   r"   r8   )patterns_dictr"   r#   r:      s      Couldn't resolve pattern  with resolver N)
ALL_SPLIT_PATTERNSreplaceFileNotFoundErrorrR   DEFAULT_SPLITSsortedrU   ALL_DEFAULT_PATTERNSrP   append)rf   r3   
data_filesZsorted_splitsZnon_empty_splitsr9   rD   r"   )rl   rj   rW   r#   _get_data_files_patterns   s4    



rw   c              	   C   sf   g }t D ]<}z"| |}t|dkr,|| W q tk
rB   Y qX q|rN|S td| d|  dS )zM
    Get the supported metadata patterns from a directory or repository.
    r   rm   rn   N)METADATA_PATTERNSrR   ru   rq   )rf   Znon_empty_patternsr3   Zmetadata_filesr"   r"   r#   _get_metadata_files_patterns  s    ry   )r3   	base_pathallowed_extensionsdownload_configr<   c                    s  t | rt|| } n$t| r4tj| d tj }nd}t| |d\} }t| |d\}}}|	dd 	dd pv|j
| 	dd 	dd ttt| h t|jtr|jn|jd }|dkr|d ndfd	d
|j| dd D } dk	rR fdd
|D }	t|	t|k rVtt|t|	 }
td|  d|
  n|}	|	sd|  d} dk	r|dt  7 }t||	S )a  
    Resolve the paths and URLs of the data files from the pattern passed by the user.

    You can use patterns to resolve multiple local files. Here are a few examples:
    - *.csv to match all the CSV files at the first level
    - **.csv to match all the CSV files at any level
    - data/* to match all the files inside "data"
    - data/** to match all the files inside "data" and its subdirectories

    The patterns are resolved using the fsspec glob.
    Here are some behaviors specific to fsspec glob that are different from glob.glob, Path.glob, Path.match or fnmatch:
    - '*' matches only first level items
    - '**' matches all items
    - '**/*' matches all at least second level items

    More generally:
    - '*' matches any character except a forward-slash (to match just the file or directory name)
    - '**' matches any character including a forward-slash /

    Hidden files and directories (i.e. whose names start with a dot) are ignored, unless they are explicitly requested.
    The same applies to special directories that start with a double underscore like "__pycache__".
    You can still include one if the pattern explicilty mentions it:
    - to include a hidden file: "*/.hidden.txt" or "*/.*"
    - to include a hidden directory: ".hidden/*" or ".*/*"
    - to include a special directory: "__special__/*" or "__*/*"

    Example::

        >>> from datasets.data_files import resolve_pattern
        >>> base_path = "."
        >>> resolve_pattern("docs/**/*.py", base_path)
        [/Users/mariosasko/Desktop/projects/datasets/docs/source/_config.py']

    Args:
        pattern (str): Unix pattern or paths or URLs of the data files to resolve.
            The paths can be absolute or relative to base_path.
            Remote filesystems using fsspec are supported, e.g. with the hf:// protocol.
        base_path (str): Base path to use when resolving relative paths.
        allowed_extensions (Optional[list], optional): White-list of file extensions to use. Defaults to None (all extensions).
            For example: allowed_extensions=[".csv", ".json", ".txt", ".parquet"]
    Returns:
        List[str]: List of paths or URLs to the local or remote files that match the patterns.
    r    r|   storage_optionsz::z://filec                    sz   g | ]r\}}|d  dkrt | krttj|tjsttj|tjs|rn|n| qS )typer   )r   ra   osrN   relpathre   r\   )r2   filepathinfo)files_to_ignorefs_base_path
fs_patternprotocol_prefixr"   r#   r4   S  s     z#resolve_pattern.<locals>.<listcomp>T)detailNc                    s8   g | ]0}t  fd dt|ddd D r|qS )c                 3   s   | ]}d |  kV  qdS )rc   Nr"   )r2   suffixr{   r"   r#   r?   c  s     z-resolve_pattern.<locals>.<listcomp>.<genexpr>rc   r   N)r@   r   r9   )r2   r   r   r"   r#   r4   `  s   (z Some files matched the pattern 'z-' but don't have valid data file extensions: zUnable to find ''z with any supported extension )r   r   r   r   rN   
splitdriver-   r   r   r9   Zroot_markerrU   FILES_TO_IGNOREr   rG   protocolrF   globrP   rR   rH   loggerr   rq   )r3   rz   r{   r|   r   fs_r   Zmatched_pathsoutZinvalid_matched_files	error_msgr"   )r{   r   r   r   r   r#   resolve_pattern  s>    1


r   )rz   r|   r<   c                 C   sD   t t| |d}z
t|W S  tk
r>   td|  ddY nX dS )u  
    Get the default pattern from a directory testing all the supported patterns.
    The first patterns to return a non-empty list of data files is returned.

    Some examples of supported patterns:

    Input:

        my_dataset_repository/
        ├── README.md
        └── dataset.csv

    Output:

        {"train": ["**"]}

    Input:

        my_dataset_repository/
        ├── README.md
        ├── train.csv
        └── test.csv

        my_dataset_repository/
        ├── README.md
        └── data/
            ├── train.csv
            └── test.csv

        my_dataset_repository/
        ├── README.md
        ├── train_0.csv
        ├── train_1.csv
        ├── train_2.csv
        ├── train_3.csv
        ├── test_0.csv
        └── test_1.csv

    Output:

        {"train": ["**train*"], "test": ["**test*"]}

    Input:

        my_dataset_repository/
        ├── README.md
        └── data/
            ├── train/
            │   ├── shard_0.csv
            │   ├── shard_1.csv
            │   ├── shard_2.csv
            │   └── shard_3.csv
            └── test/
                ├── shard_0.csv
                └── shard_1.csv

    Output:

        {"train": ["**train*/**"], "test": ["**test*/**"]}

    Input:

        my_dataset_repository/
        ├── README.md
        └── data/
            ├── train-00000-of-00003.csv
            ├── train-00001-of-00003.csv
            ├── train-00002-of-00003.csv
            ├── test-00000-of-00001.csv
            ├── random-00000-of-00003.csv
            ├── random-00001-of-00003.csv
            └── random-00002-of-00003.csv

    Output:

        {
            "train": ["data/train-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9].*"],
            "test": ["data/test-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9].*"],
            "random": ["data/random-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9].*"],
        }

    In order, it first tests if SPLIT_PATTERN_SHARDED works, otherwise it tests the patterns in ALL_DEFAULT_PATTERNS.
    rz   r|   The directory at z doesn't contain any data filesN)r   r   rw   rq   r$   rz   r|   resolverr"   r"   r#   get_data_patternst  s
    T
r   c                 C   sD   t t| |d}z
t|W S  tk
r>   td|  ddY nX dS )zE
    Get the supported metadata patterns from a local directory.
    r   r   z" doesn't contain any metadata fileN)r   r   ry   rq   r   r"   r"   r#   get_metadata_patterns  s
    
r   )	data_filer|   r<   c           	      C   s   t | |d\} }t| |d\}}}t|trB|| }|j|jfS t|tr| t	j
rtt	j
|jd}d| tt	j
d d  ddd } || }|j|jfS || }dD ]}||krt|| f  S qd	S )
Nr~   r   )Zendpointtokenzhf://r   z	/resolve/@)ETagetagmtimer"   )r   r   rG   r   Zresolve_pathZrepo_idrevisionr   r\   r   ZHF_ENDPOINTr   rR   rp   r   rF   )	r   r|   r   r   r   resolved_pathZhffsr   rI   r"   r"   r#   _get_single_origin_metadata  s    

$

r   @   )rv   r|   r<   c                 C   s0   t tt|d| |tjdt| dkp*t  dS )Nr~   zResolving data files   )max_workersZ
tqdm_classdescdisable)r   r   r   r   ZtqdmrR   Zis_progress_bar_enabled)rv   r   r|   r"   r"   r#   _get_origin_metadata  s    
r   c                	       s   e Zd ZdZee eee  d fddZdd Ze	dee e
jjee eee  ee d dd	d
Ze	dee ee eee  ee d dddZe	dee ee eee  ee d dddZee d dddZ  ZS )rC   a  
    List of data files (absolute local paths or URLs).
    It has two construction methods given the user's data files patterns :
    - ``from_hf_repo``: resolve patterns inside a dataset repository
    - ``from_local_or_remote``: resolve patterns from a local path

    Moreover DataFilesList has an additional attribute ``origin_metadata``.
    It can store:
    - the last modified time of local files
    - ETag of remote files
    - commit sha of a dataset repository

    Thanks to this additional attribute, it is possible to hash the list
    and get a different hash if and only if at least one file changed.
    This is useful for caching Dataset objects that are obtained from a list of data files.
    )rv   origin_metadatac                    s   t  | || _d S r=   )super__init__r   )selfrv   r   	__class__r"   r#   r     s    zDataFilesList.__init__c                 C   s   t | || j|j S r=   )rC   r   )r   otherr"   r"   r#   __add__  s    zDataFilesList.__add__NrD   dataset_inforz   r{   r|   r<   c                 C   s6   d|j  d|j d|pd d}| j||||dS )Nzhf://datasets/r   /r}   rz   r{   r|   )idsharstripfrom_patterns)clsrD   r   rz   r{   r|   r"   r"   r#   from_hf_repo  s    	$   zDataFilesList.from_hf_reporD   rz   r{   r|   r<   c                 C   s,   |d k	r|nt    }| j||||dS Nr   )r   resolveas_posixr   )r   rD   rz   r{   r|   r"   r"   r#   from_local_or_remote)  s       z"DataFilesList.from_local_or_remotec              	   C   sx   |d k	r|nt    }g }|D ]>}z|t||||d W q" tk
r^   t|sZ Y q"X q"t||d}| ||S )Nr   r~   )r   r   r   extendr   rq   r   r   )r   rD   rz   r{   r|   rv   r3   r   r"   r"   r#   r   6  s"    
zDataFilesList.from_patterns
extensionsr<   c                    sB   d dd |D  td  d t fdd| D | jdS )	N|c                 s   s   | ]}d | V  qdS )\Nr"   )r2   extr"   r"   r#   r?   Q  s     z2DataFilesList.filter_extensions.<locals>.<genexpr>z.*(z	)(\..+)?$c                    s   g | ]}  |r|qS r"   )match)r2   r   r>   r"   r#   r4   T  s     
 z3DataFilesList.filter_extensions.<locals>.<listcomp>)r   )joinrecompilerC   r   )r   r   r"   r>   r#   filter_extensionsP  s    zDataFilesList.filter_extensions)NNN)NNN)NNN)r   r    r!   __doc__r   rF   r   r   r   classmethodhuggingface_hubhf_apiDatasetInfor	   r   r   r   r   r   __classcell__r"   r"   r   r#   rC     sL       
   
   
c                	   @   s   e Zd ZdZedeeeee e	f f e
e e
ee  e
e d dddZedeeeee e	f f ejje
e e
ee  e
e d dddZedeeeee e	f f e
e e
ee  e
e d dd	d
Zee d dddZdS )DataFilesDicta  
    Dict of split_name -> list of data files (absolute local paths or URLs).
    It has two construction methods given the user's data files patterns :
    - ``from_hf_repo``: resolve patterns inside a dataset repository
    - ``from_local_or_remote``: resolve patterns from a local path

    Moreover each list is a DataFilesList. It is possible to hash the dictionary
    and get a different hash if and only if at least one file changed.
    For more info, see ``DataFilesList``.

    This is useful for caching Dataset objects that are obtained from a list of data files.

    Changing the order of the keys of this dictionary also doesn't change its hash.
    Nr   c                 C   s@   |  }|  D ],\}}t|ts2tj||||dn|||< q|S r   )rP   rG   rC   r   r   rD   rz   r{   r|   r   rI   patterns_for_keyr"   r"   r#   r   i  s    
z"DataFilesDict.from_local_or_remoter   c           	      C   sB   |  }|  D ].\}}t|ts4tj|||||dn|||< q|S )N)r   rz   r{   r|   )rP   rG   rC   r   )	r   rD   r   rz   r{   r|   r   rI   r   r"   r"   r#   r     s    		zDataFilesDict.from_hf_repoc                 C   s@   |  }|  D ],\}}t|ts2tj||||dn|||< q|S r   )rP   rG   rC   r   r   r"   r"   r#   r     s    
zDataFilesDict.from_patternsr   c                 C   s.   t |  }|  D ]\}}||||< q|S r=   )r   rP   r   )r   r   r   rI   Zdata_files_listr"   r"   r#   r     s    
zDataFilesDict.filter_extensions)NNN)NNN)NNN)r   r    r!   r   r   r   rF   r   r   rC   r	   r   r   r   r   r   r   r   r   r"   r"   r"   r#   r   Y  sH      
   
   
r   )NN)N)N)N)r   N)Rr   r   	functoolsr   r   r   pathlibr   r   typingr   r   r   r	   r
   r   r   r   Zfsspecr   Zfsspec.implementations.httpr   r   Ztqdm.contrib.concurrentr   r}   r   downloadr   Z#download.streaming_download_managerr   r   r   rW   r   utilsr   Zutils.file_utilsr   r   Zutils.py_utilsr   r   rF   ZTRAINrQ   Z
get_loggerr   r   r   rq   r$   ZSPLIT_PATTERN_SHARDEDZ
VALIDATIONZTESTr7   r0   r.   r;   rr   Z"DEFAULT_PATTERNS_SPLIT_IN_FILENAMEZ"DEFAULT_PATTERNS_SPLIT_IN_DIR_NAMEZDEFAULT_PATTERNS_ALLro   rt   rx   rA   r   boolrB   rV   ra   re   rw   ry   r   r   r   r   r   rC   r   r"   r"   r"   r#   <module>   s   $

  
 

 .&!>*%"  
_$]    W