chunkparser_app.py 56 KB

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