downloader.py 90 KB

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