
    +gd~                     ^   d dl 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mZmZ ddlmZ ddlm Z   e!ej"                  Z# ej$        e%          Z& G d de!          Z' G d de(          Z)dZ*ej"        ddgej+        g dej,        g diZ-dZ.ddgZ/ddgZ0ej"        ej+        ej,        gZ1d e1D             Z2d e1D             Z3ej"        dgiZ4e*gZ5e3e2e4gZ6g dZ7d Z8g d!Z9d"e!d#e:fd$Z;d%eee	e!f         d#ee!ee	e!         d&f         f         fd'Z<d(e!d"e!d#e:fd)Z=d(e!d"e!d#e:fd*Z>d+ee!ge	e         f         d#ee!e	e!         f         fd,Z?d+ee!ge	e         f         d#ee!e	e!         f         fd-Z@	 dBd.e!d"e!d/e
e	e!                  d#e	e         fd0ZA	 dBd.e!d%e	e!         d/e
e	e!                  d#e	eee'f                  fd1ZBd.e!d#ee!e	e!         f         fd2ZCd.e!d#e	e!         fd3ZD	 	 dCd4ejE        jF        d"e!d.e
e!         d/e
eG         d#e	e         f
d5ZH	 	 dCd4ejE        jF        d%e	e!         d.e
e!         d/e
eG         d#e	e'         f
d6ZId4ejE        jF        d.e!d#ee!e	e!         f         fd7ZJd4ejE        jF        d.e!d#e	e!         fd8ZK	 dBd9eee'f         d:e
ee:e!f                  d#ee!         fd;ZL	 dDd=e	eee'f                  d:e
ee:e!f                  d#ee!         fd>ZM G d? d&e	eee'f                            ZN G d@ dAee!eNf                   ZOdS )E    N)partial)PathPurePath)CallableDictListOptionalSetTupleUnion)LocalFileSystem)
thread_map   )HfFileSystem)Split)logging)is_relative_pathis_remote_urlrequest_etag)
hf_hub_urlstring_to_dictc                       e Zd ZdS )UrlN__name__
__module____qualname__     3lib/python3.11/site-packages/datasets/data_files.pyr   r              Dr    r   c                       e Zd ZdS )EmptyDatasetErrorNr   r   r    r!   r$   r$      r"   r    r$   zFdata/{split}-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9]*.*traintraining)
validationvaliddevval)testtestingeval
evaluationz-._ 0-9z**[{sep}/]{keyword}[{sep}]*z{keyword}[{sep}]*z{keyword}[{sep}/]**z**[{sep}/]{keyword}[{sep}/]**c                 >    i | ]}|d  t           |         D             S )c                 Z    g | ](}t           D ]}|                    |t                     )S )keywordsep)"KEYWORDS_IN_FILENAME_BASE_PATTERNSformatNON_WORDS_CHARS.0r2   patterns      r!   
<listcomp>z<dictcomp>.<listcomp>-   O       9   	wO<<   r    SPLIT_KEYWORDSr8   splits     r!   
<dictcomp>r@   ,   K     & & & 	 
  %e,  & & &r    c                 >    i | ]}|d  t           |         D             S )c                 Z    g | ](}t           D ]}|                    |t                     )S r1   )"KEYWORDS_IN_DIR_NAME_BASE_PATTERNSr5   r6   r7   s      r!   r:   z<dictcomp>.<listcomp>5   r;   r    r<   r>   s     r!   r@   r@   4   rA   r    z**)zmetadata.csvz**/metadata.csvzmetadata.jsonlz**/metadata.jsonlz*[])z	README.mdzconfig.jsonzdataset_infos.jsonzdummy_data.zipzdataset_dict.jsonr9   returnc                 D     t           fdt          D                       S )Nc              3       K   | ]}|v V  	d S Nr   )r8   wilcard_characterr9   s     r!   	<genexpr>z%contains_wildcards.<locals>.<genexpr>R   s*      YY0A G+YYYYYYr    )anyWILDCARD_CHARACTERS)r9   s   `r!   contains_wildcardsrM   Q   s'    YYYYEXYYYYYYr    patternsDataFilesListc                    t          | t                    rd |                                 D             S t          | t                    r
t          | giS t          | t
                    r	t          | iS t          t          |           i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 _atterns
    c                 d    i | ]-\  }}t          |          t          |t                    r|n|g.S r   )str
isinstancelist)r8   keyvalues      r!   r@   z%sanitize_patterns.<locals>.<dictcomp>_   s:    kkkJCQVC:eT#:#:G%%kkkr    )rS   dictitemsrR   SANITIZED_DEFAULT_SPLITrT   )rN   s    r!   sanitize_patternsrZ   U   s     (D!! 9kkZbZhZhZjZjkkkk	Hc	"	" 9'(44	Hd	#	# 9'22'h88r    matched_rel_pathc                     d t          |           j        j        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                 <    g | ]}|                     d           |S __
startswithr8   parts     r!   r:   z6_is_inside_unrequested_special_dir.<locals>.<listcomp>   s-    "u"u"uD_c_n_nos_t_t"u4"u"u"ur    c                 <    g | ]}|                     d           |S r^   r`   rb   s     r!   r:   z6_is_inside_unrequested_special_dir.<locals>.<listcomp>   s-    %o%o%otY]YhYhimYnYn%od%o%o%or    )r   parentpartslen)r[   r9   data_dirs_to_ignore_in_pathdata_dirs_to_ignore_in_patterns       r!   "_is_inside_unrequested_special_dirrj   h   sg    8 #v"uH=M4N4N4U4["u"u"u%o%ox7H7H7O7U%o%o%o"*++s3Q/R/RRRr    c                     d t          |           j        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                 d    g | ]-}|                     d           rt          |          d hk    +|.S .ra   setrb   s     r!   r:   zS_is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir.<locals>.<listcomp>   sJ     " " "T__S=Q=Q"Z]^bZcZchkglZlZlZlZlZlr    c                 d    g | ]-}|                     d           rt          |          d hk    +|.S rm   ro   rb   s     r!   r:   zS_is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir.<locals>.<listcomp>   sJ     % % %DOOC4H4H%QTUYQZQZ_b^cQcQcQcQcQcr    )r   rf   rg   )r[   r9   hidden_directories_in_pathhidden_directories_in_patterns       r!   ?_is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dirrt      sw    j" "!"2339" " "% %!'**0% % %! )**c2O.P.PPPr    pattern_resolverc                 x  	 t           D ]                    dd          } | |          }t          |          dk    rbd |D             }fd|D             		fdt          D             t	          	t          t                    z
            z   }fd|D             c S t          D ]{g }                                D ]P\  }}	 |D ]7} | |          }t          |          dk    r|                    |            n8A# t          $ r Y Mw xY w|rfd|D             c S |t          d	| d
|            )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                 6    g | ]}|                                 S r   )as_posix)r8   ps     r!   r:   z,_get_data_files_patterns.<locals>.<listcomp>   s     ;;;1!**,,;;;r    c                 <    h | ]}t          |          d          S r?   r   )r8   rz   split_patterns     r!   	<setcomp>z+_get_data_files_patterns.<locals>.<setcomp>   s(    ^^^aq- @ @ I^^^r    c                 6    g | ]}|v t          |          S r   )rR   )r8   r?   splitss     r!   r:   z,_get_data_files_patterns.<locals>.<listcomp>   s%    WWWEuPVSZZr    c                 @    i | ]}|                     |           gS )r|   )r5   )r8   r?   r}   s     r!   r@   z,_get_data_files_patterns.<locals>.<dictcomp>   s/    ZZZ5EM00u0==>ZZZr    c                 "    i | ]}||         S r   r   )r8   r?   patterns_dicts     r!   r@   z,_get_data_files_patterns.<locals>.<dictcomp>   s     NNNEE=/NNNr    Couldn't resolve pattern  with resolver )
ALL_SPLIT_PATTERNSreplacerg   DEFAULT_SPLITSsortedrp   ALL_DEFAULT_PATTERNSrX   appendFileNotFoundError)
ru   r9   
data_filessorted_splitsnon_empty_splitsr?   rN   r   r}   r   s
          @@@r!   _get_data_files_patternsr      s    , 	[ 	[''	377%%g..
z??Q;;
;;;J^^^^S]^^^FWWWW^WWWZ`^,,,[ [ M [ZZZMZZZZZZ  . O O,2244 	 	OE8'  G!1!1'!:!:J:**(//666 + %    	ONNNN=MNNNNNN	O
bbbP`bb
c
ccs   	:D
DDc                     g }t           D ]F}	  | |          }t          |          dk    r|                    |           7# t          $ r Y Cw xY w|r|S t          d| d|            )zM
    Get the supported metadata patterns from a directory or repository.
    r   r   r   )METADATA_PATTERNSrg   r   r   )ru   non_empty_patternsr9   metadata_filess       r!   _get_metadata_files_patternsr      s     $  	--g66N>""Q&&"))'222  	 	 	D	 "!!
bbbP`bb
c
ccs   3A
AA	base_pathallowed_extensionsc                 f    t                    r!t          j                                       n2t          j                                      d         t          j        z    t                      fd                              D             } fd|D             }fd|D             }t          |          t          |          k     rnt          t          |          t          |          z
            }t                              d dt                                                      d|            n|}|s\t                    sMd	 dt                                                      }|d
t                     z  }t!          |          t#          |          S )z
    Return the absolute paths to all the files that match the given patterns.
    It also supports absolute paths in patterns.
    If an URL is passed, it is returned as is.
    r   c                 X    g | ]&}                     |          t          |          'S r   isfiler   r8   filepathfss     r!   r:   z3_resolve_single_pattern_locally.<locals>.<listcomp>  s3    \\\		RZH[H[\(##\\\r    c           	         g | ]}|j         t          vst                    j         |j         k    -t          t          j                            |          t          j                                                yt          t          j                            |          t          j                                                t          t          j        	                    |                    S r   )
nameFILES_TO_IGNOREr   rj   ospathrelpathrt   r   abspathr8   r   r   r9   s     r!   r:   z3_resolve_single_pattern_locally.<locals>.<listcomp>	  s     
 
 
M00HW4E4E4Jhm4[4[2GOOHi00"'//'92U2U
 
 5\ PGOOHi00"'//'92U2U
 
	 5\ 	RW__X&&''4[4[4[r    Nc                 T    g | ]$}t          fd |j        D                       "|%S )c              3   0   K   | ]}|d d         v V  dS r   Nr   r8   suffixr   s     r!   rJ   z=_resolve_single_pattern_locally.<locals>.<listcomp>.<genexpr>  1      TT6!"":!33TTTTTTr    rK   suffixesr8   r   r   s     r!   r:   z3_resolve_single_pattern_locally.<locals>.<listcomp>  O     
 
 
TTTT(BSTTTTT

 
 
r    z Some files matched the pattern '' at , but don't have valid data file extensions: zUnable to find ' with any supported extension )r   r   r   join
splitdriver3   r   globrg   rT   rp   loggerinfor   resolverM   r   r   )	r   r9   r   	glob_itermatched_pathsoutinvalid_matched_files	error_msgr   s	   ```     @r!   _resolve_single_pattern_locallyr      s       <',,y'22G&&w//2RV;				B\\\\BGGG4D4D\\\I
 
 
 
 
!
 
 
M %
 
 
 
)
 
 

 s88c-(((($(]););c#hh)F$G$G!KK `7  `  `iAXAXAZAZ  `  `  I^  `  `    +)'22 +PwPPT)__5L5L5N5NPP	)T$?Q:R:RTTTI	***#;;r    c                 h   g }|D ]]}t          |          r#|                    t          |                     4t          | ||          D ]}|                    |           ^|sMd| dt	          |                                            }||dt          |           z  }t          |          |S )a  
    Resolve the paths and URLs of the data files from the patterns passed by the user.
    URLs are just returned as is.

    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_patterns_locally_or_by_urls
        >>> base_path = "."
        >>> resolve_patterns_locally_or_by_urls(base_path, ["src/**/*.yaml"])
        [PosixPath('/Users/quentinlhoest/Desktop/hf/datasets/src/datasets/utils/resources/readme_structure.yaml')]

    Args:
        base_path (str): Base path to use when resolving relative paths.
        patterns (List[str]): Unix patterns or paths or URLs of the data files to resolve.
            The paths can be absolute or relative to base_path.
        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[Union[Path, Url]]: List of paths or URLs to the local or remote files that match the patterns.
    z.Unable to resolve any data file that matches 'r   Nr   )r   r   r   r   r   r   rT   r   )r   rN   r   r   r9   r   r   s          r!   #resolve_patterns_locally_or_by_urlsr   )  s    ^ J ( (!! 	(c'll++++7	7L^__ ( (!!$''''(  +oXooTXYbTcTcTkTkTmTmoo	)T$?Q:R:RTTTI	***r    c                     t          t          |           }	 t          |          S # t          $ r t	          d|  d          dw xY w)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.
    The directory at z doesn't contain any data filesN)r   r   r   r   r$   r   resolvers     r!   get_data_patterns_locallyr   h  se    h 6	BBHj'111 j j j ^I ^ ^ ^__eiij	   & Ac                     t          t          |           }	 t          |          S # t          $ r t          d|  d          dw xY w)zE
    Get the supported metadata patterns from a local directory.
    r   z" doesn't contain any metadata fileN)r   r   r   r   r   s     r!   get_metadata_patterns_locallyr     sd     6	BBHm+H555 m m m aI a a abbhllmr   dataset_infoc                   	 t          |           	r d nd	fd	                    t                                                              D             }fd|D             }fd|D             }t	          |          t	          |          k     rTt          t          |          t          |          z
            }t                              d d| j	         d|            n|}|sBt                    s3d	 d| j	         }|d
t                     z  }t          |          t          |          S )N)	repo_info/c                 X    g | ]&}                     |          t          |          'S r   r   r   s     r!   r:   zA_resolve_single_pattern_in_dataset_repository.<locals>.<listcomp>  s6    qqq]_]f]fgo]p]pq(##qqqr    c           	         g | ]}|j         t          vst                    j         |j         k    -t          t          j                            |          t          j                                                yt          t          j                            |          t          j                                                |S r   )r   r   r   rj   r   r   r   rt   r   s     r!   r:   zA_resolve_single_pattern_in_dataset_repository.<locals>.<listcomp>  s     
 
 
M00HW4E4E4Jhm4[4[2GOOHi00"'//'92U2U
 
 5\ PGOOHi00"'//'92U2U
 
	 5\ 	4[4[4[r    c                 T    g | ]$}t          fd |j        D                       "|%S )c              3   0   K   | ]}|d d         v V  dS r   r   r   s     r!   rJ   zK_resolve_single_pattern_in_dataset_repository.<locals>.<listcomp>.<genexpr>  r   r    r   r   s     r!   r:   zA_resolve_single_pattern_in_dataset_repository.<locals>.<listcomp>  r   r    zSome files matched the pattern  in dataset repository r   zUnable to find r   )r   r   r   ry   rg   rT   rp   r   r   idrM   r   r   )
r   r9   r   r   r   r   r   r   r   r   s
    ```     @r!   -_resolve_single_pattern_in_dataset_repositoryr     s    
	-	-	-B ****	qqqqBGGHW<M<M<V<V<X<X4Y4YqqqI
 
 
 
 
!
 
 
M %
 
 
 
)
 
 

 s88c-(((($(]););c#hh)F$G$G!KK g'  g  gR^Ra  g  g  Pe  g  g    +)'22 +WgWWloWW	)T$?Q:R:RTTTI	***#;;r    c                 D   g }|D ]e}t          | |||          D ]P}|                    t          t          | j        |                                | j                                       Qf|s3d| d| j         }||dt          |           z  }t          |          |S )a
  
    Resolve the URLs of the data files from the patterns passed by the user.

    You can use patterns to resolve multiple 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::

        >>> import huggingface_hub
        >>> from datasets.data_files import resolve_patterns_in_dataset_repository
        >>> dataset_info = huggingface_hub.HfApi().dataset_info("lhoestq/demo1")
        >>> resolve_patterns_in_dataset_repository(dataset_info, ["data/*.csv"])
        ['https://huggingface.co/datasets/lhoestq/demo1/resolve/0ca0d9f35b390ad11516095aeb27fd30cfe72578/data/test.csv',
        'https://huggingface.co/datasets/lhoestq/demo1/resolve/0ca0d9f35b390ad11516095aeb27fd30cfe72578/data/train.csv']

    Args:
        dataset_info (huggingface_hub.hf_api.DatasetInfo): dataset info obtained using the hugginggace_hub.HfApi
        patterns (List[str]): Unix patterns or paths of the files in the dataset repository.
            The paths should be relative to the root of the repository.
        base_path (Optional[str], optional): Path inside a repo to use when resolving relative paths.
            Defaults to None (search from a repository's root). Used if files only from a specific
            directory should be resolved.
        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[Url]: List of URLs to the files in the dataset repository that match the patterns.
    )revisionz-Unable to resolve any data file that matches r   Nr   )	r   r   r   r   r   ry   sharT   r   )r   rN   r   r   data_files_urlsr9   rel_pathr   s           r!   &resolve_patterns_in_dataset_repositoryr     s    l "$O u uE'9.@
 
 	u 	uH ""3z,/8CTCTCVCVamaq'r'r'r#s#stttt	u  +vHvveqetvv	)T$?Q:R:RTTTI	***r    c                     t          t          | |          }	 t          |          S # t          $ r t	          d| j         d          dw xY w)u  
    Get the default pattern from a repository by 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.
    r   The dataset repository at 'z ' doesn't contain any data filesN)r   r   r   r   r$   r   r   r   r   s      r!   'get_data_patterns_in_dataset_repositoryr   >  sn    l Dl^ghhhH'111   [,/[[[
 
		   ( $Ac                     t          t          | |          }	 t          |          S # t          $ r t          d| j         d          dw xY w)zG
    Get the supported metadata patterns from a remote repository.
    r   r   z$' doesn't contain any metadata file.N)r   r   r   r   r   r   s      r!   +get_metadata_patterns_in_dataset_repositoryr     sm     Dl^ghhhH+H555   _,/___
 
	r   	data_fileuse_auth_tokenc                 
   t          | t                    r!t          |           } t          | |          fS t          |                                           } t          t
          j                            |                     fS Nr   )rS   r   rR   r   r   r   r   getmtime)r   r   s     r!   ._get_single_origin_metadata_locally_or_by_urlsr     sq     )S!! 3	NN	Y~FFFHH	))++,,	BG$$Y//0022r    @   r   c           
          t          t          t          |          | |t          j        dt          |           dk    pt          j                               S )Nr   zResolving data files   )max_workers
tqdm_classdescdisable)r   r   r   r   tqdmrg   is_progress_bar_enabled)r   r   r   s      r!   '_get_origin_metadata_locally_or_by_urlsr     sY     >~^^^<#J2%NW-L-N-N)N   r    c                   V    e Zd ZdZdeeeef                  deee	                  f fdZ
e	 	 ddee	         dej        j        dee	         d	eee	                  d
d f
d            Ze	 	 	 ddee	         dee	         d	eee	                  deeee	f                  d
d f
d            Z xZS )rO   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.
    r   origin_metadatac                 X    t                                          |           || _        d S rH   )super__init__r   )selfr   r   	__class__s      r!   r   zDataFilesList.__init__  s)    $$$.r    NrN   r   r   r   rE   c                 \    t          |||          }fd|D             } | ||          S )Nc                 ,    g | ]}j         j        fS r   )r   r   )r8   _r   s     r!   r:   z.DataFilesList.from_hf_repo.<locals>.<listcomp>  s#    QQQ1LO\-=>QQQr    )r   )clsrN   r   r   r   r   r   s     `    r!   from_hf_repozDataFilesList.from_hf_repo  sE     <L(T]_qrr
QQQQQQQs:///r    r   c                     ||n,t          t                                                                }t          |||          }t	          ||          } | ||          S r   )rR   r   r   r   r   )r   rN   r   r   r   r   r   s          r!   from_local_or_remotez"DataFilesList.from_local_or_remote  s_     "+!6IIC@P@P<Q<Q	8HN`aa
A*]kllls:///r    NNNNN)r   r   r   __doc__r   r   r   r   r   rR   r   classmethodhuggingface_hubhf_apiDatasetInfor	   r   boolr  __classcell__)r   s   @r!   rO   rO     sb        "/4dCi(8#9 /DQVWZQ[L\ / / / / / / 
 $(26	0 	0s)	0 &,8	0 C=		0
 %T#Y/	0 
	0 	0 	0 [	0  $(2659
0 
0s)
0 C=
0 %T#Y/	
0
 !tSy!12
0 

0 
0 
0 [
0 
0 
0 
0 
0r    c                   N   e Zd ZdZe	 	 	 ddeeeee         e	f         f         de
e         de
ee                  de
eeef                  dd f
d            Ze	 	 ddeeeee         e	f         f         d	ej        j        de
e         de
ee                  dd f
d
            Z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.
    NrN   r   r   r   rE   c                      |             }|                                 D ]=\  }}t          |t                    st                              ||||          n|||<   >|S )N)r   r   r   )rX   rS   rO   r  )r   rN   r   r   r   r   rU   patterns_for_keys           r!   r  z"DataFilesDict.from_local_or_remote  s     cee%-^^%5%5 
	 
	!C! ""2MBB&22$''9#1	 3    & HH 
r    r   c                      |             }|                                 D ]=\  }}t          |t                    st                              ||||          n|||<   >|S )N)r   r   r   )rX   rS   rO   r   )r   rN   r   r   r   r   rU   r  s           r!   r   zDataFilesDict.from_hf_repo  s     cee%-^^%5%5 
	 
	!C! ""2MBB&**$!-''9	 +    & HH 
r    c                 n    t           t          t          |                                                     ffS )a2  
        To make sure the order of the keys doesn't matter when pickling and hashing:

        >>> from datasets.data_files import DataFilesDict
        >>> from datasets.fingerprint import Hasher
        >>> assert Hasher.hash(DataFilesDict(a=[], b=[])) == Hasher.hash(DataFilesDict(b=[], a=[]))

        )r  rW   r   rX   )r   s    r!   
__reduce__zDataFilesDict.__reduce__0  s*     tF4::<<$8$899;;;r    r  r  )r   r   r   r  r  r   rR   r   r   rO   r	   r	  r  r  r  r  r   r  r   r    r!   r  r    sH          $(2659 sE$s)]":;;< C= %T#Y/	
 !tSy!12 
   [* 
 $(26 sE$s)]":;;< &,8 C=	
 %T#Y/ 
   [*	< 	< 	< 	< 	<r    r  rH   r  )r   N)Pr   	functoolsr   pathlibr   r   typingr   r   r   r	   r
   r   r   r  fsspec.implementations.localr   tqdm.contrib.concurrentr   filesystems.hffilesystemr   r   r   utilsr   utils.file_utilsr   r   r   	utils.hubr   utils.py_utilsr   rR   TRAINrY   
get_loggerr   r   r   r   r$   SPLIT_PATTERN_SHARDED
VALIDATIONTESTr=   r6   r4   rD   r   "DEFAULT_PATTERNS_SPLIT_IN_FILENAME"DEFAULT_PATTERNS_SPLIT_IN_DIR_NAMEDEFAULT_PATTERNS_ALLr   r   r   rL   r   r	  rM   rZ   rj   rt   r   r   r   r   r   r   r  r  rT   r   r   r   r   r   r   rO   r  r   r    r!   <module>r$     s   				       " " " " " " " " D D D D D D D D D D D D D D D D D D     8 8 8 8 8 8 . . . . . . 2 2 2 2 2 2             K K K K K K K K K K ! ! ! ! ! ! * * * * * * #ek**  
	H	%	%	 	 	 	 	# 	 	 		 	 	 	 	) 	 	 	 a  
K':&	;;;	J999
 &CEX%Y "&;=\%] "+u/<& &  & & & "& &  & & & " 
K$  ,, && 
     kkkZ Z Z Z Z Z9dD#o 6 94U4PS9VeKeEf@f;g 9 9 9 9&S Ss St S S S SB;QVY ;Qdg ;Qlp ;Q ;Q ;Q ;Q| dxtH~8M/N  dSWX[]abe]fXfSg  d  d  d  dFd8SE4><Q3R dW[\_aefiaj\jWk d d d d$ MQ+ ++ +6>tCy6I+	$Z+ + + +^ TX< <<"3i<=Ed3i=P<	%c	
< < < <~Xj Xjc49n1E Xj Xj Xj XjvmS mT#Y m m m m  $)-	) )!(4)) }) !	)
 
(^) ) ) )^  $)-	A A!(4A3iA }A !	A
 
#YA A A AH\!(4\AD\	#tCy.\ \ \ \~!(4AD	#Y     OS3 3T3Y319%c	:J1K3
3Z3 3 3 3 fj
 
U49%&
HPQVW[]`W`QaHb

3Z
 
 
 
-0 -0 -0 -0 -0DtSy)* -0 -0 -0`E< E< E< E< E<Dm+, E< E< E< E< E<r    