bggXdZddlZddlZddlmZeZdZGddZeZ dej ddfd Zed Gd d Z Gd de 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_modulecd|vrd|vrtd|dS|td|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: Nz0Argument 'encoding' not supported in binary modez/Argument 'newline' not supported in binary mode) ValueErrormodeencodingnewlines L/opt/cloudlinux/venv/lib64/python3.11/site-packages/numpy/lib/_datasource.py _check_moder.sf d{{ $;;*449:: : ;  OPP P  NOO O  c*eZdZdZdZdZdZdZdS) _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 c:d|_dtji|_dS)NF)_loadedioopen _file_openersselfs r __init__z_FileOpeners.__init__cs "BG_rc0|jrdS ddl}|j|jd<n#t$rYnwxYw ddl}|j|jd<n#t$rYnwxYw ddl}|j|jd<|j|jd<n#ttf$rYnwxYwd|_dS)Nrz.bz2z.gzz.xzz.lzmaT)rbz2rr ImportErrorgziplzmaAttributeError)rrrrs r _loadz_FileOpeners._loadgs <  F  JJJ),D v & &    D   KKK(, D u % %    D   KKK(, D u %*.)D w ' '^,    D   s/ ,,A AA"A88B  B cv|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 listrkeysrs r r#z_FileOpeners.keyss. D&++--...rcD||j|SN)r r)rkeys r __getitem__z_FileOpeners.__getitem__s !#&&rN)__name__ __module__ __qualname____doc__rr r#r'rr rrJsZ0---6///&'''''rrrcRt|}|||||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. 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 ) DataSourcer)pathr destpathr r dss r rrs,J H  B 774'7 B BBrnumpycpeZdZdZejfdZdZdZdZ dZ dZ dZ d Z d Zd Zd Zd ZddZdS)r0a 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' c|r-tj||_d|_dSddl}||_d|_dS)z2Create a DataSource with a local path at destpath.FrNT)osr1abspath _destpath _istmpdesttempfilemkdtemp)rr2r;s r rzDataSource.__init__sQ  #W__X66DN#DOOO OOO%--//DN"DOOOrcxt|dr'|jr"ddl}||jdSdSdS)Nr:r)hasattrr:shutilrmtreer9)rr?s r __del__zDataSource.__del__sT 4 & & *4? * MMM MM$. ) ) ) ) ) * * * *rc|tj|\}}|tvS)zNTest if the filename is a zip file by looking at the file extension. )r7r1splitextrr#)rfilenamefnameexts r _iszipzDataSource._iszips4W%%h// sm((****rc"d}|D] }||vrdS dS)z4Test if the given mode will open a file for writing.)w+TFr,)rr _writemodescs r _iswritemodezDataSource._iswritemodes4!   AKtt urcr||rtj|S|dfS)zSplit zip extension from filename and return filename. Returns ------- base, zip_ext : {tuple} N)rGr7r1rC)rrDs r _splitzipextzDataSource._splitzipexts8 ;;x  "7##H-- -T> !rc|g}||s6tD]}|r|||z|S)z9Return a tuple containing compressed filename variations.)rGrr#append)rrDnameszipexts r _possible_nameszDataSource._possible_names&s\ {{8$$ 2',,.. 2 22LL&111 rcTddlm}||\}}}}}}t|o|S)z=Test if path is a net location. Tests the scheme and netloc.rurlparse) urllib.parserWbool) rr1rWschemenetlocupathuparamsuqueryufrags r _isurlzDataSource._isurl/sF *)))))9A5wF%v&&&rc8ddl}ddlm}||}tjtj|s1t jtj|| |rb||5}t|d5}| ||dddn #1swxYwYdddn #1swxYwYn| |||S)zhCache the file specified by path. Creates a copy of the file in the datasource cache. rNurlopenwb) r?urllib.requestrcr8r7r1existsdirnamemakedirsr`_open copyfileobjcopyfile)rr1r?rcr\ openedurlfs r _cachezDataSource._cache>s~  ****** T""w~~bgooe4455 0 K.. / / / ;;t   ) 5)5$''51&&y!444555555555555555 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 OOD% ( ( ( s6-C8>C! C8!C% %C8(C% )C88C<?C<c||sA||}||||z }n@|||}|||z}|D]E}||r.||r||}|cSFdS)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`rTr8rfrn)rr1filelistnames r _findfilezDataSource._findfileXs{{4  =++D11H ,,T\\$-?-?@@ @HH++DLL,>,>??H$"6"6t"<"<ddlm}||jd}t |dkr|d}||\}}}}}} ||}||}t j|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`. rrVr) rXrWsplitr9len_sanitize_relative_pathr7r1join) rr1rW splitpathrZr[r\r]r^r_s r r8zDataSource.abspathws0 *)))))JJt~q11 y>>A  Q>$   4 +*****)))))) T"" 7>>%  4 ;;t    !'$-- t   uu us: BB%$B%r-Nc`||r$||rtd||}|rM||\}}|dkr|ddt |||||St|d)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 writeablerrJr z not found.)r`rMrrrrOreplacerFileNotFoundError)rr1r r r found_fnamerFs r rzDataSource.opensD ;;t   7!2!24!8!8 7566 6t$$  :++E22KFCe|| S"%%% %e$/7JJJ J$t$8$8$899 9rr-NN)r(r)r*r+r7curdirrrArGrMrOrTr`rnrrr8rwrfrr,rr r0r0s..`!# ####***+++ " " " ' ' '4>(;(;(;T   666p.:.:.:.:.:.:rr0cReZdZdZejfdZdZdZdZ dZ dZ d d Z d Z d S) 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') cLt||||_dS)z>Create a Repository with a shared url or directory of baseurl.)r2N)r0r_baseurl)rbaseurlr2s r rzRepository.__init__@s&D8444 rc:t|dSr%)r0rArs r rAzRepository.__del__Es4     rc||jd}t|dkr&tj|j|}n|}|S)z>Return complete path for path. Prepends baseurl if necessary.rrt)rurrvr7r1rx)rr1ryresults r _fullpathzRepository._fullpathHsKJJt}a00 y>>Q  W\\$-66FFF rc^t|||S)z8Extend DataSource method to prepend baseurl to ``path``.)r0rrrrr1s r rrzRepository._findfileQs$##D$..*>*>???rc^t|||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. )r0r8rrs r r8zRepository.abspathUs&*!!$t(<(<===rc^t|||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. )r0rfrrs r rfzRepository.existsls'@  t~~d';';<<>>. = = =DCCCC@-----rr) r+r7r_utilsrrrirrrrr0rr,rr rs7##H  PPP8M'M'M'M'M'M'M'M'^  ")dD&C&C&C&CR GP:P:P:P:P:P:P:P:f h-h-h-h-h-*h-h-h-h-h-r