_datasource.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. """A file interface for handling local and remote data files.
  2. The goal of datasource is to abstract some of the file system operations
  3. when dealing with data files so the researcher doesn't have to know all the
  4. low-level details. Through datasource, a researcher can obtain and use a
  5. file with one function call, regardless of location of the file.
  6. DataSource is meant to augment standard python libraries, not replace them.
  7. It should work seamlessly with standard file IO operations and the os
  8. module.
  9. DataSource files can originate locally or remotely:
  10. - local files : '/home/guido/src/local/data.txt'
  11. - URLs (http, ftp, ...) : 'http://www.scipy.org/not/real/data.txt'
  12. DataSource files can also be compressed or uncompressed. Currently only
  13. gzip, bz2 and xz are supported.
  14. Example::
  15. >>> # Create a DataSource, use os.curdir (default) for local storage.
  16. >>> from numpy import DataSource
  17. >>> ds = DataSource()
  18. >>>
  19. >>> # Open a remote file.
  20. >>> # DataSource downloads the file, stores it locally in:
  21. >>> # './www.google.com/index.html'
  22. >>> # opens the file and returns a file object.
  23. >>> fp = ds.open('http://www.google.com/') # doctest: +SKIP
  24. >>>
  25. >>> # Use the file as you normally would
  26. >>> fp.read() # doctest: +SKIP
  27. >>> fp.close() # doctest: +SKIP
  28. """
  29. import os
  30. from numpy._utils import set_module
  31. _open = open
  32. def _check_mode(mode, encoding, newline):
  33. """Check mode and that encoding and newline are compatible.
  34. Parameters
  35. ----------
  36. mode : str
  37. File open mode.
  38. encoding : str
  39. File encoding.
  40. newline : str
  41. Newline for text files.
  42. """
  43. if "t" in mode:
  44. if "b" in mode:
  45. raise ValueError(f"Invalid mode: {mode!r}")
  46. else:
  47. if encoding is not None:
  48. raise ValueError("Argument 'encoding' not supported in binary mode")
  49. if newline is not None:
  50. raise ValueError("Argument 'newline' not supported in binary mode")
  51. # Using a class instead of a module-level dictionary
  52. # to reduce the initial 'import numpy' overhead by
  53. # deferring the import of lzma, bz2 and gzip until needed
  54. # TODO: .zip support, .tar support?
  55. class _FileOpeners:
  56. """
  57. Container for different methods to open (un-)compressed files.
  58. `_FileOpeners` contains a dictionary that holds one method for each
  59. supported file format. Attribute lookup is implemented in such a way
  60. that an instance of `_FileOpeners` itself can be indexed with the keys
  61. of that dictionary. Currently uncompressed files as well as files
  62. compressed with ``gzip``, ``bz2`` or ``xz`` compression are supported.
  63. Notes
  64. -----
  65. `_file_openers`, an instance of `_FileOpeners`, is made available for
  66. use in the `_datasource` module.
  67. Examples
  68. --------
  69. >>> import gzip
  70. >>> np.lib._datasource._file_openers.keys()
  71. [None, '.bz2', '.gz', '.xz', '.lzma']
  72. >>> np.lib._datasource._file_openers['.gz'] is gzip.open
  73. True
  74. """
  75. def __init__(self):
  76. self._loaded = False
  77. self._file_openers = {None: open}
  78. def _load(self):
  79. if self._loaded:
  80. return
  81. try:
  82. import bz2
  83. self._file_openers[".bz2"] = bz2.open
  84. except ImportError:
  85. pass
  86. try:
  87. import gzip
  88. self._file_openers[".gz"] = gzip.open
  89. except ImportError:
  90. pass
  91. try:
  92. import lzma
  93. self._file_openers[".xz"] = lzma.open
  94. self._file_openers[".lzma"] = lzma.open
  95. except (ImportError, AttributeError):
  96. # There are incompatible backports of lzma that do not have the
  97. # lzma.open attribute, so catch that as well as ImportError.
  98. pass
  99. self._loaded = True
  100. def keys(self):
  101. """
  102. Return the keys of currently supported file openers.
  103. Parameters
  104. ----------
  105. None
  106. Returns
  107. -------
  108. keys : list
  109. The keys are None for uncompressed files and the file extension
  110. strings (i.e. ``'.gz'``, ``'.xz'``) for supported compression
  111. methods.
  112. """
  113. self._load()
  114. return list(self._file_openers.keys())
  115. def __getitem__(self, key):
  116. self._load()
  117. return self._file_openers[key]
  118. _file_openers = _FileOpeners()
  119. def open(path, mode='r', destpath=os.curdir, encoding=None, newline=None):
  120. """
  121. Open `path` with `mode` and return the file object.
  122. If ``path`` is an URL, it will be downloaded, stored in the
  123. `DataSource` `destpath` directory and opened from there.
  124. Parameters
  125. ----------
  126. path : str or pathlib.Path
  127. Local file path or URL to open.
  128. mode : str, optional
  129. Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to
  130. append. Available modes depend on the type of object specified by
  131. path. Default is 'r'.
  132. destpath : str, optional
  133. Path to the directory where the source file gets downloaded to for
  134. use. If `destpath` is None, a temporary directory will be created.
  135. The default path is the current directory.
  136. encoding : {None, str}, optional
  137. Open text file with given encoding. The default encoding will be
  138. what `open` uses.
  139. newline : {None, str}, optional
  140. Newline to use when reading text file.
  141. Returns
  142. -------
  143. out : file object
  144. The opened file.
  145. Notes
  146. -----
  147. This is a convenience function that instantiates a `DataSource` and
  148. returns the file object from ``DataSource.open(path)``.
  149. """
  150. ds = DataSource(destpath)
  151. return ds.open(path, mode, encoding=encoding, newline=newline)
  152. @set_module('numpy.lib.npyio')
  153. class DataSource:
  154. """
  155. DataSource(destpath='.')
  156. A generic data source file (file, http, ftp, ...).
  157. DataSources can be local files or remote files/URLs. The files may
  158. also be compressed or uncompressed. DataSource hides some of the
  159. low-level details of downloading the file, allowing you to simply pass
  160. in a valid file path (or URL) and obtain a file object.
  161. Parameters
  162. ----------
  163. destpath : str or None, optional
  164. Path to the directory where the source file gets downloaded to for
  165. use. If `destpath` is None, a temporary directory will be created.
  166. The default path is the current directory.
  167. Notes
  168. -----
  169. URLs require a scheme string (``http://``) to be used, without it they
  170. will fail::
  171. >>> repos = np.lib.npyio.DataSource()
  172. >>> repos.exists('www.google.com/index.html')
  173. False
  174. >>> repos.exists('http://www.google.com/index.html')
  175. True
  176. Temporary directories are deleted when the DataSource is deleted.
  177. Examples
  178. --------
  179. ::
  180. >>> ds = np.lib.npyio.DataSource('/home/guido')
  181. >>> urlname = 'http://www.google.com/'
  182. >>> gfile = ds.open('http://www.google.com/')
  183. >>> ds.abspath(urlname)
  184. '/home/guido/www.google.com/index.html'
  185. >>> ds = np.lib.npyio.DataSource(None) # use with temporary file
  186. >>> ds.open('/home/guido/foobar.txt')
  187. <open file '/home/guido.foobar.txt', mode 'r' at 0x91d4430>
  188. >>> ds.abspath('/home/guido/foobar.txt')
  189. '/tmp/.../home/guido/foobar.txt'
  190. """
  191. def __init__(self, destpath=os.curdir):
  192. """Create a DataSource with a local path at destpath."""
  193. if destpath:
  194. self._destpath = os.path.abspath(destpath)
  195. self._istmpdest = False
  196. else:
  197. import tempfile # deferring import to improve startup time
  198. self._destpath = tempfile.mkdtemp()
  199. self._istmpdest = True
  200. def __del__(self):
  201. # Remove temp directories
  202. if hasattr(self, '_istmpdest') and self._istmpdest:
  203. import shutil
  204. shutil.rmtree(self._destpath)
  205. def _iszip(self, filename):
  206. """Test if the filename is a zip file by looking at the file extension.
  207. """
  208. fname, ext = os.path.splitext(filename)
  209. return ext in _file_openers.keys()
  210. def _iswritemode(self, mode):
  211. """Test if the given mode will open a file for writing."""
  212. # Currently only used to test the bz2 files.
  213. _writemodes = ("w", "+")
  214. return any(c in _writemodes for c in mode)
  215. def _splitzipext(self, filename):
  216. """Split zip extension from filename and return filename.
  217. Returns
  218. -------
  219. base, zip_ext : {tuple}
  220. """
  221. if self._iszip(filename):
  222. return os.path.splitext(filename)
  223. else:
  224. return filename, None
  225. def _possible_names(self, filename):
  226. """Return a tuple containing compressed filename variations."""
  227. names = [filename]
  228. if not self._iszip(filename):
  229. for zipext in _file_openers.keys():
  230. if zipext:
  231. names.append(filename + zipext)
  232. return names
  233. def _isurl(self, path):
  234. """Test if path is a net location. Tests the scheme and netloc."""
  235. # We do this here to reduce the 'import numpy' initial import time.
  236. from urllib.parse import urlparse
  237. # BUG : URLs require a scheme string ('http://') to be used.
  238. # www.google.com will fail.
  239. # Should we prepend the scheme for those that don't have it and
  240. # test that also? Similar to the way we append .gz and test for
  241. # for compressed versions of files.
  242. scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path)
  243. return bool(scheme and netloc)
  244. def _cache(self, path):
  245. """Cache the file specified by path.
  246. Creates a copy of the file in the datasource cache.
  247. """
  248. # We import these here because importing them is slow and
  249. # a significant fraction of numpy's total import time.
  250. import shutil
  251. from urllib.request import urlopen
  252. upath = self.abspath(path)
  253. # ensure directory exists
  254. if not os.path.exists(os.path.dirname(upath)):
  255. os.makedirs(os.path.dirname(upath))
  256. # TODO: Doesn't handle compressed files!
  257. if self._isurl(path):
  258. with urlopen(path) as openedurl:
  259. with _open(upath, 'wb') as f:
  260. shutil.copyfileobj(openedurl, f)
  261. else:
  262. shutil.copyfile(path, upath)
  263. return upath
  264. def _findfile(self, path):
  265. """Searches for ``path`` and returns full path if found.
  266. If path is an URL, _findfile will cache a local copy and return the
  267. path to the cached file. If path is a local file, _findfile will
  268. return a path to that local file.
  269. The search will include possible compressed versions of the file
  270. and return the first occurrence found.
  271. """
  272. # Build list of possible local file paths
  273. if not self._isurl(path):
  274. # Valid local paths
  275. filelist = self._possible_names(path)
  276. # Paths in self._destpath
  277. filelist += self._possible_names(self.abspath(path))
  278. else:
  279. # Cached URLs in self._destpath
  280. filelist = self._possible_names(self.abspath(path))
  281. # Remote URLs
  282. filelist = filelist + self._possible_names(path)
  283. for name in filelist:
  284. if self.exists(name):
  285. if self._isurl(name):
  286. name = self._cache(name)
  287. return name
  288. return None
  289. def abspath(self, path):
  290. """
  291. Return absolute path of file in the DataSource directory.
  292. If `path` is an URL, then `abspath` will return either the location
  293. the file exists locally or the location it would exist when opened
  294. using the `open` method.
  295. Parameters
  296. ----------
  297. path : str or pathlib.Path
  298. Can be a local file or a remote URL.
  299. Returns
  300. -------
  301. out : str
  302. Complete path, including the `DataSource` destination directory.
  303. Notes
  304. -----
  305. The functionality is based on `os.path.abspath`.
  306. """
  307. # We do this here to reduce the 'import numpy' initial import time.
  308. from urllib.parse import urlparse
  309. # TODO: This should be more robust. Handles case where path includes
  310. # the destpath, but not other sub-paths. Failing case:
  311. # path = /home/guido/datafile.txt
  312. # destpath = /home/alex/
  313. # upath = self.abspath(path)
  314. # upath == '/home/alex/home/guido/datafile.txt'
  315. # handle case where path includes self._destpath
  316. splitpath = path.split(self._destpath, 2)
  317. if len(splitpath) > 1:
  318. path = splitpath[1]
  319. scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path)
  320. netloc = self._sanitize_relative_path(netloc)
  321. upath = self._sanitize_relative_path(upath)
  322. return os.path.join(self._destpath, netloc, upath)
  323. def _sanitize_relative_path(self, path):
  324. """Return a sanitised relative path for which
  325. os.path.abspath(os.path.join(base, path)).startswith(base)
  326. """
  327. last = None
  328. path = os.path.normpath(path)
  329. while path != last:
  330. last = path
  331. # Note: os.path.join treats '/' as os.sep on Windows
  332. path = path.lstrip(os.sep).lstrip('/')
  333. path = path.lstrip(os.pardir).removeprefix('..')
  334. drive, path = os.path.splitdrive(path) # for Windows
  335. return path
  336. def exists(self, path):
  337. """
  338. Test if path exists.
  339. Test if `path` exists as (and in this order):
  340. - a local file.
  341. - a remote URL that has been downloaded and stored locally in the
  342. `DataSource` directory.
  343. - a remote URL that has not been downloaded, but is valid and
  344. accessible.
  345. Parameters
  346. ----------
  347. path : str or pathlib.Path
  348. Can be a local file or a remote URL.
  349. Returns
  350. -------
  351. out : bool
  352. True if `path` exists.
  353. Notes
  354. -----
  355. When `path` is an URL, `exists` will return True if it's either
  356. stored locally in the `DataSource` directory, or is a valid remote
  357. URL. `DataSource` does not discriminate between the two, the file
  358. is accessible if it exists in either location.
  359. """
  360. # First test for local path
  361. if os.path.exists(path):
  362. return True
  363. # We import this here because importing urllib is slow and
  364. # a significant fraction of numpy's total import time.
  365. from urllib.error import URLError
  366. from urllib.request import urlopen
  367. # Test cached url
  368. upath = self.abspath(path)
  369. if os.path.exists(upath):
  370. return True
  371. # Test remote url
  372. if self._isurl(path):
  373. try:
  374. netfile = urlopen(path)
  375. netfile.close()
  376. del netfile
  377. return True
  378. except URLError:
  379. return False
  380. return False
  381. def open(self, path, mode='r', encoding=None, newline=None):
  382. """
  383. Open and return file-like object.
  384. If `path` is an URL, it will be downloaded, stored in the
  385. `DataSource` directory and opened from there.
  386. Parameters
  387. ----------
  388. path : str or pathlib.Path
  389. Local file path or URL to open.
  390. mode : {'r', 'w', 'a'}, optional
  391. Mode to open `path`. Mode 'r' for reading, 'w' for writing,
  392. 'a' to append. Available modes depend on the type of object
  393. specified by `path`. Default is 'r'.
  394. encoding : {None, str}, optional
  395. Open text file with given encoding. The default encoding will be
  396. what `open` uses.
  397. newline : {None, str}, optional
  398. Newline to use when reading text file.
  399. Returns
  400. -------
  401. out : file object
  402. File object.
  403. """
  404. # TODO: There is no support for opening a file for writing which
  405. # doesn't exist yet (creating a file). Should there be?
  406. # TODO: Add a ``subdir`` parameter for specifying the subdirectory
  407. # used to store URLs in self._destpath.
  408. if self._isurl(path) and self._iswritemode(mode):
  409. raise ValueError("URLs are not writeable")
  410. # NOTE: _findfile will fail on a new file opened for writing.
  411. found = self._findfile(path)
  412. if found:
  413. _fname, ext = self._splitzipext(found)
  414. if ext == 'bz2':
  415. mode.replace("+", "")
  416. return _file_openers[ext](found, mode=mode,
  417. encoding=encoding, newline=newline)
  418. else:
  419. raise FileNotFoundError(f"{path} not found.")
  420. class Repository (DataSource):
  421. """
  422. Repository(baseurl, destpath='.')
  423. A data repository where multiple DataSource's share a base
  424. URL/directory.
  425. `Repository` extends `DataSource` by prepending a base URL (or
  426. directory) to all the files it handles. Use `Repository` when you will
  427. be working with multiple files from one base URL. Initialize
  428. `Repository` with the base URL, then refer to each file by its filename
  429. only.
  430. Parameters
  431. ----------
  432. baseurl : str
  433. Path to the local directory or remote location that contains the
  434. data files.
  435. destpath : str or None, optional
  436. Path to the directory where the source file gets downloaded to for
  437. use. If `destpath` is None, a temporary directory will be created.
  438. The default path is the current directory.
  439. Examples
  440. --------
  441. To analyze all files in the repository, do something like this
  442. (note: this is not self-contained code)::
  443. >>> repos = np.lib._datasource.Repository('/home/user/data/dir/')
  444. >>> for filename in filelist:
  445. ... fp = repos.open(filename)
  446. ... fp.analyze()
  447. ... fp.close()
  448. Similarly you could use a URL for a repository::
  449. >>> repos = np.lib._datasource.Repository('http://www.xyz.edu/data')
  450. """
  451. def __init__(self, baseurl, destpath=os.curdir):
  452. """Create a Repository with a shared url or directory of baseurl."""
  453. DataSource.__init__(self, destpath=destpath)
  454. self._baseurl = baseurl
  455. def __del__(self):
  456. DataSource.__del__(self)
  457. def _fullpath(self, path):
  458. """Return complete path for path. Prepends baseurl if necessary."""
  459. splitpath = path.split(self._baseurl, 2)
  460. if len(splitpath) == 1:
  461. result = os.path.join(self._baseurl, path)
  462. else:
  463. result = path # path contains baseurl already
  464. return result
  465. def _findfile(self, path):
  466. """Extend DataSource method to prepend baseurl to ``path``."""
  467. return DataSource._findfile(self, self._fullpath(path))
  468. def abspath(self, path):
  469. """
  470. Return absolute path of file in the Repository directory.
  471. If `path` is an URL, then `abspath` will return either the location
  472. the file exists locally or the location it would exist when opened
  473. using the `open` method.
  474. Parameters
  475. ----------
  476. path : str or pathlib.Path
  477. Can be a local file or a remote URL. This may, but does not
  478. have to, include the `baseurl` with which the `Repository` was
  479. initialized.
  480. Returns
  481. -------
  482. out : str
  483. Complete path, including the `DataSource` destination directory.
  484. """
  485. return DataSource.abspath(self, self._fullpath(path))
  486. def exists(self, path):
  487. """
  488. Test if path exists prepending Repository base URL to path.
  489. Test if `path` exists as (and in this order):
  490. - a local file.
  491. - a remote URL that has been downloaded and stored locally in the
  492. `DataSource` directory.
  493. - a remote URL that has not been downloaded, but is valid and
  494. accessible.
  495. Parameters
  496. ----------
  497. path : str or pathlib.Path
  498. Can be a local file or a remote URL. This may, but does not
  499. have to, include the `baseurl` with which the `Repository` was
  500. initialized.
  501. Returns
  502. -------
  503. out : bool
  504. True if `path` exists.
  505. Notes
  506. -----
  507. When `path` is an URL, `exists` will return True if it's either
  508. stored locally in the `DataSource` directory, or is a valid remote
  509. URL. `DataSource` does not discriminate between the two, the file
  510. is accessible if it exists in either location.
  511. """
  512. return DataSource.exists(self, self._fullpath(path))
  513. def open(self, path, mode='r', encoding=None, newline=None):
  514. """
  515. Open and return file-like object prepending Repository base URL.
  516. If `path` is an URL, it will be downloaded, stored in the
  517. DataSource directory and opened from there.
  518. Parameters
  519. ----------
  520. path : str or pathlib.Path
  521. Local file path or URL to open. This may, but does not have to,
  522. include the `baseurl` with which the `Repository` was
  523. initialized.
  524. mode : {'r', 'w', 'a'}, optional
  525. Mode to open `path`. Mode 'r' for reading, 'w' for writing,
  526. 'a' to append. Available modes depend on the type of object
  527. specified by `path`. Default is 'r'.
  528. encoding : {None, str}, optional
  529. Open text file with given encoding. The default encoding will be
  530. what `open` uses.
  531. newline : {None, str}, optional
  532. Newline to use when reading text file.
  533. Returns
  534. -------
  535. out : file object
  536. File object.
  537. """
  538. return DataSource.open(self, self._fullpath(path), mode,
  539. encoding=encoding, newline=newline)
  540. def listdir(self):
  541. """
  542. List files in the source Repository.
  543. Returns
  544. -------
  545. files : list of str or pathlib.Path
  546. List of file names (not containing a directory part).
  547. Notes
  548. -----
  549. Does not currently work for remote repositories.
  550. """
  551. if self._isurl(self._baseurl):
  552. raise NotImplementedError(
  553. "Directory listing of URLs, not supported yet.")
  554. else:
  555. return os.listdir(self._baseurl)