B <ÓFdSã@s~dZddlmZmZmZddlZddlZddlZeZ Gdd„de ƒZ e ƒZ dej fdd„ZGd d „d e ƒZGd d „d eƒZdS) 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 and bz2 are supported. Example:: >>> # Create a DataSource, use os.curdir (default) for local storage. >>> ds = datasource.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/index.html') >>> >>> # Use the file as you normally would >>> fp.read() >>> fp.close() é)ÚdivisionÚabsolute_importÚprint_functionNc@s0eZdZdZdd„Zdd„Zdd„Zdd „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`` or ``bz2`` compression are supported. Notes ----- `_file_openers`, an instance of `_FileOpeners`, is made available for use in the `_datasource` module. Examples -------- >>> np.lib._datasource._file_openers.keys() [None, '.bz2', '.gz'] >>> np.lib._datasource._file_openers['.gz'] is gzip.open True cCsd|_dti|_dS)NF)Ú_loadedÚopenÚ _file_openers)Úself©r úH/opt/alt/python37/lib64/python3.7/site-packages/numpy/lib/_datasource.pyÚ__init__Jsz_FileOpeners.__init__cCsp|jr dSyddl}|j|jd<Wntk r6YnXyddl}|j|jd<Wntk rdYnXd|_dS)Nrz.bz2z.gzT)rÚbz2ZBZ2FilerÚ ImportErrorÚgzipr)r r rr r r Ú_loadNsz_FileOpeners._loadcCs| ¡t|j ¡ƒS)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'``, ``'.bz2'``) for supported compression methods. )rÚlistrÚkeys)r r r r r]sz_FileOpeners.keyscCs| ¡|j|S)N)rr)r Úkeyr r r Ú __getitem__psz_FileOpeners.__getitem__N)Ú__name__Ú __module__Ú __qualname__Ú__doc__r rrrr r r r r2s rÚrcCst|ƒ}| ||¡S)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 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. 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)``. )Ú DataSourcer)ÚpathÚmodeÚdestpathZdsr r r rvs rc@s€eZdZdZejfdd„Zdd„Zdd„Zdd „Z d d „Z d d „Z dd„Z dd„Z dd„Zdd„Zdd„Zdd„Zddd„ZdS)ra  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 = 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 = DataSource('/home/guido') >>> urlname = 'http://www.google.com/index.html' >>> gfile = ds.open('http://www.google.com/index.html') # remote file >>> ds.abspath(urlname) '/home/guido/www.google.com/site/index.html' >>> ds = DataSource(None) # use with temporary file >>> ds.open('/home/guido/foobar.txt') >>> ds.abspath('/home/guido/foobar.txt') '/tmp/tmpy4pgsP/home/guido/foobar.txt' cCs6|rtj |¡|_d|_nddl}| ¡|_d|_dS)z2Create a DataSource with a local path at destpath.FrNT)ÚosrÚabspathÚ _destpathÚ _istmpdestÚtempfileZmkdtemp)r rr"r r r r Ës  zDataSource.__init__cCs|jrt |j¡dS)N)r!ÚshutilZrmtreer )r r r r Ú__del__ÕszDataSource.__del__cCstj |¡\}}|t ¡kS)zNTest if the filename is a zip file by looking at the file extension. )rrÚsplitextrr)r ÚfilenameZfnameÚextr r r Ú_iszipÚszDataSource._iszipcCs"d}x|D]}||kr dSq WdS)z4Test if the given mode will open a file for writing.)Úwú+TFr )r rZ _writemodesÚcr r r Ú _iswritemodeás  zDataSource._iswritemodecCs"| |¡rtj |¡S|dfSdS)zxSplit zip extension from filename and return filename. *Returns*: base, zip_ext : {tuple} N)r(rrr%)r r&r r r Ú _splitzipextës  zDataSource._splitzipextcCs8|g}| |¡s4x"t ¡D]}|r| ||¡qW|S)z9Return a tuple containing compressed filename variations.)r(rrÚappend)r r&ÚnamesZzipextr r r Ú_possible_namesøs  zDataSource._possible_namesc CsHtjddkrddlm}n ddlm}||ƒ\}}}}}}t|oD|ƒS)z=Test if path is a net location. Tests the scheme and netloc.ré)Úurlparse)ÚsysÚ version_infoÚ urllib.parser2Úbool) r rr2ÚschemeÚnetlocÚupathÚuparamsÚuqueryÚufragr r r Ú_isurls  zDataSource._isurlcCsètjddkr(ddlm}ddlm}nddlm}ddlm}| |¡}tj   tj   |¡¡spt  tj   |¡¡|  |¡rØy:||ƒ}t|dƒ}zt ||¡Wd| ¡| ¡XWqä|k rÔ|d|ƒ‚YqäXn t ||¡|S)zhCache the file specified by path. Creates a copy of the file in the datasource cache. rr1)Úurlopen)ÚURLErrorÚwbNzURL not found: %s)r3r4Úurllib.requestr>Ú urllib.errorr?Úurllib2rrrÚexistsÚdirnameÚmakedirsr=Ú_openr#Z copyfileobjÚcloseZcopyfile)r rr>r?r9Z openedurlÚfr r r Ú_caches(       zDataSource._cachecCs|| |¡s*| |¡}|| | |¡¡7}n| | |¡¡}|| |¡}x.|D]&}| |¡rN| |¡rp| |¡}|SqNWdS)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)r=r0rrDrJ)r rZfilelistÚnamer r r Ú _findfile8s      zDataSource._findfilec Cs„tjddkrddlm}n ddlm}| |jd¡}t|ƒdkrJ|d}||ƒ\}}}}}} | |¡}| |¡}tj   |j||¡S)aF 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 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`. rr1)r2éé) r3r4r5r2Úsplitr ÚlenÚ_sanitize_relative_pathrrÚjoin) r rr2Ú splitpathr7r8r9r:r;r<r r r rWs    zDataSource.abspathcCsZd}tj |¡}xD||krT|}| tj¡ d¡}| tj¡ d¡}tj |¡\}}qW|S)zvReturn a sanitised relative path for which os.path.abspath(os.path.join(base, path)).startswith(base) Nú/z..)rrÚnormpathÚlstripÚsepÚpardirÚ splitdrive)r rZlastZdriver r r rQ„s  z"DataSource._sanitize_relative_pathcCs¤tjddkr(ddlm}ddlm}nddlm}ddlm}tj  |¡rPdS|  |¡}tj  |¡rjdS|  |¡r y||ƒ}|  ¡~dS|k rždSXdS)a3 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 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. rr1)r>)r?TF) r3r4rAr>rBr?rCrrrDrr=rH)r rr>r?r9Znetfiler r r rD’s&        zDataSource.existsrcCsl| |¡r| |¡rtdƒ‚| |¡}|r\| |¡\}}|dkrL| dd¡t|||dStd|ƒ‚dS)aR 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 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'. Returns ------- out : file object File object. zURLs are not writeabler r*Ú)rz %s not found.N)r=r,Ú ValueErrorrLr-ÚreplacerÚIOError)r rrÚfoundZ_fnamer'r r r rÍs  zDataSource.openN)r)rrrrrÚcurdirr r$r(r,r-r0r=rJrLrrQrDrr r r r ršs/    %-;rc@sXeZdZdZejfdd„Zdd„Zdd„Zdd „Z d d „Z d d „Z ddd„Z dd„Z 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.)rN)rr Ú_baseurl)r Zbaseurlrr r r r szRepository.__init__cCst |¡dS)N)rr$)r r r r r$%szRepository.__del__cCs4| |jd¡}t|ƒdkr,tj |j|¡}n|}|S)z>Return complete path for path. Prepends baseurl if necessary.rMrN)rOrarPrrrR)r rrSÚresultr r r Ú _fullpath(s  zRepository._fullpathcCst || |¡¡S)z8Extend DataSource method to prepend baseurl to ``path``.)rrLrc)r rr r r rL1szRepository._findfilecCst || |¡¡S)ak 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 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. )rrrc)r rr r r r5szRepository.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 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. )rrDrc)r rr r r rDLs zRepository.existsrcCst || |¡|¡S)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 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'. Returns ------- out : file object File object. )rrrc)r rrr r r rnszRepository.opencCs&| |j¡rtdƒ‚n t |j¡SdS)a  List files in the source Repository. Returns ------- files : list of str 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)r=raÚNotImplementedErrorrÚlistdir)r r r r reˆs zRepository.listdirN)r)rrrrrr_r r$rcrLrrDrrer r r r r`øs& " r`)rZ __future__rrrrr3r#rrGÚobjectrrr_rr`r r r r Ú#sB$`