a :jgX@svdZddlZddlmZeZddZGdddZeZd ej ddfd d Zed Gd ddZ Gddde Z dS)a"A file interface for handling local and remote data files. The goal of datasource is to abstract some of the file system operations when dealing with data files so the researcher doesn't have to know all the low-level details. Through datasource, a researcher can obtain and use a file with one function call, regardless of location of the file. DataSource is meant to augment standard python libraries, not replace them. It should work seamlessly with standard file IO operations and the os module. DataSource files can originate locally or remotely: - local files : '/home/guido/src/local/data.txt' - URLs (http, ftp, ...) : 'http://www.scipy.org/not/real/data.txt' DataSource files can also be compressed or uncompressed. Currently only gzip, bz2 and xz are supported. Example:: >>> # Create a DataSource, use os.curdir (default) for local storage. >>> from numpy import DataSource >>> ds = DataSource() >>> >>> # Open a remote file. >>> # DataSource downloads the file, stores it locally in: >>> # './www.google.com/index.html' >>> # opens the file and returns a file object. >>> fp = ds.open('http://www.google.com/') # doctest: +SKIP >>> >>> # Use the file as you normally would >>> fp.read() # doctest: +SKIP >>> fp.close() # doctest: +SKIP N) set_modulecCsDd|vr d|vr@td|fn |dur0td|dur@tddS)zCheck mode and that encoding and newline are compatible. Parameters ---------- mode : str File open mode. encoding : str File encoding. newline : str Newline for text files. tbzInvalid mode: %rNz0Argument 'encoding' not supported in binary modez/Argument 'newline' not supported in binary mode) ValueErrormodeencodingnewliner ?/usr/local/lib/python3.9/site-packages/numpy/lib/_datasource.py _check_mode-s r c@s0eZdZdZddZddZddZdd Zd S) _FileOpenersa  Container for different methods to open (un-)compressed files. `_FileOpeners` contains a dictionary that holds one method for each supported file format. Attribute lookup is implemented in such a way that an instance of `_FileOpeners` itself can be indexed with the keys of that dictionary. Currently uncompressed files as well as files compressed with ``gzip``, ``bz2`` or ``xz`` compression are supported. Notes ----- `_file_openers`, an instance of `_FileOpeners`, is made available for use in the `_datasource` module. Examples -------- >>> import gzip >>> np.lib._datasource._file_openers.keys() [None, '.bz2', '.gz', '.xz', '.lzma'] >>> np.lib._datasource._file_openers['.gz'] is gzip.open True cCsd|_dti|_dS)NF)_loadedopen _file_openersselfr r r __init__bsz_FileOpeners.__init__c Cs|jr dSzddl}|j|jd<Wnty4Yn0zddl}|j|jd<Wnty`Yn0z$ddl}|j|jd<|j|jd<WnttfyYn0d|_dS)Nrz.bz2z.gzz.xzz.lzmaT)rbz2rr ImportErrorgziplzmaAttributeError)rrrrr r r _loadfs&   z_FileOpeners._loadcCs|t|jS)a[ Return the keys of currently supported file openers. Parameters ---------- None Returns ------- keys : list The keys are None for uncompressed files and the file extension strings (i.e. ``'.gz'``, ``'.xz'``) for supported compression methods. )rlistrkeysrr r r rsz_FileOpeners.keyscCs||j|SN)rr)rkeyr r r __getitem__sz_FileOpeners.__getitem__N)__name__ __module__ __qualname____doc__rrrrr r r r rIs rrcCst|}|j||||dS)a Open `path` with `mode` and return the file object. If ``path`` is an URL, it will be downloaded, stored in the `DataSource` `destpath` directory and opened from there. Parameters ---------- path : str or pathlib.Path Local file path or URL to open. mode : str, optional Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to append. Available modes depend on the type of object specified by path. Default is 'r'. destpath : str, optional Path to the directory where the source file gets downloaded to for use. If `destpath` is None, a temporary directory will be created. The default path is the current directory. encoding : {None, str}, optional Open text file with given encoding. The default encoding will be what `open` uses. newline : {None, str}, optional Newline to use when reading text file. Returns ------- out : file object The opened file. Notes ----- This is a convenience function that instantiates a `DataSource` and returns the file object from ``DataSource.open(path)``. r r ) DataSourcer)pathrdestpathr r Zdsr r r rs%rznumpy.lib.npyioc@seZdZdZejfddZddZddZdd Z d d Z d d Z ddZ ddZ ddZddZddZddZdddZdS)r&a DataSource(destpath='.') A generic data source file (file, http, ftp, ...). DataSources can be local files or remote files/URLs. The files may also be compressed or uncompressed. DataSource hides some of the low-level details of downloading the file, allowing you to simply pass in a valid file path (or URL) and obtain a file object. Parameters ---------- destpath : str or None, optional Path to the directory where the source file gets downloaded to for use. If `destpath` is None, a temporary directory will be created. The default path is the current directory. Notes ----- URLs require a scheme string (``http://``) to be used, without it they will fail:: >>> repos = np.lib.npyio.DataSource() >>> repos.exists('www.google.com/index.html') False >>> repos.exists('http://www.google.com/index.html') True Temporary directories are deleted when the DataSource is deleted. Examples -------- :: >>> ds = np.lib.npyio.DataSource('/home/guido') >>> urlname = 'http://www.google.com/' >>> gfile = ds.open('http://www.google.com/') >>> ds.abspath(urlname) '/home/guido/www.google.com/index.html' >>> ds = np.lib.npyio.DataSource(None) # use with temporary file >>> ds.open('/home/guido/foobar.txt') >>> ds.abspath('/home/guido/foobar.txt') '/tmp/.../home/guido/foobar.txt' cCs6|rtj||_d|_nddl}||_d|_dS)z2Create a DataSource with a local path at destpath.FrNT)osr'abspath _destpath _istmpdesttempfilemkdtemp)rr(r-r r r rs  zDataSource.__init__cCs(t|dr$|jr$ddl}||jdS)Nr,r)hasattrr,shutilrmtreer+)rr0r r r __del__szDataSource.__del__cCstj|\}}|tvS)zNTest if the filename is a zip file by looking at the file extension. )r)r'splitextrr)rfilenamefnameextr r r _iszipszDataSource._iszipcCs d}|D]}||vrdSqdS)z4Test if the given mode will open a file for writing.)w+TFr )rrZ _writemodescr r r _iswritemode s zDataSource._iswritemodecCs"||rtj|S|dfSdS)zSplit zip extension from filename and return filename. Returns ------- base, zip_ext : {tuple} N)r7r)r'r3)rr4r r r _splitzipexts  zDataSource._splitzipextcCs4|g}||s0tD]}|r|||q|S)z9Return a tuple containing compressed filename variations.)r7rrappend)rr4namesZzipextr r r _possible_names%s   zDataSource._possible_namesc Cs,ddlm}||\}}}}}}t|o(|S)z=Test if path is a net location. Tests the scheme and netloc.rurlparse) urllib.parserAbool) rr'rAschemenetlocupathuparamsuqueryufragr r r _isurl.s zDataSource._isurlc Csddl}ddlm}||}tjtj|sDttj|| |r||F}t |d}| ||Wdn1s0YWdq1s0Yn | |||S)zhCache the file specified by path. Creates a copy of the file in the datasource cache. rNurlopenwb) r0urllib.requestrLr*r)r'existsdirnamemakedirsrJ_open copyfileobjcopyfile)rr'r0rLrFZ openedurlfr r r _cache=s     J zDataSource._cachecCs|||s*||}||||7}n|||}|||}|D]*}||rL||rn||}|SqLdS)aySearches for ``path`` and returns full path if found. If path is an URL, _findfile will cache a local copy and return the path to the cached file. If path is a local file, _findfile will return a path to that local file. The search will include possible compressed versions of the file and return the first occurrence found. N)rJr?r*rOrV)rr'filelistnamer r r _findfileWs      zDataSource._findfilec Cshddlm}||jd}t|dkr.|d}||\}}}}}} ||}||}tj|j||S)aV Return absolute path of file in the DataSource directory. If `path` is an URL, then `abspath` will return either the location the file exists locally or the location it would exist when opened using the `open` method. Parameters ---------- path : str or pathlib.Path Can be a local file or a remote URL. Returns ------- out : str Complete path, including the `DataSource` destination directory. Notes ----- The functionality is based on `os.path.abspath`. rr@r) rBrAsplitr+len_sanitize_relative_pathr)r'join) rr'rA splitpathrDrErFrGrHrIr r r r*vs    zDataSource.abspathcCsVd}tj|}||krR|}|tjd}|tjd}tj|\}}q|S)zvReturn a sanitised relative path for which os.path.abspath(os.path.join(base, path)).startswith(base) N/z..)r)r'normpathlstripseppardir splitdrive)rr'lastdriver r r r]s z"DataSource._sanitize_relative_pathcCs~tj|rdSddlm}ddlm}||}tj|rBdS||rzz||}| ~WdS|yxYdS0dS)aC Test if path exists. Test if `path` exists as (and in this order): - a local file. - a remote URL that has been downloaded and stored locally in the `DataSource` directory. - a remote URL that has not been downloaded, but is valid and accessible. Parameters ---------- path : str or pathlib.Path Can be a local file or a remote URL. Returns ------- out : bool True if `path` exists. Notes ----- When `path` is an URL, `exists` will return True if it's either stored locally in the `DataSource` directory, or is a valid remote URL. `DataSource` does not discriminate between the two, the file is accessible if it exists in either location. TrrK)URLErrorF) r)r'rOrNrL urllib.errorrhr*rJclose)rr'rLrhrFZnetfiler r r rOs       zDataSource.existsr$NcCsr||r||rtd||}|r`||\}}|dkrL|ddt|||||dSt|ddS)aQ Open and return file-like object. If `path` is an URL, it will be downloaded, stored in the `DataSource` directory and opened from there. Parameters ---------- path : str or pathlib.Path Local file path or URL to open. mode : {'r', 'w', 'a'}, optional Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to append. Available modes depend on the type of object specified by `path`. Default is 'r'. encoding : {None, str}, optional Open text file with given encoding. The default encoding will be what `open` uses. newline : {None, str}, optional Newline to use when reading text file. Returns ------- out : file object File object. zURLs are not writeablerr9rz not found.N)rJr;rrYr<replacerFileNotFoundError)rr'rr r foundZ_fnamer6r r r rs"   zDataSource.open)r$NN)r r!r"r#r)curdirrr2r7r;r<r?rJrVrYr*r]rOrr r r r r&s0   *8r&c@sXeZdZdZejfddZddZddZdd Z d d Z d d Z dddZ ddZ dS) Repositorya Repository(baseurl, destpath='.') A data repository where multiple DataSource's share a base URL/directory. `Repository` extends `DataSource` by prepending a base URL (or directory) to all the files it handles. Use `Repository` when you will be working with multiple files from one base URL. Initialize `Repository` with the base URL, then refer to each file by its filename only. Parameters ---------- baseurl : str Path to the local directory or remote location that contains the data files. destpath : str or None, optional Path to the directory where the source file gets downloaded to for use. If `destpath` is None, a temporary directory will be created. The default path is the current directory. Examples -------- To analyze all files in the repository, do something like this (note: this is not self-contained code):: >>> repos = np.lib._datasource.Repository('/home/user/data/dir/') >>> for filename in filelist: ... fp = repos.open(filename) ... fp.analyze() ... fp.close() Similarly you could use a URL for a repository:: >>> repos = np.lib._datasource.Repository('http://www.xyz.edu/data') cCstj||d||_dS)z>Create a Repository with a shared url or directory of baseurl.)r(N)r&r_baseurl)rZbaseurlr(r r r r?szRepository.__init__cCst|dSr)r&r2rr r r r2DszRepository.__del__cCs4||jd}t|dkr,tj|j|}n|}|S)z>Return complete path for path. Prepends baseurl if necessary.rrZ)r[rqr\r)r'r^)rr'r_resultr r r _fullpathGs  zRepository._fullpathcCst|||S)z8Extend DataSource method to prepend baseurl to ``path``.)r&rYrsrr'r r r rYPszRepository._findfilecCst|||S)a{ Return absolute path of file in the Repository directory. If `path` is an URL, then `abspath` will return either the location the file exists locally or the location it would exist when opened using the `open` method. Parameters ---------- path : str or pathlib.Path Can be a local file or a remote URL. This may, but does not have to, include the `baseurl` with which the `Repository` was initialized. Returns ------- out : str Complete path, including the `DataSource` destination directory. )r&r*rsrtr r r r*TszRepository.abspathcCst|||S)a Test if path exists prepending Repository base URL to path. Test if `path` exists as (and in this order): - a local file. - a remote URL that has been downloaded and stored locally in the `DataSource` directory. - a remote URL that has not been downloaded, but is valid and accessible. Parameters ---------- path : str or pathlib.Path Can be a local file or a remote URL. This may, but does not have to, include the `baseurl` with which the `Repository` was initialized. Returns ------- out : bool True if `path` exists. Notes ----- When `path` is an URL, `exists` will return True if it's either stored locally in the `DataSource` directory, or is a valid remote URL. `DataSource` does not discriminate between the two, the file is accessible if it exists in either location. )r&rOrsrtr r r rOks zRepository.existsr$NcCstj||||||dS)a Open and return file-like object prepending Repository base URL. If `path` is an URL, it will be downloaded, stored in the DataSource directory and opened from there. Parameters ---------- path : str or pathlib.Path Local file path or URL to open. This may, but does not have to, include the `baseurl` with which the `Repository` was initialized. mode : {'r', 'w', 'a'}, optional Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to append. Available modes depend on the type of object specified by `path`. Default is 'r'. encoding : {None, str}, optional Open text file with given encoding. The default encoding will be what `open` uses. newline : {None, str}, optional Newline to use when reading text file. Returns ------- out : file object File object. r%)r&rrs)rr'rr r r r r rszRepository.opencCs&||jrtdn t|jSdS)a List files in the source Repository. Returns ------- files : list of str or pathlib.Path List of file names (not containing a directory part). Notes ----- Does not currently work for remote repositories. z-Directory listing of URLs, not supported yet.N)rJrqNotImplementedErrorr)listdirrr r r rvs  zRepository.listdir)r$NN)r r!r"r#r)rorr2rsrYr*rOrrvr r r r rps' " rp) r#r)Z_utilsrrrRr rrror&rpr r r r s$ O)U