_datasource.py 22 KB

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