/
chunkparser_app.py
1500 lines (1354 loc) · 55.5 KB
/
chunkparser_app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Natural Language Toolkit: Regexp Chunk Parser Application
#
# Copyright (C) 2001-2021 NLTK Project
# Author: Edward Loper <edloper@gmail.com>
# URL: <https://www.nltk.org/>
# For license information, see LICENSE.TXT
"""
A graphical tool for exploring the regular expression based chunk
parser ``nltk.chunk.RegexpChunkParser``.
"""
# Todo: Add a way to select the development set from the menubar. This
# might just need to be a selection box (conll vs treebank etc) plus
# configuration parameters to select what's being chunked (eg VP vs NP)
# and what part of the data is being used as the development set.
import random
import re
import textwrap
import time
from tkinter import (
Button,
Canvas,
Checkbutton,
Frame,
IntVar,
Label,
Menu,
Scrollbar,
Text,
Tk,
)
from tkinter.filedialog import askopenfilename, asksaveasfilename
from tkinter.font import Font
from nltk.chunk import ChunkScore, RegexpChunkParser
from nltk.chunk.regexp import RegexpChunkRule
from nltk.corpus import conll2000, treebank_chunk
from nltk.draw.util import ShowText
from nltk.tree import Tree
from nltk.util import in_idle
class RegexpChunkApp:
"""
A graphical tool for exploring the regular expression based chunk
parser ``nltk.chunk.RegexpChunkParser``.
See ``HELP`` for instructional text.
"""
##/////////////////////////////////////////////////////////////////
## Help Text
##/////////////////////////////////////////////////////////////////
#: A dictionary mapping from part of speech tags to descriptions,
#: which is used in the help text. (This should probably live with
#: the conll and/or treebank corpus instead.)
TAGSET = {
"CC": "Coordinating conjunction",
"PRP$": "Possessive pronoun",
"CD": "Cardinal number",
"RB": "Adverb",
"DT": "Determiner",
"RBR": "Adverb, comparative",
"EX": "Existential there",
"RBS": "Adverb, superlative",
"FW": "Foreign word",
"RP": "Particle",
"JJ": "Adjective",
"TO": "to",
"JJR": "Adjective, comparative",
"UH": "Interjection",
"JJS": "Adjective, superlative",
"VB": "Verb, base form",
"LS": "List item marker",
"VBD": "Verb, past tense",
"MD": "Modal",
"NNS": "Noun, plural",
"NN": "Noun, singular or masps",
"VBN": "Verb, past participle",
"VBZ": "Verb,3rd ps. sing. present",
"NNP": "Proper noun, singular",
"NNPS": "Proper noun plural",
"WDT": "wh-determiner",
"PDT": "Predeterminer",
"WP": "wh-pronoun",
"POS": "Possessive ending",
"WP$": "Possessive wh-pronoun",
"PRP": "Personal pronoun",
"WRB": "wh-adverb",
"(": "open parenthesis",
")": "close parenthesis",
"``": "open quote",
",": "comma",
"''": "close quote",
".": "period",
"#": "pound sign (currency marker)",
"$": "dollar sign (currency marker)",
"IN": "Preposition/subord. conjunction",
"SYM": "Symbol (mathematical or scientific)",
"VBG": "Verb, gerund/present participle",
"VBP": "Verb, non-3rd ps. sing. present",
":": "colon",
}
#: Contents for the help box. This is a list of tuples, one for
#: each help page, where each tuple has four elements:
#: - A title (displayed as a tab)
#: - A string description of tabstops (see Tkinter.Text for details)
#: - The text contents for the help page. You can use expressions
#: like <red>...</red> to colorize the text; see ``HELP_AUTOTAG``
#: for a list of tags you can use for colorizing.
HELP = [
(
"Help",
"20",
"Welcome to the regular expression chunk-parser grammar editor. "
"You can use this editor to develop and test chunk parser grammars "
"based on NLTK's RegexpChunkParser class.\n\n"
# Help box.
"Use this box ('Help') to learn more about the editor; click on the "
"tabs for help on specific topics:"
"<indent>\n"
"Rules: grammar rule types\n"
"Regexps: regular expression syntax\n"
"Tags: part of speech tags\n</indent>\n"
# Grammar.
"Use the upper-left box ('Grammar') to edit your grammar. "
"Each line of your grammar specifies a single 'rule', "
"which performs an action such as creating a chunk or merging "
"two chunks.\n\n"
# Dev set.
"The lower-left box ('Development Set') runs your grammar on the "
"development set, and displays the results. "
"Your grammar's chunks are <highlight>highlighted</highlight>, and "
"the correct (gold standard) chunks are "
"<underline>underlined</underline>. If they "
"match, they are displayed in <green>green</green>; otherwise, "
"they are displayed in <red>red</red>. The box displays a single "
"sentence from the development set at a time; use the scrollbar or "
"the next/previous buttons view additional sentences.\n\n"
# Performance
"The lower-right box ('Evaluation') tracks the performance of "
"your grammar on the development set. The 'precision' axis "
"indicates how many of your grammar's chunks are correct; and "
"the 'recall' axis indicates how many of the gold standard "
"chunks your system generated. Typically, you should try to "
"design a grammar that scores high on both metrics. The "
"exact precision and recall of the current grammar, as well "
"as their harmonic mean (the 'f-score'), are displayed in "
"the status bar at the bottom of the window.",
),
(
"Rules",
"10",
"<h1>{...regexp...}</h1>"
"<indent>\nChunk rule: creates new chunks from words matching "
"regexp.</indent>\n\n"
"<h1>}...regexp...{</h1>"
"<indent>\nStrip rule: removes words matching regexp from existing "
"chunks.</indent>\n\n"
"<h1>...regexp1...}{...regexp2...</h1>"
"<indent>\nSplit rule: splits chunks that match regexp1 followed by "
"regexp2 in two.</indent>\n\n"
"<h1>...regexp...{}...regexp...</h1>"
"<indent>\nMerge rule: joins consecutive chunks that match regexp1 "
"and regexp2</indent>\n",
),
(
"Regexps",
"10 60",
# "Regular Expression Syntax Summary:\n\n"
"<h1>Pattern\t\tMatches...</h1>\n"
"<hangindent>"
"\t<<var>T</var>>\ta word with tag <var>T</var> "
"(where <var>T</var> may be a regexp).\n"
"\t<var>x</var>?\tan optional <var>x</var>\n"
"\t<var>x</var>+\ta sequence of 1 or more <var>x</var>'s\n"
"\t<var>x</var>*\ta sequence of 0 or more <var>x</var>'s\n"
"\t<var>x</var>|<var>y</var>\t<var>x</var> or <var>y</var>\n"
"\t.\tmatches any character\n"
"\t(<var>x</var>)\tTreats <var>x</var> as a group\n"
"\t# <var>x...</var>\tTreats <var>x...</var> "
"(to the end of the line) as a comment\n"
"\t\\<var>C</var>\tmatches character <var>C</var> "
"(useful when <var>C</var> is a special character "
"like + or #)\n"
"</hangindent>"
"\n<h1>Examples:</h1>\n"
"<hangindent>"
"\t<regexp><NN></regexp>\n"
'\t\tMatches <match>"cow/NN"</match>\n'
'\t\tMatches <match>"green/NN"</match>\n'
"\t<regexp><VB.*></regexp>\n"
'\t\tMatches <match>"eating/VBG"</match>\n'
'\t\tMatches <match>"ate/VBD"</match>\n'
"\t<regexp><IN><DT><NN></regexp>\n"
'\t\tMatches <match>"on/IN the/DT car/NN"</match>\n'
"\t<regexp><RB>?<VBD></regexp>\n"
'\t\tMatches <match>"ran/VBD"</match>\n'
'\t\tMatches <match>"slowly/RB ate/VBD"</match>\n'
r"\t<regexp><\#><CD> # This is a comment...</regexp>\n"
'\t\tMatches <match>"#/# 100/CD"</match>\n'
"</hangindent>",
),
(
"Tags",
"10 60",
"<h1>Part of Speech Tags:</h1>\n"
+ "<hangindent>"
+ "<<TAGSET>>"
+ "</hangindent>\n", # this gets auto-substituted w/ self.TAGSET
),
]
HELP_AUTOTAG = [
("red", dict(foreground="#a00")),
("green", dict(foreground="#080")),
("highlight", dict(background="#ddd")),
("underline", dict(underline=True)),
("h1", dict(underline=True)),
("indent", dict(lmargin1=20, lmargin2=20)),
("hangindent", dict(lmargin1=0, lmargin2=60)),
("var", dict(foreground="#88f")),
("regexp", dict(foreground="#ba7")),
("match", dict(foreground="#6a6")),
]
##/////////////////////////////////////////////////////////////////
## Config Parameters
##/////////////////////////////////////////////////////////////////
_EVAL_DELAY = 1
"""If the user has not pressed any key for this amount of time (in
seconds), and the current grammar has not been evaluated, then
the eval demon will evaluate it."""
_EVAL_CHUNK = 15
"""The number of sentences that should be evaluated by the eval
demon each time it runs."""
_EVAL_FREQ = 0.2
"""The frequency (in seconds) at which the eval demon is run"""
_EVAL_DEMON_MIN = 0.02
"""The minimum amount of time that the eval demon should take each time
it runs -- if it takes less than this time, _EVAL_CHUNK will be
modified upwards."""
_EVAL_DEMON_MAX = 0.04
"""The maximum amount of time that the eval demon should take each time
it runs -- if it takes more than this time, _EVAL_CHUNK will be
modified downwards."""
_GRAMMARBOX_PARAMS = dict(
width=40,
height=12,
background="#efe",
highlightbackground="#efe",
highlightthickness=1,
relief="groove",
border=2,
wrap="word",
)
_HELPBOX_PARAMS = dict(
width=15,
height=15,
background="#efe",
highlightbackground="#efe",
foreground="#555",
highlightthickness=1,
relief="groove",
border=2,
wrap="word",
)
_DEVSETBOX_PARAMS = dict(
width=70,
height=10,
background="#eef",
highlightbackground="#eef",
highlightthickness=1,
relief="groove",
border=2,
wrap="word",
tabs=(30,),
)
_STATUS_PARAMS = dict(background="#9bb", relief="groove", border=2)
_FONT_PARAMS = dict(family="helvetica", size=-20)
_FRAME_PARAMS = dict(background="#777", padx=2, pady=2, border=3)
_EVALBOX_PARAMS = dict(
background="#eef",
highlightbackground="#eef",
highlightthickness=1,
relief="groove",
border=2,
width=300,
height=280,
)
_BUTTON_PARAMS = dict(
background="#777", activebackground="#777", highlightbackground="#777"
)
_HELPTAB_BG_COLOR = "#aba"
_HELPTAB_FG_COLOR = "#efe"
_HELPTAB_FG_PARAMS = dict(background="#efe")
_HELPTAB_BG_PARAMS = dict(background="#aba")
_HELPTAB_SPACER = 6
def normalize_grammar(self, grammar):
# Strip comments
grammar = re.sub(r"((\\.|[^#])*)(#.*)?", r"\1", grammar)
# Normalize whitespace
grammar = re.sub(" +", " ", grammar)
grammar = re.sub(r"\n\s+", r"\n", grammar)
grammar = grammar.strip()
# [xx] Hack: automatically backslash $!
grammar = re.sub(r"([^\\])\$", r"\1\\$", grammar)
return grammar
def __init__(
self,
devset_name="conll2000",
devset=None,
grammar="",
chunk_label="NP",
tagset=None,
):
"""
:param devset_name: The name of the development set; used for
display & for save files. If either the name 'treebank'
or the name 'conll2000' is used, and devset is None, then
devset will be set automatically.
:param devset: A list of chunked sentences
:param grammar: The initial grammar to display.
:param tagset: Dictionary from tags to string descriptions, used
for the help page. Defaults to ``self.TAGSET``.
"""
self._chunk_label = chunk_label
if tagset is None:
tagset = self.TAGSET
self.tagset = tagset
# Named development sets:
if devset is None:
if devset_name == "conll2000":
devset = conll2000.chunked_sents("train.txt") # [:100]
elif devset == "treebank":
devset = treebank_chunk.chunked_sents() # [:100]
else:
raise ValueError("Unknown development set %s" % devset_name)
self.chunker = None
"""The chunker built from the grammar string"""
self.grammar = grammar
"""The unparsed grammar string"""
self.normalized_grammar = None
"""A normalized version of ``self.grammar``."""
self.grammar_changed = 0
"""The last time() that the grammar was changed."""
self.devset = devset
"""The development set -- a list of chunked sentences."""
self.devset_name = devset_name
"""The name of the development set (for save files)."""
self.devset_index = -1
"""The index into the development set of the first instance
that's currently being viewed."""
self._last_keypress = 0
"""The time() when a key was most recently pressed"""
self._history = []
"""A list of (grammar, precision, recall, fscore) tuples for
grammars that the user has already tried."""
self._history_index = 0
"""When the user is scrolling through previous grammars, this
is used to keep track of which grammar they're looking at."""
self._eval_grammar = None
"""The grammar that is being currently evaluated by the eval
demon."""
self._eval_normalized_grammar = None
"""A normalized copy of ``_eval_grammar``."""
self._eval_index = 0
"""The index of the next sentence in the development set that
should be looked at by the eval demon."""
self._eval_score = ChunkScore(chunk_label=chunk_label)
"""The ``ChunkScore`` object that's used to keep track of the score
of the current grammar on the development set."""
# Set up the main window.
top = self.top = Tk()
top.geometry("+50+50")
top.title("Regexp Chunk Parser App")
top.bind("<Control-q>", self.destroy)
# Variable that restricts how much of the devset we look at.
self._devset_size = IntVar(top)
self._devset_size.set(100)
# Set up all the tkinter widgets
self._init_fonts(top)
self._init_widgets(top)
self._init_bindings(top)
self._init_menubar(top)
self.grammarbox.focus()
# If a grammar was given, then display it.
if grammar:
self.grammarbox.insert("end", grammar + "\n")
self.grammarbox.mark_set("insert", "1.0")
# Display the first item in the development set
self.show_devset(0)
self.update()
def _init_bindings(self, top):
top.bind("<Control-n>", self._devset_next)
top.bind("<Control-p>", self._devset_prev)
top.bind("<Control-t>", self.toggle_show_trace)
top.bind("<KeyPress>", self.update)
top.bind("<Control-s>", lambda e: self.save_grammar())
top.bind("<Control-o>", lambda e: self.load_grammar())
self.grammarbox.bind("<Control-t>", self.toggle_show_trace)
self.grammarbox.bind("<Control-n>", self._devset_next)
self.grammarbox.bind("<Control-p>", self._devset_prev)
# Redraw the eval graph when the window size changes
self.evalbox.bind("<Configure>", self._eval_plot)
def _init_fonts(self, top):
# TWhat's our font size (default=same as sysfont)
self._size = IntVar(top)
self._size.set(20)
self._font = Font(family="helvetica", size=-self._size.get())
self._smallfont = Font(
family="helvetica", size=-(int(self._size.get() * 14 // 20))
)
def _init_menubar(self, parent):
menubar = Menu(parent)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Reset Application", underline=0, command=self.reset)
filemenu.add_command(
label="Save Current Grammar",
underline=0,
accelerator="Ctrl-s",
command=self.save_grammar,
)
filemenu.add_command(
label="Load Grammar",
underline=0,
accelerator="Ctrl-o",
command=self.load_grammar,
)
filemenu.add_command(
label="Save Grammar History", underline=13, command=self.save_history
)
filemenu.add_command(
label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-q"
)
menubar.add_cascade(label="File", underline=0, menu=filemenu)
viewmenu = Menu(menubar, tearoff=0)
viewmenu.add_radiobutton(
label="Tiny",
variable=self._size,
underline=0,
value=10,
command=self.resize,
)
viewmenu.add_radiobutton(
label="Small",
variable=self._size,
underline=0,
value=16,
command=self.resize,
)
viewmenu.add_radiobutton(
label="Medium",
variable=self._size,
underline=0,
value=20,
command=self.resize,
)
viewmenu.add_radiobutton(
label="Large",
variable=self._size,
underline=0,
value=24,
command=self.resize,
)
viewmenu.add_radiobutton(
label="Huge",
variable=self._size,
underline=0,
value=34,
command=self.resize,
)
menubar.add_cascade(label="View", underline=0, menu=viewmenu)
devsetmenu = Menu(menubar, tearoff=0)
devsetmenu.add_radiobutton(
label="50 sentences",
variable=self._devset_size,
value=50,
command=self.set_devset_size,
)
devsetmenu.add_radiobutton(
label="100 sentences",
variable=self._devset_size,
value=100,
command=self.set_devset_size,
)
devsetmenu.add_radiobutton(
label="200 sentences",
variable=self._devset_size,
value=200,
command=self.set_devset_size,
)
devsetmenu.add_radiobutton(
label="500 sentences",
variable=self._devset_size,
value=500,
command=self.set_devset_size,
)
menubar.add_cascade(label="Development-Set", underline=0, menu=devsetmenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="About", underline=0, command=self.about)
menubar.add_cascade(label="Help", underline=0, menu=helpmenu)
parent.config(menu=menubar)
def toggle_show_trace(self, *e):
if self._showing_trace:
self.show_devset()
else:
self.show_trace()
return "break"
_SCALE_N = 5 # center on the last 5 examples.
_DRAW_LINES = False
def _eval_plot(self, *e, **config):
width = config.get("width", self.evalbox.winfo_width())
height = config.get("height", self.evalbox.winfo_height())
# Clear the canvas
self.evalbox.delete("all")
# Draw the precision & recall labels.
tag = self.evalbox.create_text(
10, height // 2 - 10, justify="left", anchor="w", text="Precision"
)
left, right = self.evalbox.bbox(tag)[2] + 5, width - 10
tag = self.evalbox.create_text(
left + (width - left) // 2,
height - 10,
anchor="s",
text="Recall",
justify="center",
)
top, bot = 10, self.evalbox.bbox(tag)[1] - 10
# Draw masks for clipping the plot.
bg = self._EVALBOX_PARAMS["background"]
self.evalbox.lower(
self.evalbox.create_rectangle(0, 0, left - 1, 5000, fill=bg, outline=bg)
)
self.evalbox.lower(
self.evalbox.create_rectangle(0, bot + 1, 5000, 5000, fill=bg, outline=bg)
)
# Calculate the plot's scale.
if self._autoscale.get() and len(self._history) > 1:
max_precision = max_recall = 0
min_precision = min_recall = 1
for i in range(1, min(len(self._history), self._SCALE_N + 1)):
grammar, precision, recall, fmeasure = self._history[-i]
min_precision = min(precision, min_precision)
min_recall = min(recall, min_recall)
max_precision = max(precision, max_precision)
max_recall = max(recall, max_recall)
# if max_precision-min_precision > max_recall-min_recall:
# min_recall -= (max_precision-min_precision)/2
# max_recall += (max_precision-min_precision)/2
# else:
# min_precision -= (max_recall-min_recall)/2
# max_precision += (max_recall-min_recall)/2
# if min_recall < 0:
# max_recall -= min_recall
# min_recall = 0
# if min_precision < 0:
# max_precision -= min_precision
# min_precision = 0
min_precision = max(min_precision - 0.01, 0)
min_recall = max(min_recall - 0.01, 0)
max_precision = min(max_precision + 0.01, 1)
max_recall = min(max_recall + 0.01, 1)
else:
min_precision = min_recall = 0
max_precision = max_recall = 1
# Draw the axis lines & grid lines
for i in range(11):
x = left + (right - left) * (
(i / 10.0 - min_recall) / (max_recall - min_recall)
)
y = bot - (bot - top) * (
(i / 10.0 - min_precision) / (max_precision - min_precision)
)
if left < x < right:
self.evalbox.create_line(x, top, x, bot, fill="#888")
if top < y < bot:
self.evalbox.create_line(left, y, right, y, fill="#888")
self.evalbox.create_line(left, top, left, bot)
self.evalbox.create_line(left, bot, right, bot)
# Display the plot's scale
self.evalbox.create_text(
left - 3,
bot,
justify="right",
anchor="se",
text="%d%%" % (100 * min_precision),
)
self.evalbox.create_text(
left - 3,
top,
justify="right",
anchor="ne",
text="%d%%" % (100 * max_precision),
)
self.evalbox.create_text(
left,
bot + 3,
justify="center",
anchor="nw",
text="%d%%" % (100 * min_recall),
)
self.evalbox.create_text(
right,
bot + 3,
justify="center",
anchor="ne",
text="%d%%" % (100 * max_recall),
)
# Display the scores.
prev_x = prev_y = None
for i, (_, precision, recall, fscore) in enumerate(self._history):
x = left + (right - left) * (
(recall - min_recall) / (max_recall - min_recall)
)
y = bot - (bot - top) * (
(precision - min_precision) / (max_precision - min_precision)
)
if i == self._history_index:
self.evalbox.create_oval(
x - 2, y - 2, x + 2, y + 2, fill="#0f0", outline="#000"
)
self.status["text"] = (
"Precision: %.2f%%\t" % (precision * 100)
+ "Recall: %.2f%%\t" % (recall * 100)
+ "F-score: %.2f%%" % (fscore * 100)
)
else:
self.evalbox.lower(
self.evalbox.create_oval(
x - 2, y - 2, x + 2, y + 2, fill="#afa", outline="#8c8"
)
)
if prev_x is not None and self._eval_lines.get():
self.evalbox.lower(
self.evalbox.create_line(prev_x, prev_y, x, y, fill="#8c8")
)
prev_x, prev_y = x, y
_eval_demon_running = False
def _eval_demon(self):
if self.top is None:
return
if self.chunker is None:
self._eval_demon_running = False
return
# Note our starting time.
t0 = time.time()
# If are still typing, then wait for them to finish.
if (
time.time() - self._last_keypress < self._EVAL_DELAY
and self.normalized_grammar != self._eval_normalized_grammar
):
self._eval_demon_running = True
return self.top.after(int(self._EVAL_FREQ * 1000), self._eval_demon)
# If the grammar changed, restart the evaluation.
if self.normalized_grammar != self._eval_normalized_grammar:
# Check if we've seen this grammar already. If so, then
# just use the old evaluation values.
for (g, p, r, f) in self._history:
if self.normalized_grammar == self.normalize_grammar(g):
self._history.append((g, p, r, f))
self._history_index = len(self._history) - 1
self._eval_plot()
self._eval_demon_running = False
self._eval_normalized_grammar = None
return
self._eval_index = 0
self._eval_score = ChunkScore(chunk_label=self._chunk_label)
self._eval_grammar = self.grammar
self._eval_normalized_grammar = self.normalized_grammar
# If the grammar is empty, the don't bother evaluating it, or
# recording it in history -- the score will just be 0.
if self.normalized_grammar.strip() == "":
# self._eval_index = self._devset_size.get()
self._eval_demon_running = False
return
# Score the next set of examples
for gold in self.devset[
self._eval_index : min(
self._eval_index + self._EVAL_CHUNK, self._devset_size.get()
)
]:
guess = self._chunkparse(gold.leaves())
self._eval_score.score(gold, guess)
# update our index in the devset.
self._eval_index += self._EVAL_CHUNK
# Check if we're done
if self._eval_index >= self._devset_size.get():
self._history.append(
(
self._eval_grammar,
self._eval_score.precision(),
self._eval_score.recall(),
self._eval_score.f_measure(),
)
)
self._history_index = len(self._history) - 1
self._eval_plot()
self._eval_demon_running = False
self._eval_normalized_grammar = None
else:
progress = 100 * self._eval_index / self._devset_size.get()
self.status["text"] = "Evaluating on Development Set (%d%%)" % progress
self._eval_demon_running = True
self._adaptively_modify_eval_chunk(time.time() - t0)
self.top.after(int(self._EVAL_FREQ * 1000), self._eval_demon)
def _adaptively_modify_eval_chunk(self, t):
"""
Modify _EVAL_CHUNK to try to keep the amount of time that the
eval demon takes between _EVAL_DEMON_MIN and _EVAL_DEMON_MAX.
:param t: The amount of time that the eval demon took.
"""
if t > self._EVAL_DEMON_MAX and self._EVAL_CHUNK > 5:
self._EVAL_CHUNK = min(
self._EVAL_CHUNK - 1,
max(
int(self._EVAL_CHUNK * (self._EVAL_DEMON_MAX / t)),
self._EVAL_CHUNK - 10,
),
)
elif t < self._EVAL_DEMON_MIN:
self._EVAL_CHUNK = max(
self._EVAL_CHUNK + 1,
min(
int(self._EVAL_CHUNK * (self._EVAL_DEMON_MIN / t)),
self._EVAL_CHUNK + 10,
),
)
def _init_widgets(self, top):
frame0 = Frame(top, **self._FRAME_PARAMS)
frame0.grid_columnconfigure(0, weight=4)
frame0.grid_columnconfigure(3, weight=2)
frame0.grid_rowconfigure(1, weight=1)
frame0.grid_rowconfigure(5, weight=1)
# The grammar
self.grammarbox = Text(frame0, font=self._font, **self._GRAMMARBOX_PARAMS)
self.grammarlabel = Label(
frame0,
font=self._font,
text="Grammar:",
highlightcolor="black",
background=self._GRAMMARBOX_PARAMS["background"],
)
self.grammarlabel.grid(column=0, row=0, sticky="SW")
self.grammarbox.grid(column=0, row=1, sticky="NEWS")
# Scroll bar for grammar
grammar_scrollbar = Scrollbar(frame0, command=self.grammarbox.yview)
grammar_scrollbar.grid(column=1, row=1, sticky="NWS")
self.grammarbox.config(yscrollcommand=grammar_scrollbar.set)
# grammar buttons
bg = self._FRAME_PARAMS["background"]
frame3 = Frame(frame0, background=bg)
frame3.grid(column=0, row=2, sticky="EW")
Button(
frame3,
text="Prev Grammar",
command=self._history_prev,
**self._BUTTON_PARAMS,
).pack(side="left")
Button(
frame3,
text="Next Grammar",
command=self._history_next,
**self._BUTTON_PARAMS,
).pack(side="left")
# Help box
self.helpbox = Text(frame0, font=self._smallfont, **self._HELPBOX_PARAMS)
self.helpbox.grid(column=3, row=1, sticky="NEWS")
self.helptabs = {}
bg = self._FRAME_PARAMS["background"]
helptab_frame = Frame(frame0, background=bg)
helptab_frame.grid(column=3, row=0, sticky="SW")
for i, (tab, tabstops, text) in enumerate(self.HELP):
label = Label(helptab_frame, text=tab, font=self._smallfont)
label.grid(column=i * 2, row=0, sticky="S")
# help_frame.grid_columnconfigure(i, weight=1)
# label.pack(side='left')
label.bind("<ButtonPress>", lambda e, tab=tab: self.show_help(tab))
self.helptabs[tab] = label
Frame(
helptab_frame, height=1, width=self._HELPTAB_SPACER, background=bg
).grid(column=i * 2 + 1, row=0)
self.helptabs[self.HELP[0][0]].configure(font=self._font)
self.helpbox.tag_config("elide", elide=True)
for (tag, params) in self.HELP_AUTOTAG:
self.helpbox.tag_config("tag-%s" % tag, **params)
self.show_help(self.HELP[0][0])
# Scroll bar for helpbox
help_scrollbar = Scrollbar(frame0, command=self.helpbox.yview)
self.helpbox.config(yscrollcommand=help_scrollbar.set)
help_scrollbar.grid(column=4, row=1, sticky="NWS")
# The dev set
frame4 = Frame(frame0, background=self._FRAME_PARAMS["background"])
self.devsetbox = Text(frame4, font=self._font, **self._DEVSETBOX_PARAMS)
self.devsetbox.pack(expand=True, fill="both")
self.devsetlabel = Label(
frame0,
font=self._font,
text="Development Set:",
justify="right",
background=self._DEVSETBOX_PARAMS["background"],
)
self.devsetlabel.grid(column=0, row=4, sticky="SW")
frame4.grid(column=0, row=5, sticky="NEWS")
# dev set scrollbars
self.devset_scroll = Scrollbar(frame0, command=self._devset_scroll)
self.devset_scroll.grid(column=1, row=5, sticky="NWS")
self.devset_xscroll = Scrollbar(
frame4, command=self.devsetbox.xview, orient="horiz"
)
self.devsetbox["xscrollcommand"] = self.devset_xscroll.set
self.devset_xscroll.pack(side="bottom", fill="x")
# dev set buttons
bg = self._FRAME_PARAMS["background"]
frame1 = Frame(frame0, background=bg)
frame1.grid(column=0, row=7, sticky="EW")
Button(
frame1,
text="Prev Example (Ctrl-p)",
command=self._devset_prev,
**self._BUTTON_PARAMS,
).pack(side="left")
Button(
frame1,
text="Next Example (Ctrl-n)",
command=self._devset_next,
**self._BUTTON_PARAMS,
).pack(side="left")
self.devset_button = Button(
frame1,
text="Show example",
command=self.show_devset,
state="disabled",
**self._BUTTON_PARAMS,
)
self.devset_button.pack(side="right")
self.trace_button = Button(
frame1, text="Show trace", command=self.show_trace, **self._BUTTON_PARAMS
)
self.trace_button.pack(side="right")
# evaluation box
self.evalbox = Canvas(frame0, **self._EVALBOX_PARAMS)
label = Label(
frame0,
font=self._font,
text="Evaluation:",
justify="right",
background=self._EVALBOX_PARAMS["background"],
)
label.grid(column=3, row=4, sticky="SW")
self.evalbox.grid(column=3, row=5, sticky="NEWS", columnspan=2)
# evaluation box buttons
bg = self._FRAME_PARAMS["background"]
frame2 = Frame(frame0, background=bg)
frame2.grid(column=3, row=7, sticky="EW")
self._autoscale = IntVar(self.top)
self._autoscale.set(False)
Checkbutton(
frame2,
variable=self._autoscale,
command=self._eval_plot,
text="Zoom",
**self._BUTTON_PARAMS,
).pack(side="left")
self._eval_lines = IntVar(self.top)
self._eval_lines.set(False)
Checkbutton(
frame2,
variable=self._eval_lines,
command=self._eval_plot,
text="Lines",
**self._BUTTON_PARAMS,
).pack(side="left")
Button(frame2, text="History", **self._BUTTON_PARAMS).pack(side="right")
# The status label
self.status = Label(frame0, font=self._font, **self._STATUS_PARAMS)
self.status.grid(column=0, row=9, sticky="NEW", padx=3, pady=2, columnspan=5)
# Help box & devset box can't be edited.
self.helpbox["state"] = "disabled"
self.devsetbox["state"] = "disabled"
# Spacers
bg = self._FRAME_PARAMS["background"]
Frame(frame0, height=10, width=0, background=bg).grid(column=0, row=3)
Frame(frame0, height=0, width=10, background=bg).grid(column=2, row=0)
Frame(frame0, height=6, width=0, background=bg).grid(column=0, row=8)
# pack the frame.
frame0.pack(fill="both", expand=True)
# Set up colors for the devset box
self.devsetbox.tag_config("true-pos", background="#afa", underline="True")
self.devsetbox.tag_config("false-neg", underline="True", foreground="#800")
self.devsetbox.tag_config("false-pos", background="#faa")
self.devsetbox.tag_config("trace", foreground="#666", wrap="none")
self.devsetbox.tag_config("wrapindent", lmargin2=30, wrap="none")
self.devsetbox.tag_config("error", foreground="#800")
# And for the grammarbox
self.grammarbox.tag_config("error", background="#fec")
self.grammarbox.tag_config("comment", foreground="#840")
self.grammarbox.tag_config("angle", foreground="#00f")
self.grammarbox.tag_config("brace", foreground="#0a0")
self.grammarbox.tag_config("hangindent", lmargin1=0, lmargin2=40)
_showing_trace = False
def show_trace(self, *e):
self._showing_trace = True
self.trace_button["state"] = "disabled"
self.devset_button["state"] = "normal"
self.devsetbox["state"] = "normal"
# self.devsetbox['wrap'] = 'none'
self.devsetbox.delete("1.0", "end")
self.devsetlabel["text"] = "Development Set (%d/%d)" % (
(self.devset_index + 1, self._devset_size.get())
)
if self.chunker is None:
self.devsetbox.insert("1.0", "Trace: waiting for a valid grammar.")
self.devsetbox.tag_add("error", "1.0", "end")
return # can't do anything more