nltk 3.2__zip → 3.3__zip

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (406) hide show
  1. {nltk-3.2 → nltk-3.3}/INSTALL.txt +6 -6
  2. {nltk-3.2 → nltk-3.3}/LICENSE.txt +13 -13
  3. {nltk-3.2 → nltk-3.3}/MANIFEST.in +6 -6
  4. {nltk-3.2/nltk.egg-info → nltk-3.3}/PKG-INFO +13 -5
  5. nltk-3.2/README.txt → nltk-3.3/README.md +49 -48
  6. nltk-3.3/nltk/VERSION +1 -0
  7. {nltk-3.2 → nltk-3.3}/nltk/__init__.py +185 -185
  8. {nltk-3.2 → nltk-3.3}/nltk/app/__init__.py +52 -53
  9. {nltk-3.2 → nltk-3.3}/nltk/app/chartparser_app.py +2276 -2276
  10. {nltk-3.2 → nltk-3.3}/nltk/app/chunkparser_app.py +1262 -1264
  11. {nltk-3.2 → nltk-3.3}/nltk/app/collocations_app.py +347 -350
  12. {nltk-3.2 → nltk-3.3}/nltk/app/concordance_app.py +568 -570
  13. {nltk-3.2 → nltk-3.3}/nltk/app/nemo_app.py +156 -155
  14. {nltk-3.2 → nltk-3.3}/nltk/app/rdparser_app.py +892 -894
  15. {nltk-3.2 → nltk-3.3}/nltk/app/srparser_app.py +809 -809
  16. {nltk-3.2 → nltk-3.3}/nltk/app/wordfreq_app.py +32 -32
  17. {nltk-3.2 → nltk-3.3}/nltk/app/wordnet_app.py +968 -968
  18. {nltk-3.2 → nltk-3.3}/nltk/book.py +91 -90
  19. {nltk-3.2 → nltk-3.3}/nltk/ccg/__init__.py +22 -22
  20. {nltk-3.2 → nltk-3.3}/nltk/ccg/api.py +359 -335
  21. {nltk-3.2 → nltk-3.3}/nltk/ccg/chart.py +394 -361
  22. {nltk-3.2 → nltk-3.3}/nltk/ccg/combinator.py +343 -312
  23. {nltk-3.2 → nltk-3.3}/nltk/ccg/lexicon.py +328 -290
  24. nltk-3.3/nltk/ccg/logic.py +46 -0
  25. {nltk-3.2 → nltk-3.3}/nltk/chat/__init__.py +49 -49
  26. {nltk-3.2 → nltk-3.3}/nltk/chat/eliza.py +244 -244
  27. {nltk-3.2 → nltk-3.3}/nltk/chat/iesha.py +140 -140
  28. {nltk-3.2 → nltk-3.3}/nltk/chat/rude.py +92 -92
  29. {nltk-3.2 → nltk-3.3}/nltk/chat/suntsu.py +117 -117
  30. {nltk-3.2 → nltk-3.3}/nltk/chat/util.py +122 -120
  31. {nltk-3.2 → nltk-3.3}/nltk/chat/zen.py +282 -282
  32. {nltk-3.2 → nltk-3.3}/nltk/chunk/__init__.py +190 -190
  33. {nltk-3.2 → nltk-3.3}/nltk/chunk/api.py +51 -51
  34. {nltk-3.2 → nltk-3.3}/nltk/chunk/named_entity.py +331 -331
  35. {nltk-3.2 → nltk-3.3}/nltk/chunk/regexp.py +1390 -1384
  36. {nltk-3.2 → nltk-3.3}/nltk/chunk/util.py +600 -600
  37. {nltk-3.2 → nltk-3.3}/nltk/classify/__init__.py +98 -98
  38. {nltk-3.2 → nltk-3.3}/nltk/classify/api.py +193 -193
  39. {nltk-3.2 → nltk-3.3}/nltk/classify/decisiontree.py +295 -295
  40. {nltk-3.2 → nltk-3.3}/nltk/classify/maxent.py +1510 -1492
  41. {nltk-3.2 → nltk-3.3}/nltk/classify/megam.py +179 -178
  42. {nltk-3.2 → nltk-3.3}/nltk/classify/naivebayes.py +245 -242
  43. {nltk-3.2 → nltk-3.3}/nltk/classify/positivenaivebayes.py +170 -170
  44. {nltk-3.2 → nltk-3.3}/nltk/classify/rte_classify.py +160 -191
  45. {nltk-3.2 → nltk-3.3}/nltk/classify/scikitlearn.py +153 -151
  46. {nltk-3.2 → nltk-3.3}/nltk/classify/senna.py +183 -181
  47. {nltk-3.2 → nltk-3.3}/nltk/classify/svm.py +15 -15
  48. {nltk-3.2 → nltk-3.3}/nltk/classify/tadm.py +113 -112
  49. {nltk-3.2 → nltk-3.3}/nltk/classify/textcat.py +193 -193
  50. {nltk-3.2 → nltk-3.3}/nltk/classify/util.py +324 -312
  51. {nltk-3.2 → nltk-3.3}/nltk/classify/weka.py +346 -345
  52. {nltk-3.2 → nltk-3.3}/nltk/cluster/__init__.py +86 -86
  53. {nltk-3.2 → nltk-3.3}/nltk/cluster/api.py +74 -70
  54. {nltk-3.2 → nltk-3.3}/nltk/cluster/em.py +247 -247
  55. {nltk-3.2 → nltk-3.3}/nltk/cluster/gaac.py +168 -168
  56. {nltk-3.2 → nltk-3.3}/nltk/cluster/kmeans.py +221 -221
  57. {nltk-3.2 → nltk-3.3}/nltk/cluster/util.py +304 -289
  58. nltk-3.3/nltk/collections.py +640 -0
  59. {nltk-3.2 → nltk-3.3}/nltk/collocations.py +388 -388
  60. nltk-3.3/nltk/compat.py +365 -0
  61. {nltk-3.2 → nltk-3.3}/nltk/corpus/__init__.py +341 -320
  62. {nltk-3.2 → nltk-3.3}/nltk/corpus/europarl_raw.py +44 -44
  63. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/__init__.py +147 -145
  64. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/aligned.py +115 -114
  65. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/api.py +448 -446
  66. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/bnc.py +252 -252
  67. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/bracket_parse.py +227 -227
  68. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/categorized_sents.py +179 -178
  69. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/chasen.py +140 -139
  70. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/childes.py +522 -494
  71. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/chunked.py +212 -212
  72. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/cmudict.py +97 -95
  73. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/comparative_sents.py +280 -278
  74. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/conll.py +528 -521
  75. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/crubadan.py +116 -116
  76. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/dependency.py +101 -101
  77. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/framenet.py +3059 -2093
  78. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/ieer.py +112 -111
  79. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/indian.py +85 -86
  80. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/ipipan.py +332 -331
  81. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/knbc.py +187 -187
  82. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/lin.py +156 -156
  83. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/mte.py +311 -310
  84. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/nkjp.py +429 -428
  85. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/nombank.py +421 -421
  86. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/nps_chat.py +73 -73
  87. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/opinion_lexicon.py +115 -115
  88. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/panlex_lite.py +165 -165
  89. nltk-3.3/nltk/corpus/reader/pl196x.py +292 -0
  90. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/plaintext.py +232 -233
  91. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/ppattach.py +96 -95
  92. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/propbank.py +479 -481
  93. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/pros_cons.py +128 -126
  94. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/reviews.py +330 -328
  95. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/rte.py +144 -146
  96. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/semcor.py +256 -256
  97. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/senseval.py +203 -201
  98. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/sentiwordnet.py +137 -137
  99. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/sinica_treebank.py +75 -75
  100. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/string_category.py +60 -59
  101. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/switchboard.py +119 -119
  102. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/tagged.py +295 -294
  103. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/timit.py +452 -450
  104. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/toolbox.py +68 -68
  105. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/twitter.py +155 -157
  106. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/udhr.py +80 -80
  107. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/util.py +804 -800
  108. nltk-3.3/nltk/corpus/reader/verbnet.py +595 -0
  109. nltk-3.3/nltk/corpus/reader/wordlist.py +134 -0
  110. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/wordnet.py +2108 -2036
  111. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/xmldocs.py +392 -387
  112. {nltk-3.2 → nltk-3.3}/nltk/corpus/reader/ycoe.py +243 -242
  113. {nltk-3.2 → nltk-3.3}/nltk/corpus/util.py +144 -127
  114. {nltk-3.2 → nltk-3.3}/nltk/data.py +1487 -1451
  115. {nltk-3.2 → nltk-3.3}/nltk/decorators.py +219 -215
  116. {nltk-3.2 → nltk-3.3}/nltk/downloader.py +2278 -2274
  117. {nltk-3.2 → nltk-3.3}/nltk/draw/__init__.py +27 -27
  118. {nltk-3.2 → nltk-3.3}/nltk/draw/cfg.py +774 -777
  119. {nltk-3.2 → nltk-3.3}/nltk/draw/dispersion.py +58 -58
  120. {nltk-3.2 → nltk-3.3}/nltk/draw/table.py +1098 -1098
  121. {nltk-3.2 → nltk-3.3}/nltk/draw/tree.py +963 -966
  122. {nltk-3.2 → nltk-3.3}/nltk/draw/util.py +2356 -2356
  123. {nltk-3.2 → nltk-3.3}/nltk/featstruct.py +2617 -2500
  124. {nltk-3.2 → nltk-3.3}/nltk/grammar.py +1559 -1516
  125. {nltk-3.2 → nltk-3.3}/nltk/help.py +56 -56
  126. {nltk-3.2 → nltk-3.3}/nltk/inference/__init__.py +20 -20
  127. {nltk-3.2 → nltk-3.3}/nltk/inference/api.py +597 -589
  128. {nltk-3.2 → nltk-3.3}/nltk/inference/discourse.py +612 -608
  129. {nltk-3.2 → nltk-3.3}/nltk/inference/mace.py +311 -311
  130. {nltk-3.2 → nltk-3.3}/nltk/inference/nonmonotonic.py +509 -509
  131. {nltk-3.2 → nltk-3.3}/nltk/inference/prover9.py +431 -431
  132. {nltk-3.2 → nltk-3.3}/nltk/inference/resolution.py +687 -687
  133. {nltk-3.2 → nltk-3.3}/nltk/inference/tableau.py +607 -607
  134. {nltk-3.2 → nltk-3.3}/nltk/internals.py +982 -982
  135. {nltk-3.2 → nltk-3.3}/nltk/jsontags.py +63 -63
  136. {nltk-3.2 → nltk-3.3}/nltk/lazyimport.py +142 -142
  137. {nltk-3.2 → nltk-3.3}/nltk/metrics/__init__.py +30 -29
  138. {nltk-3.2 → nltk-3.3}/nltk/metrics/agreement.py +421 -401
  139. nltk-3.3/nltk/metrics/aline.py +607 -0
  140. {nltk-3.2 → nltk-3.3}/nltk/metrics/association.py +414 -410
  141. {nltk-3.2 → nltk-3.3}/nltk/metrics/confusionmatrix.py +206 -206
  142. {nltk-3.2 → nltk-3.3}/nltk/metrics/distance.py +207 -202
  143. {nltk-3.2 → nltk-3.3}/nltk/metrics/paice.py +381 -381
  144. {nltk-3.2 → nltk-3.3}/nltk/metrics/scores.py +228 -228
  145. {nltk-3.2 → nltk-3.3}/nltk/metrics/segmentation.py +231 -232
  146. {nltk-3.2 → nltk-3.3}/nltk/metrics/spearman.py +69 -69
  147. {nltk-3.2 → nltk-3.3}/nltk/misc/__init__.py +11 -11
  148. {nltk-3.2 → nltk-3.3}/nltk/misc/babelfish.py +10 -10
  149. {nltk-3.2 → nltk-3.3}/nltk/misc/chomsky.py +135 -133
  150. {nltk-3.2 → nltk-3.3}/nltk/misc/minimalset.py +83 -83
  151. {nltk-3.2 → nltk-3.3}/nltk/misc/sort.py +157 -157
  152. {nltk-3.2 → nltk-3.3}/nltk/misc/wordfinder.py +129 -129
  153. {nltk-3.2 → nltk-3.3}/nltk/parse/__init__.py +81 -80
  154. {nltk-3.2 → nltk-3.3}/nltk/parse/api.py +66 -66
  155. {nltk-3.2 → nltk-3.3}/nltk/parse/bllip.py +282 -282
  156. {nltk-3.2 → nltk-3.3}/nltk/parse/chart.py +1682 -1681
  157. nltk-3.3/nltk/parse/corenlp.py +780 -0
  158. {nltk-3.2 → nltk-3.3}/nltk/parse/dependencygraph.py +760 -758
  159. {nltk-3.2 → nltk-3.3}/nltk/parse/earleychart.py +452 -451
  160. {nltk-3.2 → nltk-3.3}/nltk/parse/evaluate.py +129 -129
  161. {nltk-3.2 → nltk-3.3}/nltk/parse/featurechart.py +580 -578
  162. {nltk-3.2 → nltk-3.3}/nltk/parse/generate.py +87 -76
  163. {nltk-3.2 → nltk-3.3}/nltk/parse/malt.py +356 -356
  164. {nltk-3.2 → nltk-3.3}/nltk/parse/nonprojectivedependencyparser.py +783 -783
  165. {nltk-3.2 → nltk-3.3}/nltk/parse/pchart.py +522 -522
  166. {nltk-3.2 → nltk-3.3}/nltk/parse/projectivedependencyparser.py +579 -578
  167. {nltk-3.2 → nltk-3.3}/nltk/parse/recursivedescent.py +655 -656
  168. {nltk-3.2 → nltk-3.3}/nltk/parse/shiftreduce.py +458 -459
  169. {nltk-3.2 → nltk-3.3}/nltk/parse/stanford.py +431 -406
  170. {nltk-3.2 → nltk-3.3}/nltk/parse/transitionparser.py +774 -772
  171. {nltk-3.2 → nltk-3.3}/nltk/parse/util.py +231 -231
  172. {nltk-3.2 → nltk-3.3}/nltk/parse/viterbi.py +401 -401
  173. {nltk-3.2 → nltk-3.3}/nltk/probability.py +2410 -2355
  174. {nltk-3.2 → nltk-3.3}/nltk/sem/__init__.py +61 -61
  175. {nltk-3.2 → nltk-3.3}/nltk/sem/boxer.py +1261 -1261
  176. {nltk-3.2 → nltk-3.3}/nltk/sem/chat80.py +782 -782
  177. {nltk-3.2 → nltk-3.3}/nltk/sem/cooper_storage.py +118 -118
  178. {nltk-3.2 → nltk-3.3}/nltk/sem/drt.py +1258 -1257
  179. {nltk-3.2 → nltk-3.3}/nltk/sem/drt_glue_demo.py +485 -489
  180. {nltk-3.2 → nltk-3.3}/nltk/sem/evaluate.py +790 -784
  181. {nltk-3.2 → nltk-3.3}/nltk/sem/glue.py +696 -694
  182. {nltk-3.2 → nltk-3.3}/nltk/sem/hole.py +386 -384
  183. {nltk-3.2 → nltk-3.3}/nltk/sem/lfg.py +210 -208
  184. {nltk-3.2 → nltk-3.3}/nltk/sem/linearlogic.py +451 -449
  185. {nltk-3.2 → nltk-3.3}/nltk/sem/logic.py +1910 -1910
  186. {nltk-3.2 → nltk-3.3}/nltk/sem/relextract.py +476 -483
  187. {nltk-3.2 → nltk-3.3}/nltk/sem/skolemize.py +101 -101
  188. {nltk-3.2 → nltk-3.3}/nltk/sem/util.py +249 -249
  189. {nltk-3.2 → nltk-3.3}/nltk/sentiment/__init__.py +14 -14
  190. {nltk-3.2 → nltk-3.3}/nltk/sentiment/sentiment_analyzer.py +229 -229
  191. {nltk-3.2 → nltk-3.3}/nltk/sentiment/util.py +762 -752
  192. {nltk-3.2 → nltk-3.3}/nltk/sentiment/vader.py +443 -445
  193. {nltk-3.2 → nltk-3.3}/nltk/stem/__init__.py +31 -33
  194. {nltk-3.2 → nltk-3.3}/nltk/stem/api.py +28 -25
  195. nltk-3.3/nltk/stem/arlstem.py +369 -0
  196. {nltk-3.2 → nltk-3.3}/nltk/stem/isri.py +345 -345
  197. {nltk-3.2 → nltk-3.3}/nltk/stem/lancaster.py +337 -310
  198. nltk-3.3/nltk/stem/porter.py +710 -0
  199. {nltk-3.2 → nltk-3.3}/nltk/stem/regexp.py +61 -61
  200. {nltk-3.2 → nltk-3.3}/nltk/stem/rslp.py +142 -142
  201. {nltk-3.2 → nltk-3.3}/nltk/stem/snowball.py +4236 -3712
  202. {nltk-3.2 → nltk-3.3}/nltk/stem/util.py +22 -12
  203. {nltk-3.2 → nltk-3.3}/nltk/stem/wordnet.py +51 -51
  204. {nltk-3.2 → nltk-3.3}/nltk/tag/__init__.py +152 -127
  205. {nltk-3.2 → nltk-3.3}/nltk/tag/api.py +86 -81
  206. {nltk-3.2 → nltk-3.3}/nltk/tag/brill.py +424 -426
  207. {nltk-3.2 → nltk-3.3}/nltk/tag/brill_trainer.py +608 -608
  208. {nltk-3.2 → nltk-3.3}/nltk/tag/crf.py +204 -200
  209. {nltk-3.2 → nltk-3.3}/nltk/tag/hmm.py +1277 -1277
  210. {nltk-3.2 → nltk-3.3}/nltk/tag/hunpos.py +132 -132
  211. {nltk-3.2 → nltk-3.3}/nltk/tag/mapping.py +101 -101
  212. {nltk-3.2 → nltk-3.3}/nltk/tag/perceptron.py +329 -314
  213. {nltk-3.2 → nltk-3.3}/nltk/tag/senna.py +147 -145
  214. {nltk-3.2 → nltk-3.3}/nltk/tag/sequential.py +740 -736
  215. {nltk-3.2 → nltk-3.3}/nltk/tag/stanford.py +219 -196
  216. {nltk-3.2 → nltk-3.3}/nltk/tag/tnt.py +595 -604
  217. {nltk-3.2 → nltk-3.3}/nltk/tag/util.py +72 -72
  218. {nltk-3.2 → nltk-3.3}/nltk/tbl/__init__.py +28 -28
  219. {nltk-3.2 → nltk-3.3}/nltk/tbl/api.py +1 -1
  220. {nltk-3.2 → nltk-3.3}/nltk/tbl/demo.py +366 -366
  221. {nltk-3.2 → nltk-3.3}/nltk/tbl/erroranalysis.py +39 -39
  222. {nltk-3.2 → nltk-3.3}/nltk/tbl/feature.py +259 -261
  223. {nltk-3.2 → nltk-3.3}/nltk/tbl/rule.py +321 -321
  224. {nltk-3.2 → nltk-3.3}/nltk/tbl/template.py +303 -308
  225. {nltk-3.2 → nltk-3.3}/nltk/test/__init__.py +18 -18
  226. {nltk-3.2 → nltk-3.3}/nltk/test/all.py +24 -23
  227. {nltk-3.2 → nltk-3.3}/nltk/test/bleu.doctest +14 -14
  228. {nltk-3.2 → nltk-3.3}/nltk/test/bnc.doctest +60 -60
  229. {nltk-3.2 → nltk-3.3}/nltk/test/ccg.doctest +376 -395
  230. nltk-3.3/nltk/test/ccg_semantics.doctest +553 -0
  231. {nltk-3.2 → nltk-3.3}/nltk/test/chat80.doctest +234 -234
  232. {nltk-3.2 → nltk-3.3}/nltk/test/childes.doctest +184 -184
  233. {nltk-3.2 → nltk-3.3}/nltk/test/childes_fixt.py +14 -13
  234. {nltk-3.2 → nltk-3.3}/nltk/test/chunk.doctest +373 -373
  235. {nltk-3.2 → nltk-3.3}/nltk/test/classify.doctest +185 -185
  236. {nltk-3.2 → nltk-3.3}/nltk/test/classify_fixt.py +11 -10
  237. nltk-3.3/nltk/test/collections.doctest +20 -0
  238. {nltk-3.2 → nltk-3.3}/nltk/test/collocations.doctest +276 -276
  239. {nltk-3.2 → nltk-3.3}/nltk/test/compat.doctest +134 -138
  240. {nltk-3.2 → nltk-3.3}/nltk/test/compat_fixt.py +9 -8
  241. nltk-3.3/nltk/test/concordance.doctest +55 -0
  242. {nltk-3.2 → nltk-3.3}/nltk/test/corpus.doctest +2200 -2212
  243. {nltk-3.2 → nltk-3.3}/nltk/test/corpus_fixt.py +3 -3
  244. {nltk-3.2 → nltk-3.3}/nltk/test/crubadan.doctest +65 -65
  245. {nltk-3.2 → nltk-3.3}/nltk/test/data.doctest +379 -379
  246. {nltk-3.2 → nltk-3.3}/nltk/test/dependency.doctest +241 -241
  247. {nltk-3.2 → nltk-3.3}/nltk/test/discourse.doctest +546 -546
  248. {nltk-3.2 → nltk-3.3}/nltk/test/discourse_fixt.py +14 -13
  249. {nltk-3.2 → nltk-3.3}/nltk/test/doctest_nose_plugin.py +159 -156
  250. {nltk-3.2 → nltk-3.3}/nltk/test/drt.doctest +517 -517
  251. {nltk-3.2 → nltk-3.3}/nltk/test/featgram.doctest +607 -607
  252. {nltk-3.2 → nltk-3.3}/nltk/test/featstruct.doctest +1229 -1230
  253. {nltk-3.2 → nltk-3.3}/nltk/test/framenet.doctest +288 -239
  254. {nltk-3.2 → nltk-3.3}/nltk/test/generate.doctest +67 -67
  255. {nltk-3.2 → nltk-3.3}/nltk/test/gensim.doctest +140 -141
  256. {nltk-3.2 → nltk-3.3}/nltk/test/gensim_fixt.py +10 -9
  257. {nltk-3.2 → nltk-3.3}/nltk/test/gluesemantics.doctest +384 -386
  258. {nltk-3.2 → nltk-3.3}/nltk/test/gluesemantics_malt.doctest +68 -68
  259. {nltk-3.2 → nltk-3.3}/nltk/test/gluesemantics_malt_fixt.py +12 -11
  260. {nltk-3.2 → nltk-3.3}/nltk/test/grammar.doctest +48 -48
  261. {nltk-3.2 → nltk-3.3}/nltk/test/grammartestsuites.doctest +109 -109
  262. {nltk-3.2 → nltk-3.3}/nltk/test/index.doctest +100 -100
  263. {nltk-3.2 → nltk-3.3}/nltk/test/inference.doctest +534 -534
  264. {nltk-3.2 → nltk-3.3}/nltk/test/inference_fixt.py +12 -11
  265. {nltk-3.2 → nltk-3.3}/nltk/test/internals.doctest +140 -140
  266. {nltk-3.2 → nltk-3.3}/nltk/test/japanese.doctest +48 -48
  267. {nltk-3.2 → nltk-3.3}/nltk/test/logic.doctest +1098 -1098
  268. {nltk-3.2 → nltk-3.3}/nltk/test/metrics.doctest +270 -270
  269. {nltk-3.2 → nltk-3.3}/nltk/test/misc.doctest +118 -118
  270. {nltk-3.2 → nltk-3.3}/nltk/test/nonmonotonic.doctest +286 -286
  271. {nltk-3.2 → nltk-3.3}/nltk/test/nonmonotonic_fixt.py +12 -11
  272. {nltk-3.2 → nltk-3.3}/nltk/test/paice.doctest +35 -35
  273. {nltk-3.2 → nltk-3.3}/nltk/test/parse.doctest +884 -884
  274. {nltk-3.2 → nltk-3.3}/nltk/test/portuguese_en.doctest +565 -565
  275. {nltk-3.2 → nltk-3.3}/nltk/test/portuguese_en_fixt.py +16 -16
  276. {nltk-3.2 → nltk-3.3}/nltk/test/probability.doctest +304 -304
  277. {nltk-3.2 → nltk-3.3}/nltk/test/probability_fixt.py +13 -12
  278. {nltk-3.2 → nltk-3.3}/nltk/test/propbank.doctest +176 -176
  279. {nltk-3.2 → nltk-3.3}/nltk/test/relextract.doctest +263 -263
  280. {nltk-3.2 → nltk-3.3}/nltk/test/resolution.doctest +221 -221
  281. {nltk-3.2 → nltk-3.3}/nltk/test/runtests.py +86 -64
  282. {nltk-3.2 → nltk-3.3}/nltk/test/segmentation_fixt.py +10 -10
  283. {nltk-3.2 → nltk-3.3}/nltk/test/semantics.doctest +665 -665
  284. {nltk-3.2 → nltk-3.3}/nltk/test/semantics_fixt.py +7 -7
  285. {nltk-3.2 → nltk-3.3}/nltk/test/sentiment.doctest +233 -233
  286. {nltk-3.2 → nltk-3.3}/nltk/test/sentiwordnet.doctest +41 -41
  287. {nltk-3.2 → nltk-3.3}/nltk/test/simple.doctest +85 -85
  288. {nltk-3.2 → nltk-3.3}/nltk/test/stem.doctest +78 -78
  289. {nltk-3.2 → nltk-3.3}/nltk/test/tag.doctest +33 -33
  290. {nltk-3.2 → nltk-3.3}/nltk/test/tokenize.doctest +273 -166
  291. {nltk-3.2 → nltk-3.3}/nltk/test/toolbox.doctest +307 -307
  292. {nltk-3.2 → nltk-3.3}/nltk/test/translate.doctest +242 -242
  293. {nltk-3.2 → nltk-3.3}/nltk/test/translate_fixt.py +3 -3
  294. {nltk-3.2 → nltk-3.3}/nltk/test/tree.doctest +1101 -1101
  295. {nltk-3.2 → nltk-3.3}/nltk/test/treeprettyprinter.doctest +127 -127
  296. {nltk-3.2 → nltk-3.3}/nltk/test/treetransforms.doctest +156 -156
  297. nltk-3.3/nltk/test/unit/test_2x_compat.py +63 -0
  298. nltk-3.3/nltk/test/unit/test_aline.py +52 -0
  299. nltk-3.3/nltk/test/unit/test_chunk.py +56 -0
  300. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_classify.py +55 -53
  301. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_collocations.py +88 -79
  302. nltk-3.3/nltk/test/unit/test_concordance.py +98 -0
  303. nltk-3.3/nltk/test/unit/test_corenlp.py +1000 -0
  304. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_corpora.py +200 -183
  305. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_corpus_views.py +45 -45
  306. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_hmm.py +88 -88
  307. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_json2csv_corpus.py +188 -187
  308. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_naivebayes.py +26 -26
  309. nltk-3.3/nltk/test/unit/test_rte_classify.py +86 -0
  310. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_seekable_unicode_stream_reader.py +124 -124
  311. nltk-3.3/nltk/test/unit/test_senna.py +74 -0
  312. nltk-3.3/nltk/test/unit/test_stem.py +121 -0
  313. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_tag.py +20 -20
  314. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_tgrep.py +628 -626
  315. nltk-3.3/nltk/test/unit/test_tokenize.py +168 -0
  316. {nltk-3.2 → nltk-3.3}/nltk/test/unit/test_twitter_auth.py +185 -185
  317. nltk-3.3/nltk/test/unit/test_wordnet.py +134 -0
  318. nltk-3.3/nltk/test/unit/translate/test_bleu.py +244 -0
  319. nltk-3.3/nltk/test/unit/translate/test_gdfa.py +57 -0
  320. {nltk-3.2 → nltk-3.3}/nltk/test/unit/translate/test_ibm1.py +75 -75
  321. {nltk-3.2 → nltk-3.3}/nltk/test/unit/translate/test_ibm2.py +87 -87
  322. {nltk-3.2 → nltk-3.3}/nltk/test/unit/translate/test_ibm3.py +105 -105
  323. {nltk-3.2 → nltk-3.3}/nltk/test/unit/translate/test_ibm4.py +126 -126
  324. {nltk-3.2 → nltk-3.3}/nltk/test/unit/translate/test_ibm5.py +166 -166
  325. {nltk-3.2 → nltk-3.3}/nltk/test/unit/translate/test_ibm_model.py +270 -270
  326. nltk-3.3/nltk/test/unit/translate/test_nist.py +37 -0
  327. {nltk-3.2 → nltk-3.3}/nltk/test/unit/translate/test_stack_decoder.py +300 -300
  328. {nltk-3.2 → nltk-3.3}/nltk/test/unit/utils.py +41 -41
  329. {nltk-3.2 → nltk-3.3}/nltk/test/util.doctest +48 -48
  330. {nltk-3.2 → nltk-3.3}/nltk/test/wordnet.doctest +595 -581
  331. {nltk-3.2 → nltk-3.3}/nltk/test/wordnet_fixt.py +7 -6
  332. {nltk-3.2 → nltk-3.3}/nltk/test/wordnet_lch.doctest +53 -53
  333. {nltk-3.2 → nltk-3.3}/nltk/test/wsd.doctest +68 -68
  334. {nltk-3.2 → nltk-3.3}/nltk/text.py +663 -610
  335. {nltk-3.2 → nltk-3.3}/nltk/tgrep.py +938 -937
  336. {nltk-3.2 → nltk-3.3}/nltk/tokenize/__init__.py +130 -107
  337. {nltk-3.2 → nltk-3.3}/nltk/tokenize/api.py +77 -78
  338. {nltk-3.2 → nltk-3.3}/nltk/tokenize/casual.py +343 -342
  339. {nltk-3.2 → nltk-3.3}/nltk/tokenize/mwe.py +120 -120
  340. nltk-3.3/nltk/tokenize/nist.py +173 -0
  341. {nltk-3.2 → nltk-3.3}/nltk/tokenize/punkt.py +1620 -1601
  342. {nltk-3.2 → nltk-3.3}/nltk/tokenize/regexp.py +208 -202
  343. nltk-3.3/nltk/tokenize/repp.py +151 -0
  344. {nltk-3.2 → nltk-3.3}/nltk/tokenize/sexpr.py +140 -142
  345. {nltk-3.2 → nltk-3.3}/nltk/tokenize/simple.py +138 -136
  346. {nltk-3.2 → nltk-3.3}/nltk/tokenize/stanford.py +117 -113
  347. nltk-3.3/nltk/tokenize/stanford_segmenter.py +246 -0
  348. {nltk-3.2 → nltk-3.3}/nltk/tokenize/texttiling.py +458 -460
  349. nltk-3.3/nltk/tokenize/toktok.py +155 -0
  350. nltk-3.3/nltk/tokenize/treebank.py +363 -0
  351. nltk-3.3/nltk/tokenize/util.py +261 -0
  352. {nltk-3.2 → nltk-3.3}/nltk/toolbox.py +499 -497
  353. {nltk-3.2 → nltk-3.3}/nltk/translate/__init__.py +24 -24
  354. {nltk-3.2 → nltk-3.3}/nltk/translate/api.py +331 -321
  355. {nltk-3.2 → nltk-3.3}/nltk/translate/bleu_score.py +615 -556
  356. nltk-3.3/nltk/translate/chrf_score.py +137 -0
  357. {nltk-3.2 → nltk-3.3}/nltk/translate/gale_church.py +248 -235
  358. {nltk-3.2 → nltk-3.3}/nltk/translate/gdfa.py +135 -131
  359. nltk-3.3/nltk/translate/gleu_score.py +193 -0
  360. {nltk-3.2 → nltk-3.3}/nltk/translate/ibm1.py +250 -241
  361. {nltk-3.2 → nltk-3.3}/nltk/translate/ibm2.py +308 -308
  362. {nltk-3.2 → nltk-3.3}/nltk/translate/ibm3.py +337 -337
  363. {nltk-3.2 → nltk-3.3}/nltk/translate/ibm4.py +467 -467
  364. {nltk-3.2 → nltk-3.3}/nltk/translate/ibm5.py +639 -639
  365. {nltk-3.2 → nltk-3.3}/nltk/translate/ibm_model.py +536 -533
  366. {nltk-3.2 → nltk-3.3}/nltk/translate/metrics.py +40 -40
  367. nltk-3.3/nltk/translate/nist_score.py +178 -0
  368. {nltk-3.2 → nltk-3.3}/nltk/translate/phrase_based.py +175 -175
  369. {nltk-3.2 → nltk-3.3}/nltk/translate/ribes_score.py +325 -325
  370. {nltk-3.2 → nltk-3.3}/nltk/translate/stack_decoder.py +499 -495
  371. {nltk-3.2 → nltk-3.3}/nltk/tree.py +1605 -1603
  372. {nltk-3.2 → nltk-3.3}/nltk/treeprettyprinter.py +564 -564
  373. {nltk-3.2 → nltk-3.3}/nltk/treetransforms.py +309 -309
  374. {nltk-3.2 → nltk-3.3}/nltk/twitter/__init__.py +28 -28
  375. {nltk-3.2 → nltk-3.3}/nltk/twitter/api.py +141 -136
  376. {nltk-3.2 → nltk-3.3}/nltk/twitter/common.py +264 -258
  377. {nltk-3.2 → nltk-3.3}/nltk/twitter/twitter_demo.py +288 -288
  378. {nltk-3.2 → nltk-3.3}/nltk/twitter/twitterclient.py +530 -530
  379. {nltk-3.2 → nltk-3.3}/nltk/twitter/util.py +147 -146
  380. nltk-3.3/nltk/util.py +751 -0
  381. {nltk-3.2 → nltk-3.3}/nltk/wsd.py +53 -53
  382. {nltk-3.2 → nltk-3.3/nltk.egg-info}/PKG-INFO +13 -5
  383. {nltk-3.2 → nltk-3.3}/nltk.egg-info/SOURCES.txt +26 -3
  384. nltk-3.3/nltk.egg-info/requires.txt +31 -0
  385. {nltk-3.2 → nltk-3.3}/setup.cfg +0 -1
  386. {nltk-3.2 → nltk-3.3}/setup.py +102 -75
  387. nltk-3.2/nltk/VERSION +0 -1
  388. nltk-3.2/nltk/compat.py +0 -680
  389. nltk-3.2/nltk/corpus/reader/pl196x.py +0 -278
  390. nltk-3.2/nltk/corpus/reader/verbnet.py +0 -408
  391. nltk-3.2/nltk/corpus/reader/wordlist.py +0 -37
  392. nltk-3.2/nltk/sentiment/vader_lexicon.txt +0 -7517
  393. nltk-3.2/nltk/six.py +0 -868
  394. nltk-3.2/nltk/stem/porter.py +0 -692
  395. nltk-3.2/nltk/test/unit/test_2x_compat.py +0 -26
  396. nltk-3.2/nltk/test/unit/test_stem.py +0 -36
  397. nltk-3.2/nltk/test/unit/test_tokenize.py +0 -23
  398. nltk-3.2/nltk/test/unit/translate/test_bleu.py +0 -84
  399. nltk-3.2/nltk/tokenize/treebank.py +0 -124
  400. nltk-3.2/nltk/tokenize/util.py +0 -90
  401. nltk-3.2/nltk/util.py +0 -1364
  402. {nltk-3.2 → nltk-3.3}/nltk/test/unit/__init__.py +0 -0
  403. {nltk-3.2 → nltk-3.3}/nltk/test/unit/translate/__init__.py +0 -0
  404. {nltk-3.2 → nltk-3.3}/nltk.egg-info/dependency_links.txt +0 -0
  405. {nltk-3.2 → nltk-3.3}/nltk.egg-info/not-zip-safe +0 -0
  406. {nltk-3.2 → nltk-3.3}/nltk.egg-info/top_level.txt +0 -0
@@ -1,1264 +1,1262 @@
1
- # Natural Language Toolkit: Regexp Chunk Parser Application
2
- #
3
- # Copyright (C) 2001-2015 NLTK Project
4
- # Author: Edward Loper <edloper@gmail.com>
5
- # URL: <http://nltk.org/>
6
- # For license information, see LICENSE.TXT
7
-
8
- """
9
- A graphical tool for exploring the regular expression based chunk
10
- parser ``nltk.chunk.RegexpChunkParser``.
11
- """
12
-
13
- # Todo: Add a way to select the development set from the menubar. This
14
- # might just need to be a selection box (conll vs treebank etc) plus
15
- # configuration parameters to select what's being chunked (eg VP vs NP)
16
- # and what part of the data is being used as the development set.
17
-
18
- from __future__ import division
19
- import nltk.compat
20
- import time
21
- import textwrap
22
- import re
23
- import random
24
- import tkinter.filedialog, tkinter.font
25
-
26
- from tkinter import (Button, Canvas, Checkbutton,
27
- Frame, IntVar, Label, Menu,
28
- Scrollbar, Text, Tk)
29
-
30
- from nltk.tree import Tree
31
- from nltk.util import in_idle
32
- from nltk.draw.util import ShowText
33
- from nltk.corpus import conll2000, treebank_chunk
34
- from nltk.chunk import ChunkScore, RegexpChunkParser
35
- from nltk.chunk.regexp import RegexpChunkRule
36
-
37
- class RegexpChunkApp(object):
38
- """
39
- A graphical tool for exploring the regular expression based chunk
40
- parser ``nltk.chunk.RegexpChunkParser``.
41
-
42
- See ``HELP`` for instructional text.
43
- """
44
-
45
- ##/////////////////////////////////////////////////////////////////
46
- ## Help Text
47
- ##/////////////////////////////////////////////////////////////////
48
-
49
- #: A dictionary mapping from part of speech tags to descriptions,
50
- #: which is used in the help text. (This should probably live with
51
- #: the conll and/or treebank corpus instead.)
52
- TAGSET = {
53
- 'CC': 'Coordinating conjunction', 'PRP$': 'Possessive pronoun',
54
- 'CD': 'Cardinal number', 'RB': 'Adverb',
55
- 'DT': 'Determiner', 'RBR': 'Adverb, comparative',
56
- 'EX': 'Existential there', 'RBS': 'Adverb, superlative',
57
- 'FW': 'Foreign word', 'RP': 'Particle',
58
- 'JJ': 'Adjective', 'TO': 'to',
59
- 'JJR': 'Adjective, comparative', 'UH': 'Interjection',
60
- 'JJS': 'Adjective, superlative', 'VB': 'Verb, base form',
61
- 'LS': 'List item marker', 'VBD': 'Verb, past tense',
62
- 'MD': 'Modal', 'NNS': 'Noun, plural',
63
- 'NN': 'Noun, singular or masps', 'VBN': 'Verb, past participle',
64
- 'VBZ': 'Verb,3rd ps. sing. present', 'NNP': 'Proper noun, singular',
65
- 'NNPS': 'Proper noun plural', 'WDT': 'wh-determiner',
66
- 'PDT': 'Predeterminer', 'WP': 'wh-pronoun',
67
- 'POS': 'Possessive ending', 'WP$': 'Possessive wh-pronoun',
68
- 'PRP': 'Personal pronoun', 'WRB': 'wh-adverb',
69
- '(': 'open parenthesis', ')': 'close parenthesis',
70
- '``': 'open quote', ',': 'comma',
71
- "''": 'close quote', '.': 'period',
72
- '#': 'pound sign (currency marker)',
73
- '$': 'dollar sign (currency marker)',
74
- 'IN': 'Preposition/subord. conjunction',
75
- 'SYM': 'Symbol (mathematical or scientific)',
76
- 'VBG': 'Verb, gerund/present participle',
77
- 'VBP': 'Verb, non-3rd ps. sing. present',
78
- ':': 'colon',
79
- }
80
-
81
- #: Contents for the help box. This is a list of tuples, one for
82
- #: each help page, where each tuple has four elements:
83
- #: - A title (displayed as a tab)
84
- #: - A string description of tabstops (see Tkinter.Text for details)
85
- #: - The text contents for the help page. You can use expressions
86
- #: like <red>...</red> to colorize the text; see ``HELP_AUTOTAG``
87
- #: for a list of tags you can use for colorizing.
88
- HELP = [
89
- ('Help', '20',
90
- "Welcome to the regular expression chunk-parser grammar editor. "
91
- "You can use this editor to develop and test chunk parser grammars "
92
- "based on NLTK's RegexpChunkParser class.\n\n"
93
- # Help box.
94
- "Use this box ('Help') to learn more about the editor; click on the "
95
- "tabs for help on specific topics:"
96
- "<indent>\n"
97
- "Rules: grammar rule types\n"
98
- "Regexps: regular expression syntax\n"
99
- "Tags: part of speech tags\n</indent>\n"
100
- # Grammar.
101
- "Use the upper-left box ('Grammar') to edit your grammar. "
102
- "Each line of your grammar specifies a single 'rule', "
103
- "which performs an action such as creating a chunk or merging "
104
- "two chunks.\n\n"
105
- # Dev set.
106
- "The lower-left box ('Development Set') runs your grammar on the "
107
- "development set, and displays the results. "
108
- "Your grammar's chunks are <highlight>highlighted</highlight>, and "
109
- "the correct (gold standard) chunks are "
110
- "<underline>underlined</underline>. If they "
111
- "match, they are displayed in <green>green</green>; otherwise, "
112
- "they are displayed in <red>red</red>. The box displays a single "
113
- "sentence from the development set at a time; use the scrollbar or "
114
- "the next/previous buttons view additional sentences.\n\n"
115
- # Performance
116
- "The lower-right box ('Evaluation') tracks the performance of "
117
- "your grammar on the development set. The 'precision' axis "
118
- "indicates how many of your grammar's chunks are correct; and "
119
- "the 'recall' axis indicates how many of the gold standard "
120
- "chunks your system generated. Typically, you should try to "
121
- "design a grammar that scores high on both metrics. The "
122
- "exact precision and recall of the current grammar, as well "
123
- "as their harmonic mean (the 'f-score'), are displayed in "
124
- "the status bar at the bottom of the window."
125
- ),
126
- ('Rules', '10',
127
- "<h1>{...regexp...}</h1>"
128
- "<indent>\nChunk rule: creates new chunks from words matching "
129
- "regexp.</indent>\n\n"
130
- "<h1>}...regexp...{</h1>"
131
- "<indent>\nChink rule: removes words matching regexp from existing "
132
- "chunks.</indent>\n\n"
133
- "<h1>...regexp1...}{...regexp2...</h1>"
134
- "<indent>\nSplit rule: splits chunks that match regexp1 followed by "
135
- "regexp2 in two.</indent>\n\n"
136
- "<h1>...regexp...{}...regexp...</h1>"
137
- "<indent>\nMerge rule: joins consecutive chunks that match regexp1 "
138
- "and regexp2</indent>\n"
139
- ),
140
- ('Regexps', '10 60',
141
- #"Regular Expression Syntax Summary:\n\n"
142
- "<h1>Pattern\t\tMatches...</h1>\n"
143
- "<hangindent>"
144
- "\t<<var>T</var>>\ta word with tag <var>T</var> "
145
- "(where <var>T</var> may be a regexp).\n"
146
- "\t<var>x</var>?\tan optional <var>x</var>\n"
147
- "\t<var>x</var>+\ta sequence of 1 or more <var>x</var>'s\n"
148
- "\t<var>x</var>*\ta sequence of 0 or more <var>x</var>'s\n"
149
- "\t<var>x</var>|<var>y</var>\t<var>x</var> or <var>y</var>\n"
150
- "\t.\tmatches any character\n"
151
- "\t(<var>x</var>)\tTreats <var>x</var> as a group\n"
152
- "\t# <var>x...</var>\tTreats <var>x...</var> "
153
- "(to the end of the line) as a comment\n"
154
- "\t\\<var>C</var>\tmatches character <var>C</var> "
155
- "(useful when <var>C</var> is a special character "
156
- "like + or #)\n"
157
- "</hangindent>"
158
- "\n<h1>Examples:</h1>\n"
159
- "<hangindent>"
160
- '\t<regexp><NN></regexp>\n'
161
- '\t\tMatches <match>"cow/NN"</match>\n'
162
- '\t\tMatches <match>"green/NN"</match>\n'
163
- '\t<regexp><VB.*></regexp>\n'
164
- '\t\tMatches <match>"eating/VBG"</match>\n'
165
- '\t\tMatches <match>"ate/VBD"</match>\n'
166
- '\t<regexp><IN><DT><NN></regexp>\n'
167
- '\t\tMatches <match>"on/IN the/DT car/NN"</match>\n'
168
- '\t<regexp><RB>?<VBD></regexp>\n'
169
- '\t\tMatches <match>"ran/VBD"</match>\n'
170
- '\t\tMatches <match>"slowly/RB ate/VBD"</match>\n'
171
- '\t<regexp><\#><CD> # This is a comment...</regexp>\n'
172
- '\t\tMatches <match>"#/# 100/CD"</match>\n'
173
- "</hangindent>"
174
- ),
175
- ('Tags', '10 60',
176
- "<h1>Part of Speech Tags:</h1>\n" +
177
- '<hangindent>' +
178
- '<<TAGSET>>' + # this gets auto-substituted w/ self.TAGSET
179
- '</hangindent>\n')
180
- ]
181
-
182
- HELP_AUTOTAG = [
183
- ('red', dict(foreground='#a00')),
184
- ('green', dict(foreground='#080')),
185
- ('highlight', dict(background='#ddd')),
186
- ('underline', dict(underline=True)),
187
- ('h1', dict(underline=True)),
188
- ('indent', dict(lmargin1=20, lmargin2=20)),
189
- ('hangindent', dict(lmargin1=0, lmargin2=60)),
190
- ('var', dict(foreground='#88f')),
191
- ('regexp', dict(foreground='#ba7')),
192
- ('match', dict(foreground='#6a6')),
193
- ]
194
-
195
- ##/////////////////////////////////////////////////////////////////
196
- ## Config Parmeters
197
- ##/////////////////////////////////////////////////////////////////
198
-
199
- _EVAL_DELAY = 1
200
- """If the user has not pressed any key for this amount of time (in
201
- seconds), and the current grammar has not been evaluated, then
202
- the eval demon will evaluate it."""
203
-
204
- _EVAL_CHUNK = 15
205
- """The number of sentences that should be evaluated by the eval
206
- demon each time it runs."""
207
- _EVAL_FREQ = 0.2
208
- """The frequency (in seconds) at which the eval demon is run"""
209
- _EVAL_DEMON_MIN = .02
210
- """The minimum amount of time that the eval demon should take each time
211
- it runs -- if it takes less than this time, _EVAL_CHUNK will be
212
- modified upwards."""
213
- _EVAL_DEMON_MAX = .04
214
- """The maximum amount of time that the eval demon should take each time
215
- it runs -- if it takes more than this time, _EVAL_CHUNK will be
216
- modified downwards."""
217
-
218
- _GRAMMARBOX_PARAMS = dict(
219
- width=40, height=12, background='#efe', highlightbackground='#efe',
220
- highlightthickness=1, relief='groove', border=2, wrap='word')
221
- _HELPBOX_PARAMS = dict(
222
- width=15, height=15, background='#efe', highlightbackground='#efe',
223
- foreground='#555',
224
- highlightthickness=1, relief='groove', border=2, wrap='word')
225
- _DEVSETBOX_PARAMS = dict(
226
- width=70, height=10, background='#eef', highlightbackground='#eef',
227
- highlightthickness=1, relief='groove', border=2, wrap='word',
228
- tabs=(30,))
229
- _STATUS_PARAMS = dict(
230
- background='#9bb', relief='groove', border=2)
231
- _FONT_PARAMS = dict(
232
- family='helvetica', size=-20)
233
- _FRAME_PARAMS = dict(
234
- background='#777', padx=2, pady=2, border=3)
235
- _EVALBOX_PARAMS = dict(
236
- background='#eef', highlightbackground='#eef',
237
- highlightthickness=1, relief='groove', border=2,
238
- width=300, height=280)
239
- _BUTTON_PARAMS = dict(
240
- background='#777', activebackground='#777',
241
- highlightbackground='#777')
242
- _HELPTAB_BG_COLOR = '#aba'
243
- _HELPTAB_FG_COLOR = '#efe'
244
-
245
- _HELPTAB_FG_PARAMS = dict(background='#efe')
246
- _HELPTAB_BG_PARAMS = dict(background='#aba')
247
- _HELPTAB_SPACER = 6
248
-
249
- def normalize_grammar(self, grammar):
250
- # Strip comments
251
- grammar = re.sub(r'((\\.|[^#])*)(#.*)?', r'\1', grammar)
252
- # Normalize whitespace
253
- grammar = re.sub(' +', ' ', grammar)
254
- grammar = re.sub('\n\s+', '\n', grammar)
255
- grammar = grammar.strip()
256
- # [xx] Hack: automatically backslash $!
257
- grammar = re.sub(r'([^\\])\$', r'\1\\$', grammar)
258
- return grammar
259
-
260
- def __init__(self, devset_name='conll2000', devset=None,
261
- grammar = '', chunk_label='NP', tagset=None):
262
- """
263
- :param devset_name: The name of the development set; used for
264
- display & for save files. If either the name 'treebank'
265
- or the name 'conll2000' is used, and devset is None, then
266
- devset will be set automatically.
267
- :param devset: A list of chunked sentences
268
- :param grammar: The initial grammar to display.
269
- :param tagset: Dictionary from tags to string descriptions, used
270
- for the help page. Defaults to ``self.TAGSET``.
271
- """
272
- self._chunk_label = chunk_label
273
-
274
- if tagset is None: tagset = self.TAGSET
275
- self.tagset = tagset
276
-
277
- # Named development sets:
278
- if devset is None:
279
- if devset_name == 'conll2000':
280
- devset = conll2000.chunked_sents('train.txt')#[:100]
281
- elif devset == 'treebank':
282
- devset = treebank_chunk.chunked_sents()#[:100]
283
- else:
284
- raise ValueError('Unknown development set %s' % devset_name)
285
-
286
- self.chunker = None
287
- """The chunker built from the grammar string"""
288
-
289
- self.grammar = grammar
290
- """The unparsed grammar string"""
291
-
292
- self.normalized_grammar = None
293
- """A normalized version of ``self.grammar``."""
294
-
295
- self.grammar_changed = 0
296
- """The last time() that the grammar was changed."""
297
-
298
- self.devset = devset
299
- """The development set -- a list of chunked sentences."""
300
-
301
- self.devset_name = devset_name
302
- """The name of the development set (for save files)."""
303
-
304
- self.devset_index = -1
305
- """The index into the development set of the first instance
306
- that's currently being viewed."""
307
-
308
- self._last_keypress = 0
309
- """The time() when a key was most recently pressed"""
310
-
311
- self._history = []
312
- """A list of (grammar, precision, recall, fscore) tuples for
313
- grammars that the user has already tried."""
314
-
315
- self._history_index = 0
316
- """When the user is scrolling through previous grammars, this
317
- is used to keep track of which grammar they're looking at."""
318
-
319
- self._eval_grammar = None
320
- """The grammar that is being currently evaluated by the eval
321
- demon."""
322
-
323
- self._eval_normalized_grammar = None
324
- """A normalized copy of ``_eval_grammar``."""
325
-
326
- self._eval_index = 0
327
- """The index of the next sentence in the development set that
328
- should be looked at by the eval demon."""
329
-
330
- self._eval_score = ChunkScore(chunk_label=chunk_label)
331
- """The ``ChunkScore`` object that's used to keep track of the score
332
- of the current grammar on the development set."""
333
-
334
- # Set up the main window.
335
- top = self.top = Tk()
336
- top.geometry('+50+50')
337
- top.title('Regexp Chunk Parser App')
338
- top.bind('<Control-q>', self.destroy)
339
-
340
- # Varaible that restricts how much of the devset we look at.
341
- self._devset_size = IntVar(top)
342
- self._devset_size.set(100)
343
-
344
- # Set up all the tkinter widgets
345
- self._init_fonts(top)
346
- self._init_widgets(top)
347
- self._init_bindings(top)
348
- self._init_menubar(top)
349
- self.grammarbox.focus()
350
-
351
-
352
- # If a grammar was given, then display it.
353
- if grammar:
354
- self.grammarbox.insert('end', grammar+'\n')
355
- self.grammarbox.mark_set('insert', '1.0')
356
-
357
- # Display the first item in the development set
358
- self.show_devset(0)
359
- self.update()
360
-
361
- def _init_bindings(self, top):
362
- top.bind('<Control-n>', self._devset_next)
363
- top.bind('<Control-p>', self._devset_prev)
364
- top.bind('<Control-t>', self.toggle_show_trace)
365
- top.bind('<KeyPress>', self.update)
366
- top.bind('<Control-s>', lambda e: self.save_grammar())
367
- top.bind('<Control-o>', lambda e: self.load_grammar())
368
- self.grammarbox.bind('<Control-t>', self.toggle_show_trace)
369
- self.grammarbox.bind('<Control-n>', self._devset_next)
370
- self.grammarbox.bind('<Control-p>', self._devset_prev)
371
-
372
- # Redraw the eval graph when the window size changes
373
- self.evalbox.bind('<Configure>', self._eval_plot)
374
-
375
- def _init_fonts(self, top):
376
- # TWhat's our font size (default=same as sysfont)
377
- self._size = IntVar(top)
378
- self._size.set(20)
379
- self._font = tkinter.font.Font(family='helvetica',
380
- size=-self._size.get())
381
- self._smallfont = tkinter.font.Font(family='helvetica',
382
- size=-(int(self._size.get()*14//20)))
383
-
384
- def _init_menubar(self, parent):
385
- menubar = Menu(parent)
386
-
387
- filemenu = Menu(menubar, tearoff=0)
388
- filemenu.add_command(label='Reset Application', underline=0,
389
- command=self.reset)
390
- filemenu.add_command(label='Save Current Grammar', underline=0,
391
- accelerator='Ctrl-s',
392
- command=self.save_grammar)
393
- filemenu.add_command(label='Load Grammar', underline=0,
394
- accelerator='Ctrl-o',
395
- command=self.load_grammar)
396
-
397
- filemenu.add_command(label='Save Grammar History', underline=13,
398
- command=self.save_history)
399
-
400
- filemenu.add_command(label='Exit', underline=1,
401
- command=self.destroy, accelerator='Ctrl-q')
402
- menubar.add_cascade(label='File', underline=0, menu=filemenu)
403
-
404
- viewmenu = Menu(menubar, tearoff=0)
405
- viewmenu.add_radiobutton(label='Tiny', variable=self._size,
406
- underline=0, value=10, command=self.resize)
407
- viewmenu.add_radiobutton(label='Small', variable=self._size,
408
- underline=0, value=16, command=self.resize)
409
- viewmenu.add_radiobutton(label='Medium', variable=self._size,
410
- underline=0, value=20, command=self.resize)
411
- viewmenu.add_radiobutton(label='Large', variable=self._size,
412
- underline=0, value=24, command=self.resize)
413
- viewmenu.add_radiobutton(label='Huge', variable=self._size,
414
- underline=0, value=34, command=self.resize)
415
- menubar.add_cascade(label='View', underline=0, menu=viewmenu)
416
-
417
- devsetmenu = Menu(menubar, tearoff=0)
418
- devsetmenu.add_radiobutton(label='50 sentences',
419
- variable=self._devset_size,
420
- value=50, command=self.set_devset_size)
421
- devsetmenu.add_radiobutton(label='100 sentences',
422
- variable=self._devset_size,
423
- value=100, command=self.set_devset_size)
424
- devsetmenu.add_radiobutton(label='200 sentences',
425
- variable=self._devset_size,
426
- value=200, command=self.set_devset_size)
427
- devsetmenu.add_radiobutton(label='500 sentences',
428
- variable=self._devset_size,
429
- value=500, command=self.set_devset_size)
430
- menubar.add_cascade(label='Development-Set', underline=0,
431
- menu=devsetmenu)
432
-
433
- helpmenu = Menu(menubar, tearoff=0)
434
- helpmenu.add_command(label='About', underline=0,
435
- command=self.about)
436
- menubar.add_cascade(label='Help', underline=0, menu=helpmenu)
437
-
438
- parent.config(menu=menubar)
439
-
440
- def toggle_show_trace(self, *e):
441
- if self._showing_trace:
442
- self.show_devset()
443
- else:
444
- self.show_trace()
445
- return 'break'
446
-
447
-
448
- _SCALE_N = 5 # center on the last 5 examples.
449
- _DRAW_LINES = False
450
- def _eval_plot(self, *e, **config):
451
- width = config.get('width', self.evalbox.winfo_width())
452
- height = config.get('height', self.evalbox.winfo_height())
453
-
454
- # Clear the canvas
455
- self.evalbox.delete('all')
456
-
457
- # Draw the precision & recall labels.
458
- tag = self.evalbox.create_text(10, height//2-10, justify='left',
459
- anchor='w', text='Precision')
460
- left, right = self.evalbox.bbox(tag)[2] + 5, width-10
461
- tag = self.evalbox.create_text(left + (width-left)//2, height-10,
462
- anchor='s', text='Recall', justify='center')
463
- top, bot = 10, self.evalbox.bbox(tag)[1]-10
464
-
465
- # Draw masks for clipping the plot.
466
- bg = self._EVALBOX_PARAMS['background']
467
- self.evalbox.lower(self.evalbox.create_rectangle(0, 0, left-1, 5000,
468
- fill=bg, outline=bg))
469
- self.evalbox.lower(self.evalbox.create_rectangle(0, bot+1, 5000, 5000,
470
- fill=bg, outline=bg))
471
-
472
- # Calculate the plot's scale.
473
- if self._autoscale.get() and len(self._history) > 1:
474
- max_precision = max_recall = 0
475
- min_precision = min_recall = 1
476
- for i in range(1, min(len(self._history), self._SCALE_N+1)):
477
- grammar, precision, recall, fmeasure = self._history[-i]
478
- min_precision = min(precision, min_precision)
479
- min_recall = min(recall, min_recall)
480
- max_precision = max(precision, max_precision)
481
- max_recall = max(recall, max_recall)
482
- # if max_precision-min_precision > max_recall-min_recall:
483
- # min_recall -= (max_precision-min_precision)/2
484
- # max_recall += (max_precision-min_precision)/2
485
- # else:
486
- # min_precision -= (max_recall-min_recall)/2
487
- # max_precision += (max_recall-min_recall)/2
488
- # if min_recall < 0:
489
- # max_recall -= min_recall
490
- # min_recall = 0
491
- # if min_precision < 0:
492
- # max_precision -= min_precision
493
- # min_precision = 0
494
- min_precision = max(min_precision-.01, 0)
495
- min_recall = max(min_recall-.01, 0)
496
- max_precision = min(max_precision+.01, 1)
497
- max_recall = min(max_recall+.01, 1)
498
- else:
499
- min_precision = min_recall = 0
500
- max_precision = max_recall = 1
501
-
502
- # Draw the axis lines & grid lines
503
- for i in range(11):
504
- x = left + (right-left)*((i/10.-min_recall)/
505
- (max_recall-min_recall))
506
- y = bot - (bot-top)*((i/10.-min_precision)/
507
- (max_precision-min_precision))
508
- if left < x < right:
509
- self.evalbox.create_line(x, top, x, bot, fill='#888')
510
- if top < y < bot:
511
- self.evalbox.create_line(left, y, right, y, fill='#888')
512
- self.evalbox.create_line(left, top, left, bot)
513
- self.evalbox.create_line(left, bot, right, bot)
514
-
515
- # Display the plot's scale
516
- self.evalbox.create_text(
517
- left-3, bot, justify='right', anchor='se',
518
- text='%d%%' % (100*min_precision))
519
- self.evalbox.create_text(
520
- left-3, top, justify='right', anchor='ne',
521
- text='%d%%' % (100*max_precision))
522
- self.evalbox.create_text(
523
- left, bot+3, justify='center', anchor='nw',
524
- text='%d%%' % (100*min_recall))
525
- self.evalbox.create_text(
526
- right, bot+3, justify='center', anchor='ne',
527
- text='%d%%' % (100*max_recall))
528
-
529
- # Display the scores.
530
- prev_x = prev_y = None
531
- for i, (_, precision, recall, fscore) in enumerate(self._history):
532
- x = left + (right-left) * ((recall-min_recall) /
533
- (max_recall-min_recall))
534
- y = bot - (bot-top) * ((precision-min_precision) /
535
- (max_precision-min_precision))
536
- if i == self._history_index:
537
- self.evalbox.create_oval(x-2,y-2,x+2,y+2,
538
- fill='#0f0', outline='#000')
539
- self.status['text'] = (
540
- 'Precision: %.2f%%\t' % (precision*100)+
541
- 'Recall: %.2f%%\t' % (recall*100)+
542
- 'F-score: %.2f%%' % (fscore*100))
543
- else:
544
- self.evalbox.lower(
545
- self.evalbox.create_oval(x-2,y-2,x+2,y+2,
546
- fill='#afa', outline='#8c8'))
547
- if prev_x is not None and self._eval_lines.get():
548
- self.evalbox.lower(
549
- self.evalbox.create_line(prev_x, prev_y, x, y,
550
- fill='#8c8'))
551
- prev_x, prev_y = x, y
552
-
553
- _eval_demon_running = False
554
- def _eval_demon(self):
555
- if self.top is None: return
556
- if self.chunker is None:
557
- self._eval_demon_running = False
558
- return
559
-
560
- # Note our starting time.
561
- t0 = time.time()
562
-
563
- # If are still typing, then wait for them to finish.
564
- if (time.time()-self._last_keypress < self._EVAL_DELAY and
565
- self.normalized_grammar != self._eval_normalized_grammar):
566
- self._eval_demon_running = True
567
- return self.top.after(int(self._EVAL_FREQ*1000), self._eval_demon)
568
-
569
- # If the grammar changed, restart the evaluation.
570
- if self.normalized_grammar != self._eval_normalized_grammar:
571
- # Check if we've seen this grammar already. If so, then
572
- # just use the old evaluation values.
573
- for (g, p, r, f) in self._history:
574
- if self.normalized_grammar == self.normalize_grammar(g):
575
- self._history.append( (g, p, r, f) )
576
- self._history_index = len(self._history) - 1
577
- self._eval_plot()
578
- self._eval_demon_running = False
579
- self._eval_normalized_grammar = None
580
- return
581
- self._eval_index = 0
582
- self._eval_score = ChunkScore(chunk_label=self._chunk_label)
583
- self._eval_grammar = self.grammar
584
- self._eval_normalized_grammar = self.normalized_grammar
585
-
586
- # If the grammar is empty, the don't bother evaluating it, or
587
- # recording it in history -- the score will just be 0.
588
- if self.normalized_grammar.strip() == '':
589
- #self._eval_index = self._devset_size.get()
590
- self._eval_demon_running = False
591
- return
592
-
593
- # Score the next set of examples
594
- for gold in self.devset[self._eval_index:
595
- min(self._eval_index+self._EVAL_CHUNK,
596
- self._devset_size.get())]:
597
- guess = self._chunkparse(gold.leaves())
598
- self._eval_score.score(gold, guess)
599
-
600
- # update our index in the devset.
601
- self._eval_index += self._EVAL_CHUNK
602
-
603
- # Check if we're done
604
- if self._eval_index >= self._devset_size.get():
605
- self._history.append( (self._eval_grammar,
606
- self._eval_score.precision(),
607
- self._eval_score.recall(),
608
- self._eval_score.f_measure()) )
609
- self._history_index = len(self._history)-1
610
- self._eval_plot()
611
- self._eval_demon_running = False
612
- self._eval_normalized_grammar = None
613
- else:
614
- progress = 100*self._eval_index/self._devset_size.get()
615
- self.status['text'] = ('Evaluating on Development Set (%d%%)' %
616
- progress)
617
- self._eval_demon_running = True
618
- self._adaptively_modify_eval_chunk(time.time() - t0)
619
- self.top.after(int(self._EVAL_FREQ*1000), self._eval_demon)
620
-
621
- def _adaptively_modify_eval_chunk(self, t):
622
- """
623
- Modify _EVAL_CHUNK to try to keep the amount of time that the
624
- eval demon takes between _EVAL_DEMON_MIN and _EVAL_DEMON_MAX.
625
-
626
- :param t: The amount of time that the eval demon took.
627
- """
628
- if t > self._EVAL_DEMON_MAX and self._EVAL_CHUNK > 5:
629
- self._EVAL_CHUNK = min(self._EVAL_CHUNK-1,
630
- max(int(self._EVAL_CHUNK*(self._EVAL_DEMON_MAX/t)),
631
- self._EVAL_CHUNK-10))
632
- elif t < self._EVAL_DEMON_MIN:
633
- self._EVAL_CHUNK = max(self._EVAL_CHUNK+1,
634
- min(int(self._EVAL_CHUNK*(self._EVAL_DEMON_MIN/t)),
635
- self._EVAL_CHUNK+10))
636
-
637
- def _init_widgets(self, top):
638
- frame0 = Frame(top, **self._FRAME_PARAMS)
639
- frame0.grid_columnconfigure(0, weight=4)
640
- frame0.grid_columnconfigure(3, weight=2)
641
- frame0.grid_rowconfigure(1, weight=1)
642
- frame0.grid_rowconfigure(5, weight=1)
643
-
644
- # The grammar
645
- self.grammarbox = Text(frame0, font=self._font,
646
- **self._GRAMMARBOX_PARAMS)
647
- self.grammarlabel = Label(frame0, font=self._font, text='Grammar:',
648
- highlightcolor='black',
649
- background=self._GRAMMARBOX_PARAMS['background'])
650
- self.grammarlabel.grid(column=0, row=0, sticky='SW')
651
- self.grammarbox.grid(column=0, row=1, sticky='NEWS')
652
-
653
- # Scroll bar for grammar
654
- grammar_scrollbar = Scrollbar(frame0, command=self.grammarbox.yview)
655
- grammar_scrollbar.grid(column=1, row=1, sticky='NWS')
656
- self.grammarbox.config(yscrollcommand=grammar_scrollbar.set)
657
-
658
- # grammar buttons
659
- bg = self._FRAME_PARAMS['background']
660
- frame3 = Frame(frame0, background=bg)
661
- frame3.grid(column=0, row=2, sticky='EW')
662
- Button(frame3, text='Prev Grammar', command=self._history_prev,
663
- **self._BUTTON_PARAMS).pack(side='left')
664
- Button(frame3, text='Next Grammar', command=self._history_next,
665
- **self._BUTTON_PARAMS).pack(side='left')
666
-
667
- # Help box
668
- self.helpbox = Text(frame0, font=self._smallfont,
669
- **self._HELPBOX_PARAMS)
670
- self.helpbox.grid(column=3, row=1, sticky='NEWS')
671
- self.helptabs = {}
672
- bg = self._FRAME_PARAMS['background']
673
- helptab_frame = Frame(frame0, background=bg)
674
- helptab_frame.grid(column=3, row=0, sticky='SW')
675
- for i, (tab, tabstops, text) in enumerate(self.HELP):
676
- label = Label(helptab_frame, text=tab, font=self._smallfont)
677
- label.grid(column=i*2, row=0, sticky='S')
678
- #help_frame.grid_columnconfigure(i, weight=1)
679
- #label.pack(side='left')
680
- label.bind('<ButtonPress>', lambda e, tab=tab: self.show_help(tab))
681
- self.helptabs[tab] = label
682
- Frame(helptab_frame, height=1, width=self._HELPTAB_SPACER,
683
- background=bg).grid(column=i*2+1, row=0)
684
- self.helptabs[self.HELP[0][0]].configure(font=self._font)
685
- self.helpbox.tag_config('elide', elide=True)
686
- for (tag, params) in self.HELP_AUTOTAG:
687
- self.helpbox.tag_config('tag-%s' % tag, **params)
688
- self.show_help(self.HELP[0][0])
689
-
690
- # Scroll bar for helpbox
691
- help_scrollbar = Scrollbar(frame0, command=self.helpbox.yview)
692
- self.helpbox.config(yscrollcommand=help_scrollbar.set)
693
- help_scrollbar.grid(column=4, row=1, sticky='NWS')
694
-
695
- # The dev set
696
- frame4 = Frame(frame0, background=self._FRAME_PARAMS['background'])
697
- self.devsetbox = Text(frame4, font=self._font,
698
- **self._DEVSETBOX_PARAMS)
699
- self.devsetbox.pack(expand=True, fill='both')
700
- self.devsetlabel = Label(frame0, font=self._font,
701
- text='Development Set:', justify='right',
702
- background=self._DEVSETBOX_PARAMS['background'])
703
- self.devsetlabel.grid(column=0, row=4, sticky='SW')
704
- frame4.grid(column=0, row=5, sticky='NEWS')
705
-
706
- # dev set scrollbars
707
- self.devset_scroll = Scrollbar(frame0, command=self._devset_scroll)
708
- self.devset_scroll.grid(column=1, row=5, sticky='NWS')
709
- self.devset_xscroll = Scrollbar(frame4, command=self.devsetbox.xview,
710
- orient='horiz')
711
- self.devsetbox['xscrollcommand'] = self.devset_xscroll.set
712
- self.devset_xscroll.pack(side='bottom', fill='x')
713
-
714
- # dev set buttons
715
- bg = self._FRAME_PARAMS['background']
716
- frame1 = Frame(frame0, background=bg)
717
- frame1.grid(column=0, row=7, sticky='EW')
718
- Button(frame1, text='Prev Example (Ctrl-p)',
719
- command=self._devset_prev,
720
- **self._BUTTON_PARAMS).pack(side='left')
721
- Button(frame1, text='Next Example (Ctrl-n)',
722
- command=self._devset_next,
723
- **self._BUTTON_PARAMS).pack(side='left')
724
- self.devset_button = Button(frame1, text='Show example',
725
- command=self.show_devset,
726
- state='disabled',
727
- **self._BUTTON_PARAMS)
728
- self.devset_button.pack(side='right')
729
- self.trace_button = Button(frame1, text='Show trace',
730
- command=self.show_trace,
731
- **self._BUTTON_PARAMS)
732
- self.trace_button.pack(side='right')
733
-
734
-
735
- # evaluation box
736
- self.evalbox = Canvas(frame0, **self._EVALBOX_PARAMS)
737
- label = Label(frame0, font=self._font, text='Evaluation:',
738
- justify='right', background=self._EVALBOX_PARAMS['background'])
739
- label.grid(column=3, row=4, sticky='SW')
740
- self.evalbox.grid(column=3, row=5, sticky='NEWS', columnspan=2)
741
-
742
- # evaluation box buttons
743
- bg = self._FRAME_PARAMS['background']
744
- frame2 = Frame(frame0, background=bg)
745
- frame2.grid(column=3, row=7, sticky='EW')
746
- self._autoscale = IntVar(self.top)
747
- self._autoscale.set(False)
748
- Checkbutton(frame2, variable=self._autoscale, command=self._eval_plot,
749
- text='Zoom', **self._BUTTON_PARAMS).pack(side='left')
750
- self._eval_lines = IntVar(self.top)
751
- self._eval_lines.set(False)
752
- Checkbutton(frame2, variable=self._eval_lines, command=self._eval_plot,
753
- text='Lines', **self._BUTTON_PARAMS).pack(side='left')
754
- Button(frame2, text='History',
755
- **self._BUTTON_PARAMS).pack(side='right')
756
-
757
- # The status label
758
- self.status = Label(frame0, font=self._font, **self._STATUS_PARAMS)
759
- self.status.grid(column=0, row=9, sticky='NEW', padx=3, pady=2,
760
- columnspan=5)
761
-
762
- # Help box & devset box can't be edited.
763
- self.helpbox['state'] = 'disabled'
764
- self.devsetbox['state'] = 'disabled'
765
-
766
- # Spacers
767
- bg = self._FRAME_PARAMS['background']
768
- Frame(frame0, height=10, width=0, background=bg).grid(column=0, row=3)
769
- Frame(frame0, height=0, width=10, background=bg).grid(column=2, row=0)
770
- Frame(frame0, height=6, width=0, background=bg).grid(column=0, row=8)
771
-
772
- # pack the frame.
773
- frame0.pack(fill='both', expand=True)
774
-
775
- # Set up colors for the devset box
776
- self.devsetbox.tag_config('true-pos', background='#afa',
777
- underline='True')
778
- self.devsetbox.tag_config('false-neg', underline='True',
779
- foreground='#800')
780
- self.devsetbox.tag_config('false-pos', background='#faa')
781
- self.devsetbox.tag_config('trace', foreground='#666', wrap='none')
782
- self.devsetbox.tag_config('wrapindent', lmargin2=30, wrap='none')
783
- self.devsetbox.tag_config('error', foreground='#800')
784
-
785
- # And for the grammarbox
786
- self.grammarbox.tag_config('error', background='#fec')
787
- self.grammarbox.tag_config('comment', foreground='#840')
788
- self.grammarbox.tag_config('angle', foreground='#00f')
789
- self.grammarbox.tag_config('brace', foreground='#0a0')
790
- self.grammarbox.tag_config('hangindent', lmargin1=0, lmargin2=40)
791
-
792
- _showing_trace = False
793
- def show_trace(self, *e):
794
- self._showing_trace = True
795
- self.trace_button['state'] = 'disabled'
796
- self.devset_button['state'] = 'normal'
797
-
798
- self.devsetbox['state'] = 'normal'
799
- #self.devsetbox['wrap'] = 'none'
800
- self.devsetbox.delete('1.0', 'end')
801
- self.devsetlabel['text']='Development Set (%d/%d)' % (
802
- (self.devset_index+1, self._devset_size.get()))
803
-
804
- if self.chunker is None:
805
- self.devsetbox.insert('1.0', 'Trace: waiting for a valid grammar.')
806
- self.devsetbox.tag_add('error', '1.0', 'end')
807
- return # can't do anything more
808
-
809
- gold_tree = self.devset[self.devset_index]
810
- rules = self.chunker.rules()
811
-
812
- # Calculate the tag sequence
813
- tagseq = '\t'
814
- charnum = [1]
815
- for wordnum, (word, pos) in enumerate(gold_tree.leaves()):
816
- tagseq += '%s ' % pos
817
- charnum.append(len(tagseq))
818
- self.charnum = dict(((i, j), charnum[j])
819
- for i in range(len(rules)+1)
820
- for j in range(len(charnum)))
821
- self.linenum = dict((i,i*2+2) for i in range(len(rules)+1))
822
-
823
- for i in range(len(rules)+1):
824
- if i == 0:
825
- self.devsetbox.insert('end', 'Start:\n')
826
- self.devsetbox.tag_add('trace', 'end -2c linestart', 'end -2c')
827
- else:
828
- self.devsetbox.insert('end', 'Apply %s:\n' % rules[i-1])
829
- self.devsetbox.tag_add('trace', 'end -2c linestart', 'end -2c')
830
- # Display the tag sequence.
831
- self.devsetbox.insert('end', tagseq+'\n')
832
- self.devsetbox.tag_add('wrapindent','end -2c linestart','end -2c')
833
- # Run a partial parser, and extract gold & test chunks
834
- chunker = RegexpChunkParser(rules[:i])
835
- test_tree = self._chunkparse(gold_tree.leaves())
836
- gold_chunks = self._chunks(gold_tree)
837
- test_chunks = self._chunks(test_tree)
838
- # Compare them.
839
- for chunk in gold_chunks.intersection(test_chunks):
840
- self._color_chunk(i, chunk, 'true-pos')
841
- for chunk in gold_chunks - test_chunks:
842
- self._color_chunk(i, chunk, 'false-neg')
843
- for chunk in test_chunks - gold_chunks:
844
- self._color_chunk(i, chunk, 'false-pos')
845
- self.devsetbox.insert('end', 'Finished.\n')
846
- self.devsetbox.tag_add('trace', 'end -2c linestart', 'end -2c')
847
-
848
- # This is a hack, because the x-scrollbar isn't updating its
849
- # position right -- I'm not sure what the underlying cause is
850
- # though. (This is on OS X w/ python 2.5)
851
- self.top.after(100, self.devset_xscroll.set, 0, .3)
852
-
853
- def show_help(self, tab):
854
- self.helpbox['state'] = 'normal'
855
- self.helpbox.delete('1.0', 'end')
856
- for (name, tabstops, text) in self.HELP:
857
- if name == tab:
858
- text = text.replace('<<TAGSET>>', '\n'.join(
859
- ('\t%s\t%s' % item for item in sorted(list(self.tagset.items()),
860
- key=lambda t_w:re.match('\w+',t_w[0]) and (0,t_w[0]) or (1,t_w[0])))))
861
-
862
- self.helptabs[name].config(**self._HELPTAB_FG_PARAMS)
863
- self.helpbox.config(tabs=tabstops)
864
- self.helpbox.insert('1.0', text+'\n'*20)
865
- C = '1.0 + %d chars'
866
- for (tag, params) in self.HELP_AUTOTAG:
867
- pattern = '(?s)(<%s>)(.*?)(</%s>)' % (tag, tag)
868
- for m in re.finditer(pattern, text):
869
- self.helpbox.tag_add('elide',
870
- C % m.start(1), C % m.end(1))
871
- self.helpbox.tag_add('tag-%s' % tag,
872
- C % m.start(2), C % m.end(2))
873
- self.helpbox.tag_add('elide',
874
- C % m.start(3), C % m.end(3))
875
- else:
876
- self.helptabs[name].config(**self._HELPTAB_BG_PARAMS)
877
- self.helpbox['state'] = 'disabled'
878
-
879
- def _history_prev(self, *e):
880
- self._view_history(self._history_index-1)
881
- return 'break'
882
-
883
- def _history_next(self, *e):
884
- self._view_history(self._history_index+1)
885
- return 'break'
886
-
887
- def _view_history(self, index):
888
- # Bounds & sanity checking:
889
- index = max(0, min(len(self._history)-1, index))
890
- if not self._history: return
891
- # Already viewing the requested history item?
892
- if index == self._history_index:
893
- return
894
- # Show the requested grammar. It will get added to _history
895
- # only if they edit it (causing self.update() to get run.)
896
- self.grammarbox['state'] = 'normal'
897
- self.grammarbox.delete('1.0', 'end')
898
- self.grammarbox.insert('end', self._history[index][0])
899
- self.grammarbox.mark_set('insert', '1.0')
900
- self._history_index = index
901
- self._syntax_highlight_grammar(self._history[index][0])
902
- # Record the normalized grammar & regenerate the chunker.
903
- self.normalized_grammar = self.normalize_grammar(
904
- self._history[index][0])
905
- if self.normalized_grammar:
906
- rules = [RegexpChunkRule.fromstring(line)
907
- for line in self.normalized_grammar.split('\n')]
908
- else:
909
- rules = []
910
- self.chunker = RegexpChunkParser(rules)
911
- # Show the score.
912
- self._eval_plot()
913
- # Update the devset box
914
- self._highlight_devset()
915
- if self._showing_trace: self.show_trace()
916
- # Update the grammar label
917
- if self._history_index < len(self._history)-1:
918
- self.grammarlabel['text'] = 'Grammar %s/%s:' % (
919
- self._history_index+1, len(self._history))
920
- else:
921
- self.grammarlabel['text'] = 'Grammar:'
922
-
923
- def _devset_next(self, *e):
924
- self._devset_scroll('scroll', 1, 'page')
925
- return 'break'
926
-
927
- def _devset_prev(self, *e):
928
- self._devset_scroll('scroll', -1, 'page')
929
- return 'break'
930
-
931
- def destroy(self, *e):
932
- if self.top is None: return
933
- self.top.destroy()
934
- self.top = None
935
-
936
- def _devset_scroll(self, command, *args):
937
- N = 1 # size of a page -- one sentence.
938
- showing_trace = self._showing_trace
939
- if command == 'scroll' and args[1].startswith('unit'):
940
- self.show_devset(self.devset_index+int(args[0]))
941
- elif command == 'scroll' and args[1].startswith('page'):
942
- self.show_devset(self.devset_index+N*int(args[0]))
943
- elif command == 'moveto':
944
- self.show_devset(int(float(args[0])*self._devset_size.get()))
945
- else:
946
- assert 0, 'bad scroll command %s %s' % (command, args)
947
- if showing_trace:
948
- self.show_trace()
949
-
950
- def show_devset(self, index=None):
951
- if index is None: index = self.devset_index
952
-
953
- # Bounds checking
954
- index = min(max(0, index), self._devset_size.get()-1)
955
-
956
- if index == self.devset_index and not self._showing_trace: return
957
- self.devset_index = index
958
-
959
- self._showing_trace = False
960
- self.trace_button['state'] = 'normal'
961
- self.devset_button['state'] = 'disabled'
962
-
963
- # Clear the text box.
964
- self.devsetbox['state'] = 'normal'
965
- self.devsetbox['wrap'] = 'word'
966
- self.devsetbox.delete('1.0', 'end')
967
- self.devsetlabel['text']='Development Set (%d/%d)' % (
968
- (self.devset_index+1, self._devset_size.get()))
969
-
970
- # Add the sentences
971
- sample = self.devset[self.devset_index:self.devset_index+1]
972
- self.charnum = {}
973
- self.linenum = {0:1}
974
- for sentnum, sent in enumerate(sample):
975
- linestr = ''
976
- for wordnum, (word, pos) in enumerate(sent.leaves()):
977
- self.charnum[sentnum, wordnum] = len(linestr)
978
- linestr += '%s/%s ' % (word, pos)
979
- self.charnum[sentnum, wordnum+1] = len(linestr)
980
- self.devsetbox.insert('end', linestr[:-1]+'\n\n')
981
-
982
- # Highlight chunks in the dev set
983
- if self.chunker is not None:
984
- self._highlight_devset()
985
- self.devsetbox['state'] = 'disabled'
986
-
987
- # Update the scrollbar
988
- first = self.devset_index/self._devset_size.get()
989
- last = (self.devset_index + 2) / self._devset_size.get()
990
- self.devset_scroll.set(first, last)
991
-
992
- def _chunks(self, tree):
993
- chunks = set()
994
- wordnum = 0
995
- for child in tree:
996
- if isinstance(child, Tree):
997
- if child.label() == self._chunk_label:
998
- chunks.add( (wordnum, wordnum+len(child)) )
999
- wordnum += len(child)
1000
- else:
1001
- wordnum += 1
1002
- return chunks
1003
-
1004
- def _syntax_highlight_grammar(self, grammar):
1005
- if self.top is None: return
1006
- self.grammarbox.tag_remove('comment', '1.0', 'end')
1007
- self.grammarbox.tag_remove('angle', '1.0', 'end')
1008
- self.grammarbox.tag_remove('brace', '1.0', 'end')
1009
- self.grammarbox.tag_add('hangindent', '1.0', 'end')
1010
- for lineno, line in enumerate(grammar.split('\n')):
1011
- if not line.strip(): continue
1012
- m = re.match(r'(\\.|[^#])*(#.*)?', line)
1013
- comment_start = None
1014
- if m.group(2):
1015
- comment_start = m.start(2)
1016
- s = '%d.%d' % (lineno+1, m.start(2))
1017
- e = '%d.%d' % (lineno+1, m.end(2))
1018
- self.grammarbox.tag_add('comment', s, e)
1019
- for m in re.finditer('[<>{}]', line):
1020
- if comment_start is not None and m.start() >= comment_start:
1021
- break
1022
- s = '%d.%d' % (lineno+1, m.start())
1023
- e = '%d.%d' % (lineno+1, m.end())
1024
- if m.group() in '<>':
1025
- self.grammarbox.tag_add('angle', s, e)
1026
- else:
1027
- self.grammarbox.tag_add('brace', s, e)
1028
-
1029
-
1030
- def _grammarcheck(self, grammar):
1031
- if self.top is None: return
1032
- self.grammarbox.tag_remove('error', '1.0', 'end')
1033
- self._grammarcheck_errs = []
1034
- for lineno, line in enumerate(grammar.split('\n')):
1035
- line = re.sub(r'((\\.|[^#])*)(#.*)?', r'\1', line)
1036
- line = line.strip()
1037
- if line:
1038
- try:
1039
- RegexpChunkRule.fromstring(line)
1040
- except ValueError as e:
1041
- self.grammarbox.tag_add('error', '%s.0' % (lineno+1),
1042
- '%s.0 lineend' % (lineno+1))
1043
- self.status['text'] = ''
1044
-
1045
- def update(self, *event):
1046
- # Record when update was called (for grammarcheck)
1047
- if event:
1048
- self._last_keypress = time.time()
1049
-
1050
- # Read the grammar from the Text box.
1051
- self.grammar = grammar = self.grammarbox.get('1.0', 'end')
1052
-
1053
- # If the grammar hasn't changed, do nothing:
1054
- normalized_grammar = self.normalize_grammar(grammar)
1055
- if normalized_grammar == self.normalized_grammar:
1056
- return
1057
- else:
1058
- self.normalized_grammar = normalized_grammar
1059
-
1060
- # If the grammar has changed, and we're looking at history,
1061
- # then stop looking at history.
1062
- if self._history_index < len(self._history)-1:
1063
- self.grammarlabel['text'] = 'Grammar:'
1064
-
1065
- self._syntax_highlight_grammar(grammar)
1066
-
1067
- # The grammar has changed; try parsing it. If it doesn't
1068
- # parse, do nothing. (flag error location?)
1069
- try:
1070
- # Note: the normalized grammar has no blank lines.
1071
- if normalized_grammar:
1072
- rules = [RegexpChunkRule.fromstring(line)
1073
- for line in normalized_grammar.split('\n')]
1074
- else:
1075
- rules = []
1076
- except ValueError as e:
1077
- # Use the un-normalized grammar for error highlighting.
1078
- self._grammarcheck(grammar)
1079
- self.chunker = None
1080
- return
1081
-
1082
- self.chunker = RegexpChunkParser(rules)
1083
- self.grammarbox.tag_remove('error', '1.0', 'end')
1084
- self.grammar_changed = time.time()
1085
- # Display the results
1086
- if self._showing_trace:
1087
- self.show_trace()
1088
- else:
1089
- self._highlight_devset()
1090
- # Start the eval demon
1091
- if not self._eval_demon_running:
1092
- self._eval_demon()
1093
-
1094
- def _highlight_devset(self, sample=None):
1095
- if sample is None:
1096
- sample = self.devset[self.devset_index:self.devset_index+1]
1097
-
1098
- self.devsetbox.tag_remove('true-pos', '1.0', 'end')
1099
- self.devsetbox.tag_remove('false-neg', '1.0', 'end')
1100
- self.devsetbox.tag_remove('false-pos', '1.0', 'end')
1101
-
1102
- # Run the grammar on the test cases.
1103
- for sentnum, gold_tree in enumerate(sample):
1104
- # Run the chunk parser
1105
- test_tree = self._chunkparse(gold_tree.leaves())
1106
- # Extract gold & test chunks
1107
- gold_chunks = self._chunks(gold_tree)
1108
- test_chunks = self._chunks(test_tree)
1109
- # Compare them.
1110
- for chunk in gold_chunks.intersection(test_chunks):
1111
- self._color_chunk(sentnum, chunk, 'true-pos')
1112
- for chunk in gold_chunks - test_chunks:
1113
- self._color_chunk(sentnum, chunk, 'false-neg')
1114
- for chunk in test_chunks - gold_chunks:
1115
- self._color_chunk(sentnum, chunk, 'false-pos')
1116
-
1117
- def _chunkparse(self, words):
1118
- try:
1119
- return self.chunker.parse(words)
1120
- except (ValueError, IndexError) as e:
1121
- # There's an error somewhere in the grammar, but we're not sure
1122
- # exactly where, so just mark the whole grammar as bad.
1123
- # E.g., this is caused by: "({<NN>})"
1124
- self.grammarbox.tag_add('error', '1.0', 'end')
1125
- # Treat it as tagging nothing:
1126
- return words
1127
-
1128
- def _color_chunk(self, sentnum, chunk, tag):
1129
- start, end = chunk
1130
- self.devsetbox.tag_add(tag,
1131
- '%s.%s' % (self.linenum[sentnum], self.charnum[sentnum, start]),
1132
- '%s.%s' % (self.linenum[sentnum], self.charnum[sentnum, end]-1))
1133
-
1134
- def reset(self):
1135
- # Clear various variables
1136
- self.chunker = None
1137
- self.grammar = None
1138
- self.normalized_grammar = None
1139
- self.grammar_changed = 0
1140
- self._history = []
1141
- self._history_index = 0
1142
- # Update the on-screen display.
1143
- self.grammarbox.delete('1.0', 'end')
1144
- self.show_devset(0)
1145
- self.update()
1146
- #self._eval_plot()
1147
-
1148
- SAVE_GRAMMAR_TEMPLATE = (
1149
- '# Regexp Chunk Parsing Grammar\n'
1150
- '# Saved %(date)s\n'
1151
- '#\n'
1152
- '# Development set: %(devset)s\n'
1153
- '# Precision: %(precision)s\n'
1154
- '# Recall: %(recall)s\n'
1155
- '# F-score: %(fscore)s\n\n'
1156
- '%(grammar)s\n')
1157
-
1158
- def save_grammar(self, filename=None):
1159
- if not filename:
1160
- ftypes = [('Chunk Gramamr', '.chunk'),
1161
- ('All files', '*')]
1162
- filename = tkinter.filedialog.asksaveasfilename(filetypes=ftypes,
1163
- defaultextension='.chunk')
1164
- if not filename: return
1165
- if (self._history and self.normalized_grammar ==
1166
- self.normalize_grammar(self._history[-1][0])):
1167
- precision, recall, fscore = ['%.2f%%' % (100*v) for v in
1168
- self._history[-1][1:]]
1169
- elif self.chunker is None:
1170
- precision = recall = fscore = 'Grammar not well formed'
1171
- else:
1172
- precision = recall = fscore = 'Not finished evaluation yet'
1173
-
1174
- with open(filename, 'w') as outfile:
1175
- outfile.write(self.SAVE_GRAMMAR_TEMPLATE % dict(
1176
- date=time.ctime(), devset=self.devset_name,
1177
- precision=precision, recall=recall, fscore=fscore,
1178
- grammar=self.grammar.strip()))
1179
-
1180
- def load_grammar(self, filename=None):
1181
- if not filename:
1182
- ftypes = [('Chunk Gramamr', '.chunk'),
1183
- ('All files', '*')]
1184
- filename = tkinter.filedialog.askopenfilename(filetypes=ftypes,
1185
- defaultextension='.chunk')
1186
- if not filename: return
1187
- self.grammarbox.delete('1.0', 'end')
1188
- self.update()
1189
- with open(filename, 'r') as infile:
1190
- grammar = infile.read()
1191
- grammar = re.sub('^\# Regexp Chunk Parsing Grammar[\s\S]*'
1192
- 'F-score:.*\n', '', grammar).lstrip()
1193
- self.grammarbox.insert('1.0', grammar)
1194
- self.update()
1195
-
1196
- def save_history(self, filename=None):
1197
- if not filename:
1198
- ftypes = [('Chunk Gramamr History', '.txt'),
1199
- ('All files', '*')]
1200
- filename = tkinter.filedialog.asksaveasfilename(filetypes=ftypes,
1201
- defaultextension='.txt')
1202
- if not filename: return
1203
-
1204
- with open(filename, 'w') as outfile:
1205
- outfile.write('# Regexp Chunk Parsing Grammar History\n')
1206
- outfile.write('# Saved %s\n' % time.ctime())
1207
- outfile.write('# Development set: %s\n' % self.devset_name)
1208
- for i, (g, p, r, f) in enumerate(self._history):
1209
- hdr = ('Grammar %d/%d (precision=%.2f%%, recall=%.2f%%, '
1210
- 'fscore=%.2f%%)' % (i+1, len(self._history),
1211
- p*100, r*100, f*100))
1212
- outfile.write('\n%s\n' % hdr)
1213
- outfile.write(''.join(' %s\n' % line for line in g.strip().split()))
1214
-
1215
- if not (self._history and self.normalized_grammar ==
1216
- self.normalize_grammar(self._history[-1][0])):
1217
- if self.chunker is None:
1218
- outfile.write('\nCurrent Grammar (not well-formed)\n')
1219
- else:
1220
- outfile.write('\nCurrent Grammar (not evaluated)\n')
1221
- outfile.write(''.join(' %s\n' % line for line
1222
- in self.grammar.strip().split()))
1223
-
1224
- def about(self, *e):
1225
- ABOUT = ("NLTK RegExp Chunk Parser Application\n"+
1226
- "Written by Edward Loper")
1227
- TITLE = 'About: Regular Expression Chunk Parser Application'
1228
- try:
1229
- from tkinter.messagebox import Message
1230
- Message(message=ABOUT, title=TITLE).show()
1231
- except:
1232
- ShowText(self.top, TITLE, ABOUT)
1233
-
1234
- def set_devset_size(self, size=None):
1235
- if size is not None: self._devset_size.set(size)
1236
- self._devset_size.set(min(len(self.devset), self._devset_size.get()))
1237
- self.show_devset(1)
1238
- self.show_devset(0)
1239
- # what about history? Evaluated at diff dev set sizes!
1240
-
1241
- def resize(self, size=None):
1242
- if size is not None: self._size.set(size)
1243
- size = self._size.get()
1244
- self._font.configure(size=-(abs(size)))
1245
- self._smallfont.configure(size=min(-10, -(abs(size))*14//20))
1246
-
1247
- def mainloop(self, *args, **kwargs):
1248
- """
1249
- Enter the Tkinter mainloop. This function must be called if
1250
- this demo is created from a non-interactive program (e.g.
1251
- from a secript); otherwise, the demo will close as soon as
1252
- the script completes.
1253
- """
1254
- if in_idle(): return
1255
- self.top.mainloop(*args, **kwargs)
1256
-
1257
- def app():
1258
- RegexpChunkApp().mainloop()
1259
-
1260
- if __name__ == '__main__':
1261
- app()
1262
-
1263
- __all__ = ['app']
1264
-
1
+ # Natural Language Toolkit: Regexp Chunk Parser Application
2
+ #
3
+ # Copyright (C) 2001-2018 NLTK Project
4
+ # Author: Edward Loper <edloper@gmail.com>
5
+ # URL: <http://nltk.org/>
6
+ # For license information, see LICENSE.TXT
7
+
8
+ """
9
+ A graphical tool for exploring the regular expression based chunk
10
+ parser ``nltk.chunk.RegexpChunkParser``.
11
+ """
12
+
13
+ # Todo: Add a way to select the development set from the menubar. This
14
+ # might just need to be a selection box (conll vs treebank etc) plus
15
+ # configuration parameters to select what's being chunked (eg VP vs NP)
16
+ # and what part of the data is being used as the development set.
17
+
18
+ from __future__ import division
19
+ import time
20
+ import textwrap
21
+ import re
22
+ import random
23
+
24
+ from six.moves.tkinter import (Button, Canvas, Checkbutton, Frame, IntVar,
25
+ Label, Menu, Scrollbar, Text, Tk)
26
+ from six.moves.tkinter_tkfiledialog import askopenfilename, asksaveasfilename
27
+ from six.moves.tkinter_font import Font
28
+
29
+ from nltk.tree import Tree
30
+ from nltk.util import in_idle
31
+ from nltk.draw.util import ShowText
32
+ from nltk.corpus import conll2000, treebank_chunk
33
+ from nltk.chunk import ChunkScore, RegexpChunkParser
34
+ from nltk.chunk.regexp import RegexpChunkRule
35
+
36
+ class RegexpChunkApp(object):
37
+ """
38
+ A graphical tool for exploring the regular expression based chunk
39
+ parser ``nltk.chunk.RegexpChunkParser``.
40
+
41
+ See ``HELP`` for instructional text.
42
+ """
43
+
44
+ ##/////////////////////////////////////////////////////////////////
45
+ ## Help Text
46
+ ##/////////////////////////////////////////////////////////////////
47
+
48
+ #: A dictionary mapping from part of speech tags to descriptions,
49
+ #: which is used in the help text. (This should probably live with
50
+ #: the conll and/or treebank corpus instead.)
51
+ TAGSET = {
52
+ 'CC': 'Coordinating conjunction', 'PRP$': 'Possessive pronoun',
53
+ 'CD': 'Cardinal number', 'RB': 'Adverb',
54
+ 'DT': 'Determiner', 'RBR': 'Adverb, comparative',
55
+ 'EX': 'Existential there', 'RBS': 'Adverb, superlative',
56
+ 'FW': 'Foreign word', 'RP': 'Particle',
57
+ 'JJ': 'Adjective', 'TO': 'to',
58
+ 'JJR': 'Adjective, comparative', 'UH': 'Interjection',
59
+ 'JJS': 'Adjective, superlative', 'VB': 'Verb, base form',
60
+ 'LS': 'List item marker', 'VBD': 'Verb, past tense',
61
+ 'MD': 'Modal', 'NNS': 'Noun, plural',
62
+ 'NN': 'Noun, singular or masps', 'VBN': 'Verb, past participle',
63
+ 'VBZ': 'Verb,3rd ps. sing. present', 'NNP': 'Proper noun, singular',
64
+ 'NNPS': 'Proper noun plural', 'WDT': 'wh-determiner',
65
+ 'PDT': 'Predeterminer', 'WP': 'wh-pronoun',
66
+ 'POS': 'Possessive ending', 'WP$': 'Possessive wh-pronoun',
67
+ 'PRP': 'Personal pronoun', 'WRB': 'wh-adverb',
68
+ '(': 'open parenthesis', ')': 'close parenthesis',
69
+ '``': 'open quote', ',': 'comma',
70
+ "''": 'close quote', '.': 'period',
71
+ '#': 'pound sign (currency marker)',
72
+ '$': 'dollar sign (currency marker)',
73
+ 'IN': 'Preposition/subord. conjunction',
74
+ 'SYM': 'Symbol (mathematical or scientific)',
75
+ 'VBG': 'Verb, gerund/present participle',
76
+ 'VBP': 'Verb, non-3rd ps. sing. present',
77
+ ':': 'colon',
78
+ }
79
+
80
+ #: Contents for the help box. This is a list of tuples, one for
81
+ #: each help page, where each tuple has four elements:
82
+ #: - A title (displayed as a tab)
83
+ #: - A string description of tabstops (see Tkinter.Text for details)
84
+ #: - The text contents for the help page. You can use expressions
85
+ #: like <red>...</red> to colorize the text; see ``HELP_AUTOTAG``
86
+ #: for a list of tags you can use for colorizing.
87
+ HELP = [
88
+ ('Help', '20',
89
+ "Welcome to the regular expression chunk-parser grammar editor. "
90
+ "You can use this editor to develop and test chunk parser grammars "
91
+ "based on NLTK's RegexpChunkParser class.\n\n"
92
+ # Help box.
93
+ "Use this box ('Help') to learn more about the editor; click on the "
94
+ "tabs for help on specific topics:"
95
+ "<indent>\n"
96
+ "Rules: grammar rule types\n"
97
+ "Regexps: regular expression syntax\n"
98
+ "Tags: part of speech tags\n</indent>\n"
99
+ # Grammar.
100
+ "Use the upper-left box ('Grammar') to edit your grammar. "
101
+ "Each line of your grammar specifies a single 'rule', "
102
+ "which performs an action such as creating a chunk or merging "
103
+ "two chunks.\n\n"
104
+ # Dev set.
105
+ "The lower-left box ('Development Set') runs your grammar on the "
106
+ "development set, and displays the results. "
107
+ "Your grammar's chunks are <highlight>highlighted</highlight>, and "
108
+ "the correct (gold standard) chunks are "
109
+ "<underline>underlined</underline>. If they "
110
+ "match, they are displayed in <green>green</green>; otherwise, "
111
+ "they are displayed in <red>red</red>. The box displays a single "
112
+ "sentence from the development set at a time; use the scrollbar or "
113
+ "the next/previous buttons view additional sentences.\n\n"
114
+ # Performance
115
+ "The lower-right box ('Evaluation') tracks the performance of "
116
+ "your grammar on the development set. The 'precision' axis "
117
+ "indicates how many of your grammar's chunks are correct; and "
118
+ "the 'recall' axis indicates how many of the gold standard "
119
+ "chunks your system generated. Typically, you should try to "
120
+ "design a grammar that scores high on both metrics. The "
121
+ "exact precision and recall of the current grammar, as well "
122
+ "as their harmonic mean (the 'f-score'), are displayed in "
123
+ "the status bar at the bottom of the window."
124
+ ),
125
+ ('Rules', '10',
126
+ "<h1>{...regexp...}</h1>"
127
+ "<indent>\nChunk rule: creates new chunks from words matching "
128
+ "regexp.</indent>\n\n"
129
+ "<h1>}...regexp...{</h1>"
130
+ "<indent>\nChink rule: removes words matching regexp from existing "
131
+ "chunks.</indent>\n\n"
132
+ "<h1>...regexp1...}{...regexp2...</h1>"
133
+ "<indent>\nSplit rule: splits chunks that match regexp1 followed by "
134
+ "regexp2 in two.</indent>\n\n"
135
+ "<h1>...regexp...{}...regexp...</h1>"
136
+ "<indent>\nMerge rule: joins consecutive chunks that match regexp1 "
137
+ "and regexp2</indent>\n"
138
+ ),
139
+ ('Regexps', '10 60',
140
+ #"Regular Expression Syntax Summary:\n\n"
141
+ "<h1>Pattern\t\tMatches...</h1>\n"
142
+ "<hangindent>"
143
+ "\t<<var>T</var>>\ta word with tag <var>T</var> "
144
+ "(where <var>T</var> may be a regexp).\n"
145
+ "\t<var>x</var>?\tan optional <var>x</var>\n"
146
+ "\t<var>x</var>+\ta sequence of 1 or more <var>x</var>'s\n"
147
+ "\t<var>x</var>*\ta sequence of 0 or more <var>x</var>'s\n"
148
+ "\t<var>x</var>|<var>y</var>\t<var>x</var> or <var>y</var>\n"
149
+ "\t.\tmatches any character\n"
150
+ "\t(<var>x</var>)\tTreats <var>x</var> as a group\n"
151
+ "\t# <var>x...</var>\tTreats <var>x...</var> "
152
+ "(to the end of the line) as a comment\n"
153
+ "\t\\<var>C</var>\tmatches character <var>C</var> "
154
+ "(useful when <var>C</var> is a special character "
155
+ "like + or #)\n"
156
+ "</hangindent>"
157
+ "\n<h1>Examples:</h1>\n"
158
+ "<hangindent>"
159
+ '\t<regexp><NN></regexp>\n'
160
+ '\t\tMatches <match>"cow/NN"</match>\n'
161
+ '\t\tMatches <match>"green/NN"</match>\n'
162
+ '\t<regexp><VB.*></regexp>\n'
163
+ '\t\tMatches <match>"eating/VBG"</match>\n'
164
+ '\t\tMatches <match>"ate/VBD"</match>\n'
165
+ '\t<regexp><IN><DT><NN></regexp>\n'
166
+ '\t\tMatches <match>"on/IN the/DT car/NN"</match>\n'
167
+ '\t<regexp><RB>?<VBD></regexp>\n'
168
+ '\t\tMatches <match>"ran/VBD"</match>\n'
169
+ '\t\tMatches <match>"slowly/RB ate/VBD"</match>\n'
170
+ '\t<regexp><\#><CD> # This is a comment...</regexp>\n'
171
+ '\t\tMatches <match>"#/# 100/CD"</match>\n'
172
+ "</hangindent>"
173
+ ),
174
+ ('Tags', '10 60',
175
+ "<h1>Part of Speech Tags:</h1>\n" +
176
+ '<hangindent>' +
177
+ '<<TAGSET>>' + # this gets auto-substituted w/ self.TAGSET
178
+ '</hangindent>\n')
179
+ ]
180
+
181
+ HELP_AUTOTAG = [
182
+ ('red', dict(foreground='#a00')),
183
+ ('green', dict(foreground='#080')),
184
+ ('highlight', dict(background='#ddd')),
185
+ ('underline', dict(underline=True)),
186
+ ('h1', dict(underline=True)),
187
+ ('indent', dict(lmargin1=20, lmargin2=20)),
188
+ ('hangindent', dict(lmargin1=0, lmargin2=60)),
189
+ ('var', dict(foreground='#88f')),
190
+ ('regexp', dict(foreground='#ba7')),
191
+ ('match', dict(foreground='#6a6')),
192
+ ]
193
+
194
+ ##/////////////////////////////////////////////////////////////////
195
+ ## Config Parmeters
196
+ ##/////////////////////////////////////////////////////////////////
197
+
198
+ _EVAL_DELAY = 1
199
+ """If the user has not pressed any key for this amount of time (in
200
+ seconds), and the current grammar has not been evaluated, then
201
+ the eval demon will evaluate it."""
202
+
203
+ _EVAL_CHUNK = 15
204
+ """The number of sentences that should be evaluated by the eval
205
+ demon each time it runs."""
206
+ _EVAL_FREQ = 0.2
207
+ """The frequency (in seconds) at which the eval demon is run"""
208
+ _EVAL_DEMON_MIN = .02
209
+ """The minimum amount of time that the eval demon should take each time
210
+ it runs -- if it takes less than this time, _EVAL_CHUNK will be
211
+ modified upwards."""
212
+ _EVAL_DEMON_MAX = .04
213
+ """The maximum amount of time that the eval demon should take each time
214
+ it runs -- if it takes more than this time, _EVAL_CHUNK will be
215
+ modified downwards."""
216
+
217
+ _GRAMMARBOX_PARAMS = dict(
218
+ width=40, height=12, background='#efe', highlightbackground='#efe',
219
+ highlightthickness=1, relief='groove', border=2, wrap='word')
220
+ _HELPBOX_PARAMS = dict(
221
+ width=15, height=15, background='#efe', highlightbackground='#efe',
222
+ foreground='#555',
223
+ highlightthickness=1, relief='groove', border=2, wrap='word')
224
+ _DEVSETBOX_PARAMS = dict(
225
+ width=70, height=10, background='#eef', highlightbackground='#eef',
226
+ highlightthickness=1, relief='groove', border=2, wrap='word',
227
+ tabs=(30,))
228
+ _STATUS_PARAMS = dict(
229
+ background='#9bb', relief='groove', border=2)
230
+ _FONT_PARAMS = dict(
231
+ family='helvetica', size=-20)
232
+ _FRAME_PARAMS = dict(
233
+ background='#777', padx=2, pady=2, border=3)
234
+ _EVALBOX_PARAMS = dict(
235
+ background='#eef', highlightbackground='#eef',
236
+ highlightthickness=1, relief='groove', border=2,
237
+ width=300, height=280)
238
+ _BUTTON_PARAMS = dict(
239
+ background='#777', activebackground='#777',
240
+ highlightbackground='#777')
241
+ _HELPTAB_BG_COLOR = '#aba'
242
+ _HELPTAB_FG_COLOR = '#efe'
243
+
244
+ _HELPTAB_FG_PARAMS = dict(background='#efe')
245
+ _HELPTAB_BG_PARAMS = dict(background='#aba')
246
+ _HELPTAB_SPACER = 6
247
+
248
+ def normalize_grammar(self, grammar):
249
+ # Strip comments
250
+ grammar = re.sub(r'((\\.|[^#])*)(#.*)?', r'\1', grammar)
251
+ # Normalize whitespace
252
+ grammar = re.sub(' +', ' ', grammar)
253
+ grammar = re.sub('\n\s+', '\n', grammar)
254
+ grammar = grammar.strip()
255
+ # [xx] Hack: automatically backslash $!
256
+ grammar = re.sub(r'([^\\])\$', r'\1\\$', grammar)
257
+ return grammar
258
+
259
+ def __init__(self, devset_name='conll2000', devset=None,
260
+ grammar = '', chunk_label='NP', tagset=None):
261
+ """
262
+ :param devset_name: The name of the development set; used for
263
+ display & for save files. If either the name 'treebank'
264
+ or the name 'conll2000' is used, and devset is None, then
265
+ devset will be set automatically.
266
+ :param devset: A list of chunked sentences
267
+ :param grammar: The initial grammar to display.
268
+ :param tagset: Dictionary from tags to string descriptions, used
269
+ for the help page. Defaults to ``self.TAGSET``.
270
+ """
271
+ self._chunk_label = chunk_label
272
+
273
+ if tagset is None: tagset = self.TAGSET
274
+ self.tagset = tagset
275
+
276
+ # Named development sets:
277
+ if devset is None:
278
+ if devset_name == 'conll2000':
279
+ devset = conll2000.chunked_sents('train.txt')#[:100]
280
+ elif devset == 'treebank':
281
+ devset = treebank_chunk.chunked_sents()#[:100]
282
+ else:
283
+ raise ValueError('Unknown development set %s' % devset_name)
284
+
285
+ self.chunker = None
286
+ """The chunker built from the grammar string"""
287
+
288
+ self.grammar = grammar
289
+ """The unparsed grammar string"""
290
+
291
+ self.normalized_grammar = None
292
+ """A normalized version of ``self.grammar``."""
293
+
294
+ self.grammar_changed = 0
295
+ """The last time() that the grammar was changed."""
296
+
297
+ self.devset = devset
298
+ """The development set -- a list of chunked sentences."""
299
+
300
+ self.devset_name = devset_name
301
+ """The name of the development set (for save files)."""
302
+
303
+ self.devset_index = -1
304
+ """The index into the development set of the first instance
305
+ that's currently being viewed."""
306
+
307
+ self._last_keypress = 0
308
+ """The time() when a key was most recently pressed"""
309
+
310
+ self._history = []
311
+ """A list of (grammar, precision, recall, fscore) tuples for
312
+ grammars that the user has already tried."""
313
+
314
+ self._history_index = 0
315
+ """When the user is scrolling through previous grammars, this
316
+ is used to keep track of which grammar they're looking at."""
317
+
318
+ self._eval_grammar = None
319
+ """The grammar that is being currently evaluated by the eval
320
+ demon."""
321
+
322
+ self._eval_normalized_grammar = None
323
+ """A normalized copy of ``_eval_grammar``."""
324
+
325
+ self._eval_index = 0
326
+ """The index of the next sentence in the development set that
327
+ should be looked at by the eval demon."""
328
+
329
+ self._eval_score = ChunkScore(chunk_label=chunk_label)
330
+ """The ``ChunkScore`` object that's used to keep track of the score
331
+ of the current grammar on the development set."""
332
+
333
+ # Set up the main window.
334
+ top = self.top = Tk()
335
+ top.geometry('+50+50')
336
+ top.title('Regexp Chunk Parser App')
337
+ top.bind('<Control-q>', self.destroy)
338
+
339
+ # Varaible that restricts how much of the devset we look at.
340
+ self._devset_size = IntVar(top)
341
+ self._devset_size.set(100)
342
+
343
+ # Set up all the tkinter widgets
344
+ self._init_fonts(top)
345
+ self._init_widgets(top)
346
+ self._init_bindings(top)
347
+ self._init_menubar(top)
348
+ self.grammarbox.focus()
349
+
350
+
351
+ # If a grammar was given, then display it.
352
+ if grammar:
353
+ self.grammarbox.insert('end', grammar+'\n')
354
+ self.grammarbox.mark_set('insert', '1.0')
355
+
356
+ # Display the first item in the development set
357
+ self.show_devset(0)
358
+ self.update()
359
+
360
+ def _init_bindings(self, top):
361
+ top.bind('<Control-n>', self._devset_next)
362
+ top.bind('<Control-p>', self._devset_prev)
363
+ top.bind('<Control-t>', self.toggle_show_trace)
364
+ top.bind('<KeyPress>', self.update)
365
+ top.bind('<Control-s>', lambda e: self.save_grammar())
366
+ top.bind('<Control-o>', lambda e: self.load_grammar())
367
+ self.grammarbox.bind('<Control-t>', self.toggle_show_trace)
368
+ self.grammarbox.bind('<Control-n>', self._devset_next)
369
+ self.grammarbox.bind('<Control-p>', self._devset_prev)
370
+
371
+ # Redraw the eval graph when the window size changes
372
+ self.evalbox.bind('<Configure>', self._eval_plot)
373
+
374
+ def _init_fonts(self, top):
375
+ # TWhat's our font size (default=same as sysfont)
376
+ self._size = IntVar(top)
377
+ self._size.set(20)
378
+ self._font = Font(family='helvetica',
379
+ size=-self._size.get())
380
+ self._smallfont = Font(family='helvetica',
381
+ size=-(int(self._size.get()*14//20)))
382
+
383
+ def _init_menubar(self, parent):
384
+ menubar = Menu(parent)
385
+
386
+ filemenu = Menu(menubar, tearoff=0)
387
+ filemenu.add_command(label='Reset Application', underline=0,
388
+ command=self.reset)
389
+ filemenu.add_command(label='Save Current Grammar', underline=0,
390
+ accelerator='Ctrl-s',
391
+ command=self.save_grammar)
392
+ filemenu.add_command(label='Load Grammar', underline=0,
393
+ accelerator='Ctrl-o',
394
+ command=self.load_grammar)
395
+
396
+ filemenu.add_command(label='Save Grammar History', underline=13,
397
+ command=self.save_history)
398
+
399
+ filemenu.add_command(label='Exit', underline=1,
400
+ command=self.destroy, accelerator='Ctrl-q')
401
+ menubar.add_cascade(label='File', underline=0, menu=filemenu)
402
+
403
+ viewmenu = Menu(menubar, tearoff=0)
404
+ viewmenu.add_radiobutton(label='Tiny', variable=self._size,
405
+ underline=0, value=10, command=self.resize)
406
+ viewmenu.add_radiobutton(label='Small', variable=self._size,
407
+ underline=0, value=16, command=self.resize)
408
+ viewmenu.add_radiobutton(label='Medium', variable=self._size,
409
+ underline=0, value=20, command=self.resize)
410
+ viewmenu.add_radiobutton(label='Large', variable=self._size,
411
+ underline=0, value=24, command=self.resize)
412
+ viewmenu.add_radiobutton(label='Huge', variable=self._size,
413
+ underline=0, value=34, command=self.resize)
414
+ menubar.add_cascade(label='View', underline=0, menu=viewmenu)
415
+
416
+ devsetmenu = Menu(menubar, tearoff=0)
417
+ devsetmenu.add_radiobutton(label='50 sentences',
418
+ variable=self._devset_size,
419
+ value=50, command=self.set_devset_size)
420
+ devsetmenu.add_radiobutton(label='100 sentences',
421
+ variable=self._devset_size,
422
+ value=100, command=self.set_devset_size)
423
+ devsetmenu.add_radiobutton(label='200 sentences',
424
+ variable=self._devset_size,
425
+ value=200, command=self.set_devset_size)
426
+ devsetmenu.add_radiobutton(label='500 sentences',
427
+ variable=self._devset_size,
428
+ value=500, command=self.set_devset_size)
429
+ menubar.add_cascade(label='Development-Set', underline=0,
430
+ menu=devsetmenu)
431
+
432
+ helpmenu = Menu(menubar, tearoff=0)
433
+ helpmenu.add_command(label='About', underline=0,
434
+ command=self.about)
435
+ menubar.add_cascade(label='Help', underline=0, menu=helpmenu)
436
+
437
+ parent.config(menu=menubar)
438
+
439
+ def toggle_show_trace(self, *e):
440
+ if self._showing_trace:
441
+ self.show_devset()
442
+ else:
443
+ self.show_trace()
444
+ return 'break'
445
+
446
+
447
+ _SCALE_N = 5 # center on the last 5 examples.
448
+ _DRAW_LINES = False
449
+ def _eval_plot(self, *e, **config):
450
+ width = config.get('width', self.evalbox.winfo_width())
451
+ height = config.get('height', self.evalbox.winfo_height())
452
+
453
+ # Clear the canvas
454
+ self.evalbox.delete('all')
455
+
456
+ # Draw the precision & recall labels.
457
+ tag = self.evalbox.create_text(10, height//2-10, justify='left',
458
+ anchor='w', text='Precision')
459
+ left, right = self.evalbox.bbox(tag)[2] + 5, width-10
460
+ tag = self.evalbox.create_text(left + (width-left)//2, height-10,
461
+ anchor='s', text='Recall', justify='center')
462
+ top, bot = 10, self.evalbox.bbox(tag)[1]-10
463
+
464
+ # Draw masks for clipping the plot.
465
+ bg = self._EVALBOX_PARAMS['background']
466
+ self.evalbox.lower(self.evalbox.create_rectangle(0, 0, left-1, 5000,
467
+ fill=bg, outline=bg))
468
+ self.evalbox.lower(self.evalbox.create_rectangle(0, bot+1, 5000, 5000,
469
+ fill=bg, outline=bg))
470
+
471
+ # Calculate the plot's scale.
472
+ if self._autoscale.get() and len(self._history) > 1:
473
+ max_precision = max_recall = 0
474
+ min_precision = min_recall = 1
475
+ for i in range(1, min(len(self._history), self._SCALE_N+1)):
476
+ grammar, precision, recall, fmeasure = self._history[-i]
477
+ min_precision = min(precision, min_precision)
478
+ min_recall = min(recall, min_recall)
479
+ max_precision = max(precision, max_precision)
480
+ max_recall = max(recall, max_recall)
481
+ # if max_precision-min_precision > max_recall-min_recall:
482
+ # min_recall -= (max_precision-min_precision)/2
483
+ # max_recall += (max_precision-min_precision)/2
484
+ # else:
485
+ # min_precision -= (max_recall-min_recall)/2
486
+ # max_precision += (max_recall-min_recall)/2
487
+ # if min_recall < 0:
488
+ # max_recall -= min_recall
489
+ # min_recall = 0
490
+ # if min_precision < 0:
491
+ # max_precision -= min_precision
492
+ # min_precision = 0
493
+ min_precision = max(min_precision-.01, 0)
494
+ min_recall = max(min_recall-.01, 0)
495
+ max_precision = min(max_precision+.01, 1)
496
+ max_recall = min(max_recall+.01, 1)
497
+ else:
498
+ min_precision = min_recall = 0
499
+ max_precision = max_recall = 1
500
+
501
+ # Draw the axis lines & grid lines
502
+ for i in range(11):
503
+ x = left + (right-left)*((i/10.-min_recall)/
504
+ (max_recall-min_recall))
505
+ y = bot - (bot-top)*((i/10.-min_precision)/
506
+ (max_precision-min_precision))
507
+ if left < x < right:
508
+ self.evalbox.create_line(x, top, x, bot, fill='#888')
509
+ if top < y < bot:
510
+ self.evalbox.create_line(left, y, right, y, fill='#888')
511
+ self.evalbox.create_line(left, top, left, bot)
512
+ self.evalbox.create_line(left, bot, right, bot)
513
+
514
+ # Display the plot's scale
515
+ self.evalbox.create_text(
516
+ left-3, bot, justify='right', anchor='se',
517
+ text='%d%%' % (100*min_precision))
518
+ self.evalbox.create_text(
519
+ left-3, top, justify='right', anchor='ne',
520
+ text='%d%%' % (100*max_precision))
521
+ self.evalbox.create_text(
522
+ left, bot+3, justify='center', anchor='nw',
523
+ text='%d%%' % (100*min_recall))
524
+ self.evalbox.create_text(
525
+ right, bot+3, justify='center', anchor='ne',
526
+ text='%d%%' % (100*max_recall))
527
+
528
+ # Display the scores.
529
+ prev_x = prev_y = None
530
+ for i, (_, precision, recall, fscore) in enumerate(self._history):
531
+ x = left + (right-left) * ((recall-min_recall) /
532
+ (max_recall-min_recall))
533
+ y = bot - (bot-top) * ((precision-min_precision) /
534
+ (max_precision-min_precision))
535
+ if i == self._history_index:
536
+ self.evalbox.create_oval(x-2,y-2,x+2,y+2,
537
+ fill='#0f0', outline='#000')
538
+ self.status['text'] = (
539
+ 'Precision: %.2f%%\t' % (precision*100)+
540
+ 'Recall: %.2f%%\t' % (recall*100)+
541
+ 'F-score: %.2f%%' % (fscore*100))
542
+ else:
543
+ self.evalbox.lower(
544
+ self.evalbox.create_oval(x-2,y-2,x+2,y+2,
545
+ fill='#afa', outline='#8c8'))
546
+ if prev_x is not None and self._eval_lines.get():
547
+ self.evalbox.lower(
548
+ self.evalbox.create_line(prev_x, prev_y, x, y,
549
+ fill='#8c8'))
550
+ prev_x, prev_y = x, y
551
+
552
+ _eval_demon_running = False
553
+ def _eval_demon(self):
554
+ if self.top is None: return
555
+ if self.chunker is None:
556
+ self._eval_demon_running = False
557
+ return
558
+
559
+ # Note our starting time.
560
+ t0 = time.time()
561
+
562
+ # If are still typing, then wait for them to finish.
563
+ if (time.time()-self._last_keypress < self._EVAL_DELAY and
564
+ self.normalized_grammar != self._eval_normalized_grammar):
565
+ self._eval_demon_running = True
566
+ return self.top.after(int(self._EVAL_FREQ*1000), self._eval_demon)
567
+
568
+ # If the grammar changed, restart the evaluation.
569
+ if self.normalized_grammar != self._eval_normalized_grammar:
570
+ # Check if we've seen this grammar already. If so, then
571
+ # just use the old evaluation values.
572
+ for (g, p, r, f) in self._history:
573
+ if self.normalized_grammar == self.normalize_grammar(g):
574
+ self._history.append( (g, p, r, f) )
575
+ self._history_index = len(self._history) - 1
576
+ self._eval_plot()
577
+ self._eval_demon_running = False
578
+ self._eval_normalized_grammar = None
579
+ return
580
+ self._eval_index = 0
581
+ self._eval_score = ChunkScore(chunk_label=self._chunk_label)
582
+ self._eval_grammar = self.grammar
583
+ self._eval_normalized_grammar = self.normalized_grammar
584
+
585
+ # If the grammar is empty, the don't bother evaluating it, or
586
+ # recording it in history -- the score will just be 0.
587
+ if self.normalized_grammar.strip() == '':
588
+ #self._eval_index = self._devset_size.get()
589
+ self._eval_demon_running = False
590
+ return
591
+
592
+ # Score the next set of examples
593
+ for gold in self.devset[self._eval_index:
594
+ min(self._eval_index+self._EVAL_CHUNK,
595
+ self._devset_size.get())]:
596
+ guess = self._chunkparse(gold.leaves())
597
+ self._eval_score.score(gold, guess)
598
+
599
+ # update our index in the devset.
600
+ self._eval_index += self._EVAL_CHUNK
601
+
602
+ # Check if we're done
603
+ if self._eval_index >= self._devset_size.get():
604
+ self._history.append( (self._eval_grammar,
605
+ self._eval_score.precision(),
606
+ self._eval_score.recall(),
607
+ self._eval_score.f_measure()) )
608
+ self._history_index = len(self._history)-1
609
+ self._eval_plot()
610
+ self._eval_demon_running = False
611
+ self._eval_normalized_grammar = None
612
+ else:
613
+ progress = 100*self._eval_index/self._devset_size.get()
614
+ self.status['text'] = ('Evaluating on Development Set (%d%%)' %
615
+ progress)
616
+ self._eval_demon_running = True
617
+ self._adaptively_modify_eval_chunk(time.time() - t0)
618
+ self.top.after(int(self._EVAL_FREQ*1000), self._eval_demon)
619
+
620
+ def _adaptively_modify_eval_chunk(self, t):
621
+ """
622
+ Modify _EVAL_CHUNK to try to keep the amount of time that the
623
+ eval demon takes between _EVAL_DEMON_MIN and _EVAL_DEMON_MAX.
624
+
625
+ :param t: The amount of time that the eval demon took.
626
+ """
627
+ if t > self._EVAL_DEMON_MAX and self._EVAL_CHUNK > 5:
628
+ self._EVAL_CHUNK = min(self._EVAL_CHUNK-1,
629
+ max(int(self._EVAL_CHUNK*(self._EVAL_DEMON_MAX/t)),
630
+ self._EVAL_CHUNK-10))
631
+ elif t < self._EVAL_DEMON_MIN:
632
+ self._EVAL_CHUNK = max(self._EVAL_CHUNK+1,
633
+ min(int(self._EVAL_CHUNK*(self._EVAL_DEMON_MIN/t)),
634
+ self._EVAL_CHUNK+10))
635
+
636
+ def _init_widgets(self, top):
637
+ frame0 = Frame(top, **self._FRAME_PARAMS)
638
+ frame0.grid_columnconfigure(0, weight=4)
639
+ frame0.grid_columnconfigure(3, weight=2)
640
+ frame0.grid_rowconfigure(1, weight=1)
641
+ frame0.grid_rowconfigure(5, weight=1)
642
+
643
+ # The grammar
644
+ self.grammarbox = Text(frame0, font=self._font,
645
+ **self._GRAMMARBOX_PARAMS)
646
+ self.grammarlabel = Label(frame0, font=self._font, text='Grammar:',
647
+ highlightcolor='black',
648
+ background=self._GRAMMARBOX_PARAMS['background'])
649
+ self.grammarlabel.grid(column=0, row=0, sticky='SW')
650
+ self.grammarbox.grid(column=0, row=1, sticky='NEWS')
651
+
652
+ # Scroll bar for grammar
653
+ grammar_scrollbar = Scrollbar(frame0, command=self.grammarbox.yview)
654
+ grammar_scrollbar.grid(column=1, row=1, sticky='NWS')
655
+ self.grammarbox.config(yscrollcommand=grammar_scrollbar.set)
656
+
657
+ # grammar buttons
658
+ bg = self._FRAME_PARAMS['background']
659
+ frame3 = Frame(frame0, background=bg)
660
+ frame3.grid(column=0, row=2, sticky='EW')
661
+ Button(frame3, text='Prev Grammar', command=self._history_prev,
662
+ **self._BUTTON_PARAMS).pack(side='left')
663
+ Button(frame3, text='Next Grammar', command=self._history_next,
664
+ **self._BUTTON_PARAMS).pack(side='left')
665
+
666
+ # Help box
667
+ self.helpbox = Text(frame0, font=self._smallfont,
668
+ **self._HELPBOX_PARAMS)
669
+ self.helpbox.grid(column=3, row=1, sticky='NEWS')
670
+ self.helptabs = {}
671
+ bg = self._FRAME_PARAMS['background']
672
+ helptab_frame = Frame(frame0, background=bg)
673
+ helptab_frame.grid(column=3, row=0, sticky='SW')
674
+ for i, (tab, tabstops, text) in enumerate(self.HELP):
675
+ label = Label(helptab_frame, text=tab, font=self._smallfont)
676
+ label.grid(column=i*2, row=0, sticky='S')
677
+ #help_frame.grid_columnconfigure(i, weight=1)
678
+ #label.pack(side='left')
679
+ label.bind('<ButtonPress>', lambda e, tab=tab: self.show_help(tab))
680
+ self.helptabs[tab] = label
681
+ Frame(helptab_frame, height=1, width=self._HELPTAB_SPACER,
682
+ background=bg).grid(column=i*2+1, row=0)
683
+ self.helptabs[self.HELP[0][0]].configure(font=self._font)
684
+ self.helpbox.tag_config('elide', elide=True)
685
+ for (tag, params) in self.HELP_AUTOTAG:
686
+ self.helpbox.tag_config('tag-%s' % tag, **params)
687
+ self.show_help(self.HELP[0][0])
688
+
689
+ # Scroll bar for helpbox
690
+ help_scrollbar = Scrollbar(frame0, command=self.helpbox.yview)
691
+ self.helpbox.config(yscrollcommand=help_scrollbar.set)
692
+ help_scrollbar.grid(column=4, row=1, sticky='NWS')
693
+
694
+ # The dev set
695
+ frame4 = Frame(frame0, background=self._FRAME_PARAMS['background'])
696
+ self.devsetbox = Text(frame4, font=self._font,
697
+ **self._DEVSETBOX_PARAMS)
698
+ self.devsetbox.pack(expand=True, fill='both')
699
+ self.devsetlabel = Label(frame0, font=self._font,
700
+ text='Development Set:', justify='right',
701
+ background=self._DEVSETBOX_PARAMS['background'])
702
+ self.devsetlabel.grid(column=0, row=4, sticky='SW')
703
+ frame4.grid(column=0, row=5, sticky='NEWS')
704
+
705
+ # dev set scrollbars
706
+ self.devset_scroll = Scrollbar(frame0, command=self._devset_scroll)
707
+ self.devset_scroll.grid(column=1, row=5, sticky='NWS')
708
+ self.devset_xscroll = Scrollbar(frame4, command=self.devsetbox.xview,
709
+ orient='horiz')
710
+ self.devsetbox['xscrollcommand'] = self.devset_xscroll.set
711
+ self.devset_xscroll.pack(side='bottom', fill='x')
712
+
713
+ # dev set buttons
714
+ bg = self._FRAME_PARAMS['background']
715
+ frame1 = Frame(frame0, background=bg)
716
+ frame1.grid(column=0, row=7, sticky='EW')
717
+ Button(frame1, text='Prev Example (Ctrl-p)',
718
+ command=self._devset_prev,
719
+ **self._BUTTON_PARAMS).pack(side='left')
720
+ Button(frame1, text='Next Example (Ctrl-n)',
721
+ command=self._devset_next,
722
+ **self._BUTTON_PARAMS).pack(side='left')
723
+ self.devset_button = Button(frame1, text='Show example',
724
+ command=self.show_devset,
725
+ state='disabled',
726
+ **self._BUTTON_PARAMS)
727
+ self.devset_button.pack(side='right')
728
+ self.trace_button = Button(frame1, text='Show trace',
729
+ command=self.show_trace,
730
+ **self._BUTTON_PARAMS)
731
+ self.trace_button.pack(side='right')
732
+
733
+
734
+ # evaluation box
735
+ self.evalbox = Canvas(frame0, **self._EVALBOX_PARAMS)
736
+ label = Label(frame0, font=self._font, text='Evaluation:',
737
+ justify='right', background=self._EVALBOX_PARAMS['background'])
738
+ label.grid(column=3, row=4, sticky='SW')
739
+ self.evalbox.grid(column=3, row=5, sticky='NEWS', columnspan=2)
740
+
741
+ # evaluation box buttons
742
+ bg = self._FRAME_PARAMS['background']
743
+ frame2 = Frame(frame0, background=bg)
744
+ frame2.grid(column=3, row=7, sticky='EW')
745
+ self._autoscale = IntVar(self.top)
746
+ self._autoscale.set(False)
747
+ Checkbutton(frame2, variable=self._autoscale, command=self._eval_plot,
748
+ text='Zoom', **self._BUTTON_PARAMS).pack(side='left')
749
+ self._eval_lines = IntVar(self.top)
750
+ self._eval_lines.set(False)
751
+ Checkbutton(frame2, variable=self._eval_lines, command=self._eval_plot,
752
+ text='Lines', **self._BUTTON_PARAMS).pack(side='left')
753
+ Button(frame2, text='History',
754
+ **self._BUTTON_PARAMS).pack(side='right')
755
+
756
+ # The status label
757
+ self.status = Label(frame0, font=self._font, **self._STATUS_PARAMS)
758
+ self.status.grid(column=0, row=9, sticky='NEW', padx=3, pady=2,
759
+ columnspan=5)
760
+
761
+ # Help box & devset box can't be edited.
762
+ self.helpbox['state'] = 'disabled'
763
+ self.devsetbox['state'] = 'disabled'
764
+
765
+ # Spacers
766
+ bg = self._FRAME_PARAMS['background']
767
+ Frame(frame0, height=10, width=0, background=bg).grid(column=0, row=3)
768
+ Frame(frame0, height=0, width=10, background=bg).grid(column=2, row=0)
769
+ Frame(frame0, height=6, width=0, background=bg).grid(column=0, row=8)
770
+
771
+ # pack the frame.
772
+ frame0.pack(fill='both', expand=True)
773
+
774
+ # Set up colors for the devset box
775
+ self.devsetbox.tag_config('true-pos', background='#afa',
776
+ underline='True')
777
+ self.devsetbox.tag_config('false-neg', underline='True',
778
+ foreground='#800')
779
+ self.devsetbox.tag_config('false-pos', background='#faa')
780
+ self.devsetbox.tag_config('trace', foreground='#666', wrap='none')
781
+ self.devsetbox.tag_config('wrapindent', lmargin2=30, wrap='none')
782
+ self.devsetbox.tag_config('error', foreground='#800')
783
+
784
+ # And for the grammarbox
785
+ self.grammarbox.tag_config('error', background='#fec')
786
+ self.grammarbox.tag_config('comment', foreground='#840')
787
+ self.grammarbox.tag_config('angle', foreground='#00f')
788
+ self.grammarbox.tag_config('brace', foreground='#0a0')
789
+ self.grammarbox.tag_config('hangindent', lmargin1=0, lmargin2=40)
790
+
791
+ _showing_trace = False
792
+ def show_trace(self, *e):
793
+ self._showing_trace = True
794
+ self.trace_button['state'] = 'disabled'
795
+ self.devset_button['state'] = 'normal'
796
+
797
+ self.devsetbox['state'] = 'normal'
798
+ #self.devsetbox['wrap'] = 'none'
799
+ self.devsetbox.delete('1.0', 'end')
800
+ self.devsetlabel['text']='Development Set (%d/%d)' % (
801
+ (self.devset_index+1, self._devset_size.get()))
802
+
803
+ if self.chunker is None:
804
+ self.devsetbox.insert('1.0', 'Trace: waiting for a valid grammar.')
805
+ self.devsetbox.tag_add('error', '1.0', 'end')
806
+ return # can't do anything more
807
+
808
+ gold_tree = self.devset[self.devset_index]
809
+ rules = self.chunker.rules()
810
+
811
+ # Calculate the tag sequence
812
+ tagseq = '\t'
813
+ charnum = [1]
814
+ for wordnum, (word, pos) in enumerate(gold_tree.leaves()):
815
+ tagseq += '%s ' % pos
816
+ charnum.append(len(tagseq))
817
+ self.charnum = dict(((i, j), charnum[j])
818
+ for i in range(len(rules)+1)
819
+ for j in range(len(charnum)))
820
+ self.linenum = dict((i,i*2+2) for i in range(len(rules)+1))
821
+
822
+ for i in range(len(rules)+1):
823
+ if i == 0:
824
+ self.devsetbox.insert('end', 'Start:\n')
825
+ self.devsetbox.tag_add('trace', 'end -2c linestart', 'end -2c')
826
+ else:
827
+ self.devsetbox.insert('end', 'Apply %s:\n' % rules[i-1])
828
+ self.devsetbox.tag_add('trace', 'end -2c linestart', 'end -2c')
829
+ # Display the tag sequence.
830
+ self.devsetbox.insert('end', tagseq+'\n')
831
+ self.devsetbox.tag_add('wrapindent','end -2c linestart','end -2c')
832
+ # Run a partial parser, and extract gold & test chunks
833
+ chunker = RegexpChunkParser(rules[:i])
834
+ test_tree = self._chunkparse(gold_tree.leaves())
835
+ gold_chunks = self._chunks(gold_tree)
836
+ test_chunks = self._chunks(test_tree)
837
+ # Compare them.
838
+ for chunk in gold_chunks.intersection(test_chunks):
839
+ self._color_chunk(i, chunk, 'true-pos')
840
+ for chunk in gold_chunks - test_chunks:
841
+ self._color_chunk(i, chunk, 'false-neg')
842
+ for chunk in test_chunks - gold_chunks:
843
+ self._color_chunk(i, chunk, 'false-pos')
844
+ self.devsetbox.insert('end', 'Finished.\n')
845
+ self.devsetbox.tag_add('trace', 'end -2c linestart', 'end -2c')
846
+
847
+ # This is a hack, because the x-scrollbar isn't updating its
848
+ # position right -- I'm not sure what the underlying cause is
849
+ # though. (This is on OS X w/ python 2.5)
850
+ self.top.after(100, self.devset_xscroll.set, 0, .3)
851
+
852
+ def show_help(self, tab):
853
+ self.helpbox['state'] = 'normal'
854
+ self.helpbox.delete('1.0', 'end')
855
+ for (name, tabstops, text) in self.HELP:
856
+ if name == tab:
857
+ text = text.replace('<<TAGSET>>', '\n'.join(
858
+ ('\t%s\t%s' % item for item in sorted(list(self.tagset.items()),
859
+ key=lambda t_w:re.match('\w+',t_w[0]) and (0,t_w[0]) or (1,t_w[0])))))
860
+
861
+ self.helptabs[name].config(**self._HELPTAB_FG_PARAMS)
862
+ self.helpbox.config(tabs=tabstops)
863
+ self.helpbox.insert('1.0', text+'\n'*20)
864
+ C = '1.0 + %d chars'
865
+ for (tag, params) in self.HELP_AUTOTAG:
866
+ pattern = '(?s)(<%s>)(.*?)(</%s>)' % (tag, tag)
867
+ for m in re.finditer(pattern, text):
868
+ self.helpbox.tag_add('elide',
869
+ C % m.start(1), C % m.end(1))
870
+ self.helpbox.tag_add('tag-%s' % tag,
871
+ C % m.start(2), C % m.end(2))
872
+ self.helpbox.tag_add('elide',
873
+ C % m.start(3), C % m.end(3))
874
+ else:
875
+ self.helptabs[name].config(**self._HELPTAB_BG_PARAMS)
876
+ self.helpbox['state'] = 'disabled'
877
+
878
+ def _history_prev(self, *e):
879
+ self._view_history(self._history_index-1)
880
+ return 'break'
881
+
882
+ def _history_next(self, *e):
883
+ self._view_history(self._history_index+1)
884
+ return 'break'
885
+
886
+ def _view_history(self, index):
887
+ # Bounds & sanity checking:
888
+ index = max(0, min(len(self._history)-1, index))
889
+ if not self._history: return
890
+ # Already viewing the requested history item?
891
+ if index == self._history_index:
892
+ return
893
+ # Show the requested grammar. It will get added to _history
894
+ # only if they edit it (causing self.update() to get run.)
895
+ self.grammarbox['state'] = 'normal'
896
+ self.grammarbox.delete('1.0', 'end')
897
+ self.grammarbox.insert('end', self._history[index][0])
898
+ self.grammarbox.mark_set('insert', '1.0')
899
+ self._history_index = index
900
+ self._syntax_highlight_grammar(self._history[index][0])
901
+ # Record the normalized grammar & regenerate the chunker.
902
+ self.normalized_grammar = self.normalize_grammar(
903
+ self._history[index][0])
904
+ if self.normalized_grammar:
905
+ rules = [RegexpChunkRule.fromstring(line)
906
+ for line in self.normalized_grammar.split('\n')]
907
+ else:
908
+ rules = []
909
+ self.chunker = RegexpChunkParser(rules)
910
+ # Show the score.
911
+ self._eval_plot()
912
+ # Update the devset box
913
+ self._highlight_devset()
914
+ if self._showing_trace: self.show_trace()
915
+ # Update the grammar label
916
+ if self._history_index < len(self._history)-1:
917
+ self.grammarlabel['text'] = 'Grammar %s/%s:' % (
918
+ self._history_index+1, len(self._history))
919
+ else:
920
+ self.grammarlabel['text'] = 'Grammar:'
921
+
922
+ def _devset_next(self, *e):
923
+ self._devset_scroll('scroll', 1, 'page')
924
+ return 'break'
925
+
926
+ def _devset_prev(self, *e):
927
+ self._devset_scroll('scroll', -1, 'page')
928
+ return 'break'
929
+
930
+ def destroy(self, *e):
931
+ if self.top is None: return
932
+ self.top.destroy()
933
+ self.top = None
934
+
935
+ def _devset_scroll(self, command, *args):
936
+ N = 1 # size of a page -- one sentence.
937
+ showing_trace = self._showing_trace
938
+ if command == 'scroll' and args[1].startswith('unit'):
939
+ self.show_devset(self.devset_index+int(args[0]))
940
+ elif command == 'scroll' and args[1].startswith('page'):
941
+ self.show_devset(self.devset_index+N*int(args[0]))
942
+ elif command == 'moveto':
943
+ self.show_devset(int(float(args[0])*self._devset_size.get()))
944
+ else:
945
+ assert 0, 'bad scroll command %s %s' % (command, args)
946
+ if showing_trace:
947
+ self.show_trace()
948
+
949
+ def show_devset(self, index=None):
950
+ if index is None: index = self.devset_index
951
+
952
+ # Bounds checking
953
+ index = min(max(0, index), self._devset_size.get()-1)
954
+
955
+ if index == self.devset_index and not self._showing_trace: return
956
+ self.devset_index = index
957
+
958
+ self._showing_trace = False
959
+ self.trace_button['state'] = 'normal'
960
+ self.devset_button['state'] = 'disabled'
961
+
962
+ # Clear the text box.
963
+ self.devsetbox['state'] = 'normal'
964
+ self.devsetbox['wrap'] = 'word'
965
+ self.devsetbox.delete('1.0', 'end')
966
+ self.devsetlabel['text']='Development Set (%d/%d)' % (
967
+ (self.devset_index+1, self._devset_size.get()))
968
+
969
+ # Add the sentences
970
+ sample = self.devset[self.devset_index:self.devset_index+1]
971
+ self.charnum = {}
972
+ self.linenum = {0:1}
973
+ for sentnum, sent in enumerate(sample):
974
+ linestr = ''
975
+ for wordnum, (word, pos) in enumerate(sent.leaves()):
976
+ self.charnum[sentnum, wordnum] = len(linestr)
977
+ linestr += '%s/%s ' % (word, pos)
978
+ self.charnum[sentnum, wordnum+1] = len(linestr)
979
+ self.devsetbox.insert('end', linestr[:-1]+'\n\n')
980
+
981
+ # Highlight chunks in the dev set
982
+ if self.chunker is not None:
983
+ self._highlight_devset()
984
+ self.devsetbox['state'] = 'disabled'
985
+
986
+ # Update the scrollbar
987
+ first = self.devset_index/self._devset_size.get()
988
+ last = (self.devset_index + 2) / self._devset_size.get()
989
+ self.devset_scroll.set(first, last)
990
+
991
+ def _chunks(self, tree):
992
+ chunks = set()
993
+ wordnum = 0
994
+ for child in tree:
995
+ if isinstance(child, Tree):
996
+ if child.label() == self._chunk_label:
997
+ chunks.add( (wordnum, wordnum+len(child)) )
998
+ wordnum += len(child)
999
+ else:
1000
+ wordnum += 1
1001
+ return chunks
1002
+
1003
+ def _syntax_highlight_grammar(self, grammar):
1004
+ if self.top is None: return
1005
+ self.grammarbox.tag_remove('comment', '1.0', 'end')
1006
+ self.grammarbox.tag_remove('angle', '1.0', 'end')
1007
+ self.grammarbox.tag_remove('brace', '1.0', 'end')
1008
+ self.grammarbox.tag_add('hangindent', '1.0', 'end')
1009
+ for lineno, line in enumerate(grammar.split('\n')):
1010
+ if not line.strip(): continue
1011
+ m = re.match(r'(\\.|[^#])*(#.*)?', line)
1012
+ comment_start = None
1013
+ if m.group(2):
1014
+ comment_start = m.start(2)
1015
+ s = '%d.%d' % (lineno+1, m.start(2))
1016
+ e = '%d.%d' % (lineno+1, m.end(2))
1017
+ self.grammarbox.tag_add('comment', s, e)
1018
+ for m in re.finditer('[<>{}]', line):
1019
+ if comment_start is not None and m.start() >= comment_start:
1020
+ break
1021
+ s = '%d.%d' % (lineno+1, m.start())
1022
+ e = '%d.%d' % (lineno+1, m.end())
1023
+ if m.group() in '<>':
1024
+ self.grammarbox.tag_add('angle', s, e)
1025
+ else:
1026
+ self.grammarbox.tag_add('brace', s, e)
1027
+
1028
+
1029
+ def _grammarcheck(self, grammar):
1030
+ if self.top is None: return
1031
+ self.grammarbox.tag_remove('error', '1.0', 'end')
1032
+ self._grammarcheck_errs = []
1033
+ for lineno, line in enumerate(grammar.split('\n')):
1034
+ line = re.sub(r'((\\.|[^#])*)(#.*)?', r'\1', line)
1035
+ line = line.strip()
1036
+ if line:
1037
+ try:
1038
+ RegexpChunkRule.fromstring(line)
1039
+ except ValueError as e:
1040
+ self.grammarbox.tag_add('error', '%s.0' % (lineno+1),
1041
+ '%s.0 lineend' % (lineno+1))
1042
+ self.status['text'] = ''
1043
+
1044
+ def update(self, *event):
1045
+ # Record when update was called (for grammarcheck)
1046
+ if event:
1047
+ self._last_keypress = time.time()
1048
+
1049
+ # Read the grammar from the Text box.
1050
+ self.grammar = grammar = self.grammarbox.get('1.0', 'end')
1051
+
1052
+ # If the grammar hasn't changed, do nothing:
1053
+ normalized_grammar = self.normalize_grammar(grammar)
1054
+ if normalized_grammar == self.normalized_grammar:
1055
+ return
1056
+ else:
1057
+ self.normalized_grammar = normalized_grammar
1058
+
1059
+ # If the grammar has changed, and we're looking at history,
1060
+ # then stop looking at history.
1061
+ if self._history_index < len(self._history)-1:
1062
+ self.grammarlabel['text'] = 'Grammar:'
1063
+
1064
+ self._syntax_highlight_grammar(grammar)
1065
+
1066
+ # The grammar has changed; try parsing it. If it doesn't
1067
+ # parse, do nothing. (flag error location?)
1068
+ try:
1069
+ # Note: the normalized grammar has no blank lines.
1070
+ if normalized_grammar:
1071
+ rules = [RegexpChunkRule.fromstring(line)
1072
+ for line in normalized_grammar.split('\n')]
1073
+ else:
1074
+ rules = []
1075
+ except ValueError as e:
1076
+ # Use the un-normalized grammar for error highlighting.
1077
+ self._grammarcheck(grammar)
1078
+ self.chunker = None
1079
+ return
1080
+
1081
+ self.chunker = RegexpChunkParser(rules)
1082
+ self.grammarbox.tag_remove('error', '1.0', 'end')
1083
+ self.grammar_changed = time.time()
1084
+ # Display the results
1085
+ if self._showing_trace:
1086
+ self.show_trace()
1087
+ else:
1088
+ self._highlight_devset()
1089
+ # Start the eval demon
1090
+ if not self._eval_demon_running:
1091
+ self._eval_demon()
1092
+
1093
+ def _highlight_devset(self, sample=None):
1094
+ if sample is None:
1095
+ sample = self.devset[self.devset_index:self.devset_index+1]
1096
+
1097
+ self.devsetbox.tag_remove('true-pos', '1.0', 'end')
1098
+ self.devsetbox.tag_remove('false-neg', '1.0', 'end')
1099
+ self.devsetbox.tag_remove('false-pos', '1.0', 'end')
1100
+
1101
+ # Run the grammar on the test cases.
1102
+ for sentnum, gold_tree in enumerate(sample):
1103
+ # Run the chunk parser
1104
+ test_tree = self._chunkparse(gold_tree.leaves())
1105
+ # Extract gold & test chunks
1106
+ gold_chunks = self._chunks(gold_tree)
1107
+ test_chunks = self._chunks(test_tree)
1108
+ # Compare them.
1109
+ for chunk in gold_chunks.intersection(test_chunks):
1110
+ self._color_chunk(sentnum, chunk, 'true-pos')
1111
+ for chunk in gold_chunks - test_chunks:
1112
+ self._color_chunk(sentnum, chunk, 'false-neg')
1113
+ for chunk in test_chunks - gold_chunks:
1114
+ self._color_chunk(sentnum, chunk, 'false-pos')
1115
+
1116
+ def _chunkparse(self, words):
1117
+ try:
1118
+ return self.chunker.parse(words)
1119
+ except (ValueError, IndexError) as e:
1120
+ # There's an error somewhere in the grammar, but we're not sure
1121
+ # exactly where, so just mark the whole grammar as bad.
1122
+ # E.g., this is caused by: "({<NN>})"
1123
+ self.grammarbox.tag_add('error', '1.0', 'end')
1124
+ # Treat it as tagging nothing:
1125
+ return words
1126
+
1127
+ def _color_chunk(self, sentnum, chunk, tag):
1128
+ start, end = chunk
1129
+ self.devsetbox.tag_add(tag,
1130
+ '%s.%s' % (self.linenum[sentnum], self.charnum[sentnum, start]),
1131
+ '%s.%s' % (self.linenum[sentnum], self.charnum[sentnum, end]-1))
1132
+
1133
+ def reset(self):
1134
+ # Clear various variables
1135
+ self.chunker = None
1136
+ self.grammar = None
1137
+ self.normalized_grammar = None
1138
+ self.grammar_changed = 0
1139
+ self._history = []
1140
+ self._history_index = 0
1141
+ # Update the on-screen display.
1142
+ self.grammarbox.delete('1.0', 'end')
1143
+ self.show_devset(0)
1144
+ self.update()
1145
+ #self._eval_plot()
1146
+
1147
+ SAVE_GRAMMAR_TEMPLATE = (
1148
+ '# Regexp Chunk Parsing Grammar\n'
1149
+ '# Saved %(date)s\n'
1150
+ '#\n'
1151
+ '# Development set: %(devset)s\n'
1152
+ '# Precision: %(precision)s\n'
1153
+ '# Recall: %(recall)s\n'
1154
+ '# F-score: %(fscore)s\n\n'
1155
+ '%(grammar)s\n')
1156
+
1157
+ def save_grammar(self, filename=None):
1158
+ if not filename:
1159
+ ftypes = [('Chunk Gramamr', '.chunk'),
1160
+ ('All files', '*')]
1161
+ filename = asksaveasfilename(filetypes=ftypes,
1162
+ defaultextension='.chunk')
1163
+ if not filename: return
1164
+ if (self._history and self.normalized_grammar ==
1165
+ self.normalize_grammar(self._history[-1][0])):
1166
+ precision, recall, fscore = ['%.2f%%' % (100*v) for v in
1167
+ self._history[-1][1:]]
1168
+ elif self.chunker is None:
1169
+ precision = recall = fscore = 'Grammar not well formed'
1170
+ else:
1171
+ precision = recall = fscore = 'Not finished evaluation yet'
1172
+
1173
+ with open(filename, 'w') as outfile:
1174
+ outfile.write(self.SAVE_GRAMMAR_TEMPLATE % dict(
1175
+ date=time.ctime(), devset=self.devset_name,
1176
+ precision=precision, recall=recall, fscore=fscore,
1177
+ grammar=self.grammar.strip()))
1178
+
1179
+ def load_grammar(self, filename=None):
1180
+ if not filename:
1181
+ ftypes = [('Chunk Gramamr', '.chunk'),
1182
+ ('All files', '*')]
1183
+ filename = askopenfilename(filetypes=ftypes,
1184
+ defaultextension='.chunk')
1185
+ if not filename: return
1186
+ self.grammarbox.delete('1.0', 'end')
1187
+ self.update()
1188
+ with open(filename, 'r') as infile:
1189
+ grammar = infile.read()
1190
+ grammar = re.sub('^\# Regexp Chunk Parsing Grammar[\s\S]*'
1191
+ 'F-score:.*\n', '', grammar).lstrip()
1192
+ self.grammarbox.insert('1.0', grammar)
1193
+ self.update()
1194
+
1195
+ def save_history(self, filename=None):
1196
+ if not filename:
1197
+ ftypes = [('Chunk Gramamr History', '.txt'),
1198
+ ('All files', '*')]
1199
+ filename = asksaveasfilename(filetypes=ftypes,
1200
+ defaultextension='.txt')
1201
+ if not filename: return
1202
+
1203
+ with open(filename, 'w') as outfile:
1204
+ outfile.write('# Regexp Chunk Parsing Grammar History\n')
1205
+ outfile.write('# Saved %s\n' % time.ctime())
1206
+ outfile.write('# Development set: %s\n' % self.devset_name)
1207
+ for i, (g, p, r, f) in enumerate(self._history):
1208
+ hdr = ('Grammar %d/%d (precision=%.2f%%, recall=%.2f%%, '
1209
+ 'fscore=%.2f%%)' % (i+1, len(self._history),
1210
+ p*100, r*100, f*100))
1211
+ outfile.write('\n%s\n' % hdr)
1212
+ outfile.write(''.join(' %s\n' % line for line in g.strip().split()))
1213
+
1214
+ if not (self._history and self.normalized_grammar ==
1215
+ self.normalize_grammar(self._history[-1][0])):
1216
+ if self.chunker is None:
1217
+ outfile.write('\nCurrent Grammar (not well-formed)\n')
1218
+ else:
1219
+ outfile.write('\nCurrent Grammar (not evaluated)\n')
1220
+ outfile.write(''.join(' %s\n' % line for line
1221
+ in self.grammar.strip().split()))
1222
+
1223
+ def about(self, *e):
1224
+ ABOUT = ("NLTK RegExp Chunk Parser Application\n"+
1225
+ "Written by Edward Loper")
1226
+ TITLE = 'About: Regular Expression Chunk Parser Application'
1227
+ try:
1228
+ from six.moves.tkinter_messagebox import Message
1229
+ Message(message=ABOUT, title=TITLE).show()
1230
+ except:
1231
+ ShowText(self.top, TITLE, ABOUT)
1232
+
1233
+ def set_devset_size(self, size=None):
1234
+ if size is not None: self._devset_size.set(size)
1235
+ self._devset_size.set(min(len(self.devset), self._devset_size.get()))
1236
+ self.show_devset(1)
1237
+ self.show_devset(0)
1238
+ # what about history? Evaluated at diff dev set sizes!
1239
+
1240
+ def resize(self, size=None):
1241
+ if size is not None: self._size.set(size)
1242
+ size = self._size.get()
1243
+ self._font.configure(size=-(abs(size)))
1244
+ self._smallfont.configure(size=min(-10, -(abs(size))*14//20))
1245
+
1246
+ def mainloop(self, *args, **kwargs):
1247
+ """
1248
+ Enter the Tkinter mainloop. This function must be called if
1249
+ this demo is created from a non-interactive program (e.g.
1250
+ from a secript); otherwise, the demo will close as soon as
1251
+ the script completes.
1252
+ """
1253
+ if in_idle(): return
1254
+ self.top.mainloop(*args, **kwargs)
1255
+
1256
+ def app():
1257
+ RegexpChunkApp().mainloop()
1258
+
1259
+ if __name__ == '__main__':
1260
+ app()
1261
+
1262
+ __all__ = ['app']