o
    "gX                     @   sv   d Z ddlZddlmZ eZdd ZG dd dZe Zd	ej	ddfd
dZedG dd dZ
G dd de
ZdS )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_modulec                 C   sF   d| v rd| v rt d| f dS |durt d|dur!t ddS )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.

    tbzInvalid mode: %rNz0Argument 'encoding' not supported in binary modez/Argument 'newline' not supported in binary mode)
ValueErrormodeencodingnewline r   W/var/www/html/ecg_monitoring/venv/lib/python3.10/site-packages/numpy/lib/_datasource.py_check_mode-   s   r   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
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

    c                 C   s   d| _ d ti| _d S )NF)_loadedopen_file_openersselfr   r   r   __init__b   s   z_FileOpeners.__init__c              	   C   s   | j rd S zdd l}|j| jd< W n	 ty   Y nw zdd l}|j| jd< W n	 ty0   Y nw zdd l}|j| jd< |j| jd< W n ttfyN   Y nw d| _ d S )Nr   z.bz2z.gzz.xzz.lzmaT)r   bz2r   r   ImportErrorgziplzmaAttributeError)r   r   r   r   r   r   r   _loadf   s,   
z_FileOpeners._loadc                 C   s   |    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'``, ``'.xz'``) for supported compression
            methods.

        )r   listr   keysr   r   r   r   r      s   z_FileOpeners.keysc                 C   s   |    | j| S N)r   r   )r   keyr   r   r   __getitem__   s   
z_FileOpeners.__getitem__N)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r   r   I   s    r   rc                 C   s   t |}|j| |||d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 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   )pathr   destpathr	   r
   dsr   r   r   r      s   %r   znumpy.lib.npyioc                   @   s   e Zd ZdZejfddZdd Zdd Zdd	 Z	d
d Z
dd Zdd Zdd Zdd Zdd Zdd Zdd ZdddZdS )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')
        <open file '/home/guido.foobar.txt', mode 'r' at 0x91d4430>
        >>> ds.abspath('/home/guido/foobar.txt')
        '/tmp/.../home/guido/foobar.txt'

    c                 C   s8   |rt j|| _d| _dS ddl}| | _d| _dS )z2Create a DataSource with a local path at destpath.Fr   NT)osr'   abspath	_destpath
_istmpdesttempfilemkdtemp)r   r(   r.   r   r   r   r      s   


zDataSource.__init__c                 C   s0   t | dr| jrdd l}|| j d S d S d S )Nr-   r   )hasattrr-   shutilrmtreer,   )r   r1   r   r   r   __del__   s   zDataSource.__del__c                 C   s   t j|\}}|t v S )zNTest if the filename is a zip file by looking at the file extension.

        )r*   r'   splitextr   r   )r   filenamefnameextr   r   r   _iszip  s   zDataSource._iszipc                    s   d t  fdd|D S )z4Test if the given mode will open a file for writing.)w+c                 3   s    | ]}| v V  qd S r   r   ).0c_writemodesr   r   	<genexpr>  s    z*DataSource._iswritemode.<locals>.<genexpr>)any)r   r   r   r=   r   _iswritemode  s   zDataSource._iswritemodec                 C   s   |  |rtj|S |dfS )zSplit zip extension from filename and return filename.

        Returns
        -------
        base, zip_ext : {tuple}

        N)r8   r*   r'   r4   )r   r5   r   r   r   _splitzipext  s   
	zDataSource._splitzipextc                 C   s4   |g}|  |st D ]}|r|||  q|S )z9Return a tuple containing compressed filename variations.)r8   r   r   append)r   r5   nameszipextr   r   r   _possible_names"  s   
zDataSource._possible_namesc           	      C   s,   ddl m} ||\}}}}}}t|o|S )z=Test if path is a net location.  Tests the scheme and netloc.r   urlparse)urllib.parserH   bool)	r   r'   rH   schemenetlocupathuparamsuqueryufragr   r   r   _isurl+  s   zDataSource._isurlc              	   C   s   ddl }ddlm} | |}tjtj|s"ttj| | 	|ra||,}t
|d}||| W d   n1 sBw   Y  W d   |S W d   |S 1 sZw   Y  |S ||| |S )zhCache the file specified by path.

        Creates a copy of the file in the datasource cache.

        r   Nurlopenwb)r1   urllib.requestrS   r+   r*   r'   existsdirnamemakedirsrQ   _opencopyfileobjcopyfile)r   r'   r1   rS   rM   	openedurlfr   r   r   _cache:  s&   




zDataSource._cachec                 C   s|   |  |s| |}|| | |7 }n| | |}|| | }|D ]}| |r;|  |r7| |}|  S q&dS )ay  Searches 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)rQ   rF   r+   rV   r^   )r   r'   filelistnamer   r   r   	_findfileT  s   




zDataSource._findfilec           
      C   sh   ddl m} || jd}t|dkr|d }||\}}}}}}	| |}| |}tj| 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`.

        r   rG   r      )	rI   rH   splitr,   len_sanitize_relative_pathr*   r'   join)
r   r'   rH   	splitpathrK   rL   rM   rN   rO   rP   r   r   r   r+   s  s   


zDataSource.abspathc                 C   s\   d}t j|}||kr,|}|t jd}|t jd}t j|\}}||ks|S )zvReturn a sanitised relative path for which
        os.path.abspath(os.path.join(base, path)).startswith(base)
        N/z..)r*   r'   normpathlstripseppardirremoveprefix
splitdrive)r   r'   lastdriver   r   r   re     s   z"DataSource._sanitize_relative_pathc                 C   s~   t j|rdS ddlm} ddlm} | |}t j|r!dS | |r=z||}|	  ~W dS  |y<   Y dS w dS )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.

        Tr   rR   )URLErrorF)
r*   r'   rV   rU   rS   urllib.errorrq   r+   rQ   close)r   r'   rS   rq   rM   netfiler   r   r   rV     s"    

zDataSource.existsr$   Nc                 C   sn   |  |r| |rtd| |}|r0| |\}}|dkr&|dd t| ||||dS t| d)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.

        zURLs are not writeabler   r:    r   z not found.)rQ   rA   r   ra   rB   replacer   FileNotFoundError)r   r'   r   r	   r
   found_fnamer7   r   r   r   r     s   "

zDataSource.openr$   NN)r    r!   r"   r#   r*   curdirr   r3   r8   rA   rB   rF   rQ   r^   ra   r+   re   rV   r   r   r   r   r   r&      s    0
	*8r&   c                   @   sX   e Zd ZdZejfddZdd Zdd Zdd	 Z	d
d Z
dd ZdddZd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')

    c                 C   s   t j| |d || _dS )z>Create a Repository with a shared url or directory of baseurl.)r(   N)r&   r   _baseurl)r   baseurlr(   r   r   r   r   <  s   
zRepository.__init__c                 C   s   t |  d S r   )r&   r3   r   r   r   r   r3   A  s   zRepository.__del__c                 C   s6   | | jd}t|dkrtj| j|}|S |}|S )z>Return complete path for path.  Prepends baseurl if necessary.r   rb   )rc   r}   rd   r*   r'   rf   )r   r'   rg   resultr   r   r   	_fullpathD  s   zRepository._fullpathc                 C      t | | |S )z8Extend DataSource method to prepend baseurl to ``path``.)r&   ra   r   r   r'   r   r   r   ra   M  s   zRepository._findfilec                 C   r   )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+   r   r   r   r   r   r+   Q  s   zRepository.abspathc                 C   r   )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&   rV   r   r   r   r   r   rV   h  s    zRepository.existsr$   Nc                 C   s   t j| | ||||d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 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&   r   r   )r   r'   r   r	   r
   r   r   r   r     s   zRepository.openc                 C   s    |  | jr
tdt| jS )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.)rQ   r}   NotImplementedErrorr*   listdirr   r   r   r   r     s
   zRepository.listdirrz   )r    r!   r"   r#   r*   r{   r   r3   r   ra   r+   rV   r   r   r   r   r   r   r|     s    '	
" r|   )r#   r*   _utilsr   r   rY   r   r   r   r{   r&   r|   r   r   r   r   <module>   s    $O)  R