U C^c@sdZddlmZmZmZddlZddlZddlZddlZddl Z ddl m Z ddl m Z eZddZdd Zd d ZGd d d eZeZdejddfddZe dGdddeZGdddeZdS)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 )divisionabsolute_importprint_functionN)closing) set_modulecCsDd|kr d|kr@td|fn |dk r0td|dk r@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) ValueErrormodeencodingnewliner8/tmp/pip-install-6_kvzl1k/numpy/numpy/lib/_datasource.py _check_mode4s rcCsDddl}t|||d|kr8tjdtdd|dd}|||S)aRWrapper to open bz2 in text mode. Parameters ---------- fn : str File name mode : {'r', 'w'} File mode. Note that bz2 Text files are not supported. encoding : str Ignored, text bz2 files not supported in Python2. newline : str Ignored, text bz2 files not supported in Python2. rNrz5Assuming latin1 encoding for bz2 text file in Python2) stacklevel)bz2rwarningswarnRuntimeWarningreplaceBZ2File)fnr r r rrrr_python2_bz2openKs  rcCsddl}Gddd|j}t||||dd}t|ttfrL|||}n,t|ds`t|drp|d||d }ntd d|krt j |||d S|SdS) a Wrapper to open gzip in text mode. Parameters ---------- fn : str, bytes, file File path or opened file. mode : str File mode. The actual files are opened as binary, but will decoded using the specified `encoding` and `newline`. encoding : str Encoding to be used when reading/writing as text. newline : str Newline to be used when reading/writing as text. rNc@seZdZddZdS)z#_python2_gzipopen..GzipWrapcSs ||SN)read)selfnrrrread1wsz)_python2_gzipopen..GzipWrap.read1N)__name__ __module__ __qualname__r rrrrGzipWrapvsr$rrrwrite)fileobjz1filename must be a str or bytes object, or a file)r ) gzipGzipFilerr isinstancestrbyteshasattr TypeErrorio TextIOWrapper)rr r r r'r$gz_mode binary_filerrr_python2_gzipopends   r2c@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|_dtji|_dS)NF)_loadedr.open _file_openersrrrr__init__sz_FileOpeners.__init__c Cs|jr dSz2ddl}tjddkr0|j|jd<n t|jd<Wntk rPYnXz2ddl}tjddkrx|j|jd<n t |jd<Wntk rYnXz$ddl }|j|jd<|j|jd<Wntt fk rYnXd|_dS)Nrz.bz2z.gzz.xzz.lzmaT) r4rsys version_infor5r6r ImportErrorr'r2lzmaAttributeError)rrr'r=rrr_loads. 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. )r?listr6keysr7rrrrAsz_FileOpeners.keyscCs||j|Sr)r?r6)rkeyrrr __getitem__sz_FileOpeners.__getitem__N)r!r"r#__doc__r8r?rArCrrrrr3s !r3rcCst|}|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 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 `io.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 ) DataSourcer5)pathr destpathr r Zdsrrrr5s%r5Znumpyc@seZdZdZejfddZddZddZdd Z d d Z d d Z ddZ ddZ ddZddZddZddZdddZdS)rGa 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.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.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.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)osrHabspath _destpath _istmpdesttempfilemkdtemp)rrIrNrrrr8Bs  zDataSource.__init__cCs t|dr|jrt|jdS)NrM)r,rMshutilrmtreerLr7rrr__del__LszDataSource.__del__cCstj|\}}|tkS)zNTest if the filename is a zip file by looking at the file extension. )rJrHsplitextr6rA)rfilenamefnameextrrr_iszipQszDataSource._iszipcCs d}|D]}||krdSqdS)z4Test if the given mode will open a file for writing.)w+TFr)rr Z _writemodescrrr _iswritemodeXs zDataSource._iswritemodecCs"||rtj|S|dfSdS)zxSplit zip extension from filename and return filename. *Returns*: base, zip_ext : {tuple} N)rWrJrHrS)rrTrrr _splitzipextbs  zDataSource._splitzipextcCs4|g}||s0tD]}|r|||q|S)z9Return a tuple containing compressed filename variations.)rWr6rAappend)rrTnamesZzipextrrr_possible_namesos   zDataSource._possible_namesc CsHtjddkrddlm}n ddlm}||\}}}}}}t|oD|S)z=Test if path is a net location. Tests the scheme and netloc.rr9urlparse)r:r; urllib.parserabool) rrHraschemenetlocupathuparamsuqueryufragrrr_isurlxs  zDataSource._isurlc Cstjddkr(ddlm}ddlm}nddlm}ddlm}||}tj tj |spt tj || |rz>t||(}t|d}t||W5QRXW5QRXWq|k r|d|YqXn t|||S)zhCache the file specified by path. Creates a copy of the file in the datasource cache. rr9urlopenURLErrorwbzURL not found: %s)r:r;urllib.requestrl urllib.errorrnurllib2rKrJrHexistsdirnamemakedirsrjr_openrP copyfileobjcopyfile)rrHrlrnrfZ openedurlfrrr_caches"      $ 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_rKrsrz)rrHfilelistnamerrr _findfiles      zDataSource._findfilec Cstjddkrddlm}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`. rr9r`) r:r;rbrasplitrLlen_sanitize_relative_pathrJrHjoin) rrHra splitpathrdrerfrgrhrirrrrKs    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..)rJrHnormpathlstripseppardir splitdrive)rrHlastdriverrrrs z"DataSource._sanitize_relative_pathcCstj|rdStjddkr8ddlm}ddlm}nddl m}ddl m}| |}tj|rjdS| |rz||}| ~WdS|k rYdSXdS)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. Trr9rkrmF) rJrHrsr:r;rprlrqrnrrrKrjclose)rrHrlrnrfZnetfilerrrrss&       zDataSource.existsrENcCsp||r||rtd||}|r`||\}}|dkrL|ddt|||||dStd|dS)aD 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'. encoding : {None, str}, optional Open text file with given encoding. The default encoding will be what `io.open` uses. newline : {None, str}, optional Newline to use when reading text file. Returns ------- out : file object File object. zURLs are not writeablerrYrr z %s not found.N)rjr[r r}r\rr6IOError)rrHr r r found_fnamerVrrrr5As"   zDataSource.open)rENN)r!r"r#rDrJcurdirr8rRrWr[r\r_rjrzr}rKrrsr5rrrrrGs0    !->> 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.)rIN)rGr8_baseurl)rZbaseurlrIrrrr8szRepository.__init__cCst|dSr)rGrRr7rrrrRszRepository.__del__cCs4||jd}t|dkr,tj|j|}n|}|S)z>Return complete path for path. Prepends baseurl if necessary.r~r)rrrrJrHr)rrHrresultrrr _fullpaths  zRepository._fullpathcCst|||S)z8Extend DataSource method to prepend baseurl to ``path``.)rGr}rrrHrrrr}szRepository._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. )rGrKrrrrrrKszRepository.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. )rGrsrrrrrrss zRepository.existsrENcCstj||||||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 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 `io.open` uses. newline : {None, str}, optional Newline to use when reading text file. Returns ------- out : file object File object. rF)rGr5r)rrHr r r rrrr5szRepository.opencCs&||jrtdn t|jSdS)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)rjrNotImplementedErrorrJlistdirr7rrrrs  zRepository.listdir)rENN)r!r"r#rDrJrr8rRrr}rKrsr5rrrrrrrs' " r)rD __future__rrrrJr:rrPr. contextlibrZnumpy.core.overridesrr5rvrrr2objectr3r6rrGrrrrrs($  ,U)c