zmc
2023-10-12 ed135d79df12a2466b52dae1a82326941211dcc9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
U
P±d3[ã@s~dZddlZddlZddlmZeZdd„ZGdd„dƒZeƒZ    dej
ddfd    d
„Zed ƒGd d „d ƒƒZ Gdd„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_modulecCsDd|kr d|kr@td|fƒ‚n |dk    r0tdƒ‚|dk    r@tdƒ‚dS)zàCheck 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ÚbzInvalid mode: %rNz0Argument 'encoding' not supported in binary modez/Argument 'newline' not supported in binary mode)Ú
ValueError©ÚmodeÚencodingÚnewline©r
úLd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\numpy/lib/_datasource.pyÚ _check_mode.s r c@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``, ``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)Ú_loadedÚioÚopenÚ _file_openers©Úselfr
r
r Ú__init__csz_FileOpeners.__init__c    Cs®|jr
dSzddl}|j|jd<Wntk
r6YnXzddl}|j|jd<Wntk
rdYnXz$ddl}|j|jd<|j|jd<Wnttfk
r¢YnXd|_dS)Nrz.bz2z.gzz.xzz.lzmaT)rÚbz2rrÚ ImportErrorÚgzipÚlzmaÚAttributeError)rrrrr
r
r Ú_loadgs& z_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'``, ``'.xz'``) for supported compression
            methods.
 
        )rÚlistrÚkeysrr
r
r r‚sz_FileOpeners.keyscCs| ¡|j|S©N)rr)rÚkeyr
r
r Ú __getitem__•sz_FileOpeners.__getitem__N)Ú__name__Ú
__module__Ú __qualname__Ú__doc__rrrrr
r
r
r r Js
r ÚrcCst|ƒ}|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
        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)``.
 
    ©rr    )Ú
DataSourcer)ÚpathrÚdestpathrr    Zdsr
r
r r›s%rÚnumpyc@s€eZdZdZejfdd„Zdd„Zdd„Zdd    „Z    d
d „Z
d d „Z dd„Z dd„Z dd„Zdd„Zdd„Zdd„Zddd„ZdS)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.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')
        <open file '/home/guido.foobar.txt', mode 'r' at 0x91d4430>
        >>> 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Ú
_istmpdestÚtempfileÚmkdtemp)rr(r.r
r
r rös 
zDataSource.__init__cCs(t|dƒr$|jr$ddl}| |j¡dS)Nr-r)Úhasattrr-ÚshutilÚrmtreer,)rr1r
r
r Ú__del__szDataSource.__del__cCstj |¡\}}|t ¡kS)zNTest if the filename is a zip file by looking at the file extension.
 
        )r*r'Úsplitextrr)rÚfilenameÚfnameÚextr
r
r Ú_iszipszDataSource._iszipcCs d}|D]}||krdSqdS)z4Test if the given mode will open a file for writing.)Úwú+TFr
)rrZ _writemodesÚcr
r
r Ú _iswritemodes
zDataSource._iswritemodecCs"| |¡rtj |¡S|dfSdS)zSplit zip extension from filename and return filename.
 
        Returns
        -------
        base, zip_ext : {tuple}
 
        N)r8r*r'r4)rr5r
r
r Ú _splitzipexts    
 zDataSource._splitzipextcCs4|g}| |¡s0t ¡D]}|r| ||¡q|S)z9Return a tuple containing compressed filename variations.)r8rrÚappend)rr5ÚnamesZzipextr
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.r©Úurlparse)Ú urllib.parserBÚbool)    rr'rBÚschemeÚnetlocÚupathÚuparamsÚuqueryÚufragr
r
r Ú_isurl/s zDataSource._isurlc
Cs–ddl}ddlm}| |¡}tj tj |¡¡sDt tj |¡¡|     |¡r†||ƒ(}t
|dƒ}|  ||¡W5QRXW5QRXn |  ||¡|S)zhCache the file specified by path.
 
        Creates a copy of the file in the datasource cache.
 
        rN©ÚurlopenÚwb) r1Úurllib.requestrMr+r*r'ÚexistsÚdirnameÚmakedirsrKÚ_openÚ copyfileobjÚcopyfile)rr'r1rMrGZ    openedurlÚfr
r
r Ú_cache>s 
 
 
 " 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)rKr@r+rPrW)rr'ÚfilelistÚnamer
r
r Ú    _findfileXs
 
 
 
 
 
zDataSource._findfilec
Cshddlm}| |jd¡}t|ƒdkr.|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`.
 
        rrAéé)    rCrBÚsplitr,ÚlenÚ_sanitize_relative_pathr*r'Újoin)
rr'rBÚ    splitpathrErFrGrHrIrJr
r
r r+ws
 
 
zDataSource.abspathcCsVd}tj |¡}||krR|}| tj¡ d¡}| tj¡ d¡}tj |¡\}}q|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Ú
splitdrive)rr'ÚlastÚdriver
r
r r_¡s z"DataSource._sanitize_relative_pathcCs€tj |¡rdSddlm}ddlm}| |¡}tj |¡rBdS| |¡r|z||ƒ}|     ¡~WdS|k
rzYdSXdS)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.
 
        TrrL)ÚURLErrorF)
r*r'rPrOrMÚ urllib.errorrjr+rKÚclose)rr'rMrjrGZnetfiler
r
r rP¯s     
 
zDataSource.existsr$NcCsr| |¡r| |¡rtdƒ‚| |¡}|r`| |¡\}}|dkrL| dd¡t|||||dSt|›dƒ‚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 writeablerr:Úrz  not found.N)rKr<rrZr=ÚreplacerÚFileNotFoundError)rr'rrr    ÚfoundZ_fnamer7r
r
r rçs"
 
ÿzDataSource.open)r$NN)r r!r"r#r*Úcurdirrr3r8r<r=r@rKrWrZr+r_rPrr
r
r
r r&Äs0
 
    *8r&c@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.)r(N)r&rÚ_baseurl)rZbaseurlr(r
r
r r@szRepository.__init__cCst |¡dSr)r&r3rr
r
r r3EszRepository.__del__cCs4| |jd¡}t|ƒdkr,tj |j|¡}n|}|S)z>Return complete path for path.  Prepends baseurl if necessary.r[r\)r]rsr^r*r'r`)rr'raÚresultr
r
r Ú    _fullpathHs
 zRepository._fullpathcCst || |¡¡S)z8Extend DataSource method to prepend baseurl to ``path``.)r&rZru©rr'r
r
r rZQszRepository._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.
 
        )r&r+rurvr
r
r r+UszRepository.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.
 
        )r&rPrurvr
r
r rPls zRepository.existsr$NcCstj|| |¡|||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
            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.
 
        r%)r&rru)rr'rrr    r
r
r rŽsÿzRepository.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)rKrsÚNotImplementedErrorr*Úlistdirrr
r
r rx®s
 ÿzRepository.listdir)r$NN)r r!r"r#r*rqrr3rurZr+rPrrxr
r
r
r rrs'    "
 rr) r#r*rZnumpy.core.overridesrrrSr r rrqr&rrr
r
r
r Ú<module>s$ O)U