You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2593 lines
92 KiB

4 years ago
  1. # Natural Language Toolkit: Corpus & Model Downloader
  2. #
  3. # Copyright (C) 2001-2019 NLTK Project
  4. # Author: Edward Loper <edloper@gmail.com>
  5. # URL: <http://nltk.org/>
  6. # For license information, see LICENSE.TXT
  7. """
  8. The NLTK corpus and module downloader. This module defines several
  9. interfaces which can be used to download corpora, models, and other
  10. data packages that can be used with NLTK.
  11. Downloading Packages
  12. ====================
  13. If called with no arguments, ``download()`` will display an interactive
  14. interface which can be used to download and install new packages.
  15. If Tkinter is available, then a graphical interface will be shown,
  16. otherwise a simple text interface will be provided.
  17. Individual packages can be downloaded by calling the ``download()``
  18. function with a single argument, giving the package identifier for the
  19. package that should be downloaded:
  20. >>> download('treebank') # doctest: +SKIP
  21. [nltk_data] Downloading package 'treebank'...
  22. [nltk_data] Unzipping corpora/treebank.zip.
  23. NLTK also provides a number of \"package collections\", consisting of
  24. a group of related packages. To download all packages in a
  25. colleciton, simply call ``download()`` with the collection's
  26. identifier:
  27. >>> download('all-corpora') # doctest: +SKIP
  28. [nltk_data] Downloading package 'abc'...
  29. [nltk_data] Unzipping corpora/abc.zip.
  30. [nltk_data] Downloading package 'alpino'...
  31. [nltk_data] Unzipping corpora/alpino.zip.
  32. ...
  33. [nltk_data] Downloading package 'words'...
  34. [nltk_data] Unzipping corpora/words.zip.
  35. Download Directory
  36. ==================
  37. By default, packages are installed in either a system-wide directory
  38. (if Python has sufficient access to write to it); or in the current
  39. user's home directory. However, the ``download_dir`` argument may be
  40. used to specify a different installation target, if desired.
  41. See ``Downloader.default_download_dir()`` for more a detailed
  42. description of how the default download directory is chosen.
  43. NLTK Download Server
  44. ====================
  45. Before downloading any packages, the corpus and module downloader
  46. contacts the NLTK download server, to retrieve an index file
  47. describing the available packages. By default, this index file is
  48. loaded from ``https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/index.xml``.
  49. If necessary, it is possible to create a new ``Downloader`` object,
  50. specifying a different URL for the package index file.
  51. Usage::
  52. python nltk/downloader.py [-d DATADIR] [-q] [-f] [-k] PACKAGE_IDS
  53. or::
  54. python -m nltk.downloader [-d DATADIR] [-q] [-f] [-k] PACKAGE_IDS
  55. """
  56. # ----------------------------------------------------------------------
  57. from __future__ import print_function, division, unicode_literals
  58. """
  59. 0 1 2 3
  60. [label][----][label][----]
  61. [column ][column ]
  62. Notes
  63. =====
  64. Handling data files.. Some questions:
  65. * Should the data files be kept zipped or unzipped? I say zipped.
  66. * Should the data files be kept in svn at all? Advantages: history;
  67. automatic version numbers; 'svn up' could be used rather than the
  68. downloader to update the corpora. Disadvantages: they're big,
  69. which makes working from svn a bit of a pain. And we're planning
  70. to potentially make them much bigger. I don't think we want
  71. people to have to download 400MB corpora just to use nltk from svn.
  72. * Compromise: keep the data files in trunk/data rather than in
  73. trunk/nltk. That way you can check them out in svn if you want
  74. to; but you don't need to, and you can use the downloader instead.
  75. * Also: keep models in mind. When we change the code, we'd
  76. potentially like the models to get updated. This could require a
  77. little thought.
  78. * So.. let's assume we have a trunk/data directory, containing a bunch
  79. of packages. The packages should be kept as zip files, because we
  80. really shouldn't be editing them much (well -- we may edit models
  81. more, but they tend to be binary-ish files anyway, where diffs
  82. aren't that helpful). So we'll have trunk/data, with a bunch of
  83. files like abc.zip and treebank.zip and propbank.zip. For each
  84. package we could also have eg treebank.xml and propbank.xml,
  85. describing the contents of the package (name, copyright, license,
  86. etc). Collections would also have .xml files. Finally, we would
  87. pull all these together to form a single index.xml file. Some
  88. directory structure wouldn't hurt. So how about::
  89. /trunk/data/ ....................... root of data svn
  90. index.xml ........................ main index file
  91. src/ ............................. python scripts
  92. packages/ ........................ dir for packages
  93. corpora/ ....................... zip & xml files for corpora
  94. grammars/ ...................... zip & xml files for grammars
  95. taggers/ ....................... zip & xml files for taggers
  96. tokenizers/ .................... zip & xml files for tokenizers
  97. etc.
  98. collections/ ..................... xml files for collections
  99. Where the root (/trunk/data) would contain a makefile; and src/
  100. would contain a script to update the info.xml file. It could also
  101. contain scripts to rebuild some of the various model files. The
  102. script that builds index.xml should probably check that each zip
  103. file expands entirely into a single subdir, whose name matches the
  104. package's uid.
  105. Changes I need to make:
  106. - in index: change "size" to "filesize" or "compressed-size"
  107. - in index: add "unzipped-size"
  108. - when checking status: check both compressed & uncompressed size.
  109. uncompressed size is important to make sure we detect a problem
  110. if something got partially unzipped. define new status values
  111. to differentiate stale vs corrupt vs corruptly-uncompressed??
  112. (we shouldn't need to re-download the file if the zip file is ok
  113. but it didn't get uncompressed fully.)
  114. - add other fields to the index: author, license, copyright, contact,
  115. etc.
  116. the current grammars/ package would become a single new package (eg
  117. toy-grammars or book-grammars).
  118. xml file should have:
  119. - authorship info
  120. - license info
  121. - copyright info
  122. - contact info
  123. - info about what type of data/annotation it contains?
  124. - recommended corpus reader?
  125. collections can contain other collections. they can also contain
  126. multiple package types (corpora & models). Have a single 'basics'
  127. package that includes everything we talk about in the book?
  128. n.b.: there will have to be a fallback to the punkt tokenizer, in case
  129. they didn't download that model.
  130. default: unzip or not?
  131. """
  132. import time, os, zipfile, sys, textwrap, threading, itertools, shutil, functools
  133. import subprocess
  134. from hashlib import md5
  135. from xml.etree import ElementTree
  136. try:
  137. TKINTER = True
  138. from six.moves.tkinter import (
  139. Tk,
  140. Frame,
  141. Label,
  142. Entry,
  143. Button,
  144. Canvas,
  145. Menu,
  146. IntVar,
  147. TclError,
  148. )
  149. from six.moves.tkinter_messagebox import showerror
  150. from nltk.draw.table import Table
  151. from nltk.draw.util import ShowText
  152. except ImportError:
  153. TKINTER = False
  154. TclError = ValueError
  155. from six import string_types, text_type
  156. from six.moves import input
  157. from six.moves.urllib.request import urlopen
  158. from six.moves.urllib.error import HTTPError, URLError
  159. import nltk
  160. from nltk.compat import python_2_unicode_compatible
  161. # urllib2 = nltk.internals.import_from_stdlib('urllib2')
  162. ######################################################################
  163. # Directory entry objects (from the data server's index file)
  164. ######################################################################
  165. @python_2_unicode_compatible
  166. class Package(object):
  167. """
  168. A directory entry for a downloadable package. These entries are
  169. extracted from the XML index file that is downloaded by
  170. ``Downloader``. Each package consists of a single file; but if
  171. that file is a zip file, then it can be automatically decompressed
  172. when the package is installed.
  173. """
  174. def __init__(
  175. self,
  176. id,
  177. url,
  178. name=None,
  179. subdir='',
  180. size=None,
  181. unzipped_size=None,
  182. checksum=None,
  183. svn_revision=None,
  184. copyright='Unknown',
  185. contact='Unknown',
  186. license='Unknown',
  187. author='Unknown',
  188. unzip=True,
  189. **kw
  190. ):
  191. self.id = id
  192. """A unique identifier for this package."""
  193. self.name = name or id
  194. """A string name for this package."""
  195. self.subdir = subdir
  196. """The subdirectory where this package should be installed.
  197. E.g., ``'corpora'`` or ``'taggers'``."""
  198. self.url = url
  199. """A URL that can be used to download this package's file."""
  200. self.size = int(size)
  201. """The filesize (in bytes) of the package file."""
  202. self.unzipped_size = int(unzipped_size)
  203. """The total filesize of the files contained in the package's
  204. zipfile."""
  205. self.checksum = checksum
  206. """The MD-5 checksum of the package file."""
  207. self.svn_revision = svn_revision
  208. """A subversion revision number for this package."""
  209. self.copyright = copyright
  210. """Copyright holder for this package."""
  211. self.contact = contact
  212. """Name & email of the person who should be contacted with
  213. questions about this package."""
  214. self.license = license
  215. """License information for this package."""
  216. self.author = author
  217. """Author of this package."""
  218. ext = os.path.splitext(url.split('/')[-1])[1]
  219. self.filename = os.path.join(subdir, id + ext)
  220. """The filename that should be used for this package's file. It
  221. is formed by joining ``self.subdir`` with ``self.id``, and
  222. using the same extension as ``url``."""
  223. self.unzip = bool(int(unzip)) # '0' or '1'
  224. """A flag indicating whether this corpus should be unzipped by
  225. default."""
  226. # Include any other attributes provided by the XML file.
  227. self.__dict__.update(kw)
  228. @staticmethod
  229. def fromxml(xml):
  230. if isinstance(xml, string_types):
  231. xml = ElementTree.parse(xml)
  232. for key in xml.attrib:
  233. xml.attrib[key] = text_type(xml.attrib[key])
  234. return Package(**xml.attrib)
  235. def __lt__(self, other):
  236. return self.id < other.id
  237. def __repr__(self):
  238. return '<Package %s>' % self.id
  239. @python_2_unicode_compatible
  240. class Collection(object):
  241. """
  242. A directory entry for a collection of downloadable packages.
  243. These entries are extracted from the XML index file that is
  244. downloaded by ``Downloader``.
  245. """
  246. def __init__(self, id, children, name=None, **kw):
  247. self.id = id
  248. """A unique identifier for this collection."""
  249. self.name = name or id
  250. """A string name for this collection."""
  251. self.children = children
  252. """A list of the ``Collections`` or ``Packages`` directly
  253. contained by this collection."""
  254. self.packages = None
  255. """A list of ``Packages`` contained by this collection or any
  256. collections it recursively contains."""
  257. # Include any other attributes provided by the XML file.
  258. self.__dict__.update(kw)
  259. @staticmethod
  260. def fromxml(xml):
  261. if isinstance(xml, string_types):
  262. xml = ElementTree.parse(xml)
  263. for key in xml.attrib:
  264. xml.attrib[key] = text_type(xml.attrib[key])
  265. children = [child.get('ref') for child in xml.findall('item')]
  266. return Collection(children=children, **xml.attrib)
  267. def __lt__(self, other):
  268. return self.id < other.id
  269. def __repr__(self):
  270. return '<Collection %s>' % self.id
  271. ######################################################################
  272. # Message Passing Objects
  273. ######################################################################
  274. class DownloaderMessage(object):
  275. """A status message object, used by ``incr_download`` to
  276. communicate its progress."""
  277. class StartCollectionMessage(DownloaderMessage):
  278. """Data server has started working on a collection of packages."""
  279. def __init__(self, collection):
  280. self.collection = collection
  281. class FinishCollectionMessage(DownloaderMessage):
  282. """Data server has finished working on a collection of packages."""
  283. def __init__(self, collection):
  284. self.collection = collection
  285. class StartPackageMessage(DownloaderMessage):
  286. """Data server has started working on a package."""
  287. def __init__(self, package):
  288. self.package = package
  289. class FinishPackageMessage(DownloaderMessage):
  290. """Data server has finished working on a package."""
  291. def __init__(self, package):
  292. self.package = package
  293. class StartDownloadMessage(DownloaderMessage):
  294. """Data server has started downloading a package."""
  295. def __init__(self, package):
  296. self.package = package
  297. class FinishDownloadMessage(DownloaderMessage):
  298. """Data server has finished downloading a package."""
  299. def __init__(self, package):
  300. self.package = package
  301. class StartUnzipMessage(DownloaderMessage):
  302. """Data server has started unzipping a package."""
  303. def __init__(self, package):
  304. self.package = package
  305. class FinishUnzipMessage(DownloaderMessage):
  306. """Data server has finished unzipping a package."""
  307. def __init__(self, package):
  308. self.package = package
  309. class UpToDateMessage(DownloaderMessage):
  310. """The package download file is already up-to-date"""
  311. def __init__(self, package):
  312. self.package = package
  313. class StaleMessage(DownloaderMessage):
  314. """The package download file is out-of-date or corrupt"""
  315. def __init__(self, package):
  316. self.package = package
  317. class ErrorMessage(DownloaderMessage):
  318. """Data server encountered an error"""
  319. def __init__(self, package, message):
  320. self.package = package
  321. if isinstance(message, Exception):
  322. self.message = str(message)
  323. else:
  324. self.message = message
  325. class ProgressMessage(DownloaderMessage):
  326. """Indicates how much progress the data server has made"""
  327. def __init__(self, progress):
  328. self.progress = progress
  329. class SelectDownloadDirMessage(DownloaderMessage):
  330. """Indicates what download directory the data server is using"""
  331. def __init__(self, download_dir):
  332. self.download_dir = download_dir
  333. ######################################################################
  334. # NLTK Data Server
  335. ######################################################################
  336. class Downloader(object):
  337. """
  338. A class used to access the NLTK data server, which can be used to
  339. download corpora and other data packages.
  340. """
  341. # /////////////////////////////////////////////////////////////////
  342. # Configuration
  343. # /////////////////////////////////////////////////////////////////
  344. INDEX_TIMEOUT = 60 * 60 # 1 hour
  345. """The amount of time after which the cached copy of the data
  346. server index will be considered 'stale,' and will be
  347. re-downloaded."""
  348. DEFAULT_URL = 'https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/index.xml'
  349. """The default URL for the NLTK data server's index. An
  350. alternative URL can be specified when creating a new
  351. ``Downloader`` object."""
  352. # /////////////////////////////////////////////////////////////////
  353. # Status Constants
  354. # /////////////////////////////////////////////////////////////////
  355. INSTALLED = 'installed'
  356. """A status string indicating that a package or collection is
  357. installed and up-to-date."""
  358. NOT_INSTALLED = 'not installed'
  359. """A status string indicating that a package or collection is
  360. not installed."""
  361. STALE = 'out of date'
  362. """A status string indicating that a package or collection is
  363. corrupt or out-of-date."""
  364. PARTIAL = 'partial'
  365. """A status string indicating that a collection is partially
  366. installed (i.e., only some of its packages are installed.)"""
  367. # /////////////////////////////////////////////////////////////////
  368. # Cosntructor
  369. # /////////////////////////////////////////////////////////////////
  370. def __init__(self, server_index_url=None, download_dir=None):
  371. self._url = server_index_url or self.DEFAULT_URL
  372. """The URL for the data server's index file."""
  373. self._collections = {}
  374. """Dictionary from collection identifier to ``Collection``"""
  375. self._packages = {}
  376. """Dictionary from package identifier to ``Package``"""
  377. self._download_dir = download_dir
  378. """The default directory to which packages will be downloaded."""
  379. self._index = None
  380. """The XML index file downloaded from the data server"""
  381. self._index_timestamp = None
  382. """Time at which ``self._index`` was downloaded. If it is more
  383. than ``INDEX_TIMEOUT`` seconds old, it will be re-downloaded."""
  384. self._status_cache = {}
  385. """Dictionary from package/collection identifier to status
  386. string (``INSTALLED``, ``NOT_INSTALLED``, ``STALE``, or
  387. ``PARTIAL``). Cache is used for packages only, not
  388. collections."""
  389. self._errors = None
  390. """Flag for telling if all packages got successfully downloaded or not."""
  391. # decide where we're going to save things to.
  392. if self._download_dir is None:
  393. self._download_dir = self.default_download_dir()
  394. # /////////////////////////////////////////////////////////////////
  395. # Information
  396. # /////////////////////////////////////////////////////////////////
  397. def list(
  398. self,
  399. download_dir=None,
  400. show_packages=True,
  401. show_collections=True,
  402. header=True,
  403. more_prompt=False,
  404. skip_installed=False,
  405. ):
  406. lines = 0 # for more_prompt
  407. if download_dir is None:
  408. download_dir = self._download_dir
  409. print('Using default data directory (%s)' % download_dir)
  410. if header:
  411. print('=' * (26 + len(self._url)))
  412. print(' Data server index for <%s>' % self._url)
  413. print('=' * (26 + len(self._url)))
  414. lines += 3 # for more_prompt
  415. stale = partial = False
  416. categories = []
  417. if show_packages:
  418. categories.append('packages')
  419. if show_collections:
  420. categories.append('collections')
  421. for category in categories:
  422. print('%s:' % category.capitalize())
  423. lines += 1 # for more_prompt
  424. for info in sorted(getattr(self, category)(), key=str):
  425. status = self.status(info, download_dir)
  426. if status == self.INSTALLED and skip_installed:
  427. continue
  428. if status == self.STALE:
  429. stale = True
  430. if status == self.PARTIAL:
  431. partial = True
  432. prefix = {
  433. self.INSTALLED: '*',
  434. self.STALE: '-',
  435. self.PARTIAL: 'P',
  436. self.NOT_INSTALLED: ' ',
  437. }[status]
  438. name = textwrap.fill(
  439. '-' * 27 + (info.name or info.id), 75, subsequent_indent=27 * ' '
  440. )[27:]
  441. print(' [%s] %s %s' % (prefix, info.id.ljust(20, '.'), name))
  442. lines += len(name.split('\n')) # for more_prompt
  443. if more_prompt and lines > 20:
  444. user_input = input("Hit Enter to continue: ")
  445. if user_input.lower() in ('x', 'q'):
  446. return
  447. lines = 0
  448. print()
  449. msg = '([*] marks installed packages'
  450. if stale:
  451. msg += '; [-] marks out-of-date or corrupt packages'
  452. if partial:
  453. msg += '; [P] marks partially installed collections'
  454. print(textwrap.fill(msg + ')', subsequent_indent=' ', width=76))
  455. def packages(self):
  456. self._update_index()
  457. return self._packages.values()
  458. def corpora(self):
  459. self._update_index()
  460. return [pkg for (id, pkg) in self._packages.items() if pkg.subdir == 'corpora']
  461. def models(self):
  462. self._update_index()
  463. return [pkg for (id, pkg) in self._packages.items() if pkg.subdir != 'corpora']
  464. def collections(self):
  465. self._update_index()
  466. return self._collections.values()
  467. # /////////////////////////////////////////////////////////////////
  468. # Downloading
  469. # /////////////////////////////////////////////////////////////////
  470. def _info_or_id(self, info_or_id):
  471. if isinstance(info_or_id, string_types):
  472. return self.info(info_or_id)
  473. else:
  474. return info_or_id
  475. # [xx] When during downloading is it 'safe' to abort? Only unsafe
  476. # time is *during* an unzip -- we don't want to leave a
  477. # partially-unzipped corpus in place because we wouldn't notice
  478. # it. But if we had the exact total size of the unzipped corpus,
  479. # then that would be fine. Then we could abort anytime we want!
  480. # So this is really what we should do. That way the threaded
  481. # downloader in the gui can just kill the download thread anytime
  482. # it wants.
  483. def incr_download(self, info_or_id, download_dir=None, force=False):
  484. # If they didn't specify a download_dir, then use the default one.
  485. if download_dir is None:
  486. download_dir = self._download_dir
  487. yield SelectDownloadDirMessage(download_dir)
  488. # If they gave us a list of ids, then download each one.
  489. if isinstance(info_or_id, (list, tuple)):
  490. for msg in self._download_list(info_or_id, download_dir, force):
  491. yield msg
  492. return
  493. # Look up the requested collection or package.
  494. try:
  495. info = self._info_or_id(info_or_id)
  496. except (IOError, ValueError) as e:
  497. yield ErrorMessage(None, 'Error loading %s: %s' % (info_or_id, e))
  498. return
  499. # Handle collections.
  500. if isinstance(info, Collection):
  501. yield StartCollectionMessage(info)
  502. for msg in self.incr_download(info.children, download_dir, force):
  503. yield msg
  504. yield FinishCollectionMessage(info)
  505. # Handle Packages (delegate to a helper function).
  506. else:
  507. for msg in self._download_package(info, download_dir, force):
  508. yield msg
  509. def _num_packages(self, item):
  510. if isinstance(item, Package):
  511. return 1
  512. else:
  513. return len(item.packages)
  514. def _download_list(self, items, download_dir, force):
  515. # Look up the requested items.
  516. for i in range(len(items)):
  517. try:
  518. items[i] = self._info_or_id(items[i])
  519. except (IOError, ValueError) as e:
  520. yield ErrorMessage(items[i], e)
  521. return
  522. # Download each item, re-scaling their progress.
  523. num_packages = sum(self._num_packages(item) for item in items)
  524. progress = 0
  525. for i, item in enumerate(items):
  526. if isinstance(item, Package):
  527. delta = 1.0 / num_packages
  528. else:
  529. delta = len(item.packages) / num_packages
  530. for msg in self.incr_download(item, download_dir, force):
  531. if isinstance(msg, ProgressMessage):
  532. yield ProgressMessage(progress + msg.progress * delta)
  533. else:
  534. yield msg
  535. progress += 100 * delta
  536. def _download_package(self, info, download_dir, force):
  537. yield StartPackageMessage(info)
  538. yield ProgressMessage(0)
  539. # Do we already have the current version?
  540. status = self.status(info, download_dir)
  541. if not force and status == self.INSTALLED:
  542. yield UpToDateMessage(info)
  543. yield ProgressMessage(100)
  544. yield FinishPackageMessage(info)
  545. return
  546. # Remove the package from our status cache
  547. self._status_cache.pop(info.id, None)
  548. # Check for (and remove) any old/stale version.
  549. filepath = os.path.join(download_dir, info.filename)
  550. if os.path.exists(filepath):
  551. if status == self.STALE:
  552. yield StaleMessage(info)
  553. os.remove(filepath)
  554. # Ensure the download_dir exists
  555. if not os.path.exists(download_dir):
  556. os.mkdir(download_dir)
  557. if not os.path.exists(os.path.join(download_dir, info.subdir)):
  558. os.mkdir(os.path.join(download_dir, info.subdir))
  559. # Download the file. This will raise an IOError if the url
  560. # is not found.
  561. yield StartDownloadMessage(info)
  562. yield ProgressMessage(5)
  563. try:
  564. infile = urlopen(info.url)
  565. with open(filepath, 'wb') as outfile:
  566. # print info.size
  567. num_blocks = max(1, info.size / (1024 * 16))
  568. for block in itertools.count():
  569. s = infile.read(1024 * 16) # 16k blocks.
  570. outfile.write(s)
  571. if not s:
  572. break
  573. if block % 2 == 0: # how often?
  574. yield ProgressMessage(min(80, 5 + 75 * (block / num_blocks)))
  575. infile.close()
  576. except IOError as e:
  577. yield ErrorMessage(
  578. info,
  579. 'Error downloading %r from <%s>:' '\n %s' % (info.id, info.url, e),
  580. )
  581. return
  582. yield FinishDownloadMessage(info)
  583. yield ProgressMessage(80)
  584. # If it's a zipfile, uncompress it.
  585. if info.filename.endswith('.zip'):
  586. zipdir = os.path.join(download_dir, info.subdir)
  587. # Unzip if we're unzipping by default; *or* if it's already
  588. # been unzipped (presumably a previous version).
  589. if info.unzip or os.path.exists(os.path.join(zipdir, info.id)):
  590. yield StartUnzipMessage(info)
  591. for msg in _unzip_iter(filepath, zipdir, verbose=False):
  592. # Somewhat of a hack, but we need a proper package reference
  593. msg.package = info
  594. yield msg
  595. yield FinishUnzipMessage(info)
  596. yield FinishPackageMessage(info)
  597. def download(
  598. self,
  599. info_or_id=None,
  600. download_dir=None,
  601. quiet=False,
  602. force=False,
  603. prefix='[nltk_data] ',
  604. halt_on_error=True,
  605. raise_on_error=False,
  606. print_error_to=sys.stderr,
  607. ):
  608. print_to = functools.partial(print, file=print_error_to)
  609. # If no info or id is given, then use the interactive shell.
  610. if info_or_id is None:
  611. # [xx] hmm -- changing self._download_dir here seems like
  612. # the wrong thing to do. Maybe the _interactive_download
  613. # function should make a new copy of self to use?
  614. if download_dir is not None:
  615. self._download_dir = download_dir
  616. self._interactive_download()
  617. return True
  618. else:
  619. # Define a helper function for displaying output:
  620. def show(s, prefix2=''):
  621. print_to(
  622. textwrap.fill(
  623. s,
  624. initial_indent=prefix + prefix2,
  625. subsequent_indent=prefix + prefix2 + ' ' * 4,
  626. )
  627. )
  628. for msg in self.incr_download(info_or_id, download_dir, force):
  629. # Error messages
  630. if isinstance(msg, ErrorMessage):
  631. show(msg.message)
  632. if raise_on_error:
  633. raise ValueError(msg.message)
  634. if halt_on_error:
  635. return False
  636. self._errors = True
  637. if not quiet:
  638. print_to("Error installing package. Retry? [n/y/e]")
  639. choice = input().strip()
  640. if choice in ['y', 'Y']:
  641. if not self.download(
  642. msg.package.id,
  643. download_dir,
  644. quiet,
  645. force,
  646. prefix,
  647. halt_on_error,
  648. raise_on_error,
  649. ):
  650. return False
  651. elif choice in ['e', 'E']:
  652. return False
  653. # All other messages
  654. if not quiet:
  655. # Collection downloading messages:
  656. if isinstance(msg, StartCollectionMessage):
  657. show('Downloading collection %r' % msg.collection.id)
  658. prefix += ' | '
  659. print_to(prefix)
  660. elif isinstance(msg, FinishCollectionMessage):
  661. print_to(prefix)
  662. prefix = prefix[:-4]
  663. if self._errors:
  664. show(
  665. 'Downloaded collection %r with errors'
  666. % msg.collection.id
  667. )
  668. else:
  669. show('Done downloading collection %s' % msg.collection.id)
  670. # Package downloading messages:
  671. elif isinstance(msg, StartPackageMessage):
  672. show(
  673. 'Downloading package %s to %s...'
  674. % (msg.package.id, download_dir)
  675. )
  676. elif isinstance(msg, UpToDateMessage):
  677. show('Package %s is already up-to-date!' % msg.package.id, ' ')
  678. # elif isinstance(msg, StaleMessage):
  679. # show('Package %s is out-of-date or corrupt' %
  680. # msg.package.id, ' ')
  681. elif isinstance(msg, StartUnzipMessage):
  682. show('Unzipping %s.' % msg.package.filename, ' ')
  683. # Data directory message:
  684. elif isinstance(msg, SelectDownloadDirMessage):
  685. download_dir = msg.download_dir
  686. return True
  687. def is_stale(self, info_or_id, download_dir=None):
  688. return self.status(info_or_id, download_dir) == self.STALE
  689. def is_installed(self, info_or_id, download_dir=None):
  690. return self.status(info_or_id, download_dir) == self.INSTALLED
  691. def clear_status_cache(self, id=None):
  692. if id is None:
  693. self._status_cache.clear()
  694. else:
  695. self._status_cache.pop(id, None)
  696. def status(self, info_or_id, download_dir=None):
  697. """
  698. Return a constant describing the status of the given package
  699. or collection. Status can be one of ``INSTALLED``,
  700. ``NOT_INSTALLED``, ``STALE``, or ``PARTIAL``.
  701. """
  702. if download_dir is None:
  703. download_dir = self._download_dir
  704. info = self._info_or_id(info_or_id)
  705. # Handle collections:
  706. if isinstance(info, Collection):
  707. pkg_status = [self.status(pkg.id) for pkg in info.packages]
  708. if self.STALE in pkg_status:
  709. return self.STALE
  710. elif self.PARTIAL in pkg_status:
  711. return self.PARTIAL
  712. elif self.INSTALLED in pkg_status and self.NOT_INSTALLED in pkg_status:
  713. return self.PARTIAL
  714. elif self.NOT_INSTALLED in pkg_status:
  715. return self.NOT_INSTALLED
  716. else:
  717. return self.INSTALLED
  718. # Handle packages:
  719. else:
  720. filepath = os.path.join(download_dir, info.filename)
  721. if download_dir != self._download_dir:
  722. return self._pkg_status(info, filepath)
  723. else:
  724. if info.id not in self._status_cache:
  725. self._status_cache[info.id] = self._pkg_status(info, filepath)
  726. return self._status_cache[info.id]
  727. def _pkg_status(self, info, filepath):
  728. if not os.path.exists(filepath):
  729. return self.NOT_INSTALLED
  730. # Check if the file has the correct size.
  731. try:
  732. filestat = os.stat(filepath)
  733. except OSError:
  734. return self.NOT_INSTALLED
  735. if filestat.st_size != int(info.size):
  736. return self.STALE
  737. # Check if the file's checksum matches
  738. if md5_hexdigest(filepath) != info.checksum:
  739. return self.STALE
  740. # If it's a zipfile, and it's been at least partially
  741. # unzipped, then check if it's been fully unzipped.
  742. if filepath.endswith('.zip'):
  743. unzipdir = filepath[:-4]
  744. if not os.path.exists(unzipdir):
  745. return self.INSTALLED # but not unzipped -- ok!
  746. if not os.path.isdir(unzipdir):
  747. return self.STALE
  748. unzipped_size = sum(
  749. os.stat(os.path.join(d, f)).st_size
  750. for d, _, files in os.walk(unzipdir)
  751. for f in files
  752. )
  753. if unzipped_size != info.unzipped_size:
  754. return self.STALE
  755. # Otherwise, everything looks good.
  756. return self.INSTALLED
  757. def update(self, quiet=False, prefix='[nltk_data] '):
  758. """
  759. Re-download any packages whose status is STALE.
  760. """
  761. self.clear_status_cache()
  762. for pkg in self.packages():
  763. if self.status(pkg) == self.STALE:
  764. self.download(pkg, quiet=quiet, prefix=prefix)
  765. # /////////////////////////////////////////////////////////////////
  766. # Index
  767. # /////////////////////////////////////////////////////////////////
  768. def _update_index(self, url=None):
  769. """A helper function that ensures that self._index is
  770. up-to-date. If the index is older than self.INDEX_TIMEOUT,
  771. then download it again."""
  772. # Check if the index is aleady up-to-date. If so, do nothing.
  773. if not (
  774. self._index is None
  775. or url is not None
  776. or time.time() - self._index_timestamp > self.INDEX_TIMEOUT
  777. ):
  778. return
  779. # If a URL was specified, then update our URL.
  780. self._url = url or self._url
  781. # Download the index file.
  782. self._index = nltk.internals.ElementWrapper(
  783. ElementTree.parse(urlopen(self._url)).getroot()
  784. )
  785. self._index_timestamp = time.time()
  786. # Build a dictionary of packages.
  787. packages = [Package.fromxml(p) for p in self._index.findall('packages/package')]
  788. self._packages = dict((p.id, p) for p in packages)
  789. # Build a dictionary of collections.
  790. collections = [
  791. Collection.fromxml(c) for c in self._index.findall('collections/collection')
  792. ]
  793. self._collections = dict((c.id, c) for c in collections)
  794. # Replace identifiers with actual children in collection.children.
  795. for collection in self._collections.values():
  796. for i, child_id in enumerate(collection.children):
  797. if child_id in self._packages:
  798. collection.children[i] = self._packages[child_id]
  799. elif child_id in self._collections:
  800. collection.children[i] = self._collections[child_id]
  801. else:
  802. print(
  803. 'removing collection member with no package: {}'.format(
  804. child_id
  805. )
  806. )
  807. del collection.children[i]
  808. # Fill in collection.packages for each collection.
  809. for collection in self._collections.values():
  810. packages = {}
  811. queue = [collection]
  812. for child in queue:
  813. if isinstance(child, Collection):
  814. queue.extend(child.children)
  815. elif isinstance(child, Package):
  816. packages[child.id] = child
  817. else:
  818. pass
  819. collection.packages = packages.values()
  820. # Flush the status cache
  821. self._status_cache.clear()
  822. def index(self):
  823. """
  824. Return the XML index describing the packages available from
  825. the data server. If necessary, this index will be downloaded
  826. from the data server.
  827. """
  828. self._update_index()
  829. return self._index
  830. def info(self, id):
  831. """Return the ``Package`` or ``Collection`` record for the
  832. given item."""
  833. self._update_index()
  834. if id in self._packages:
  835. return self._packages[id]
  836. if id in self._collections:
  837. return self._collections[id]
  838. raise ValueError('Package %r not found in index' % id)
  839. def xmlinfo(self, id):
  840. """Return the XML info record for the given item"""
  841. self._update_index()
  842. for package in self._index.findall('packages/package'):
  843. if package.get('id') == id:
  844. return package
  845. for collection in self._index.findall('collections/collection'):
  846. if collection.get('id') == id:
  847. return collection
  848. raise ValueError('Package %r not found in index' % id)
  849. # /////////////////////////////////////////////////////////////////
  850. # URL & Data Directory
  851. # /////////////////////////////////////////////////////////////////
  852. def _get_url(self):
  853. """The URL for the data server's index file."""
  854. return self._url
  855. def _set_url(self, url):
  856. """
  857. Set a new URL for the data server. If we're unable to contact
  858. the given url, then the original url is kept.
  859. """
  860. original_url = self._url
  861. try:
  862. self._update_index(url)
  863. except:
  864. self._url = original_url
  865. raise
  866. url = property(_get_url, _set_url)
  867. def default_download_dir(self):
  868. """
  869. Return the directory to which packages will be downloaded by
  870. default. This value can be overridden using the constructor,
  871. or on a case-by-case basis using the ``download_dir`` argument when
  872. calling ``download()``.
  873. On Windows, the default download directory is
  874. ``PYTHONHOME/lib/nltk``, where *PYTHONHOME* is the
  875. directory containing Python, e.g. ``C:\\Python25``.
  876. On all other platforms, the default directory is the first of
  877. the following which exists or which can be created with write
  878. permission: ``/usr/share/nltk_data``, ``/usr/local/share/nltk_data``,
  879. ``/usr/lib/nltk_data``, ``/usr/local/lib/nltk_data``, ``~/nltk_data``.
  880. """
  881. # Check if we are on GAE where we cannot write into filesystem.
  882. if 'APPENGINE_RUNTIME' in os.environ:
  883. return
  884. # Check if we have sufficient permissions to install in a
  885. # variety of system-wide locations.
  886. for nltkdir in nltk.data.path:
  887. if os.path.exists(nltkdir) and nltk.internals.is_writable(nltkdir):
  888. return nltkdir
  889. # On Windows, use %APPDATA%
  890. if sys.platform == 'win32' and 'APPDATA' in os.environ:
  891. homedir = os.environ['APPDATA']
  892. # Otherwise, install in the user's home directory.
  893. else:
  894. homedir = os.path.expanduser('~/')
  895. if homedir == '~/':
  896. raise ValueError("Could not find a default download directory")
  897. # append "nltk_data" to the home directory
  898. return os.path.join(homedir, 'nltk_data')
  899. def _get_download_dir(self):
  900. """
  901. The default directory to which packages will be downloaded.
  902. This defaults to the value returned by ``default_download_dir()``.
  903. To override this default on a case-by-case basis, use the
  904. ``download_dir`` argument when calling ``download()``.
  905. """
  906. return self._download_dir
  907. def _set_download_dir(self, download_dir):
  908. self._download_dir = download_dir
  909. # Clear the status cache.
  910. self._status_cache.clear()
  911. download_dir = property(_get_download_dir, _set_download_dir)
  912. # /////////////////////////////////////////////////////////////////
  913. # Interactive Shell
  914. # /////////////////////////////////////////////////////////////////
  915. def _interactive_download(self):
  916. # Try the GUI first; if that doesn't work, try the simple
  917. # interactive shell.
  918. if TKINTER:
  919. try:
  920. DownloaderGUI(self).mainloop()
  921. except TclError:
  922. DownloaderShell(self).run()
  923. else:
  924. DownloaderShell(self).run()
  925. class DownloaderShell(object):
  926. def __init__(self, dataserver):
  927. self._ds = dataserver
  928. def _simple_interactive_menu(self, *options):
  929. print('-' * 75)
  930. spc = (68 - sum(len(o) for o in options)) // (len(options) - 1) * ' '
  931. print(' ' + spc.join(options))
  932. # w = 76/len(options)
  933. # fmt = ' ' + ('%-'+str(w)+'s')*(len(options)-1) + '%s'
  934. # print fmt % options
  935. print('-' * 75)
  936. def run(self):
  937. print('NLTK Downloader')
  938. while True:
  939. self._simple_interactive_menu(
  940. 'd) Download',
  941. 'l) List',
  942. ' u) Update',
  943. 'c) Config',
  944. 'h) Help',
  945. 'q) Quit',
  946. )
  947. user_input = input('Downloader> ').strip()
  948. if not user_input:
  949. print()
  950. continue
  951. command = user_input.lower().split()[0]
  952. args = user_input.split()[1:]
  953. try:
  954. if command == 'l':
  955. print()
  956. self._ds.list(self._ds.download_dir, header=False, more_prompt=True)
  957. elif command == 'h':
  958. self._simple_interactive_help()
  959. elif command == 'c':
  960. self._simple_interactive_config()
  961. elif command in ('q', 'x'):
  962. return
  963. elif command == 'd':
  964. self._simple_interactive_download(args)
  965. elif command == 'u':
  966. self._simple_interactive_update()
  967. else:
  968. print('Command %r unrecognized' % user_input)
  969. except HTTPError as e:
  970. print('Error reading from server: %s' % e)
  971. except URLError as e:
  972. print('Error connecting to server: %s' % e.reason)
  973. # try checking if user_input is a package name, &
  974. # downloading it?
  975. print()
  976. def _simple_interactive_download(self, args):
  977. if args:
  978. for arg in args:
  979. try:
  980. self._ds.download(arg, prefix=' ')
  981. except (IOError, ValueError) as e:
  982. print(e)
  983. else:
  984. while True:
  985. print()
  986. print('Download which package (l=list; x=cancel)?')
  987. user_input = input(' Identifier> ')
  988. if user_input.lower() == 'l':
  989. self._ds.list(
  990. self._ds.download_dir,
  991. header=False,
  992. more_prompt=True,
  993. skip_installed=True,
  994. )
  995. continue
  996. elif user_input.lower() in ('x', 'q', ''):
  997. return
  998. elif user_input:
  999. for id in user_input.split():
  1000. try:
  1001. self._ds.download(id, prefix=' ')
  1002. except (IOError, ValueError) as e:
  1003. print(e)
  1004. break
  1005. def _simple_interactive_update(self):
  1006. while True:
  1007. stale_packages = []
  1008. stale = partial = False
  1009. for info in sorted(getattr(self._ds, 'packages')(), key=str):
  1010. if self._ds.status(info) == self._ds.STALE:
  1011. stale_packages.append((info.id, info.name))
  1012. print()
  1013. if stale_packages:
  1014. print('Will update following packages (o=ok; x=cancel)')
  1015. for pid, pname in stale_packages:
  1016. name = textwrap.fill(
  1017. '-' * 27 + (pname), 75, subsequent_indent=27 * ' '
  1018. )[27:]
  1019. print(' [ ] %s %s' % (pid.ljust(20, '.'), name))
  1020. print()
  1021. user_input = input(' Identifier> ')
  1022. if user_input.lower() == 'o':
  1023. for pid, pname in stale_packages:
  1024. try:
  1025. self._ds.download(pid, prefix=' ')
  1026. except (IOError, ValueError) as e:
  1027. print(e)
  1028. break
  1029. elif user_input.lower() in ('x', 'q', ''):
  1030. return
  1031. else:
  1032. print('Nothing to update.')
  1033. return
  1034. def _simple_interactive_help(self):
  1035. print()
  1036. print('Commands:')
  1037. print(
  1038. ' d) Download a package or collection u) Update out of date packages'
  1039. )
  1040. print(' l) List packages & collections h) Help')
  1041. print(' c) View & Modify Configuration q) Quit')
  1042. def _show_config(self):
  1043. print()
  1044. print('Data Server:')
  1045. print(' - URL: <%s>' % self._ds.url)
  1046. print((' - %d Package Collections Available' % len(self._ds.collections())))
  1047. print((' - %d Individual Packages Available' % len(self._ds.packages())))
  1048. print()
  1049. print('Local Machine:')
  1050. print(' - Data directory: %s' % self._ds.download_dir)
  1051. def _simple_interactive_config(self):
  1052. self._show_config()
  1053. while True:
  1054. print()
  1055. self._simple_interactive_menu(
  1056. 's) Show Config', 'u) Set Server URL', 'd) Set Data Dir', 'm) Main Menu'
  1057. )
  1058. user_input = input('Config> ').strip().lower()
  1059. if user_input == 's':
  1060. self._show_config()
  1061. elif user_input == 'd':
  1062. new_dl_dir = input(' New Directory> ').strip()
  1063. if new_dl_dir in ('', 'x', 'q', 'X', 'Q'):
  1064. print(' Cancelled!')
  1065. elif os.path.isdir(new_dl_dir):
  1066. self._ds.download_dir = new_dl_dir
  1067. else:
  1068. print(('Directory %r not found! Create it first.' % new_dl_dir))
  1069. elif user_input == 'u':
  1070. new_url = input(' New URL> ').strip()
  1071. if new_url in ('', 'x', 'q', 'X', 'Q'):
  1072. print(' Cancelled!')
  1073. else:
  1074. if not new_url.startswith(('http://', 'https://')):
  1075. new_url = 'http://' + new_url
  1076. try:
  1077. self._ds.url = new_url
  1078. except Exception as e:
  1079. print('Error reading <%r>:\n %s' % (new_url, e))
  1080. elif user_input == 'm':
  1081. break
  1082. class DownloaderGUI(object):
  1083. """
  1084. Graphical interface for downloading packages from the NLTK data
  1085. server.
  1086. """
  1087. # /////////////////////////////////////////////////////////////////
  1088. # Column Configuration
  1089. # /////////////////////////////////////////////////////////////////
  1090. COLUMNS = [
  1091. '',
  1092. 'Identifier',
  1093. 'Name',
  1094. 'Size',
  1095. 'Status',
  1096. 'Unzipped Size',
  1097. 'Copyright',
  1098. 'Contact',
  1099. 'License',
  1100. 'Author',
  1101. 'Subdir',
  1102. 'Checksum',
  1103. ]
  1104. """A list of the names of columns. This controls the order in
  1105. which the columns will appear. If this is edited, then
  1106. ``_package_to_columns()`` may need to be edited to match."""
  1107. COLUMN_WEIGHTS = {'': 0, 'Name': 5, 'Size': 0, 'Status': 0}
  1108. """A dictionary specifying how columns should be resized when the
  1109. table is resized. Columns with weight 0 will not be resized at
  1110. all; and columns with high weight will be resized more.
  1111. Default weight (for columns not explicitly listed) is 1."""
  1112. COLUMN_WIDTHS = {
  1113. '': 1,
  1114. 'Identifier': 20,
  1115. 'Name': 45,
  1116. 'Size': 10,
  1117. 'Unzipped Size': 10,
  1118. 'Status': 12,
  1119. }
  1120. """A dictionary specifying how wide each column should be, in
  1121. characters. The default width (for columns not explicitly
  1122. listed) is specified by ``DEFAULT_COLUMN_WIDTH``."""
  1123. DEFAULT_COLUMN_WIDTH = 30
  1124. """The default width for columns that are not explicitly listed
  1125. in ``COLUMN_WIDTHS``."""
  1126. INITIAL_COLUMNS = ['', 'Identifier', 'Name', 'Size', 'Status']
  1127. """The set of columns that should be displayed by default."""
  1128. # Perform a few import-time sanity checks to make sure that the
  1129. # column configuration variables are defined consistently:
  1130. for c in COLUMN_WEIGHTS:
  1131. assert c in COLUMNS
  1132. for c in COLUMN_WIDTHS:
  1133. assert c in COLUMNS
  1134. for c in INITIAL_COLUMNS:
  1135. assert c in COLUMNS
  1136. # /////////////////////////////////////////////////////////////////
  1137. # Color Configuration
  1138. # /////////////////////////////////////////////////////////////////
  1139. _BACKDROP_COLOR = ('#000', '#ccc')
  1140. _ROW_COLOR = {
  1141. Downloader.INSTALLED: ('#afa', '#080'),
  1142. Downloader.PARTIAL: ('#ffa', '#880'),
  1143. Downloader.STALE: ('#faa', '#800'),
  1144. Downloader.NOT_INSTALLED: ('#fff', '#888'),
  1145. }
  1146. _MARK_COLOR = ('#000', '#ccc')
  1147. # _FRONT_TAB_COLOR = ('#ccf', '#008')
  1148. # _BACK_TAB_COLOR = ('#88a', '#448')
  1149. _FRONT_TAB_COLOR = ('#fff', '#45c')
  1150. _BACK_TAB_COLOR = ('#aaa', '#67a')
  1151. _PROGRESS_COLOR = ('#f00', '#aaa')
  1152. _TAB_FONT = 'helvetica -16 bold'
  1153. # /////////////////////////////////////////////////////////////////
  1154. # Constructor
  1155. # /////////////////////////////////////////////////////////////////
  1156. def __init__(self, dataserver, use_threads=True):
  1157. self._ds = dataserver
  1158. self._use_threads = use_threads
  1159. # For the threaded downloader:
  1160. self._download_lock = threading.Lock()
  1161. self._download_msg_queue = []
  1162. self._download_abort_queue = []
  1163. self._downloading = False
  1164. # For tkinter after callbacks:
  1165. self._afterid = {}
  1166. # A message log.
  1167. self._log_messages = []
  1168. self._log_indent = 0
  1169. self._log('NLTK Downloader Started!')
  1170. # Create the main window.
  1171. top = self.top = Tk()
  1172. top.geometry('+50+50')
  1173. top.title('NLTK Downloader')
  1174. top.configure(background=self._BACKDROP_COLOR[1])
  1175. # Set up some bindings now, in case anything goes wrong.
  1176. top.bind('<Control-q>', self.destroy)
  1177. top.bind('<Control-x>', self.destroy)
  1178. self._destroyed = False
  1179. self._column_vars = {}
  1180. # Initialize the GUI.
  1181. self._init_widgets()
  1182. self._init_menu()
  1183. try:
  1184. self._fill_table()
  1185. except HTTPError as e:
  1186. showerror('Error reading from server', e)
  1187. except URLError as e:
  1188. showerror('Error connecting to server', e.reason)
  1189. self._show_info()
  1190. self._select_columns()
  1191. self._table.select(0)
  1192. # Make sure we get notified when we're destroyed, so we can
  1193. # cancel any download in progress.
  1194. self._table.bind('<Destroy>', self._destroy)
  1195. def _log(self, msg):
  1196. self._log_messages.append(
  1197. '%s %s%s' % (time.ctime(), ' | ' * self._log_indent, msg)
  1198. )
  1199. # /////////////////////////////////////////////////////////////////
  1200. # Internals
  1201. # /////////////////////////////////////////////////////////////////
  1202. def _init_widgets(self):
  1203. # Create the top-level frame structures
  1204. f1 = Frame(self.top, relief='raised', border=2, padx=8, pady=0)
  1205. f1.pack(sid='top', expand=True, fill='both')
  1206. f1.grid_rowconfigure(2, weight=1)
  1207. f1.grid_columnconfigure(0, weight=1)
  1208. Frame(f1, height=8).grid(column=0, row=0) # spacer
  1209. tabframe = Frame(f1)
  1210. tabframe.grid(column=0, row=1, sticky='news')
  1211. tableframe = Frame(f1)
  1212. tableframe.grid(column=0, row=2, sticky='news')
  1213. buttonframe = Frame(f1)
  1214. buttonframe.grid(column=0, row=3, sticky='news')
  1215. Frame(f1, height=8).grid(column=0, row=4) # spacer
  1216. infoframe = Frame(f1)
  1217. infoframe.grid(column=0, row=5, sticky='news')
  1218. Frame(f1, height=8).grid(column=0, row=6) # spacer
  1219. progressframe = Frame(
  1220. self.top, padx=3, pady=3, background=self._BACKDROP_COLOR[1]
  1221. )
  1222. progressframe.pack(side='bottom', fill='x')
  1223. self.top['border'] = 0
  1224. self.top['highlightthickness'] = 0
  1225. # Create the tabs
  1226. self._tab_names = ['Collections', 'Corpora', 'Models', 'All Packages']
  1227. self._tabs = {}
  1228. for i, tab in enumerate(self._tab_names):
  1229. label = Label(tabframe, text=tab, font=self._TAB_FONT)
  1230. label.pack(side='left', padx=((i + 1) % 2) * 10)
  1231. label.bind('<Button-1>', self._select_tab)
  1232. self._tabs[tab.lower()] = label
  1233. # Create the table.
  1234. column_weights = [self.COLUMN_WEIGHTS.get(column, 1) for column in self.COLUMNS]
  1235. self._table = Table(
  1236. tableframe,
  1237. self.COLUMNS,
  1238. column_weights=column_weights,
  1239. highlightthickness=0,
  1240. listbox_height=16,
  1241. reprfunc=self._table_reprfunc,
  1242. )
  1243. self._table.columnconfig(0, foreground=self._MARK_COLOR[0]) # marked
  1244. for i, column in enumerate(self.COLUMNS):
  1245. width = self.COLUMN_WIDTHS.get(column, self.DEFAULT_COLUMN_WIDTH)
  1246. self._table.columnconfig(i, width=width)
  1247. self._table.pack(expand=True, fill='both')
  1248. self._table.focus()
  1249. self._table.bind_to_listboxes('<Double-Button-1>', self._download)
  1250. self._table.bind('<space>', self._table_mark)
  1251. self._table.bind('<Return>', self._download)
  1252. self._table.bind('<Left>', self._prev_tab)
  1253. self._table.bind('<Right>', self._next_tab)
  1254. self._table.bind('<Control-a>', self._mark_all)
  1255. # Create entry boxes for URL & download_dir
  1256. infoframe.grid_columnconfigure(1, weight=1)
  1257. info = [
  1258. ('url', 'Server Index:', self._set_url),
  1259. ('download_dir', 'Download Directory:', self._set_download_dir),
  1260. ]
  1261. self._info = {}
  1262. for (i, (key, label, callback)) in enumerate(info):
  1263. Label(infoframe, text=label).grid(column=0, row=i, sticky='e')
  1264. entry = Entry(
  1265. infoframe, font='courier', relief='groove', disabledforeground='black'
  1266. )
  1267. self._info[key] = (entry, callback)
  1268. entry.bind('<Return>', self._info_save)
  1269. entry.bind('<Button-1>', lambda e, key=key: self._info_edit(key))
  1270. entry.grid(column=1, row=i, sticky='ew')
  1271. # If the user edits url or download_dir, and then clicks outside
  1272. # the entry box, then save their results.
  1273. self.top.bind('<Button-1>', self._info_save)
  1274. # Create Download & Refresh buttons.
  1275. self._download_button = Button(
  1276. buttonframe, text='Download', command=self._download, width=8
  1277. )
  1278. self._download_button.pack(side='left')
  1279. self._refresh_button = Button(
  1280. buttonframe, text='Refresh', command=self._refresh, width=8
  1281. )
  1282. self._refresh_button.pack(side='right')
  1283. # Create Progress bar
  1284. self._progresslabel = Label(
  1285. progressframe,
  1286. text='',
  1287. foreground=self._BACKDROP_COLOR[0],
  1288. background=self._BACKDROP_COLOR[1],
  1289. )
  1290. self._progressbar = Canvas(
  1291. progressframe,
  1292. width=200,
  1293. height=16,
  1294. background=self._PROGRESS_COLOR[1],
  1295. relief='sunken',
  1296. border=1,
  1297. )
  1298. self._init_progressbar()
  1299. self._progressbar.pack(side='right')
  1300. self._progresslabel.pack(side='left')
  1301. def _init_menu(self):
  1302. menubar = Menu(self.top)
  1303. filemenu = Menu(menubar, tearoff=0)
  1304. filemenu.add_command(
  1305. label='Download', underline=0, command=self._download, accelerator='Return'
  1306. )
  1307. filemenu.add_separator()
  1308. filemenu.add_command(
  1309. label='Change Server Index',
  1310. underline=7,
  1311. command=lambda: self._info_edit('url'),
  1312. )
  1313. filemenu.add_command(
  1314. label='Change Download Directory',
  1315. underline=0,
  1316. command=lambda: self._info_edit('download_dir'),
  1317. )
  1318. filemenu.add_separator()
  1319. filemenu.add_command(label='Show Log', underline=5, command=self._show_log)
  1320. filemenu.add_separator()
  1321. filemenu.add_command(
  1322. label='Exit', underline=1, command=self.destroy, accelerator='Ctrl-x'
  1323. )
  1324. menubar.add_cascade(label='File', underline=0, menu=filemenu)
  1325. # Create a menu to control which columns of the table are
  1326. # shown. n.b.: we never hide the first two columns (mark and
  1327. # identifier).
  1328. viewmenu = Menu(menubar, tearoff=0)
  1329. for column in self._table.column_names[2:]:
  1330. var = IntVar(self.top)
  1331. assert column not in self._column_vars
  1332. self._column_vars[column] = var
  1333. if column in self.INITIAL_COLUMNS:
  1334. var.set(1)
  1335. viewmenu.add_checkbutton(
  1336. label=column, underline=0, variable=var, command=self._select_columns
  1337. )
  1338. menubar.add_cascade(label='View', underline=0, menu=viewmenu)
  1339. # Create a sort menu
  1340. # [xx] this should be selectbuttons; and it should include
  1341. # reversed sorts as options.
  1342. sortmenu = Menu(menubar, tearoff=0)
  1343. for column in self._table.column_names[1:]:
  1344. sortmenu.add_command(
  1345. label='Sort by %s' % column,
  1346. command=(lambda c=column: self._table.sort_by(c, 'ascending')),
  1347. )
  1348. sortmenu.add_separator()
  1349. # sortmenu.add_command(label='Descending Sort:')
  1350. for column in self._table.column_names[1:]:
  1351. sortmenu.add_command(
  1352. label='Reverse sort by %s' % column,
  1353. command=(lambda c=column: self._table.sort_by(c, 'descending')),
  1354. )
  1355. menubar.add_cascade(label='Sort', underline=0, menu=sortmenu)
  1356. helpmenu = Menu(menubar, tearoff=0)
  1357. helpmenu.add_command(label='About', underline=0, command=self.about)
  1358. helpmenu.add_command(
  1359. label='Instructions', underline=0, command=self.help, accelerator='F1'
  1360. )
  1361. menubar.add_cascade(label='Help', underline=0, menu=helpmenu)
  1362. self.top.bind('<F1>', self.help)
  1363. self.top.config(menu=menubar)
  1364. def _select_columns(self):
  1365. for (column, var) in self._column_vars.items():
  1366. if var.get():
  1367. self._table.show_column(column)
  1368. else:
  1369. self._table.hide_column(column)
  1370. def _refresh(self):
  1371. self._ds.clear_status_cache()
  1372. try:
  1373. self._fill_table()
  1374. except HTTPError as e:
  1375. showerror('Error reading from server', e)
  1376. except URLError as e:
  1377. showerror('Error connecting to server', e.reason)
  1378. self._table.select(0)
  1379. def _info_edit(self, info_key):
  1380. self._info_save() # just in case.
  1381. (entry, callback) = self._info[info_key]
  1382. entry['state'] = 'normal'
  1383. entry['relief'] = 'sunken'
  1384. entry.focus()
  1385. def _info_save(self, e=None):
  1386. focus = self._table
  1387. for entry, callback in self._info.values():
  1388. if entry['state'] == 'disabled':
  1389. continue
  1390. if e is not None and e.widget is entry and e.keysym != 'Return':
  1391. focus = entry
  1392. else:
  1393. entry['state'] = 'disabled'
  1394. entry['relief'] = 'groove'
  1395. callback(entry.get())
  1396. focus.focus()
  1397. def _table_reprfunc(self, row, col, val):
  1398. if self._table.column_names[col].endswith('Size'):
  1399. if isinstance(val, string_types):
  1400. return ' %s' % val
  1401. elif val < 1024 ** 2:
  1402. return ' %.1f KB' % (val / 1024.0 ** 1)
  1403. elif val < 1024 ** 3:
  1404. return ' %.1f MB' % (val / 1024.0 ** 2)
  1405. else:
  1406. return ' %.1f GB' % (val / 1024.0 ** 3)
  1407. if col in (0, ''):
  1408. return str(val)
  1409. else:
  1410. return ' %s' % val
  1411. def _set_url(self, url):
  1412. if url == self._ds.url:
  1413. return
  1414. try:
  1415. self._ds.url = url
  1416. self._fill_table()
  1417. except IOError as e:
  1418. showerror('Error Setting Server Index', str(e))
  1419. self._show_info()
  1420. def _set_download_dir(self, download_dir):
  1421. if self._ds.download_dir == download_dir:
  1422. return
  1423. # check if the dir exists, and if not, ask if we should create it?
  1424. # Clear our status cache, & re-check what's installed
  1425. self._ds.download_dir = download_dir
  1426. try:
  1427. self._fill_table()
  1428. except HTTPError as e:
  1429. showerror('Error reading from server', e)
  1430. except URLError as e:
  1431. showerror('Error connecting to server', e.reason)
  1432. self._show_info()
  1433. def _show_info(self):
  1434. print('showing info', self._ds.url)
  1435. for entry, cb in self._info.values():
  1436. entry['state'] = 'normal'
  1437. entry.delete(0, 'end')
  1438. self._info['url'][0].insert(0, self._ds.url)
  1439. self._info['download_dir'][0].insert(0, self._ds.download_dir)
  1440. for entry, cb in self._info.values():
  1441. entry['state'] = 'disabled'
  1442. def _prev_tab(self, *e):
  1443. for i, tab in enumerate(self._tab_names):
  1444. if tab.lower() == self._tab and i > 0:
  1445. self._tab = self._tab_names[i - 1].lower()
  1446. try:
  1447. return self._fill_table()
  1448. except HTTPError as e:
  1449. showerror('Error reading from server', e)
  1450. except URLError as e:
  1451. showerror('Error connecting to server', e.reason)
  1452. def _next_tab(self, *e):
  1453. for i, tab in enumerate(self._tab_names):
  1454. if tab.lower() == self._tab and i < (len(self._tabs) - 1):
  1455. self._tab = self._tab_names[i + 1].lower()
  1456. try:
  1457. return self._fill_table()
  1458. except HTTPError as e:
  1459. showerror('Error reading from server', e)
  1460. except URLError as e:
  1461. showerror('Error connecting to server', e.reason)
  1462. def _select_tab(self, event):
  1463. self._tab = event.widget['text'].lower()
  1464. try:
  1465. self._fill_table()
  1466. except HTTPError as e:
  1467. showerror('Error reading from server', e)
  1468. except URLError as e:
  1469. showerror('Error connecting to server', e.reason)
  1470. _tab = 'collections'
  1471. # _tab = 'corpora'
  1472. _rows = None
  1473. def _fill_table(self):
  1474. selected_row = self._table.selected_row()
  1475. self._table.clear()
  1476. if self._tab == 'all packages':
  1477. items = self._ds.packages()
  1478. elif self._tab == 'corpora':
  1479. items = self._ds.corpora()
  1480. elif self._tab == 'models':
  1481. items = self._ds.models()
  1482. elif self._tab == 'collections':
  1483. items = self._ds.collections()
  1484. else:
  1485. assert 0, 'bad tab value %r' % self._tab
  1486. rows = [self._package_to_columns(item) for item in items]
  1487. self._table.extend(rows)
  1488. # Highlight the active tab.
  1489. for tab, label in self._tabs.items():
  1490. if tab == self._tab:
  1491. label.configure(
  1492. foreground=self._FRONT_TAB_COLOR[0],
  1493. background=self._FRONT_TAB_COLOR[1],
  1494. )
  1495. else:
  1496. label.configure(
  1497. foreground=self._BACK_TAB_COLOR[0],
  1498. background=self._BACK_TAB_COLOR[1],
  1499. )
  1500. self._table.sort_by('Identifier', order='ascending')
  1501. self._color_table()
  1502. self._table.select(selected_row)
  1503. # This is a hack, because the scrollbar isn't updating its
  1504. # position right -- I'm not sure what the underlying cause is
  1505. # though. (This is on OS X w/ python 2.5) The length of
  1506. # delay that's necessary seems to depend on how fast the
  1507. # comptuer is. :-/
  1508. self.top.after(150, self._table._scrollbar.set, *self._table._mlb.yview())
  1509. self.top.after(300, self._table._scrollbar.set, *self._table._mlb.yview())
  1510. def _update_table_status(self):
  1511. for row_num in range(len(self._table)):
  1512. status = self._ds.status(self._table[row_num, 'Identifier'])
  1513. self._table[row_num, 'Status'] = status
  1514. self._color_table()
  1515. def _download(self, *e):
  1516. # If we're using threads, then delegate to the threaded
  1517. # downloader instead.
  1518. if self._use_threads:
  1519. return self._download_threaded(*e)
  1520. marked = [
  1521. self._table[row, 'Identifier']
  1522. for row in range(len(self._table))
  1523. if self._table[row, 0] != ''
  1524. ]
  1525. selection = self._table.selected_row()
  1526. if not marked and selection is not None:
  1527. marked = [self._table[selection, 'Identifier']]
  1528. download_iter = self._ds.incr_download(marked, self._ds.download_dir)
  1529. self._log_indent = 0
  1530. self._download_cb(download_iter, marked)
  1531. _DL_DELAY = 10
  1532. def _download_cb(self, download_iter, ids):
  1533. try:
  1534. msg = next(download_iter)
  1535. except StopIteration:
  1536. # self._fill_table(sort=False)
  1537. self._update_table_status()
  1538. afterid = self.top.after(10, self._show_progress, 0)
  1539. self._afterid['_download_cb'] = afterid
  1540. return
  1541. def show(s):
  1542. self._progresslabel['text'] = s
  1543. self._log(s)
  1544. if isinstance(msg, ProgressMessage):
  1545. self._show_progress(msg.progress)
  1546. elif isinstance(msg, ErrorMessage):
  1547. show(msg.message)
  1548. if msg.package is not None:
  1549. self._select(msg.package.id)
  1550. self._show_progress(None)
  1551. return # halt progress.
  1552. elif isinstance(msg, StartCollectionMessage):
  1553. show('Downloading collection %s' % msg.collection.id)
  1554. self._log_indent += 1
  1555. elif isinstance(msg, StartPackageMessage):
  1556. show('Downloading package %s' % msg.package.id)
  1557. elif isinstance(msg, UpToDateMessage):
  1558. show('Package %s is up-to-date!' % msg.package.id)
  1559. # elif isinstance(msg, StaleMessage):
  1560. # show('Package %s is out-of-date or corrupt' % msg.package.id)
  1561. elif isinstance(msg, FinishDownloadMessage):
  1562. show('Finished downloading %r.' % msg.package.id)
  1563. elif isinstance(msg, StartUnzipMessage):
  1564. show('Unzipping %s' % msg.package.filename)
  1565. elif isinstance(msg, FinishCollectionMessage):
  1566. self._log_indent -= 1
  1567. show('Finished downloading collection %r.' % msg.collection.id)
  1568. self._clear_mark(msg.collection.id)
  1569. elif isinstance(msg, FinishPackageMessage):
  1570. self._clear_mark(msg.package.id)
  1571. afterid = self.top.after(self._DL_DELAY, self._download_cb, download_iter, ids)
  1572. self._afterid['_download_cb'] = afterid
  1573. def _select(self, id):
  1574. for row in range(len(self._table)):
  1575. if self._table[row, 'Identifier'] == id:
  1576. self._table.select(row)
  1577. return
  1578. def _color_table(self):
  1579. # Color rows according to status.
  1580. for row in range(len(self._table)):
  1581. bg, sbg = self._ROW_COLOR[self._table[row, 'Status']]
  1582. fg, sfg = ('black', 'white')
  1583. self._table.rowconfig(
  1584. row,
  1585. foreground=fg,
  1586. selectforeground=sfg,
  1587. background=bg,
  1588. selectbackground=sbg,
  1589. )
  1590. # Color the marked column
  1591. self._table.itemconfigure(
  1592. row, 0, foreground=self._MARK_COLOR[0], background=self._MARK_COLOR[1]
  1593. )
  1594. def _clear_mark(self, id):
  1595. for row in range(len(self._table)):
  1596. if self._table[row, 'Identifier'] == id:
  1597. self._table[row, 0] = ''
  1598. def _mark_all(self, *e):
  1599. for row in range(len(self._table)):
  1600. self._table[row, 0] = 'X'
  1601. def _table_mark(self, *e):
  1602. selection = self._table.selected_row()
  1603. if selection >= 0:
  1604. if self._table[selection][0] != '':
  1605. self._table[selection, 0] = ''
  1606. else:
  1607. self._table[selection, 0] = 'X'
  1608. self._table.select(delta=1)
  1609. def _show_log(self):
  1610. text = '\n'.join(self._log_messages)
  1611. ShowText(self.top, 'NLTK Downloader Log', text)
  1612. def _package_to_columns(self, pkg):
  1613. """
  1614. Given a package, return a list of values describing that
  1615. package, one for each column in ``self.COLUMNS``.
  1616. """
  1617. row = []
  1618. for column_index, column_name in enumerate(self.COLUMNS):
  1619. if column_index == 0: # Mark:
  1620. row.append('')
  1621. elif column_name == 'Identifier':
  1622. row.append(pkg.id)
  1623. elif column_name == 'Status':
  1624. row.append(self._ds.status(pkg))
  1625. else:
  1626. attr = column_name.lower().replace(' ', '_')
  1627. row.append(getattr(pkg, attr, 'n/a'))
  1628. return row
  1629. # /////////////////////////////////////////////////////////////////
  1630. # External Interface
  1631. # /////////////////////////////////////////////////////////////////
  1632. def destroy(self, *e):
  1633. if self._destroyed:
  1634. return
  1635. self.top.destroy()
  1636. self._destroyed = True
  1637. def _destroy(self, *e):
  1638. if self.top is not None:
  1639. for afterid in self._afterid.values():
  1640. self.top.after_cancel(afterid)
  1641. # Abort any download in progress.
  1642. if self._downloading and self._use_threads:
  1643. self._abort_download()
  1644. # Make sure the garbage collector destroys these now;
  1645. # otherwise, they may get destroyed when we're not in the main
  1646. # thread, which would make Tkinter unhappy.
  1647. self._column_vars.clear()
  1648. def mainloop(self, *args, **kwargs):
  1649. self.top.mainloop(*args, **kwargs)
  1650. # /////////////////////////////////////////////////////////////////
  1651. # HELP
  1652. # /////////////////////////////////////////////////////////////////
  1653. HELP = textwrap.dedent(
  1654. """\
  1655. This tool can be used to download a variety of corpora and models
  1656. that can be used with NLTK. Each corpus or model is distributed
  1657. in a single zip file, known as a \"package file.\" You can
  1658. download packages individually, or you can download pre-defined
  1659. collections of packages.
  1660. When you download a package, it will be saved to the \"download
  1661. directory.\" A default download directory is chosen when you run
  1662. the downloader; but you may also select a different download
  1663. directory. On Windows, the default download directory is
  1664. \"package.\"
  1665. The NLTK downloader can be used to download a variety of corpora,
  1666. models, and other data packages.
  1667. Keyboard shortcuts::
  1668. [return]\t Download
  1669. [up]\t Select previous package
  1670. [down]\t Select next package
  1671. [left]\t Select previous tab
  1672. [right]\t Select next tab
  1673. """
  1674. )
  1675. def help(self, *e):
  1676. # The default font's not very legible; try using 'fixed' instead.
  1677. try:
  1678. ShowText(
  1679. self.top,
  1680. 'Help: NLTK Dowloader',
  1681. self.HELP.strip(),
  1682. width=75,
  1683. font='fixed',
  1684. )
  1685. except:
  1686. ShowText(self.top, 'Help: NLTK Downloader', self.HELP.strip(), width=75)
  1687. def about(self, *e):
  1688. ABOUT = "NLTK Downloader\n" + "Written by Edward Loper"
  1689. TITLE = 'About: NLTK Downloader'
  1690. try:
  1691. from six.moves.tkinter_messagebox import Message
  1692. Message(message=ABOUT, title=TITLE).show()
  1693. except ImportError:
  1694. ShowText(self.top, TITLE, ABOUT)
  1695. # /////////////////////////////////////////////////////////////////
  1696. # Progress Bar
  1697. # /////////////////////////////////////////////////////////////////
  1698. _gradient_width = 5
  1699. def _init_progressbar(self):
  1700. c = self._progressbar
  1701. width, height = int(c['width']), int(c['height'])
  1702. for i in range(0, (int(c['width']) * 2) // self._gradient_width):
  1703. c.create_line(
  1704. i * self._gradient_width + 20,
  1705. -20,
  1706. i * self._gradient_width - height - 20,
  1707. height + 20,
  1708. width=self._gradient_width,
  1709. fill='#%02x0000' % (80 + abs(i % 6 - 3) * 12),
  1710. )
  1711. c.addtag_all('gradient')
  1712. c.itemconfig('gradient', state='hidden')
  1713. # This is used to display progress
  1714. c.addtag_withtag(
  1715. 'redbox', c.create_rectangle(0, 0, 0, 0, fill=self._PROGRESS_COLOR[0])
  1716. )
  1717. def _show_progress(self, percent):
  1718. c = self._progressbar
  1719. if percent is None:
  1720. c.coords('redbox', 0, 0, 0, 0)
  1721. c.itemconfig('gradient', state='hidden')
  1722. else:
  1723. width, height = int(c['width']), int(c['height'])
  1724. x = percent * int(width) // 100 + 1
  1725. c.coords('redbox', 0, 0, x, height + 1)
  1726. def _progress_alive(self):
  1727. c = self._progressbar
  1728. if not self._downloading:
  1729. c.itemconfig('gradient', state='hidden')
  1730. else:
  1731. c.itemconfig('gradient', state='normal')
  1732. x1, y1, x2, y2 = c.bbox('gradient')
  1733. if x1 <= -100:
  1734. c.move('gradient', (self._gradient_width * 6) - 4, 0)
  1735. else:
  1736. c.move('gradient', -4, 0)
  1737. afterid = self.top.after(200, self._progress_alive)
  1738. self._afterid['_progress_alive'] = afterid
  1739. # /////////////////////////////////////////////////////////////////
  1740. # Threaded downloader
  1741. # /////////////////////////////////////////////////////////////////
  1742. def _download_threaded(self, *e):
  1743. # If the user tries to start a new download while we're already
  1744. # downloading something, then abort the current download instead.
  1745. if self._downloading:
  1746. self._abort_download()
  1747. return
  1748. # Change the 'download' button to an 'abort' button.
  1749. self._download_button['text'] = 'Cancel'
  1750. marked = [
  1751. self._table[row, 'Identifier']
  1752. for row in range(len(self._table))
  1753. if self._table[row, 0] != ''
  1754. ]
  1755. selection = self._table.selected_row()
  1756. if not marked and selection is not None:
  1757. marked = [self._table[selection, 'Identifier']]
  1758. # Create a new data server object for the download operation,
  1759. # just in case the user modifies our data server during the
  1760. # download (e.g., clicking 'refresh' or editing the index url).
  1761. ds = Downloader(self._ds.url, self._ds.download_dir)
  1762. # Start downloading in a separate thread.
  1763. assert self._download_msg_queue == []
  1764. assert self._download_abort_queue == []
  1765. self._DownloadThread(
  1766. ds,
  1767. marked,
  1768. self._download_lock,
  1769. self._download_msg_queue,
  1770. self._download_abort_queue,
  1771. ).start()
  1772. # Monitor the download message queue & display its progress.
  1773. self._log_indent = 0
  1774. self._downloading = True
  1775. self._monitor_message_queue()
  1776. # Display an indication that we're still alive and well by
  1777. # cycling the progress bar.
  1778. self._progress_alive()
  1779. def _abort_download(self):
  1780. if self._downloading:
  1781. self._download_lock.acquire()
  1782. self._download_abort_queue.append('abort')
  1783. self._download_lock.release()
  1784. class _DownloadThread(threading.Thread):
  1785. def __init__(self, data_server, items, lock, message_queue, abort):
  1786. self.data_server = data_server
  1787. self.items = items
  1788. self.lock = lock
  1789. self.message_queue = message_queue
  1790. self.abort = abort
  1791. threading.Thread.__init__(self)
  1792. def run(self):
  1793. for msg in self.data_server.incr_download(self.items):
  1794. self.lock.acquire()
  1795. self.message_queue.append(msg)
  1796. # Check if we've been told to kill ourselves:
  1797. if self.abort:
  1798. self.message_queue.append('aborted')
  1799. self.lock.release()
  1800. return
  1801. self.lock.release()
  1802. self.lock.acquire()
  1803. self.message_queue.append('finished')
  1804. self.lock.release()
  1805. _MONITOR_QUEUE_DELAY = 100
  1806. def _monitor_message_queue(self):
  1807. def show(s):
  1808. self._progresslabel['text'] = s
  1809. self._log(s)
  1810. # Try to acquire the lock; if it's busy, then just try again later.
  1811. if not self._download_lock.acquire():
  1812. return
  1813. for msg in self._download_msg_queue:
  1814. # Done downloading?
  1815. if msg == 'finished' or msg == 'aborted':
  1816. # self._fill_table(sort=False)
  1817. self._update_table_status()
  1818. self._downloading = False
  1819. self._download_button['text'] = 'Download'
  1820. del self._download_msg_queue[:]
  1821. del self._download_abort_queue[:]
  1822. self._download_lock.release()
  1823. if msg == 'aborted':
  1824. show('Download aborted!')
  1825. self._show_progress(None)
  1826. else:
  1827. afterid = self.top.after(100, self._show_progress, None)
  1828. self._afterid['_monitor_message_queue'] = afterid
  1829. return
  1830. # All other messages
  1831. elif isinstance(msg, ProgressMessage):
  1832. self._show_progress(msg.progress)
  1833. elif isinstance(msg, ErrorMessage):
  1834. show(msg.message)
  1835. if msg.package is not None:
  1836. self._select(msg.package.id)
  1837. self._show_progress(None)
  1838. self._downloading = False
  1839. return # halt progress.
  1840. elif isinstance(msg, StartCollectionMessage):
  1841. show('Downloading collection %r' % msg.collection.id)
  1842. self._log_indent += 1
  1843. elif isinstance(msg, StartPackageMessage):
  1844. self._ds.clear_status_cache(msg.package.id)
  1845. show('Downloading package %r' % msg.package.id)
  1846. elif isinstance(msg, UpToDateMessage):
  1847. show('Package %s is up-to-date!' % msg.package.id)
  1848. # elif isinstance(msg, StaleMessage):
  1849. # show('Package %s is out-of-date or corrupt; updating it' %
  1850. # msg.package.id)
  1851. elif isinstance(msg, FinishDownloadMessage):
  1852. show('Finished downloading %r.' % msg.package.id)
  1853. elif isinstance(msg, StartUnzipMessage):
  1854. show('Unzipping %s' % msg.package.filename)
  1855. elif isinstance(msg, FinishUnzipMessage):
  1856. show('Finished installing %s' % msg.package.id)
  1857. elif isinstance(msg, FinishCollectionMessage):
  1858. self._log_indent -= 1
  1859. show('Finished downloading collection %r.' % msg.collection.id)
  1860. self._clear_mark(msg.collection.id)
  1861. elif isinstance(msg, FinishPackageMessage):
  1862. self._update_table_status()
  1863. self._clear_mark(msg.package.id)
  1864. # Let the user know when we're aborting a download (but
  1865. # waiting for a good point to abort it, so we don't end up
  1866. # with a partially unzipped package or anything like that).
  1867. if self._download_abort_queue:
  1868. self._progresslabel['text'] = 'Aborting download...'
  1869. # Clear the message queue and then release the lock
  1870. del self._download_msg_queue[:]
  1871. self._download_lock.release()
  1872. # Check the queue again after MONITOR_QUEUE_DELAY msec.
  1873. afterid = self.top.after(self._MONITOR_QUEUE_DELAY, self._monitor_message_queue)
  1874. self._afterid['_monitor_message_queue'] = afterid
  1875. ######################################################################
  1876. # Helper Functions
  1877. ######################################################################
  1878. # [xx] It may make sense to move these to nltk.internals.
  1879. def md5_hexdigest(file):
  1880. """
  1881. Calculate and return the MD5 checksum for a given file.
  1882. ``file`` may either be a filename or an open stream.
  1883. """
  1884. if isinstance(file, string_types):
  1885. with open(file, 'rb') as infile:
  1886. return _md5_hexdigest(infile)
  1887. return _md5_hexdigest(file)
  1888. def _md5_hexdigest(fp):
  1889. md5_digest = md5()
  1890. while True:
  1891. block = fp.read(1024 * 16) # 16k blocks
  1892. if not block:
  1893. break
  1894. md5_digest.update(block)
  1895. return md5_digest.hexdigest()
  1896. # change this to periodically yield progress messages?
  1897. # [xx] get rid of topdir parameter -- we should be checking
  1898. # this when we build the index, anyway.
  1899. def unzip(filename, root, verbose=True):
  1900. """
  1901. Extract the contents of the zip file ``filename`` into the
  1902. directory ``root``.
  1903. """
  1904. for message in _unzip_iter(filename, root, verbose):
  1905. if isinstance(message, ErrorMessage):
  1906. raise Exception(message)
  1907. def _unzip_iter(filename, root, verbose=True):
  1908. if verbose:
  1909. sys.stdout.write('Unzipping %s' % os.path.split(filename)[1])
  1910. sys.stdout.flush()
  1911. try:
  1912. zf = zipfile.ZipFile(filename)
  1913. except zipfile.error as e:
  1914. yield ErrorMessage(filename, 'Error with downloaded zip file')
  1915. return
  1916. except Exception as e:
  1917. yield ErrorMessage(filename, e)
  1918. return
  1919. # Get lists of directories & files
  1920. namelist = zf.namelist()
  1921. dirlist = set()
  1922. for x in namelist:
  1923. if x.endswith('/'):
  1924. dirlist.add(x)
  1925. else:
  1926. dirlist.add(x.rsplit('/', 1)[0] + '/')
  1927. filelist = [x for x in namelist if not x.endswith('/')]
  1928. # Create the target directory if it doesn't exist
  1929. if not os.path.exists(root):
  1930. os.mkdir(root)
  1931. # Create the directory structure
  1932. for dirname in sorted(dirlist):
  1933. pieces = dirname[:-1].split('/')
  1934. for i in range(len(pieces)):
  1935. dirpath = os.path.join(root, *pieces[: i + 1])
  1936. if not os.path.exists(dirpath):
  1937. os.mkdir(dirpath)
  1938. # Extract files.
  1939. for i, filename in enumerate(filelist):
  1940. filepath = os.path.join(root, *filename.split('/'))
  1941. try:
  1942. with open(filepath, 'wb') as dstfile, zf.open(filename) as srcfile:
  1943. shutil.copyfileobj(srcfile, dstfile)
  1944. except Exception as e:
  1945. yield ErrorMessage(filename, e)
  1946. return
  1947. if verbose and (i * 10 / len(filelist) > (i - 1) * 10 / len(filelist)):
  1948. sys.stdout.write('.')
  1949. sys.stdout.flush()
  1950. if verbose:
  1951. print()
  1952. ######################################################################
  1953. # Index Builder
  1954. ######################################################################
  1955. # This may move to a different file sometime.
  1956. def build_index(root, base_url):
  1957. """
  1958. Create a new data.xml index file, by combining the xml description
  1959. files for various packages and collections. ``root`` should be the
  1960. path to a directory containing the package xml and zip files; and
  1961. the collection xml files. The ``root`` directory is expected to
  1962. have the following subdirectories::
  1963. root/
  1964. packages/ .................. subdirectory for packages
  1965. corpora/ ................. zip & xml files for corpora
  1966. grammars/ ................ zip & xml files for grammars
  1967. taggers/ ................. zip & xml files for taggers
  1968. tokenizers/ .............. zip & xml files for tokenizers
  1969. etc.
  1970. collections/ ............... xml files for collections
  1971. For each package, there should be two files: ``package.zip``
  1972. (where *package* is the package name)
  1973. which contains the package itself as a compressed zip file; and
  1974. ``package.xml``, which is an xml description of the package. The
  1975. zipfile ``package.zip`` should expand to a single subdirectory
  1976. named ``package/``. The base filename ``package`` must match
  1977. the identifier given in the package's xml file.
  1978. For each collection, there should be a single file ``collection.zip``
  1979. describing the collection, where *collection* is the name of the collection.
  1980. All identifiers (for both packages and collections) must be unique.
  1981. """
  1982. # Find all packages.
  1983. packages = []
  1984. for pkg_xml, zf, subdir in _find_packages(os.path.join(root, 'packages')):
  1985. zipstat = os.stat(zf.filename)
  1986. url = '%s/%s/%s' % (base_url, subdir, os.path.split(zf.filename)[1])
  1987. unzipped_size = sum(zf_info.file_size for zf_info in zf.infolist())
  1988. # Fill in several fields of the package xml with calculated values.
  1989. pkg_xml.set('unzipped_size', '%s' % unzipped_size)
  1990. pkg_xml.set('size', '%s' % zipstat.st_size)
  1991. pkg_xml.set('checksum', '%s' % md5_hexdigest(zf.filename))
  1992. pkg_xml.set('subdir', subdir)
  1993. # pkg_xml.set('svn_revision', _svn_revision(zf.filename))
  1994. if not pkg_xml.get('url'):
  1995. pkg_xml.set('url', url)
  1996. # Record the package.
  1997. packages.append(pkg_xml)
  1998. # Find all collections
  1999. collections = list(_find_collections(os.path.join(root, 'collections')))
  2000. # Check that all UIDs are unique
  2001. uids = set()
  2002. for item in packages + collections:
  2003. if item.get('id') in uids:
  2004. raise ValueError('Duplicate UID: %s' % item.get('id'))
  2005. uids.add(item.get('id'))
  2006. # Put it all together
  2007. top_elt = ElementTree.Element('nltk_data')
  2008. top_elt.append(ElementTree.Element('packages'))
  2009. for package in packages:
  2010. top_elt[0].append(package)
  2011. top_elt.append(ElementTree.Element('collections'))
  2012. for collection in collections:
  2013. top_elt[1].append(collection)
  2014. _indent_xml(top_elt)
  2015. return top_elt
  2016. def _indent_xml(xml, prefix=''):
  2017. """
  2018. Helper for ``build_index()``: Given an XML ``ElementTree``, modify it
  2019. (and its descendents) ``text`` and ``tail`` attributes to generate
  2020. an indented tree, where each nested element is indented by 2
  2021. spaces with respect to its parent.
  2022. """
  2023. if len(xml) > 0:
  2024. xml.text = (xml.text or '').strip() + '\n' + prefix + ' '
  2025. for child in xml:
  2026. _indent_xml(child, prefix + ' ')
  2027. for child in xml[:-1]:
  2028. child.tail = (child.tail or '').strip() + '\n' + prefix + ' '
  2029. xml[-1].tail = (xml[-1].tail or '').strip() + '\n' + prefix
  2030. def _check_package(pkg_xml, zipfilename, zf):
  2031. """
  2032. Helper for ``build_index()``: Perform some checks to make sure that
  2033. the given package is consistent.
  2034. """
  2035. # The filename must patch the id given in the XML file.
  2036. uid = os.path.splitext(os.path.split(zipfilename)[1])[0]
  2037. if pkg_xml.get('id') != uid:
  2038. raise ValueError(
  2039. 'package identifier mismatch (%s vs %s)' % (pkg_xml.get('id'), uid)
  2040. )
  2041. # Zip file must expand to a subdir whose name matches uid.
  2042. if sum((name != uid and not name.startswith(uid + '/')) for name in zf.namelist()):
  2043. raise ValueError(
  2044. 'Zipfile %s.zip does not expand to a single '
  2045. 'subdirectory %s/' % (uid, uid)
  2046. )
  2047. # update for git?
  2048. def _svn_revision(filename):
  2049. """
  2050. Helper for ``build_index()``: Calculate the subversion revision
  2051. number for a given file (by using ``subprocess`` to run ``svn``).
  2052. """
  2053. p = subprocess.Popen(
  2054. ['svn', 'status', '-v', filename],
  2055. stdout=subprocess.PIPE,
  2056. stderr=subprocess.PIPE,
  2057. )
  2058. (stdout, stderr) = p.communicate()
  2059. if p.returncode != 0 or stderr or not stdout:
  2060. raise ValueError(
  2061. 'Error determining svn_revision for %s: %s'
  2062. % (os.path.split(filename)[1], textwrap.fill(stderr))
  2063. )
  2064. return stdout.split()[2]
  2065. def _find_collections(root):
  2066. """
  2067. Helper for ``build_index()``: Yield a list of ElementTree.Element
  2068. objects, each holding the xml for a single package collection.
  2069. """
  2070. packages = []
  2071. for dirname, subdirs, files in os.walk(root):
  2072. for filename in files:
  2073. if filename.endswith('.xml'):
  2074. xmlfile = os.path.join(dirname, filename)
  2075. yield ElementTree.parse(xmlfile).getroot()
  2076. def _find_packages(root):
  2077. """
  2078. Helper for ``build_index()``: Yield a list of tuples
  2079. ``(pkg_xml, zf, subdir)``, where:
  2080. - ``pkg_xml`` is an ``ElementTree.Element`` holding the xml for a
  2081. package
  2082. - ``zf`` is a ``zipfile.ZipFile`` for the package's contents.
  2083. - ``subdir`` is the subdirectory (relative to ``root``) where
  2084. the package was found (e.g. 'corpora' or 'grammars').
  2085. """
  2086. from nltk.corpus.reader.util import _path_from
  2087. # Find all packages.
  2088. packages = []
  2089. for dirname, subdirs, files in os.walk(root):
  2090. relpath = '/'.join(_path_from(root, dirname))
  2091. for filename in files:
  2092. if filename.endswith('.xml'):
  2093. xmlfilename = os.path.join(dirname, filename)
  2094. zipfilename = xmlfilename[:-4] + '.zip'
  2095. try:
  2096. zf = zipfile.ZipFile(zipfilename)
  2097. except Exception as e:
  2098. raise ValueError('Error reading file %r!\n%s' % (zipfilename, e))
  2099. try:
  2100. pkg_xml = ElementTree.parse(xmlfilename).getroot()
  2101. except Exception as e:
  2102. raise ValueError('Error reading file %r!\n%s' % (xmlfilename, e))
  2103. # Check that the UID matches the filename
  2104. uid = os.path.split(xmlfilename[:-4])[1]
  2105. if pkg_xml.get('id') != uid:
  2106. raise ValueError(
  2107. 'package identifier mismatch (%s '
  2108. 'vs %s)' % (pkg_xml.get('id'), uid)
  2109. )
  2110. # Check that the zipfile expands to a subdir whose
  2111. # name matches the uid.
  2112. if sum(
  2113. (name != uid and not name.startswith(uid + '/'))
  2114. for name in zf.namelist()
  2115. ):
  2116. raise ValueError(
  2117. 'Zipfile %s.zip does not expand to a '
  2118. 'single subdirectory %s/' % (uid, uid)
  2119. )
  2120. yield pkg_xml, zf, relpath
  2121. # Don't recurse into svn subdirectories:
  2122. try:
  2123. subdirs.remove('.svn')
  2124. except ValueError:
  2125. pass
  2126. ######################################################################
  2127. # Main:
  2128. ######################################################################
  2129. # There should be a command-line interface
  2130. # Aliases
  2131. _downloader = Downloader()
  2132. download = _downloader.download
  2133. def download_shell():
  2134. DownloaderShell(_downloader).run()
  2135. def download_gui():
  2136. DownloaderGUI(_downloader).mainloop()
  2137. def update():
  2138. _downloader.update()
  2139. if __name__ == '__main__':
  2140. from optparse import OptionParser
  2141. parser = OptionParser()
  2142. parser.add_option(
  2143. "-d",
  2144. "--dir",
  2145. dest="dir",
  2146. help="download package to directory DIR",
  2147. metavar="DIR",
  2148. )
  2149. parser.add_option(
  2150. "-q",
  2151. "--quiet",
  2152. dest="quiet",
  2153. action="store_true",
  2154. default=False,
  2155. help="work quietly",
  2156. )
  2157. parser.add_option(
  2158. "-f",
  2159. "--force",
  2160. dest="force",
  2161. action="store_true",
  2162. default=False,
  2163. help="download even if already installed",
  2164. )
  2165. parser.add_option(
  2166. "-e",
  2167. "--exit-on-error",
  2168. dest="halt_on_error",
  2169. action="store_true",
  2170. default=False,
  2171. help="exit if an error occurs",
  2172. )
  2173. parser.add_option(
  2174. "-u",
  2175. "--url",
  2176. dest="server_index_url",
  2177. default=os.environ.get('NLTK_DOWNLOAD_URL'),
  2178. help="download server index url",
  2179. )
  2180. (options, args) = parser.parse_args()
  2181. downloader = Downloader(server_index_url=options.server_index_url)
  2182. if args:
  2183. for pkg_id in args:
  2184. rv = downloader.download(
  2185. info_or_id=pkg_id,
  2186. download_dir=options.dir,
  2187. quiet=options.quiet,
  2188. force=options.force,
  2189. halt_on_error=options.halt_on_error,
  2190. )
  2191. if rv == False and options.halt_on_error:
  2192. break
  2193. else:
  2194. downloader.download(
  2195. download_dir=options.dir,
  2196. quiet=options.quiet,
  2197. force=options.force,
  2198. halt_on_error=options.halt_on_error,
  2199. )