Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- env-llmeval/lib/python3.10/site-packages/nltk/app/__init__.py +47 -0
- env-llmeval/lib/python3.10/site-packages/nltk/app/__pycache__/chunkparser_app.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/nltk/app/chartparser_app.py +2569 -0
- env-llmeval/lib/python3.10/site-packages/nltk/app/chunkparser_app.py +1500 -0
- env-llmeval/lib/python3.10/site-packages/nltk/app/collocations_app.py +438 -0
- env-llmeval/lib/python3.10/site-packages/nltk/app/concordance_app.py +709 -0
- env-llmeval/lib/python3.10/site-packages/nltk/app/nemo_app.py +163 -0
- env-llmeval/lib/python3.10/site-packages/nltk/app/rdparser_app.py +1052 -0
- env-llmeval/lib/python3.10/site-packages/nltk/app/srparser_app.py +937 -0
- env-llmeval/lib/python3.10/site-packages/nltk/app/wordfreq_app.py +36 -0
- env-llmeval/lib/python3.10/site-packages/nltk/app/wordnet_app.py +1005 -0
- env-llmeval/lib/python3.10/site-packages/nltk/classify/api.py +195 -0
- env-llmeval/lib/python3.10/site-packages/nltk/classify/decisiontree.py +349 -0
- env-llmeval/lib/python3.10/site-packages/nltk/classify/maxent.py +1569 -0
- env-llmeval/lib/python3.10/site-packages/nltk/classify/megam.py +184 -0
- env-llmeval/lib/python3.10/site-packages/nltk/classify/naivebayes.py +260 -0
- env-llmeval/lib/python3.10/site-packages/nltk/classify/positivenaivebayes.py +180 -0
- env-llmeval/lib/python3.10/site-packages/nltk/classify/rte_classify.py +183 -0
- env-llmeval/lib/python3.10/site-packages/nltk/classify/scikitlearn.py +143 -0
- env-llmeval/lib/python3.10/site-packages/nltk/classify/senna.py +176 -0
- env-llmeval/lib/python3.10/site-packages/nltk/classify/svm.py +17 -0
- env-llmeval/lib/python3.10/site-packages/nltk/classify/textcat.py +197 -0
- env-llmeval/lib/python3.10/site-packages/nltk/classify/util.py +346 -0
- env-llmeval/lib/python3.10/site-packages/nltk/classify/weka.py +377 -0
- env-llmeval/lib/python3.10/site-packages/nltk/draw/__init__.py +27 -0
- env-llmeval/lib/python3.10/site-packages/nltk/draw/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/nltk/draw/__pycache__/cfg.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/nltk/draw/__pycache__/dispersion.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/nltk/draw/__pycache__/table.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/nltk/draw/__pycache__/tree.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/nltk/draw/__pycache__/util.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/nltk/draw/cfg.py +859 -0
- env-llmeval/lib/python3.10/site-packages/nltk/draw/dispersion.py +63 -0
- env-llmeval/lib/python3.10/site-packages/nltk/draw/table.py +1177 -0
- env-llmeval/lib/python3.10/site-packages/nltk/draw/tree.py +1129 -0
- env-llmeval/lib/python3.10/site-packages/nltk/draw/util.py +2575 -0
- env-llmeval/lib/python3.10/site-packages/nltk/lm/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/nltk/lm/__pycache__/api.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/nltk/lm/__pycache__/counter.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/nltk/lm/__pycache__/models.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/nltk/lm/__pycache__/preprocessing.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/nltk/lm/__pycache__/smoothing.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/nltk/lm/__pycache__/util.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/nltk/lm/__pycache__/vocabulary.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/nltk/lm/smoothing.py +127 -0
- env-llmeval/lib/python3.10/site-packages/nltk/sem/__pycache__/boxer.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/nltk/sem/__pycache__/cooper_storage.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/nltk/sem/__pycache__/evaluate.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/nltk/sem/__pycache__/glue.cpython-310.pyc +0 -0
.gitattributes
CHANGED
@@ -129,3 +129,4 @@ env-llmeval/lib/python3.10/site-packages/lxml/etree.cpython-310-x86_64-linux-gnu
|
|
129 |
env-llmeval/lib/python3.10/site-packages/scipy.libs/libopenblasp-r0-24bff013.3.26.dev.so filter=lfs diff=lfs merge=lfs -text
|
130 |
env-llmeval/lib/python3.10/site-packages/scipy.libs/libgfortran-040039e1.so.5.0.0 filter=lfs diff=lfs merge=lfs -text
|
131 |
llmeval-env/lib/python3.10/site-packages/torch/lib/libtorch_cpu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
129 |
env-llmeval/lib/python3.10/site-packages/scipy.libs/libopenblasp-r0-24bff013.3.26.dev.so filter=lfs diff=lfs merge=lfs -text
|
130 |
env-llmeval/lib/python3.10/site-packages/scipy.libs/libgfortran-040039e1.so.5.0.0 filter=lfs diff=lfs merge=lfs -text
|
131 |
llmeval-env/lib/python3.10/site-packages/torch/lib/libtorch_cpu.so filter=lfs diff=lfs merge=lfs -text
|
132 |
+
env-llmeval/lib/python3.10/site-packages/yaml/_yaml.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
env-llmeval/lib/python3.10/site-packages/nltk/app/__init__.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Applications package
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Edward Loper <[email protected]>
|
5 |
+
# Steven Bird <[email protected]>
|
6 |
+
# URL: <https://www.nltk.org/>
|
7 |
+
# For license information, see LICENSE.TXT
|
8 |
+
|
9 |
+
"""
|
10 |
+
Interactive NLTK Applications:
|
11 |
+
|
12 |
+
chartparser: Chart Parser
|
13 |
+
chunkparser: Regular-Expression Chunk Parser
|
14 |
+
collocations: Find collocations in text
|
15 |
+
concordance: Part-of-speech concordancer
|
16 |
+
nemo: Finding (and Replacing) Nemo regular expression tool
|
17 |
+
rdparser: Recursive Descent Parser
|
18 |
+
srparser: Shift-Reduce Parser
|
19 |
+
wordnet: WordNet Browser
|
20 |
+
"""
|
21 |
+
|
22 |
+
|
23 |
+
# Import Tkinter-based modules if Tkinter is installed
|
24 |
+
try:
|
25 |
+
import tkinter
|
26 |
+
except ImportError:
|
27 |
+
import warnings
|
28 |
+
|
29 |
+
warnings.warn("nltk.app package not loaded (please install Tkinter library).")
|
30 |
+
else:
|
31 |
+
from nltk.app.chartparser_app import app as chartparser
|
32 |
+
from nltk.app.chunkparser_app import app as chunkparser
|
33 |
+
from nltk.app.collocations_app import app as collocations
|
34 |
+
from nltk.app.concordance_app import app as concordance
|
35 |
+
from nltk.app.nemo_app import app as nemo
|
36 |
+
from nltk.app.rdparser_app import app as rdparser
|
37 |
+
from nltk.app.srparser_app import app as srparser
|
38 |
+
from nltk.app.wordnet_app import app as wordnet
|
39 |
+
|
40 |
+
try:
|
41 |
+
from matplotlib import pylab
|
42 |
+
except ImportError:
|
43 |
+
import warnings
|
44 |
+
|
45 |
+
warnings.warn("nltk.app.wordfreq not loaded (requires the matplotlib library).")
|
46 |
+
else:
|
47 |
+
from nltk.app.wordfreq_app import app as wordfreq
|
env-llmeval/lib/python3.10/site-packages/nltk/app/__pycache__/chunkparser_app.cpython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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Chart Parser Application
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Edward Loper <[email protected]>
|
5 |
+
# Jean Mark Gawron <[email protected]>
|
6 |
+
# Steven Bird <[email protected]>
|
7 |
+
# URL: <https://www.nltk.org/>
|
8 |
+
# For license information, see LICENSE.TXT
|
9 |
+
|
10 |
+
"""
|
11 |
+
A graphical tool for exploring chart parsing.
|
12 |
+
|
13 |
+
Chart parsing is a flexible parsing algorithm that uses a data
|
14 |
+
structure called a "chart" to record hypotheses about syntactic
|
15 |
+
constituents. Each hypothesis is represented by a single "edge" on
|
16 |
+
the chart. A set of "chart rules" determine when new edges can be
|
17 |
+
added to the chart. This set of rules controls the overall behavior
|
18 |
+
of the parser (e.g. whether it parses top-down or bottom-up).
|
19 |
+
|
20 |
+
The chart parsing tool demonstrates the process of parsing a single
|
21 |
+
sentence, with a given grammar and lexicon. Its display is divided
|
22 |
+
into three sections: the bottom section displays the chart; the middle
|
23 |
+
section displays the sentence; and the top section displays the
|
24 |
+
partial syntax tree corresponding to the selected edge. Buttons along
|
25 |
+
the bottom of the window are used to control the execution of the
|
26 |
+
algorithm.
|
27 |
+
|
28 |
+
The chart parsing tool allows for flexible control of the parsing
|
29 |
+
algorithm. At each step of the algorithm, you can select which rule
|
30 |
+
or strategy you wish to apply. This allows you to experiment with
|
31 |
+
mixing different strategies (e.g. top-down and bottom-up). You can
|
32 |
+
exercise fine-grained control over the algorithm by selecting which
|
33 |
+
edge you wish to apply a rule to.
|
34 |
+
"""
|
35 |
+
|
36 |
+
# At some point, we should rewrite this tool to use the new canvas
|
37 |
+
# widget system.
|
38 |
+
|
39 |
+
|
40 |
+
import os.path
|
41 |
+
import pickle
|
42 |
+
from tkinter import (
|
43 |
+
Button,
|
44 |
+
Canvas,
|
45 |
+
Checkbutton,
|
46 |
+
Frame,
|
47 |
+
IntVar,
|
48 |
+
Label,
|
49 |
+
Menu,
|
50 |
+
Scrollbar,
|
51 |
+
Tk,
|
52 |
+
Toplevel,
|
53 |
+
)
|
54 |
+
from tkinter.filedialog import askopenfilename, asksaveasfilename
|
55 |
+
from tkinter.font import Font
|
56 |
+
from tkinter.messagebox import showerror, showinfo
|
57 |
+
|
58 |
+
from nltk.draw import CFGEditor, TreeSegmentWidget, tree_to_treesegment
|
59 |
+
from nltk.draw.util import (
|
60 |
+
CanvasFrame,
|
61 |
+
ColorizedList,
|
62 |
+
EntryDialog,
|
63 |
+
MutableOptionMenu,
|
64 |
+
ShowText,
|
65 |
+
SymbolWidget,
|
66 |
+
)
|
67 |
+
from nltk.grammar import CFG, Nonterminal
|
68 |
+
from nltk.parse.chart import (
|
69 |
+
BottomUpPredictCombineRule,
|
70 |
+
BottomUpPredictRule,
|
71 |
+
Chart,
|
72 |
+
LeafEdge,
|
73 |
+
LeafInitRule,
|
74 |
+
SingleEdgeFundamentalRule,
|
75 |
+
SteppingChartParser,
|
76 |
+
TopDownInitRule,
|
77 |
+
TopDownPredictRule,
|
78 |
+
TreeEdge,
|
79 |
+
)
|
80 |
+
from nltk.tree import Tree
|
81 |
+
from nltk.util import in_idle
|
82 |
+
|
83 |
+
# Known bug: ChartView doesn't handle edges generated by epsilon
|
84 |
+
# productions (e.g., [Production: PP -> ]) very well.
|
85 |
+
|
86 |
+
#######################################################################
|
87 |
+
# Edge List
|
88 |
+
#######################################################################
|
89 |
+
|
90 |
+
|
91 |
+
class EdgeList(ColorizedList):
|
92 |
+
ARROW = SymbolWidget.SYMBOLS["rightarrow"]
|
93 |
+
|
94 |
+
def _init_colortags(self, textwidget, options):
|
95 |
+
textwidget.tag_config("terminal", foreground="#006000")
|
96 |
+
textwidget.tag_config("arrow", font="symbol", underline="0")
|
97 |
+
textwidget.tag_config("dot", foreground="#000000")
|
98 |
+
textwidget.tag_config(
|
99 |
+
"nonterminal", foreground="blue", font=("helvetica", -12, "bold")
|
100 |
+
)
|
101 |
+
|
102 |
+
def _item_repr(self, item):
|
103 |
+
contents = []
|
104 |
+
contents.append(("%s\t" % item.lhs(), "nonterminal"))
|
105 |
+
contents.append((self.ARROW, "arrow"))
|
106 |
+
for i, elt in enumerate(item.rhs()):
|
107 |
+
if i == item.dot():
|
108 |
+
contents.append((" *", "dot"))
|
109 |
+
if isinstance(elt, Nonterminal):
|
110 |
+
contents.append((" %s" % elt.symbol(), "nonterminal"))
|
111 |
+
else:
|
112 |
+
contents.append((" %r" % elt, "terminal"))
|
113 |
+
if item.is_complete():
|
114 |
+
contents.append((" *", "dot"))
|
115 |
+
return contents
|
116 |
+
|
117 |
+
|
118 |
+
#######################################################################
|
119 |
+
# Chart Matrix View
|
120 |
+
#######################################################################
|
121 |
+
|
122 |
+
|
123 |
+
class ChartMatrixView:
|
124 |
+
"""
|
125 |
+
A view of a chart that displays the contents of the corresponding matrix.
|
126 |
+
"""
|
127 |
+
|
128 |
+
def __init__(
|
129 |
+
self, parent, chart, toplevel=True, title="Chart Matrix", show_numedges=False
|
130 |
+
):
|
131 |
+
self._chart = chart
|
132 |
+
self._cells = []
|
133 |
+
self._marks = []
|
134 |
+
|
135 |
+
self._selected_cell = None
|
136 |
+
|
137 |
+
if toplevel:
|
138 |
+
self._root = Toplevel(parent)
|
139 |
+
self._root.title(title)
|
140 |
+
self._root.bind("<Control-q>", self.destroy)
|
141 |
+
self._init_quit(self._root)
|
142 |
+
else:
|
143 |
+
self._root = Frame(parent)
|
144 |
+
|
145 |
+
self._init_matrix(self._root)
|
146 |
+
self._init_list(self._root)
|
147 |
+
if show_numedges:
|
148 |
+
self._init_numedges(self._root)
|
149 |
+
else:
|
150 |
+
self._numedges_label = None
|
151 |
+
|
152 |
+
self._callbacks = {}
|
153 |
+
|
154 |
+
self._num_edges = 0
|
155 |
+
|
156 |
+
self.draw()
|
157 |
+
|
158 |
+
def _init_quit(self, root):
|
159 |
+
quit = Button(root, text="Quit", command=self.destroy)
|
160 |
+
quit.pack(side="bottom", expand=0, fill="none")
|
161 |
+
|
162 |
+
def _init_matrix(self, root):
|
163 |
+
cframe = Frame(root, border=2, relief="sunken")
|
164 |
+
cframe.pack(expand=0, fill="none", padx=1, pady=3, side="top")
|
165 |
+
self._canvas = Canvas(cframe, width=200, height=200, background="white")
|
166 |
+
self._canvas.pack(expand=0, fill="none")
|
167 |
+
|
168 |
+
def _init_numedges(self, root):
|
169 |
+
self._numedges_label = Label(root, text="0 edges")
|
170 |
+
self._numedges_label.pack(expand=0, fill="none", side="top")
|
171 |
+
|
172 |
+
def _init_list(self, root):
|
173 |
+
self._list = EdgeList(root, [], width=20, height=5)
|
174 |
+
self._list.pack(side="top", expand=1, fill="both", pady=3)
|
175 |
+
|
176 |
+
def cb(edge, self=self):
|
177 |
+
self._fire_callbacks("select", edge)
|
178 |
+
|
179 |
+
self._list.add_callback("select", cb)
|
180 |
+
self._list.focus()
|
181 |
+
|
182 |
+
def destroy(self, *e):
|
183 |
+
if self._root is None:
|
184 |
+
return
|
185 |
+
try:
|
186 |
+
self._root.destroy()
|
187 |
+
except:
|
188 |
+
pass
|
189 |
+
self._root = None
|
190 |
+
|
191 |
+
def set_chart(self, chart):
|
192 |
+
if chart is not self._chart:
|
193 |
+
self._chart = chart
|
194 |
+
self._num_edges = 0
|
195 |
+
self.draw()
|
196 |
+
|
197 |
+
def update(self):
|
198 |
+
if self._root is None:
|
199 |
+
return
|
200 |
+
|
201 |
+
# Count the edges in each cell
|
202 |
+
N = len(self._cells)
|
203 |
+
cell_edges = [[0 for i in range(N)] for j in range(N)]
|
204 |
+
for edge in self._chart:
|
205 |
+
cell_edges[edge.start()][edge.end()] += 1
|
206 |
+
|
207 |
+
# Color the cells correspondingly.
|
208 |
+
for i in range(N):
|
209 |
+
for j in range(i, N):
|
210 |
+
if cell_edges[i][j] == 0:
|
211 |
+
color = "gray20"
|
212 |
+
else:
|
213 |
+
color = "#00{:02x}{:02x}".format(
|
214 |
+
min(255, 50 + 128 * cell_edges[i][j] / 10),
|
215 |
+
max(0, 128 - 128 * cell_edges[i][j] / 10),
|
216 |
+
)
|
217 |
+
cell_tag = self._cells[i][j]
|
218 |
+
self._canvas.itemconfig(cell_tag, fill=color)
|
219 |
+
if (i, j) == self._selected_cell:
|
220 |
+
self._canvas.itemconfig(cell_tag, outline="#00ffff", width=3)
|
221 |
+
self._canvas.tag_raise(cell_tag)
|
222 |
+
else:
|
223 |
+
self._canvas.itemconfig(cell_tag, outline="black", width=1)
|
224 |
+
|
225 |
+
# Update the edge list.
|
226 |
+
edges = list(self._chart.select(span=self._selected_cell))
|
227 |
+
self._list.set(edges)
|
228 |
+
|
229 |
+
# Update our edge count.
|
230 |
+
self._num_edges = self._chart.num_edges()
|
231 |
+
if self._numedges_label is not None:
|
232 |
+
self._numedges_label["text"] = "%d edges" % self._num_edges
|
233 |
+
|
234 |
+
def activate(self):
|
235 |
+
self._canvas.itemconfig("inactivebox", state="hidden")
|
236 |
+
self.update()
|
237 |
+
|
238 |
+
def inactivate(self):
|
239 |
+
self._canvas.itemconfig("inactivebox", state="normal")
|
240 |
+
self.update()
|
241 |
+
|
242 |
+
def add_callback(self, event, func):
|
243 |
+
self._callbacks.setdefault(event, {})[func] = 1
|
244 |
+
|
245 |
+
def remove_callback(self, event, func=None):
|
246 |
+
if func is None:
|
247 |
+
del self._callbacks[event]
|
248 |
+
else:
|
249 |
+
try:
|
250 |
+
del self._callbacks[event][func]
|
251 |
+
except:
|
252 |
+
pass
|
253 |
+
|
254 |
+
def _fire_callbacks(self, event, *args):
|
255 |
+
if event not in self._callbacks:
|
256 |
+
return
|
257 |
+
for cb_func in list(self._callbacks[event].keys()):
|
258 |
+
cb_func(*args)
|
259 |
+
|
260 |
+
def select_cell(self, i, j):
|
261 |
+
if self._root is None:
|
262 |
+
return
|
263 |
+
|
264 |
+
# If the cell is already selected (and the chart contents
|
265 |
+
# haven't changed), then do nothing.
|
266 |
+
if (i, j) == self._selected_cell and self._chart.num_edges() == self._num_edges:
|
267 |
+
return
|
268 |
+
|
269 |
+
self._selected_cell = (i, j)
|
270 |
+
self.update()
|
271 |
+
|
272 |
+
# Fire the callback.
|
273 |
+
self._fire_callbacks("select_cell", i, j)
|
274 |
+
|
275 |
+
def deselect_cell(self):
|
276 |
+
if self._root is None:
|
277 |
+
return
|
278 |
+
self._selected_cell = None
|
279 |
+
self._list.set([])
|
280 |
+
self.update()
|
281 |
+
|
282 |
+
def _click_cell(self, i, j):
|
283 |
+
if self._selected_cell == (i, j):
|
284 |
+
self.deselect_cell()
|
285 |
+
else:
|
286 |
+
self.select_cell(i, j)
|
287 |
+
|
288 |
+
def view_edge(self, edge):
|
289 |
+
self.select_cell(*edge.span())
|
290 |
+
self._list.view(edge)
|
291 |
+
|
292 |
+
def mark_edge(self, edge):
|
293 |
+
if self._root is None:
|
294 |
+
return
|
295 |
+
self.select_cell(*edge.span())
|
296 |
+
self._list.mark(edge)
|
297 |
+
|
298 |
+
def unmark_edge(self, edge=None):
|
299 |
+
if self._root is None:
|
300 |
+
return
|
301 |
+
self._list.unmark(edge)
|
302 |
+
|
303 |
+
def markonly_edge(self, edge):
|
304 |
+
if self._root is None:
|
305 |
+
return
|
306 |
+
self.select_cell(*edge.span())
|
307 |
+
self._list.markonly(edge)
|
308 |
+
|
309 |
+
def draw(self):
|
310 |
+
if self._root is None:
|
311 |
+
return
|
312 |
+
LEFT_MARGIN = BOT_MARGIN = 15
|
313 |
+
TOP_MARGIN = 5
|
314 |
+
c = self._canvas
|
315 |
+
c.delete("all")
|
316 |
+
N = self._chart.num_leaves() + 1
|
317 |
+
dx = (int(c["width"]) - LEFT_MARGIN) / N
|
318 |
+
dy = (int(c["height"]) - TOP_MARGIN - BOT_MARGIN) / N
|
319 |
+
|
320 |
+
c.delete("all")
|
321 |
+
|
322 |
+
# Labels and dotted lines
|
323 |
+
for i in range(N):
|
324 |
+
c.create_text(
|
325 |
+
LEFT_MARGIN - 2, i * dy + dy / 2 + TOP_MARGIN, text=repr(i), anchor="e"
|
326 |
+
)
|
327 |
+
c.create_text(
|
328 |
+
i * dx + dx / 2 + LEFT_MARGIN,
|
329 |
+
N * dy + TOP_MARGIN + 1,
|
330 |
+
text=repr(i),
|
331 |
+
anchor="n",
|
332 |
+
)
|
333 |
+
c.create_line(
|
334 |
+
LEFT_MARGIN,
|
335 |
+
dy * (i + 1) + TOP_MARGIN,
|
336 |
+
dx * N + LEFT_MARGIN,
|
337 |
+
dy * (i + 1) + TOP_MARGIN,
|
338 |
+
dash=".",
|
339 |
+
)
|
340 |
+
c.create_line(
|
341 |
+
dx * i + LEFT_MARGIN,
|
342 |
+
TOP_MARGIN,
|
343 |
+
dx * i + LEFT_MARGIN,
|
344 |
+
dy * N + TOP_MARGIN,
|
345 |
+
dash=".",
|
346 |
+
)
|
347 |
+
|
348 |
+
# A box around the whole thing
|
349 |
+
c.create_rectangle(
|
350 |
+
LEFT_MARGIN, TOP_MARGIN, LEFT_MARGIN + dx * N, dy * N + TOP_MARGIN, width=2
|
351 |
+
)
|
352 |
+
|
353 |
+
# Cells
|
354 |
+
self._cells = [[None for i in range(N)] for j in range(N)]
|
355 |
+
for i in range(N):
|
356 |
+
for j in range(i, N):
|
357 |
+
t = c.create_rectangle(
|
358 |
+
j * dx + LEFT_MARGIN,
|
359 |
+
i * dy + TOP_MARGIN,
|
360 |
+
(j + 1) * dx + LEFT_MARGIN,
|
361 |
+
(i + 1) * dy + TOP_MARGIN,
|
362 |
+
fill="gray20",
|
363 |
+
)
|
364 |
+
self._cells[i][j] = t
|
365 |
+
|
366 |
+
def cb(event, self=self, i=i, j=j):
|
367 |
+
self._click_cell(i, j)
|
368 |
+
|
369 |
+
c.tag_bind(t, "<Button-1>", cb)
|
370 |
+
|
371 |
+
# Inactive box
|
372 |
+
xmax, ymax = int(c["width"]), int(c["height"])
|
373 |
+
t = c.create_rectangle(
|
374 |
+
-100,
|
375 |
+
-100,
|
376 |
+
xmax + 100,
|
377 |
+
ymax + 100,
|
378 |
+
fill="gray50",
|
379 |
+
state="hidden",
|
380 |
+
tag="inactivebox",
|
381 |
+
)
|
382 |
+
c.tag_lower(t)
|
383 |
+
|
384 |
+
# Update the cells.
|
385 |
+
self.update()
|
386 |
+
|
387 |
+
def pack(self, *args, **kwargs):
|
388 |
+
self._root.pack(*args, **kwargs)
|
389 |
+
|
390 |
+
|
391 |
+
#######################################################################
|
392 |
+
# Chart Results View
|
393 |
+
#######################################################################
|
394 |
+
|
395 |
+
|
396 |
+
class ChartResultsView:
|
397 |
+
def __init__(self, parent, chart, grammar, toplevel=True):
|
398 |
+
self._chart = chart
|
399 |
+
self._grammar = grammar
|
400 |
+
self._trees = []
|
401 |
+
self._y = 10
|
402 |
+
self._treewidgets = []
|
403 |
+
self._selection = None
|
404 |
+
self._selectbox = None
|
405 |
+
|
406 |
+
if toplevel:
|
407 |
+
self._root = Toplevel(parent)
|
408 |
+
self._root.title("Chart Parser Application: Results")
|
409 |
+
self._root.bind("<Control-q>", self.destroy)
|
410 |
+
else:
|
411 |
+
self._root = Frame(parent)
|
412 |
+
|
413 |
+
# Buttons
|
414 |
+
if toplevel:
|
415 |
+
buttons = Frame(self._root)
|
416 |
+
buttons.pack(side="bottom", expand=0, fill="x")
|
417 |
+
Button(buttons, text="Quit", command=self.destroy).pack(side="right")
|
418 |
+
Button(buttons, text="Print All", command=self.print_all).pack(side="left")
|
419 |
+
Button(buttons, text="Print Selection", command=self.print_selection).pack(
|
420 |
+
side="left"
|
421 |
+
)
|
422 |
+
|
423 |
+
# Canvas frame.
|
424 |
+
self._cframe = CanvasFrame(self._root, closeenough=20)
|
425 |
+
self._cframe.pack(side="top", expand=1, fill="both")
|
426 |
+
|
427 |
+
# Initial update
|
428 |
+
self.update()
|
429 |
+
|
430 |
+
def update(self, edge=None):
|
431 |
+
if self._root is None:
|
432 |
+
return
|
433 |
+
# If the edge isn't a parse edge, do nothing.
|
434 |
+
if edge is not None:
|
435 |
+
if edge.lhs() != self._grammar.start():
|
436 |
+
return
|
437 |
+
if edge.span() != (0, self._chart.num_leaves()):
|
438 |
+
return
|
439 |
+
|
440 |
+
for parse in self._chart.parses(self._grammar.start()):
|
441 |
+
if parse not in self._trees:
|
442 |
+
self._add(parse)
|
443 |
+
|
444 |
+
def _add(self, parse):
|
445 |
+
# Add it to self._trees.
|
446 |
+
self._trees.append(parse)
|
447 |
+
|
448 |
+
# Create a widget for it.
|
449 |
+
c = self._cframe.canvas()
|
450 |
+
treewidget = tree_to_treesegment(c, parse)
|
451 |
+
|
452 |
+
# Add it to the canvas frame.
|
453 |
+
self._treewidgets.append(treewidget)
|
454 |
+
self._cframe.add_widget(treewidget, 10, self._y)
|
455 |
+
|
456 |
+
# Register callbacks.
|
457 |
+
treewidget.bind_click(self._click)
|
458 |
+
|
459 |
+
# Update y.
|
460 |
+
self._y = treewidget.bbox()[3] + 10
|
461 |
+
|
462 |
+
def _click(self, widget):
|
463 |
+
c = self._cframe.canvas()
|
464 |
+
if self._selection is not None:
|
465 |
+
c.delete(self._selectbox)
|
466 |
+
self._selection = widget
|
467 |
+
(x1, y1, x2, y2) = widget.bbox()
|
468 |
+
self._selectbox = c.create_rectangle(x1, y1, x2, y2, width=2, outline="#088")
|
469 |
+
|
470 |
+
def _color(self, treewidget, color):
|
471 |
+
treewidget.label()["color"] = color
|
472 |
+
for child in treewidget.subtrees():
|
473 |
+
if isinstance(child, TreeSegmentWidget):
|
474 |
+
self._color(child, color)
|
475 |
+
else:
|
476 |
+
child["color"] = color
|
477 |
+
|
478 |
+
def print_all(self, *e):
|
479 |
+
if self._root is None:
|
480 |
+
return
|
481 |
+
self._cframe.print_to_file()
|
482 |
+
|
483 |
+
def print_selection(self, *e):
|
484 |
+
if self._root is None:
|
485 |
+
return
|
486 |
+
if self._selection is None:
|
487 |
+
showerror("Print Error", "No tree selected")
|
488 |
+
else:
|
489 |
+
c = self._cframe.canvas()
|
490 |
+
for widget in self._treewidgets:
|
491 |
+
if widget is not self._selection:
|
492 |
+
self._cframe.destroy_widget(widget)
|
493 |
+
c.delete(self._selectbox)
|
494 |
+
(x1, y1, x2, y2) = self._selection.bbox()
|
495 |
+
self._selection.move(10 - x1, 10 - y1)
|
496 |
+
c["scrollregion"] = f"0 0 {x2 - x1 + 20} {y2 - y1 + 20}"
|
497 |
+
self._cframe.print_to_file()
|
498 |
+
|
499 |
+
# Restore our state.
|
500 |
+
self._treewidgets = [self._selection]
|
501 |
+
self.clear()
|
502 |
+
self.update()
|
503 |
+
|
504 |
+
def clear(self):
|
505 |
+
if self._root is None:
|
506 |
+
return
|
507 |
+
for treewidget in self._treewidgets:
|
508 |
+
self._cframe.destroy_widget(treewidget)
|
509 |
+
self._trees = []
|
510 |
+
self._treewidgets = []
|
511 |
+
if self._selection is not None:
|
512 |
+
self._cframe.canvas().delete(self._selectbox)
|
513 |
+
self._selection = None
|
514 |
+
self._y = 10
|
515 |
+
|
516 |
+
def set_chart(self, chart):
|
517 |
+
self.clear()
|
518 |
+
self._chart = chart
|
519 |
+
self.update()
|
520 |
+
|
521 |
+
def set_grammar(self, grammar):
|
522 |
+
self.clear()
|
523 |
+
self._grammar = grammar
|
524 |
+
self.update()
|
525 |
+
|
526 |
+
def destroy(self, *e):
|
527 |
+
if self._root is None:
|
528 |
+
return
|
529 |
+
try:
|
530 |
+
self._root.destroy()
|
531 |
+
except:
|
532 |
+
pass
|
533 |
+
self._root = None
|
534 |
+
|
535 |
+
def pack(self, *args, **kwargs):
|
536 |
+
self._root.pack(*args, **kwargs)
|
537 |
+
|
538 |
+
|
539 |
+
#######################################################################
|
540 |
+
# Chart Comparer
|
541 |
+
#######################################################################
|
542 |
+
|
543 |
+
|
544 |
+
class ChartComparer:
|
545 |
+
"""
|
546 |
+
|
547 |
+
:ivar _root: The root window
|
548 |
+
|
549 |
+
:ivar _charts: A dictionary mapping names to charts. When
|
550 |
+
charts are loaded, they are added to this dictionary.
|
551 |
+
|
552 |
+
:ivar _left_chart: The left ``Chart``.
|
553 |
+
:ivar _left_name: The name ``_left_chart`` (derived from filename)
|
554 |
+
:ivar _left_matrix: The ``ChartMatrixView`` for ``_left_chart``
|
555 |
+
:ivar _left_selector: The drop-down ``MutableOptionsMenu`` used
|
556 |
+
to select ``_left_chart``.
|
557 |
+
|
558 |
+
:ivar _right_chart: The right ``Chart``.
|
559 |
+
:ivar _right_name: The name ``_right_chart`` (derived from filename)
|
560 |
+
:ivar _right_matrix: The ``ChartMatrixView`` for ``_right_chart``
|
561 |
+
:ivar _right_selector: The drop-down ``MutableOptionsMenu`` used
|
562 |
+
to select ``_right_chart``.
|
563 |
+
|
564 |
+
:ivar _out_chart: The out ``Chart``.
|
565 |
+
:ivar _out_name: The name ``_out_chart`` (derived from filename)
|
566 |
+
:ivar _out_matrix: The ``ChartMatrixView`` for ``_out_chart``
|
567 |
+
:ivar _out_label: The label for ``_out_chart``.
|
568 |
+
|
569 |
+
:ivar _op_label: A Label containing the most recent operation.
|
570 |
+
"""
|
571 |
+
|
572 |
+
_OPSYMBOL = {
|
573 |
+
"-": "-",
|
574 |
+
"and": SymbolWidget.SYMBOLS["intersection"],
|
575 |
+
"or": SymbolWidget.SYMBOLS["union"],
|
576 |
+
}
|
577 |
+
|
578 |
+
def __init__(self, *chart_filenames):
|
579 |
+
# This chart is displayed when we don't have a value (eg
|
580 |
+
# before any chart is loaded).
|
581 |
+
faketok = [""] * 8
|
582 |
+
self._emptychart = Chart(faketok)
|
583 |
+
|
584 |
+
# The left & right charts start out empty.
|
585 |
+
self._left_name = "None"
|
586 |
+
self._right_name = "None"
|
587 |
+
self._left_chart = self._emptychart
|
588 |
+
self._right_chart = self._emptychart
|
589 |
+
|
590 |
+
# The charts that have been loaded.
|
591 |
+
self._charts = {"None": self._emptychart}
|
592 |
+
|
593 |
+
# The output chart.
|
594 |
+
self._out_chart = self._emptychart
|
595 |
+
|
596 |
+
# The most recent operation
|
597 |
+
self._operator = None
|
598 |
+
|
599 |
+
# Set up the root window.
|
600 |
+
self._root = Tk()
|
601 |
+
self._root.title("Chart Comparison")
|
602 |
+
self._root.bind("<Control-q>", self.destroy)
|
603 |
+
self._root.bind("<Control-x>", self.destroy)
|
604 |
+
|
605 |
+
# Initialize all widgets, etc.
|
606 |
+
self._init_menubar(self._root)
|
607 |
+
self._init_chartviews(self._root)
|
608 |
+
self._init_divider(self._root)
|
609 |
+
self._init_buttons(self._root)
|
610 |
+
self._init_bindings(self._root)
|
611 |
+
|
612 |
+
# Load any specified charts.
|
613 |
+
for filename in chart_filenames:
|
614 |
+
self.load_chart(filename)
|
615 |
+
|
616 |
+
def destroy(self, *e):
|
617 |
+
if self._root is None:
|
618 |
+
return
|
619 |
+
try:
|
620 |
+
self._root.destroy()
|
621 |
+
except:
|
622 |
+
pass
|
623 |
+
self._root = None
|
624 |
+
|
625 |
+
def mainloop(self, *args, **kwargs):
|
626 |
+
return
|
627 |
+
self._root.mainloop(*args, **kwargs)
|
628 |
+
|
629 |
+
# ////////////////////////////////////////////////////////////
|
630 |
+
# Initialization
|
631 |
+
# ////////////////////////////////////////////////////////////
|
632 |
+
|
633 |
+
def _init_menubar(self, root):
|
634 |
+
menubar = Menu(root)
|
635 |
+
|
636 |
+
# File menu
|
637 |
+
filemenu = Menu(menubar, tearoff=0)
|
638 |
+
filemenu.add_command(
|
639 |
+
label="Load Chart",
|
640 |
+
accelerator="Ctrl-o",
|
641 |
+
underline=0,
|
642 |
+
command=self.load_chart_dialog,
|
643 |
+
)
|
644 |
+
filemenu.add_command(
|
645 |
+
label="Save Output",
|
646 |
+
accelerator="Ctrl-s",
|
647 |
+
underline=0,
|
648 |
+
command=self.save_chart_dialog,
|
649 |
+
)
|
650 |
+
filemenu.add_separator()
|
651 |
+
filemenu.add_command(
|
652 |
+
label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-x"
|
653 |
+
)
|
654 |
+
menubar.add_cascade(label="File", underline=0, menu=filemenu)
|
655 |
+
|
656 |
+
# Compare menu
|
657 |
+
opmenu = Menu(menubar, tearoff=0)
|
658 |
+
opmenu.add_command(
|
659 |
+
label="Intersection", command=self._intersection, accelerator="+"
|
660 |
+
)
|
661 |
+
opmenu.add_command(label="Union", command=self._union, accelerator="*")
|
662 |
+
opmenu.add_command(
|
663 |
+
label="Difference", command=self._difference, accelerator="-"
|
664 |
+
)
|
665 |
+
opmenu.add_separator()
|
666 |
+
opmenu.add_command(label="Swap Charts", command=self._swapcharts)
|
667 |
+
menubar.add_cascade(label="Compare", underline=0, menu=opmenu)
|
668 |
+
|
669 |
+
# Add the menu
|
670 |
+
self._root.config(menu=menubar)
|
671 |
+
|
672 |
+
def _init_divider(self, root):
|
673 |
+
divider = Frame(root, border=2, relief="sunken")
|
674 |
+
divider.pack(side="top", fill="x", ipady=2)
|
675 |
+
|
676 |
+
def _init_chartviews(self, root):
|
677 |
+
opfont = ("symbol", -36) # Font for operator.
|
678 |
+
eqfont = ("helvetica", -36) # Font for equals sign.
|
679 |
+
|
680 |
+
frame = Frame(root, background="#c0c0c0")
|
681 |
+
frame.pack(side="top", expand=1, fill="both")
|
682 |
+
|
683 |
+
# The left matrix.
|
684 |
+
cv1_frame = Frame(frame, border=3, relief="groove")
|
685 |
+
cv1_frame.pack(side="left", padx=8, pady=7, expand=1, fill="both")
|
686 |
+
self._left_selector = MutableOptionMenu(
|
687 |
+
cv1_frame, list(self._charts.keys()), command=self._select_left
|
688 |
+
)
|
689 |
+
self._left_selector.pack(side="top", pady=5, fill="x")
|
690 |
+
self._left_matrix = ChartMatrixView(
|
691 |
+
cv1_frame, self._emptychart, toplevel=False, show_numedges=True
|
692 |
+
)
|
693 |
+
self._left_matrix.pack(side="bottom", padx=5, pady=5, expand=1, fill="both")
|
694 |
+
self._left_matrix.add_callback("select", self.select_edge)
|
695 |
+
self._left_matrix.add_callback("select_cell", self.select_cell)
|
696 |
+
self._left_matrix.inactivate()
|
697 |
+
|
698 |
+
# The operator.
|
699 |
+
self._op_label = Label(
|
700 |
+
frame, text=" ", width=3, background="#c0c0c0", font=opfont
|
701 |
+
)
|
702 |
+
self._op_label.pack(side="left", padx=5, pady=5)
|
703 |
+
|
704 |
+
# The right matrix.
|
705 |
+
cv2_frame = Frame(frame, border=3, relief="groove")
|
706 |
+
cv2_frame.pack(side="left", padx=8, pady=7, expand=1, fill="both")
|
707 |
+
self._right_selector = MutableOptionMenu(
|
708 |
+
cv2_frame, list(self._charts.keys()), command=self._select_right
|
709 |
+
)
|
710 |
+
self._right_selector.pack(side="top", pady=5, fill="x")
|
711 |
+
self._right_matrix = ChartMatrixView(
|
712 |
+
cv2_frame, self._emptychart, toplevel=False, show_numedges=True
|
713 |
+
)
|
714 |
+
self._right_matrix.pack(side="bottom", padx=5, pady=5, expand=1, fill="both")
|
715 |
+
self._right_matrix.add_callback("select", self.select_edge)
|
716 |
+
self._right_matrix.add_callback("select_cell", self.select_cell)
|
717 |
+
self._right_matrix.inactivate()
|
718 |
+
|
719 |
+
# The equals sign
|
720 |
+
Label(frame, text="=", width=3, background="#c0c0c0", font=eqfont).pack(
|
721 |
+
side="left", padx=5, pady=5
|
722 |
+
)
|
723 |
+
|
724 |
+
# The output matrix.
|
725 |
+
out_frame = Frame(frame, border=3, relief="groove")
|
726 |
+
out_frame.pack(side="left", padx=8, pady=7, expand=1, fill="both")
|
727 |
+
self._out_label = Label(out_frame, text="Output")
|
728 |
+
self._out_label.pack(side="top", pady=9)
|
729 |
+
self._out_matrix = ChartMatrixView(
|
730 |
+
out_frame, self._emptychart, toplevel=False, show_numedges=True
|
731 |
+
)
|
732 |
+
self._out_matrix.pack(side="bottom", padx=5, pady=5, expand=1, fill="both")
|
733 |
+
self._out_matrix.add_callback("select", self.select_edge)
|
734 |
+
self._out_matrix.add_callback("select_cell", self.select_cell)
|
735 |
+
self._out_matrix.inactivate()
|
736 |
+
|
737 |
+
def _init_buttons(self, root):
|
738 |
+
buttons = Frame(root)
|
739 |
+
buttons.pack(side="bottom", pady=5, fill="x", expand=0)
|
740 |
+
Button(buttons, text="Intersection", command=self._intersection).pack(
|
741 |
+
side="left"
|
742 |
+
)
|
743 |
+
Button(buttons, text="Union", command=self._union).pack(side="left")
|
744 |
+
Button(buttons, text="Difference", command=self._difference).pack(side="left")
|
745 |
+
Frame(buttons, width=20).pack(side="left")
|
746 |
+
Button(buttons, text="Swap Charts", command=self._swapcharts).pack(side="left")
|
747 |
+
|
748 |
+
Button(buttons, text="Detach Output", command=self._detach_out).pack(
|
749 |
+
side="right"
|
750 |
+
)
|
751 |
+
|
752 |
+
def _init_bindings(self, root):
|
753 |
+
# root.bind('<Control-s>', self.save_chart)
|
754 |
+
root.bind("<Control-o>", self.load_chart_dialog)
|
755 |
+
# root.bind('<Control-r>', self.reset)
|
756 |
+
|
757 |
+
# ////////////////////////////////////////////////////////////
|
758 |
+
# Input Handling
|
759 |
+
# ////////////////////////////////////////////////////////////
|
760 |
+
|
761 |
+
def _select_left(self, name):
|
762 |
+
self._left_name = name
|
763 |
+
self._left_chart = self._charts[name]
|
764 |
+
self._left_matrix.set_chart(self._left_chart)
|
765 |
+
if name == "None":
|
766 |
+
self._left_matrix.inactivate()
|
767 |
+
self._apply_op()
|
768 |
+
|
769 |
+
def _select_right(self, name):
|
770 |
+
self._right_name = name
|
771 |
+
self._right_chart = self._charts[name]
|
772 |
+
self._right_matrix.set_chart(self._right_chart)
|
773 |
+
if name == "None":
|
774 |
+
self._right_matrix.inactivate()
|
775 |
+
self._apply_op()
|
776 |
+
|
777 |
+
def _apply_op(self):
|
778 |
+
if self._operator == "-":
|
779 |
+
self._difference()
|
780 |
+
elif self._operator == "or":
|
781 |
+
self._union()
|
782 |
+
elif self._operator == "and":
|
783 |
+
self._intersection()
|
784 |
+
|
785 |
+
# ////////////////////////////////////////////////////////////
|
786 |
+
# File
|
787 |
+
# ////////////////////////////////////////////////////////////
|
788 |
+
CHART_FILE_TYPES = [("Pickle file", ".pickle"), ("All files", "*")]
|
789 |
+
|
790 |
+
def save_chart_dialog(self, *args):
|
791 |
+
filename = asksaveasfilename(
|
792 |
+
filetypes=self.CHART_FILE_TYPES, defaultextension=".pickle"
|
793 |
+
)
|
794 |
+
if not filename:
|
795 |
+
return
|
796 |
+
try:
|
797 |
+
with open(filename, "wb") as outfile:
|
798 |
+
pickle.dump(self._out_chart, outfile)
|
799 |
+
except Exception as e:
|
800 |
+
showerror("Error Saving Chart", f"Unable to open file: {filename!r}\n{e}")
|
801 |
+
|
802 |
+
def load_chart_dialog(self, *args):
|
803 |
+
filename = askopenfilename(
|
804 |
+
filetypes=self.CHART_FILE_TYPES, defaultextension=".pickle"
|
805 |
+
)
|
806 |
+
if not filename:
|
807 |
+
return
|
808 |
+
try:
|
809 |
+
self.load_chart(filename)
|
810 |
+
except Exception as e:
|
811 |
+
showerror("Error Loading Chart", f"Unable to open file: {filename!r}\n{e}")
|
812 |
+
|
813 |
+
def load_chart(self, filename):
|
814 |
+
with open(filename, "rb") as infile:
|
815 |
+
chart = pickle.load(infile)
|
816 |
+
name = os.path.basename(filename)
|
817 |
+
if name.endswith(".pickle"):
|
818 |
+
name = name[:-7]
|
819 |
+
if name.endswith(".chart"):
|
820 |
+
name = name[:-6]
|
821 |
+
self._charts[name] = chart
|
822 |
+
self._left_selector.add(name)
|
823 |
+
self._right_selector.add(name)
|
824 |
+
|
825 |
+
# If either left_matrix or right_matrix is empty, then
|
826 |
+
# display the new chart.
|
827 |
+
if self._left_chart is self._emptychart:
|
828 |
+
self._left_selector.set(name)
|
829 |
+
elif self._right_chart is self._emptychart:
|
830 |
+
self._right_selector.set(name)
|
831 |
+
|
832 |
+
def _update_chartviews(self):
|
833 |
+
self._left_matrix.update()
|
834 |
+
self._right_matrix.update()
|
835 |
+
self._out_matrix.update()
|
836 |
+
|
837 |
+
# ////////////////////////////////////////////////////////////
|
838 |
+
# Selection
|
839 |
+
# ////////////////////////////////////////////////////////////
|
840 |
+
|
841 |
+
def select_edge(self, edge):
|
842 |
+
if edge in self._left_chart:
|
843 |
+
self._left_matrix.markonly_edge(edge)
|
844 |
+
else:
|
845 |
+
self._left_matrix.unmark_edge()
|
846 |
+
if edge in self._right_chart:
|
847 |
+
self._right_matrix.markonly_edge(edge)
|
848 |
+
else:
|
849 |
+
self._right_matrix.unmark_edge()
|
850 |
+
if edge in self._out_chart:
|
851 |
+
self._out_matrix.markonly_edge(edge)
|
852 |
+
else:
|
853 |
+
self._out_matrix.unmark_edge()
|
854 |
+
|
855 |
+
def select_cell(self, i, j):
|
856 |
+
self._left_matrix.select_cell(i, j)
|
857 |
+
self._right_matrix.select_cell(i, j)
|
858 |
+
self._out_matrix.select_cell(i, j)
|
859 |
+
|
860 |
+
# ////////////////////////////////////////////////////////////
|
861 |
+
# Operations
|
862 |
+
# ////////////////////////////////////////////////////////////
|
863 |
+
|
864 |
+
def _difference(self):
|
865 |
+
if not self._checkcompat():
|
866 |
+
return
|
867 |
+
|
868 |
+
out_chart = Chart(self._left_chart.tokens())
|
869 |
+
for edge in self._left_chart:
|
870 |
+
if edge not in self._right_chart:
|
871 |
+
out_chart.insert(edge, [])
|
872 |
+
|
873 |
+
self._update("-", out_chart)
|
874 |
+
|
875 |
+
def _intersection(self):
|
876 |
+
if not self._checkcompat():
|
877 |
+
return
|
878 |
+
|
879 |
+
out_chart = Chart(self._left_chart.tokens())
|
880 |
+
for edge in self._left_chart:
|
881 |
+
if edge in self._right_chart:
|
882 |
+
out_chart.insert(edge, [])
|
883 |
+
|
884 |
+
self._update("and", out_chart)
|
885 |
+
|
886 |
+
def _union(self):
|
887 |
+
if not self._checkcompat():
|
888 |
+
return
|
889 |
+
|
890 |
+
out_chart = Chart(self._left_chart.tokens())
|
891 |
+
for edge in self._left_chart:
|
892 |
+
out_chart.insert(edge, [])
|
893 |
+
for edge in self._right_chart:
|
894 |
+
out_chart.insert(edge, [])
|
895 |
+
|
896 |
+
self._update("or", out_chart)
|
897 |
+
|
898 |
+
def _swapcharts(self):
|
899 |
+
left, right = self._left_name, self._right_name
|
900 |
+
self._left_selector.set(right)
|
901 |
+
self._right_selector.set(left)
|
902 |
+
|
903 |
+
def _checkcompat(self):
|
904 |
+
if (
|
905 |
+
self._left_chart.tokens() != self._right_chart.tokens()
|
906 |
+
or self._left_chart.property_names() != self._right_chart.property_names()
|
907 |
+
or self._left_chart == self._emptychart
|
908 |
+
or self._right_chart == self._emptychart
|
909 |
+
):
|
910 |
+
# Clear & inactivate the output chart.
|
911 |
+
self._out_chart = self._emptychart
|
912 |
+
self._out_matrix.set_chart(self._out_chart)
|
913 |
+
self._out_matrix.inactivate()
|
914 |
+
self._out_label["text"] = "Output"
|
915 |
+
# Issue some other warning?
|
916 |
+
return False
|
917 |
+
else:
|
918 |
+
return True
|
919 |
+
|
920 |
+
def _update(self, operator, out_chart):
|
921 |
+
self._operator = operator
|
922 |
+
self._op_label["text"] = self._OPSYMBOL[operator]
|
923 |
+
self._out_chart = out_chart
|
924 |
+
self._out_matrix.set_chart(out_chart)
|
925 |
+
self._out_label["text"] = "{} {} {}".format(
|
926 |
+
self._left_name,
|
927 |
+
self._operator,
|
928 |
+
self._right_name,
|
929 |
+
)
|
930 |
+
|
931 |
+
def _clear_out_chart(self):
|
932 |
+
self._out_chart = self._emptychart
|
933 |
+
self._out_matrix.set_chart(self._out_chart)
|
934 |
+
self._op_label["text"] = " "
|
935 |
+
self._out_matrix.inactivate()
|
936 |
+
|
937 |
+
def _detach_out(self):
|
938 |
+
ChartMatrixView(self._root, self._out_chart, title=self._out_label["text"])
|
939 |
+
|
940 |
+
|
941 |
+
#######################################################################
|
942 |
+
# Chart View
|
943 |
+
#######################################################################
|
944 |
+
|
945 |
+
|
946 |
+
class ChartView:
|
947 |
+
"""
|
948 |
+
A component for viewing charts. This is used by ``ChartParserApp`` to
|
949 |
+
allow students to interactively experiment with various chart
|
950 |
+
parsing techniques. It is also used by ``Chart.draw()``.
|
951 |
+
|
952 |
+
:ivar _chart: The chart that we are giving a view of. This chart
|
953 |
+
may be modified; after it is modified, you should call
|
954 |
+
``update``.
|
955 |
+
:ivar _sentence: The list of tokens that the chart spans.
|
956 |
+
|
957 |
+
:ivar _root: The root window.
|
958 |
+
:ivar _chart_canvas: The canvas we're using to display the chart
|
959 |
+
itself.
|
960 |
+
:ivar _tree_canvas: The canvas we're using to display the tree
|
961 |
+
that each edge spans. May be None, if we're not displaying
|
962 |
+
trees.
|
963 |
+
:ivar _sentence_canvas: The canvas we're using to display the sentence
|
964 |
+
text. May be None, if we're not displaying the sentence text.
|
965 |
+
:ivar _edgetags: A dictionary mapping from edges to the tags of
|
966 |
+
the canvas elements (lines, etc) used to display that edge.
|
967 |
+
The values of this dictionary have the form
|
968 |
+
``(linetag, rhstag1, dottag, rhstag2, lhstag)``.
|
969 |
+
:ivar _treetags: A list of all the tags that make up the tree;
|
970 |
+
used to erase the tree (without erasing the loclines).
|
971 |
+
:ivar _chart_height: The height of the chart canvas.
|
972 |
+
:ivar _sentence_height: The height of the sentence canvas.
|
973 |
+
:ivar _tree_height: The height of the tree
|
974 |
+
|
975 |
+
:ivar _text_height: The height of a text string (in the normal
|
976 |
+
font).
|
977 |
+
|
978 |
+
:ivar _edgelevels: A list of edges at each level of the chart (the
|
979 |
+
top level is the 0th element). This list is used to remember
|
980 |
+
where edges should be drawn; and to make sure that no edges
|
981 |
+
are overlapping on the chart view.
|
982 |
+
|
983 |
+
:ivar _unitsize: Pixel size of one unit (from the location). This
|
984 |
+
is determined by the span of the chart's location, and the
|
985 |
+
width of the chart display canvas.
|
986 |
+
|
987 |
+
:ivar _fontsize: The current font size
|
988 |
+
|
989 |
+
:ivar _marks: A dictionary from edges to marks. Marks are
|
990 |
+
strings, specifying colors (e.g. 'green').
|
991 |
+
"""
|
992 |
+
|
993 |
+
_LEAF_SPACING = 10
|
994 |
+
_MARGIN = 10
|
995 |
+
_TREE_LEVEL_SIZE = 12
|
996 |
+
_CHART_LEVEL_SIZE = 40
|
997 |
+
|
998 |
+
def __init__(self, chart, root=None, **kw):
|
999 |
+
"""
|
1000 |
+
Construct a new ``Chart`` display.
|
1001 |
+
"""
|
1002 |
+
# Process keyword args.
|
1003 |
+
draw_tree = kw.get("draw_tree", 0)
|
1004 |
+
draw_sentence = kw.get("draw_sentence", 1)
|
1005 |
+
self._fontsize = kw.get("fontsize", -12)
|
1006 |
+
|
1007 |
+
# The chart!
|
1008 |
+
self._chart = chart
|
1009 |
+
|
1010 |
+
# Callback functions
|
1011 |
+
self._callbacks = {}
|
1012 |
+
|
1013 |
+
# Keep track of drawn edges
|
1014 |
+
self._edgelevels = []
|
1015 |
+
self._edgetags = {}
|
1016 |
+
|
1017 |
+
# Keep track of which edges are marked.
|
1018 |
+
self._marks = {}
|
1019 |
+
|
1020 |
+
# These are used to keep track of the set of tree tokens
|
1021 |
+
# currently displayed in the tree canvas.
|
1022 |
+
self._treetoks = []
|
1023 |
+
self._treetoks_edge = None
|
1024 |
+
self._treetoks_index = 0
|
1025 |
+
|
1026 |
+
# Keep track of the tags used to draw the tree
|
1027 |
+
self._tree_tags = []
|
1028 |
+
|
1029 |
+
# Put multiple edges on each level?
|
1030 |
+
self._compact = 0
|
1031 |
+
|
1032 |
+
# If they didn't provide a main window, then set one up.
|
1033 |
+
if root is None:
|
1034 |
+
top = Tk()
|
1035 |
+
top.title("Chart View")
|
1036 |
+
|
1037 |
+
def destroy1(e, top=top):
|
1038 |
+
top.destroy()
|
1039 |
+
|
1040 |
+
def destroy2(top=top):
|
1041 |
+
top.destroy()
|
1042 |
+
|
1043 |
+
top.bind("q", destroy1)
|
1044 |
+
b = Button(top, text="Done", command=destroy2)
|
1045 |
+
b.pack(side="bottom")
|
1046 |
+
self._root = top
|
1047 |
+
else:
|
1048 |
+
self._root = root
|
1049 |
+
|
1050 |
+
# Create some fonts.
|
1051 |
+
self._init_fonts(root)
|
1052 |
+
|
1053 |
+
# Create the chart canvas.
|
1054 |
+
(self._chart_sb, self._chart_canvas) = self._sb_canvas(self._root)
|
1055 |
+
self._chart_canvas["height"] = 300
|
1056 |
+
self._chart_canvas["closeenough"] = 15
|
1057 |
+
|
1058 |
+
# Create the sentence canvas.
|
1059 |
+
if draw_sentence:
|
1060 |
+
cframe = Frame(self._root, relief="sunk", border=2)
|
1061 |
+
cframe.pack(fill="both", side="bottom")
|
1062 |
+
self._sentence_canvas = Canvas(cframe, height=50)
|
1063 |
+
self._sentence_canvas["background"] = "#e0e0e0"
|
1064 |
+
self._sentence_canvas.pack(fill="both")
|
1065 |
+
# self._sentence_canvas['height'] = self._sentence_height
|
1066 |
+
else:
|
1067 |
+
self._sentence_canvas = None
|
1068 |
+
|
1069 |
+
# Create the tree canvas.
|
1070 |
+
if draw_tree:
|
1071 |
+
(sb, canvas) = self._sb_canvas(self._root, "n", "x")
|
1072 |
+
(self._tree_sb, self._tree_canvas) = (sb, canvas)
|
1073 |
+
self._tree_canvas["height"] = 200
|
1074 |
+
else:
|
1075 |
+
self._tree_canvas = None
|
1076 |
+
|
1077 |
+
# Do some analysis to figure out how big the window should be
|
1078 |
+
self._analyze()
|
1079 |
+
self.draw()
|
1080 |
+
self._resize()
|
1081 |
+
self._grow()
|
1082 |
+
|
1083 |
+
# Set up the configure callback, which will be called whenever
|
1084 |
+
# the window is resized.
|
1085 |
+
self._chart_canvas.bind("<Configure>", self._configure)
|
1086 |
+
|
1087 |
+
def _init_fonts(self, root):
|
1088 |
+
self._boldfont = Font(family="helvetica", weight="bold", size=self._fontsize)
|
1089 |
+
self._font = Font(family="helvetica", size=self._fontsize)
|
1090 |
+
# See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
|
1091 |
+
self._sysfont = Font(font=Button()["font"])
|
1092 |
+
root.option_add("*Font", self._sysfont)
|
1093 |
+
|
1094 |
+
def _sb_canvas(self, root, expand="y", fill="both", side="bottom"):
|
1095 |
+
"""
|
1096 |
+
Helper for __init__: construct a canvas with a scrollbar.
|
1097 |
+
"""
|
1098 |
+
cframe = Frame(root, relief="sunk", border=2)
|
1099 |
+
cframe.pack(fill=fill, expand=expand, side=side)
|
1100 |
+
canvas = Canvas(cframe, background="#e0e0e0")
|
1101 |
+
|
1102 |
+
# Give the canvas a scrollbar.
|
1103 |
+
sb = Scrollbar(cframe, orient="vertical")
|
1104 |
+
sb.pack(side="right", fill="y")
|
1105 |
+
canvas.pack(side="left", fill=fill, expand="yes")
|
1106 |
+
|
1107 |
+
# Connect the scrollbars to the canvas.
|
1108 |
+
sb["command"] = canvas.yview
|
1109 |
+
canvas["yscrollcommand"] = sb.set
|
1110 |
+
|
1111 |
+
return (sb, canvas)
|
1112 |
+
|
1113 |
+
def scroll_up(self, *e):
|
1114 |
+
self._chart_canvas.yview("scroll", -1, "units")
|
1115 |
+
|
1116 |
+
def scroll_down(self, *e):
|
1117 |
+
self._chart_canvas.yview("scroll", 1, "units")
|
1118 |
+
|
1119 |
+
def page_up(self, *e):
|
1120 |
+
self._chart_canvas.yview("scroll", -1, "pages")
|
1121 |
+
|
1122 |
+
def page_down(self, *e):
|
1123 |
+
self._chart_canvas.yview("scroll", 1, "pages")
|
1124 |
+
|
1125 |
+
def _grow(self):
|
1126 |
+
"""
|
1127 |
+
Grow the window, if necessary
|
1128 |
+
"""
|
1129 |
+
# Grow, if need-be
|
1130 |
+
N = self._chart.num_leaves()
|
1131 |
+
width = max(
|
1132 |
+
int(self._chart_canvas["width"]), N * self._unitsize + ChartView._MARGIN * 2
|
1133 |
+
)
|
1134 |
+
|
1135 |
+
# It won't resize without the second (height) line, but I
|
1136 |
+
# don't understand why not.
|
1137 |
+
self._chart_canvas.configure(width=width)
|
1138 |
+
self._chart_canvas.configure(height=self._chart_canvas["height"])
|
1139 |
+
|
1140 |
+
self._unitsize = (width - 2 * ChartView._MARGIN) / N
|
1141 |
+
|
1142 |
+
# Reset the height for the sentence window.
|
1143 |
+
if self._sentence_canvas is not None:
|
1144 |
+
self._sentence_canvas["height"] = self._sentence_height
|
1145 |
+
|
1146 |
+
def set_font_size(self, size):
|
1147 |
+
self._font.configure(size=-abs(size))
|
1148 |
+
self._boldfont.configure(size=-abs(size))
|
1149 |
+
self._sysfont.configure(size=-abs(size))
|
1150 |
+
self._analyze()
|
1151 |
+
self._grow()
|
1152 |
+
self.draw()
|
1153 |
+
|
1154 |
+
def get_font_size(self):
|
1155 |
+
return abs(self._fontsize)
|
1156 |
+
|
1157 |
+
def _configure(self, e):
|
1158 |
+
"""
|
1159 |
+
The configure callback. This is called whenever the window is
|
1160 |
+
resized. It is also called when the window is first mapped.
|
1161 |
+
It figures out the unit size, and redraws the contents of each
|
1162 |
+
canvas.
|
1163 |
+
"""
|
1164 |
+
N = self._chart.num_leaves()
|
1165 |
+
self._unitsize = (e.width - 2 * ChartView._MARGIN) / N
|
1166 |
+
self.draw()
|
1167 |
+
|
1168 |
+
def update(self, chart=None):
|
1169 |
+
"""
|
1170 |
+
Draw any edges that have not been drawn. This is typically
|
1171 |
+
called when a after modifies the canvas that a CanvasView is
|
1172 |
+
displaying. ``update`` will cause any edges that have been
|
1173 |
+
added to the chart to be drawn.
|
1174 |
+
|
1175 |
+
If update is given a ``chart`` argument, then it will replace
|
1176 |
+
the current chart with the given chart.
|
1177 |
+
"""
|
1178 |
+
if chart is not None:
|
1179 |
+
self._chart = chart
|
1180 |
+
self._edgelevels = []
|
1181 |
+
self._marks = {}
|
1182 |
+
self._analyze()
|
1183 |
+
self._grow()
|
1184 |
+
self.draw()
|
1185 |
+
self.erase_tree()
|
1186 |
+
self._resize()
|
1187 |
+
else:
|
1188 |
+
for edge in self._chart:
|
1189 |
+
if edge not in self._edgetags:
|
1190 |
+
self._add_edge(edge)
|
1191 |
+
self._resize()
|
1192 |
+
|
1193 |
+
def _edge_conflict(self, edge, lvl):
|
1194 |
+
"""
|
1195 |
+
Return True if the given edge overlaps with any edge on the given
|
1196 |
+
level. This is used by _add_edge to figure out what level a
|
1197 |
+
new edge should be added to.
|
1198 |
+
"""
|
1199 |
+
(s1, e1) = edge.span()
|
1200 |
+
for otheredge in self._edgelevels[lvl]:
|
1201 |
+
(s2, e2) = otheredge.span()
|
1202 |
+
if (s1 <= s2 < e1) or (s2 <= s1 < e2) or (s1 == s2 == e1 == e2):
|
1203 |
+
return True
|
1204 |
+
return False
|
1205 |
+
|
1206 |
+
def _analyze_edge(self, edge):
|
1207 |
+
"""
|
1208 |
+
Given a new edge, recalculate:
|
1209 |
+
|
1210 |
+
- _text_height
|
1211 |
+
- _unitsize (if the edge text is too big for the current
|
1212 |
+
_unitsize, then increase _unitsize)
|
1213 |
+
"""
|
1214 |
+
c = self._chart_canvas
|
1215 |
+
|
1216 |
+
if isinstance(edge, TreeEdge):
|
1217 |
+
lhs = edge.lhs()
|
1218 |
+
rhselts = []
|
1219 |
+
for elt in edge.rhs():
|
1220 |
+
if isinstance(elt, Nonterminal):
|
1221 |
+
rhselts.append(str(elt.symbol()))
|
1222 |
+
else:
|
1223 |
+
rhselts.append(repr(elt))
|
1224 |
+
rhs = " ".join(rhselts)
|
1225 |
+
else:
|
1226 |
+
lhs = edge.lhs()
|
1227 |
+
rhs = ""
|
1228 |
+
|
1229 |
+
for s in (lhs, rhs):
|
1230 |
+
tag = c.create_text(
|
1231 |
+
0, 0, text=s, font=self._boldfont, anchor="nw", justify="left"
|
1232 |
+
)
|
1233 |
+
bbox = c.bbox(tag)
|
1234 |
+
c.delete(tag)
|
1235 |
+
width = bbox[2] # + ChartView._LEAF_SPACING
|
1236 |
+
edgelen = max(edge.length(), 1)
|
1237 |
+
self._unitsize = max(self._unitsize, width / edgelen)
|
1238 |
+
self._text_height = max(self._text_height, bbox[3] - bbox[1])
|
1239 |
+
|
1240 |
+
def _add_edge(self, edge, minlvl=0):
|
1241 |
+
"""
|
1242 |
+
Add a single edge to the ChartView:
|
1243 |
+
|
1244 |
+
- Call analyze_edge to recalculate display parameters
|
1245 |
+
- Find an available level
|
1246 |
+
- Call _draw_edge
|
1247 |
+
"""
|
1248 |
+
# Do NOT show leaf edges in the chart.
|
1249 |
+
if isinstance(edge, LeafEdge):
|
1250 |
+
return
|
1251 |
+
|
1252 |
+
if edge in self._edgetags:
|
1253 |
+
return
|
1254 |
+
self._analyze_edge(edge)
|
1255 |
+
self._grow()
|
1256 |
+
|
1257 |
+
if not self._compact:
|
1258 |
+
self._edgelevels.append([edge])
|
1259 |
+
lvl = len(self._edgelevels) - 1
|
1260 |
+
self._draw_edge(edge, lvl)
|
1261 |
+
self._resize()
|
1262 |
+
return
|
1263 |
+
|
1264 |
+
# Figure out what level to draw the edge on.
|
1265 |
+
lvl = 0
|
1266 |
+
while True:
|
1267 |
+
# If this level doesn't exist yet, create it.
|
1268 |
+
while lvl >= len(self._edgelevels):
|
1269 |
+
self._edgelevels.append([])
|
1270 |
+
self._resize()
|
1271 |
+
|
1272 |
+
# Check if we can fit the edge in this level.
|
1273 |
+
if lvl >= minlvl and not self._edge_conflict(edge, lvl):
|
1274 |
+
# Go ahead and draw it.
|
1275 |
+
self._edgelevels[lvl].append(edge)
|
1276 |
+
break
|
1277 |
+
|
1278 |
+
# Try the next level.
|
1279 |
+
lvl += 1
|
1280 |
+
|
1281 |
+
self._draw_edge(edge, lvl)
|
1282 |
+
|
1283 |
+
def view_edge(self, edge):
|
1284 |
+
level = None
|
1285 |
+
for i in range(len(self._edgelevels)):
|
1286 |
+
if edge in self._edgelevels[i]:
|
1287 |
+
level = i
|
1288 |
+
break
|
1289 |
+
if level is None:
|
1290 |
+
return
|
1291 |
+
# Try to view the new edge..
|
1292 |
+
y = (level + 1) * self._chart_level_size
|
1293 |
+
dy = self._text_height + 10
|
1294 |
+
self._chart_canvas.yview("moveto", 1.0)
|
1295 |
+
if self._chart_height != 0:
|
1296 |
+
self._chart_canvas.yview("moveto", (y - dy) / self._chart_height)
|
1297 |
+
|
1298 |
+
def _draw_edge(self, edge, lvl):
|
1299 |
+
"""
|
1300 |
+
Draw a single edge on the ChartView.
|
1301 |
+
"""
|
1302 |
+
c = self._chart_canvas
|
1303 |
+
|
1304 |
+
# Draw the arrow.
|
1305 |
+
x1 = edge.start() * self._unitsize + ChartView._MARGIN
|
1306 |
+
x2 = edge.end() * self._unitsize + ChartView._MARGIN
|
1307 |
+
if x2 == x1:
|
1308 |
+
x2 += max(4, self._unitsize / 5)
|
1309 |
+
y = (lvl + 1) * self._chart_level_size
|
1310 |
+
linetag = c.create_line(x1, y, x2, y, arrow="last", width=3)
|
1311 |
+
|
1312 |
+
# Draw a label for the edge.
|
1313 |
+
if isinstance(edge, TreeEdge):
|
1314 |
+
rhs = []
|
1315 |
+
for elt in edge.rhs():
|
1316 |
+
if isinstance(elt, Nonterminal):
|
1317 |
+
rhs.append(str(elt.symbol()))
|
1318 |
+
else:
|
1319 |
+
rhs.append(repr(elt))
|
1320 |
+
pos = edge.dot()
|
1321 |
+
else:
|
1322 |
+
rhs = []
|
1323 |
+
pos = 0
|
1324 |
+
|
1325 |
+
rhs1 = " ".join(rhs[:pos])
|
1326 |
+
rhs2 = " ".join(rhs[pos:])
|
1327 |
+
rhstag1 = c.create_text(x1 + 3, y, text=rhs1, font=self._font, anchor="nw")
|
1328 |
+
dotx = c.bbox(rhstag1)[2] + 6
|
1329 |
+
doty = (c.bbox(rhstag1)[1] + c.bbox(rhstag1)[3]) / 2
|
1330 |
+
dottag = c.create_oval(dotx - 2, doty - 2, dotx + 2, doty + 2)
|
1331 |
+
rhstag2 = c.create_text(dotx + 6, y, text=rhs2, font=self._font, anchor="nw")
|
1332 |
+
lhstag = c.create_text(
|
1333 |
+
(x1 + x2) / 2, y, text=str(edge.lhs()), anchor="s", font=self._boldfont
|
1334 |
+
)
|
1335 |
+
|
1336 |
+
# Keep track of the edge's tags.
|
1337 |
+
self._edgetags[edge] = (linetag, rhstag1, dottag, rhstag2, lhstag)
|
1338 |
+
|
1339 |
+
# Register a callback for clicking on the edge.
|
1340 |
+
def cb(event, self=self, edge=edge):
|
1341 |
+
self._fire_callbacks("select", edge)
|
1342 |
+
|
1343 |
+
c.tag_bind(rhstag1, "<Button-1>", cb)
|
1344 |
+
c.tag_bind(rhstag2, "<Button-1>", cb)
|
1345 |
+
c.tag_bind(linetag, "<Button-1>", cb)
|
1346 |
+
c.tag_bind(dottag, "<Button-1>", cb)
|
1347 |
+
c.tag_bind(lhstag, "<Button-1>", cb)
|
1348 |
+
|
1349 |
+
self._color_edge(edge)
|
1350 |
+
|
1351 |
+
def _color_edge(self, edge, linecolor=None, textcolor=None):
|
1352 |
+
"""
|
1353 |
+
Color in an edge with the given colors.
|
1354 |
+
If no colors are specified, use intelligent defaults
|
1355 |
+
(dependent on selection, etc.)
|
1356 |
+
"""
|
1357 |
+
if edge not in self._edgetags:
|
1358 |
+
return
|
1359 |
+
c = self._chart_canvas
|
1360 |
+
|
1361 |
+
if linecolor is not None and textcolor is not None:
|
1362 |
+
if edge in self._marks:
|
1363 |
+
linecolor = self._marks[edge]
|
1364 |
+
tags = self._edgetags[edge]
|
1365 |
+
c.itemconfig(tags[0], fill=linecolor)
|
1366 |
+
c.itemconfig(tags[1], fill=textcolor)
|
1367 |
+
c.itemconfig(tags[2], fill=textcolor, outline=textcolor)
|
1368 |
+
c.itemconfig(tags[3], fill=textcolor)
|
1369 |
+
c.itemconfig(tags[4], fill=textcolor)
|
1370 |
+
return
|
1371 |
+
else:
|
1372 |
+
N = self._chart.num_leaves()
|
1373 |
+
if edge in self._marks:
|
1374 |
+
self._color_edge(self._marks[edge])
|
1375 |
+
if edge.is_complete() and edge.span() == (0, N):
|
1376 |
+
self._color_edge(edge, "#084", "#042")
|
1377 |
+
elif isinstance(edge, LeafEdge):
|
1378 |
+
self._color_edge(edge, "#48c", "#246")
|
1379 |
+
else:
|
1380 |
+
self._color_edge(edge, "#00f", "#008")
|
1381 |
+
|
1382 |
+
def mark_edge(self, edge, mark="#0df"):
|
1383 |
+
"""
|
1384 |
+
Mark an edge
|
1385 |
+
"""
|
1386 |
+
self._marks[edge] = mark
|
1387 |
+
self._color_edge(edge)
|
1388 |
+
|
1389 |
+
def unmark_edge(self, edge=None):
|
1390 |
+
"""
|
1391 |
+
Unmark an edge (or all edges)
|
1392 |
+
"""
|
1393 |
+
if edge is None:
|
1394 |
+
old_marked_edges = list(self._marks.keys())
|
1395 |
+
self._marks = {}
|
1396 |
+
for edge in old_marked_edges:
|
1397 |
+
self._color_edge(edge)
|
1398 |
+
else:
|
1399 |
+
del self._marks[edge]
|
1400 |
+
self._color_edge(edge)
|
1401 |
+
|
1402 |
+
def markonly_edge(self, edge, mark="#0df"):
|
1403 |
+
self.unmark_edge()
|
1404 |
+
self.mark_edge(edge, mark)
|
1405 |
+
|
1406 |
+
def _analyze(self):
|
1407 |
+
"""
|
1408 |
+
Analyze the sentence string, to figure out how big a unit needs
|
1409 |
+
to be, How big the tree should be, etc.
|
1410 |
+
"""
|
1411 |
+
# Figure out the text height and the unit size.
|
1412 |
+
unitsize = 70 # min unitsize
|
1413 |
+
text_height = 0
|
1414 |
+
c = self._chart_canvas
|
1415 |
+
|
1416 |
+
# Check against all tokens
|
1417 |
+
for leaf in self._chart.leaves():
|
1418 |
+
tag = c.create_text(
|
1419 |
+
0, 0, text=repr(leaf), font=self._font, anchor="nw", justify="left"
|
1420 |
+
)
|
1421 |
+
bbox = c.bbox(tag)
|
1422 |
+
c.delete(tag)
|
1423 |
+
width = bbox[2] + ChartView._LEAF_SPACING
|
1424 |
+
unitsize = max(width, unitsize)
|
1425 |
+
text_height = max(text_height, bbox[3] - bbox[1])
|
1426 |
+
|
1427 |
+
self._unitsize = unitsize
|
1428 |
+
self._text_height = text_height
|
1429 |
+
self._sentence_height = self._text_height + 2 * ChartView._MARGIN
|
1430 |
+
|
1431 |
+
# Check against edges.
|
1432 |
+
for edge in self._chart.edges():
|
1433 |
+
self._analyze_edge(edge)
|
1434 |
+
|
1435 |
+
# Size of chart levels
|
1436 |
+
self._chart_level_size = self._text_height * 2
|
1437 |
+
|
1438 |
+
# Default tree size..
|
1439 |
+
self._tree_height = 3 * (ChartView._TREE_LEVEL_SIZE + self._text_height)
|
1440 |
+
|
1441 |
+
# Resize the scrollregions.
|
1442 |
+
self._resize()
|
1443 |
+
|
1444 |
+
def _resize(self):
|
1445 |
+
"""
|
1446 |
+
Update the scroll-regions for each canvas. This ensures that
|
1447 |
+
everything is within a scroll-region, so the user can use the
|
1448 |
+
scrollbars to view the entire display. This does *not*
|
1449 |
+
resize the window.
|
1450 |
+
"""
|
1451 |
+
c = self._chart_canvas
|
1452 |
+
|
1453 |
+
# Reset the chart scroll region
|
1454 |
+
width = self._chart.num_leaves() * self._unitsize + ChartView._MARGIN * 2
|
1455 |
+
|
1456 |
+
levels = len(self._edgelevels)
|
1457 |
+
self._chart_height = (levels + 2) * self._chart_level_size
|
1458 |
+
c["scrollregion"] = (0, 0, width, self._chart_height)
|
1459 |
+
|
1460 |
+
# Reset the tree scroll region
|
1461 |
+
if self._tree_canvas:
|
1462 |
+
self._tree_canvas["scrollregion"] = (0, 0, width, self._tree_height)
|
1463 |
+
|
1464 |
+
def _draw_loclines(self):
|
1465 |
+
"""
|
1466 |
+
Draw location lines. These are vertical gridlines used to
|
1467 |
+
show where each location unit is.
|
1468 |
+
"""
|
1469 |
+
BOTTOM = 50000
|
1470 |
+
c1 = self._tree_canvas
|
1471 |
+
c2 = self._sentence_canvas
|
1472 |
+
c3 = self._chart_canvas
|
1473 |
+
margin = ChartView._MARGIN
|
1474 |
+
self._loclines = []
|
1475 |
+
for i in range(0, self._chart.num_leaves() + 1):
|
1476 |
+
x = i * self._unitsize + margin
|
1477 |
+
|
1478 |
+
if c1:
|
1479 |
+
t1 = c1.create_line(x, 0, x, BOTTOM)
|
1480 |
+
c1.tag_lower(t1)
|
1481 |
+
if c2:
|
1482 |
+
t2 = c2.create_line(x, 0, x, self._sentence_height)
|
1483 |
+
c2.tag_lower(t2)
|
1484 |
+
t3 = c3.create_line(x, 0, x, BOTTOM)
|
1485 |
+
c3.tag_lower(t3)
|
1486 |
+
t4 = c3.create_text(x + 2, 0, text=repr(i), anchor="nw", font=self._font)
|
1487 |
+
c3.tag_lower(t4)
|
1488 |
+
# if i % 4 == 0:
|
1489 |
+
# if c1: c1.itemconfig(t1, width=2, fill='gray60')
|
1490 |
+
# if c2: c2.itemconfig(t2, width=2, fill='gray60')
|
1491 |
+
# c3.itemconfig(t3, width=2, fill='gray60')
|
1492 |
+
if i % 2 == 0:
|
1493 |
+
if c1:
|
1494 |
+
c1.itemconfig(t1, fill="gray60")
|
1495 |
+
if c2:
|
1496 |
+
c2.itemconfig(t2, fill="gray60")
|
1497 |
+
c3.itemconfig(t3, fill="gray60")
|
1498 |
+
else:
|
1499 |
+
if c1:
|
1500 |
+
c1.itemconfig(t1, fill="gray80")
|
1501 |
+
if c2:
|
1502 |
+
c2.itemconfig(t2, fill="gray80")
|
1503 |
+
c3.itemconfig(t3, fill="gray80")
|
1504 |
+
|
1505 |
+
def _draw_sentence(self):
|
1506 |
+
"""Draw the sentence string."""
|
1507 |
+
if self._chart.num_leaves() == 0:
|
1508 |
+
return
|
1509 |
+
c = self._sentence_canvas
|
1510 |
+
margin = ChartView._MARGIN
|
1511 |
+
y = ChartView._MARGIN
|
1512 |
+
|
1513 |
+
for i, leaf in enumerate(self._chart.leaves()):
|
1514 |
+
x1 = i * self._unitsize + margin
|
1515 |
+
x2 = x1 + self._unitsize
|
1516 |
+
x = (x1 + x2) / 2
|
1517 |
+
tag = c.create_text(
|
1518 |
+
x, y, text=repr(leaf), font=self._font, anchor="n", justify="left"
|
1519 |
+
)
|
1520 |
+
bbox = c.bbox(tag)
|
1521 |
+
rt = c.create_rectangle(
|
1522 |
+
x1 + 2,
|
1523 |
+
bbox[1] - (ChartView._LEAF_SPACING / 2),
|
1524 |
+
x2 - 2,
|
1525 |
+
bbox[3] + (ChartView._LEAF_SPACING / 2),
|
1526 |
+
fill="#f0f0f0",
|
1527 |
+
outline="#f0f0f0",
|
1528 |
+
)
|
1529 |
+
c.tag_lower(rt)
|
1530 |
+
|
1531 |
+
def erase_tree(self):
|
1532 |
+
for tag in self._tree_tags:
|
1533 |
+
self._tree_canvas.delete(tag)
|
1534 |
+
self._treetoks = []
|
1535 |
+
self._treetoks_edge = None
|
1536 |
+
self._treetoks_index = 0
|
1537 |
+
|
1538 |
+
def draw_tree(self, edge=None):
|
1539 |
+
if edge is None and self._treetoks_edge is None:
|
1540 |
+
return
|
1541 |
+
if edge is None:
|
1542 |
+
edge = self._treetoks_edge
|
1543 |
+
|
1544 |
+
# If it's a new edge, then get a new list of treetoks.
|
1545 |
+
if self._treetoks_edge != edge:
|
1546 |
+
self._treetoks = [t for t in self._chart.trees(edge) if isinstance(t, Tree)]
|
1547 |
+
self._treetoks_edge = edge
|
1548 |
+
self._treetoks_index = 0
|
1549 |
+
|
1550 |
+
# Make sure there's something to draw.
|
1551 |
+
if len(self._treetoks) == 0:
|
1552 |
+
return
|
1553 |
+
|
1554 |
+
# Erase the old tree.
|
1555 |
+
for tag in self._tree_tags:
|
1556 |
+
self._tree_canvas.delete(tag)
|
1557 |
+
|
1558 |
+
# Draw the new tree.
|
1559 |
+
tree = self._treetoks[self._treetoks_index]
|
1560 |
+
self._draw_treetok(tree, edge.start())
|
1561 |
+
|
1562 |
+
# Show how many trees are available for the edge.
|
1563 |
+
self._draw_treecycle()
|
1564 |
+
|
1565 |
+
# Update the scroll region.
|
1566 |
+
w = self._chart.num_leaves() * self._unitsize + 2 * ChartView._MARGIN
|
1567 |
+
h = tree.height() * (ChartView._TREE_LEVEL_SIZE + self._text_height)
|
1568 |
+
self._tree_canvas["scrollregion"] = (0, 0, w, h)
|
1569 |
+
|
1570 |
+
def cycle_tree(self):
|
1571 |
+
self._treetoks_index = (self._treetoks_index + 1) % len(self._treetoks)
|
1572 |
+
self.draw_tree(self._treetoks_edge)
|
1573 |
+
|
1574 |
+
def _draw_treecycle(self):
|
1575 |
+
if len(self._treetoks) <= 1:
|
1576 |
+
return
|
1577 |
+
|
1578 |
+
# Draw the label.
|
1579 |
+
label = "%d Trees" % len(self._treetoks)
|
1580 |
+
c = self._tree_canvas
|
1581 |
+
margin = ChartView._MARGIN
|
1582 |
+
right = self._chart.num_leaves() * self._unitsize + margin - 2
|
1583 |
+
tag = c.create_text(right, 2, anchor="ne", text=label, font=self._boldfont)
|
1584 |
+
self._tree_tags.append(tag)
|
1585 |
+
_, _, _, y = c.bbox(tag)
|
1586 |
+
|
1587 |
+
# Draw the triangles.
|
1588 |
+
for i in range(len(self._treetoks)):
|
1589 |
+
x = right - 20 * (len(self._treetoks) - i - 1)
|
1590 |
+
if i == self._treetoks_index:
|
1591 |
+
fill = "#084"
|
1592 |
+
else:
|
1593 |
+
fill = "#fff"
|
1594 |
+
tag = c.create_polygon(
|
1595 |
+
x, y + 10, x - 5, y, x - 10, y + 10, fill=fill, outline="black"
|
1596 |
+
)
|
1597 |
+
self._tree_tags.append(tag)
|
1598 |
+
|
1599 |
+
# Set up a callback: show the tree if they click on its
|
1600 |
+
# triangle.
|
1601 |
+
def cb(event, self=self, i=i):
|
1602 |
+
self._treetoks_index = i
|
1603 |
+
self.draw_tree()
|
1604 |
+
|
1605 |
+
c.tag_bind(tag, "<Button-1>", cb)
|
1606 |
+
|
1607 |
+
def _draw_treetok(self, treetok, index, depth=0):
|
1608 |
+
"""
|
1609 |
+
:param index: The index of the first leaf in the tree.
|
1610 |
+
:return: The index of the first leaf after the tree.
|
1611 |
+
"""
|
1612 |
+
c = self._tree_canvas
|
1613 |
+
margin = ChartView._MARGIN
|
1614 |
+
|
1615 |
+
# Draw the children
|
1616 |
+
child_xs = []
|
1617 |
+
for child in treetok:
|
1618 |
+
if isinstance(child, Tree):
|
1619 |
+
child_x, index = self._draw_treetok(child, index, depth + 1)
|
1620 |
+
child_xs.append(child_x)
|
1621 |
+
else:
|
1622 |
+
child_xs.append((2 * index + 1) * self._unitsize / 2 + margin)
|
1623 |
+
index += 1
|
1624 |
+
|
1625 |
+
# If we have children, then get the node's x by averaging their
|
1626 |
+
# node x's. Otherwise, make room for ourselves.
|
1627 |
+
if child_xs:
|
1628 |
+
nodex = sum(child_xs) / len(child_xs)
|
1629 |
+
else:
|
1630 |
+
# [XX] breaks for null productions.
|
1631 |
+
nodex = (2 * index + 1) * self._unitsize / 2 + margin
|
1632 |
+
index += 1
|
1633 |
+
|
1634 |
+
# Draw the node
|
1635 |
+
nodey = depth * (ChartView._TREE_LEVEL_SIZE + self._text_height)
|
1636 |
+
tag = c.create_text(
|
1637 |
+
nodex,
|
1638 |
+
nodey,
|
1639 |
+
anchor="n",
|
1640 |
+
justify="center",
|
1641 |
+
text=str(treetok.label()),
|
1642 |
+
fill="#042",
|
1643 |
+
font=self._boldfont,
|
1644 |
+
)
|
1645 |
+
self._tree_tags.append(tag)
|
1646 |
+
|
1647 |
+
# Draw lines to the children.
|
1648 |
+
childy = nodey + ChartView._TREE_LEVEL_SIZE + self._text_height
|
1649 |
+
for childx, child in zip(child_xs, treetok):
|
1650 |
+
if isinstance(child, Tree) and child:
|
1651 |
+
# A "real" tree token:
|
1652 |
+
tag = c.create_line(
|
1653 |
+
nodex,
|
1654 |
+
nodey + self._text_height,
|
1655 |
+
childx,
|
1656 |
+
childy,
|
1657 |
+
width=2,
|
1658 |
+
fill="#084",
|
1659 |
+
)
|
1660 |
+
self._tree_tags.append(tag)
|
1661 |
+
if isinstance(child, Tree) and not child:
|
1662 |
+
# An unexpanded tree token:
|
1663 |
+
tag = c.create_line(
|
1664 |
+
nodex,
|
1665 |
+
nodey + self._text_height,
|
1666 |
+
childx,
|
1667 |
+
childy,
|
1668 |
+
width=2,
|
1669 |
+
fill="#048",
|
1670 |
+
dash="2 3",
|
1671 |
+
)
|
1672 |
+
self._tree_tags.append(tag)
|
1673 |
+
if not isinstance(child, Tree):
|
1674 |
+
# A leaf:
|
1675 |
+
tag = c.create_line(
|
1676 |
+
nodex,
|
1677 |
+
nodey + self._text_height,
|
1678 |
+
childx,
|
1679 |
+
10000,
|
1680 |
+
width=2,
|
1681 |
+
fill="#084",
|
1682 |
+
)
|
1683 |
+
self._tree_tags.append(tag)
|
1684 |
+
|
1685 |
+
return nodex, index
|
1686 |
+
|
1687 |
+
def draw(self):
|
1688 |
+
"""
|
1689 |
+
Draw everything (from scratch).
|
1690 |
+
"""
|
1691 |
+
if self._tree_canvas:
|
1692 |
+
self._tree_canvas.delete("all")
|
1693 |
+
self.draw_tree()
|
1694 |
+
|
1695 |
+
if self._sentence_canvas:
|
1696 |
+
self._sentence_canvas.delete("all")
|
1697 |
+
self._draw_sentence()
|
1698 |
+
|
1699 |
+
self._chart_canvas.delete("all")
|
1700 |
+
self._edgetags = {}
|
1701 |
+
|
1702 |
+
# Redraw any edges we erased.
|
1703 |
+
for lvl in range(len(self._edgelevels)):
|
1704 |
+
for edge in self._edgelevels[lvl]:
|
1705 |
+
self._draw_edge(edge, lvl)
|
1706 |
+
|
1707 |
+
for edge in self._chart:
|
1708 |
+
self._add_edge(edge)
|
1709 |
+
|
1710 |
+
self._draw_loclines()
|
1711 |
+
|
1712 |
+
def add_callback(self, event, func):
|
1713 |
+
self._callbacks.setdefault(event, {})[func] = 1
|
1714 |
+
|
1715 |
+
def remove_callback(self, event, func=None):
|
1716 |
+
if func is None:
|
1717 |
+
del self._callbacks[event]
|
1718 |
+
else:
|
1719 |
+
try:
|
1720 |
+
del self._callbacks[event][func]
|
1721 |
+
except:
|
1722 |
+
pass
|
1723 |
+
|
1724 |
+
def _fire_callbacks(self, event, *args):
|
1725 |
+
if event not in self._callbacks:
|
1726 |
+
return
|
1727 |
+
for cb_func in list(self._callbacks[event].keys()):
|
1728 |
+
cb_func(*args)
|
1729 |
+
|
1730 |
+
|
1731 |
+
#######################################################################
|
1732 |
+
# Edge Rules
|
1733 |
+
#######################################################################
|
1734 |
+
# These version of the chart rules only apply to a specific edge.
|
1735 |
+
# This lets the user select an edge, and then apply a rule.
|
1736 |
+
|
1737 |
+
|
1738 |
+
class EdgeRule:
|
1739 |
+
"""
|
1740 |
+
To create an edge rule, make an empty base class that uses
|
1741 |
+
EdgeRule as the first base class, and the basic rule as the
|
1742 |
+
second base class. (Order matters!)
|
1743 |
+
"""
|
1744 |
+
|
1745 |
+
def __init__(self, edge):
|
1746 |
+
super = self.__class__.__bases__[1]
|
1747 |
+
self._edge = edge
|
1748 |
+
self.NUM_EDGES = super.NUM_EDGES - 1
|
1749 |
+
|
1750 |
+
def apply(self, chart, grammar, *edges):
|
1751 |
+
super = self.__class__.__bases__[1]
|
1752 |
+
edges += (self._edge,)
|
1753 |
+
yield from super.apply(self, chart, grammar, *edges)
|
1754 |
+
|
1755 |
+
def __str__(self):
|
1756 |
+
super = self.__class__.__bases__[1]
|
1757 |
+
return super.__str__(self)
|
1758 |
+
|
1759 |
+
|
1760 |
+
class TopDownPredictEdgeRule(EdgeRule, TopDownPredictRule):
|
1761 |
+
pass
|
1762 |
+
|
1763 |
+
|
1764 |
+
class BottomUpEdgeRule(EdgeRule, BottomUpPredictRule):
|
1765 |
+
pass
|
1766 |
+
|
1767 |
+
|
1768 |
+
class BottomUpLeftCornerEdgeRule(EdgeRule, BottomUpPredictCombineRule):
|
1769 |
+
pass
|
1770 |
+
|
1771 |
+
|
1772 |
+
class FundamentalEdgeRule(EdgeRule, SingleEdgeFundamentalRule):
|
1773 |
+
pass
|
1774 |
+
|
1775 |
+
|
1776 |
+
#######################################################################
|
1777 |
+
# Chart Parser Application
|
1778 |
+
#######################################################################
|
1779 |
+
|
1780 |
+
|
1781 |
+
class ChartParserApp:
|
1782 |
+
def __init__(self, grammar, tokens, title="Chart Parser Application"):
|
1783 |
+
# Initialize the parser
|
1784 |
+
self._init_parser(grammar, tokens)
|
1785 |
+
|
1786 |
+
self._root = None
|
1787 |
+
try:
|
1788 |
+
# Create the root window.
|
1789 |
+
self._root = Tk()
|
1790 |
+
self._root.title(title)
|
1791 |
+
self._root.bind("<Control-q>", self.destroy)
|
1792 |
+
|
1793 |
+
# Set up some frames.
|
1794 |
+
frame3 = Frame(self._root)
|
1795 |
+
frame2 = Frame(self._root)
|
1796 |
+
frame1 = Frame(self._root)
|
1797 |
+
frame3.pack(side="bottom", fill="none")
|
1798 |
+
frame2.pack(side="bottom", fill="x")
|
1799 |
+
frame1.pack(side="bottom", fill="both", expand=1)
|
1800 |
+
|
1801 |
+
self._init_fonts(self._root)
|
1802 |
+
self._init_animation()
|
1803 |
+
self._init_chartview(frame1)
|
1804 |
+
self._init_rulelabel(frame2)
|
1805 |
+
self._init_buttons(frame3)
|
1806 |
+
self._init_menubar()
|
1807 |
+
|
1808 |
+
self._matrix = None
|
1809 |
+
self._results = None
|
1810 |
+
|
1811 |
+
# Set up keyboard bindings.
|
1812 |
+
self._init_bindings()
|
1813 |
+
|
1814 |
+
except:
|
1815 |
+
print("Error creating Tree View")
|
1816 |
+
self.destroy()
|
1817 |
+
raise
|
1818 |
+
|
1819 |
+
def destroy(self, *args):
|
1820 |
+
if self._root is None:
|
1821 |
+
return
|
1822 |
+
self._root.destroy()
|
1823 |
+
self._root = None
|
1824 |
+
|
1825 |
+
def mainloop(self, *args, **kwargs):
|
1826 |
+
"""
|
1827 |
+
Enter the Tkinter mainloop. This function must be called if
|
1828 |
+
this demo is created from a non-interactive program (e.g.
|
1829 |
+
from a secript); otherwise, the demo will close as soon as
|
1830 |
+
the script completes.
|
1831 |
+
"""
|
1832 |
+
if in_idle():
|
1833 |
+
return
|
1834 |
+
self._root.mainloop(*args, **kwargs)
|
1835 |
+
|
1836 |
+
# ////////////////////////////////////////////////////////////
|
1837 |
+
# Initialization Helpers
|
1838 |
+
# ////////////////////////////////////////////////////////////
|
1839 |
+
|
1840 |
+
def _init_parser(self, grammar, tokens):
|
1841 |
+
self._grammar = grammar
|
1842 |
+
self._tokens = tokens
|
1843 |
+
self._reset_parser()
|
1844 |
+
|
1845 |
+
def _reset_parser(self):
|
1846 |
+
self._cp = SteppingChartParser(self._grammar)
|
1847 |
+
self._cp.initialize(self._tokens)
|
1848 |
+
self._chart = self._cp.chart()
|
1849 |
+
|
1850 |
+
# Insert LeafEdges before the parsing starts.
|
1851 |
+
for _new_edge in LeafInitRule().apply(self._chart, self._grammar):
|
1852 |
+
pass
|
1853 |
+
|
1854 |
+
# The step iterator -- use this to generate new edges
|
1855 |
+
self._cpstep = self._cp.step()
|
1856 |
+
|
1857 |
+
# The currently selected edge
|
1858 |
+
self._selection = None
|
1859 |
+
|
1860 |
+
def _init_fonts(self, root):
|
1861 |
+
# See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
|
1862 |
+
self._sysfont = Font(font=Button()["font"])
|
1863 |
+
root.option_add("*Font", self._sysfont)
|
1864 |
+
|
1865 |
+
# TWhat's our font size (default=same as sysfont)
|
1866 |
+
self._size = IntVar(root)
|
1867 |
+
self._size.set(self._sysfont.cget("size"))
|
1868 |
+
|
1869 |
+
self._boldfont = Font(family="helvetica", weight="bold", size=self._size.get())
|
1870 |
+
self._font = Font(family="helvetica", size=self._size.get())
|
1871 |
+
|
1872 |
+
def _init_animation(self):
|
1873 |
+
# Are we stepping? (default=yes)
|
1874 |
+
self._step = IntVar(self._root)
|
1875 |
+
self._step.set(1)
|
1876 |
+
|
1877 |
+
# What's our animation speed (default=fast)
|
1878 |
+
self._animate = IntVar(self._root)
|
1879 |
+
self._animate.set(3) # Default speed = fast
|
1880 |
+
|
1881 |
+
# Are we currently animating?
|
1882 |
+
self._animating = 0
|
1883 |
+
|
1884 |
+
def _init_chartview(self, parent):
|
1885 |
+
self._cv = ChartView(self._chart, parent, draw_tree=1, draw_sentence=1)
|
1886 |
+
self._cv.add_callback("select", self._click_cv_edge)
|
1887 |
+
|
1888 |
+
def _init_rulelabel(self, parent):
|
1889 |
+
ruletxt = "Last edge generated by:"
|
1890 |
+
|
1891 |
+
self._rulelabel1 = Label(parent, text=ruletxt, font=self._boldfont)
|
1892 |
+
self._rulelabel2 = Label(
|
1893 |
+
parent, width=40, relief="groove", anchor="w", font=self._boldfont
|
1894 |
+
)
|
1895 |
+
self._rulelabel1.pack(side="left")
|
1896 |
+
self._rulelabel2.pack(side="left")
|
1897 |
+
step = Checkbutton(parent, variable=self._step, text="Step")
|
1898 |
+
step.pack(side="right")
|
1899 |
+
|
1900 |
+
def _init_buttons(self, parent):
|
1901 |
+
frame1 = Frame(parent)
|
1902 |
+
frame2 = Frame(parent)
|
1903 |
+
frame1.pack(side="bottom", fill="x")
|
1904 |
+
frame2.pack(side="top", fill="none")
|
1905 |
+
|
1906 |
+
Button(
|
1907 |
+
frame1,
|
1908 |
+
text="Reset\nParser",
|
1909 |
+
background="#90c0d0",
|
1910 |
+
foreground="black",
|
1911 |
+
command=self.reset,
|
1912 |
+
).pack(side="right")
|
1913 |
+
# Button(frame1, text='Pause',
|
1914 |
+
# background='#90c0d0', foreground='black',
|
1915 |
+
# command=self.pause).pack(side='left')
|
1916 |
+
|
1917 |
+
Button(
|
1918 |
+
frame1,
|
1919 |
+
text="Top Down\nStrategy",
|
1920 |
+
background="#90c0d0",
|
1921 |
+
foreground="black",
|
1922 |
+
command=self.top_down_strategy,
|
1923 |
+
).pack(side="left")
|
1924 |
+
Button(
|
1925 |
+
frame1,
|
1926 |
+
text="Bottom Up\nStrategy",
|
1927 |
+
background="#90c0d0",
|
1928 |
+
foreground="black",
|
1929 |
+
command=self.bottom_up_strategy,
|
1930 |
+
).pack(side="left")
|
1931 |
+
Button(
|
1932 |
+
frame1,
|
1933 |
+
text="Bottom Up\nLeft-Corner Strategy",
|
1934 |
+
background="#90c0d0",
|
1935 |
+
foreground="black",
|
1936 |
+
command=self.bottom_up_leftcorner_strategy,
|
1937 |
+
).pack(side="left")
|
1938 |
+
|
1939 |
+
Button(
|
1940 |
+
frame2,
|
1941 |
+
text="Top Down Init\nRule",
|
1942 |
+
background="#90f090",
|
1943 |
+
foreground="black",
|
1944 |
+
command=self.top_down_init,
|
1945 |
+
).pack(side="left")
|
1946 |
+
Button(
|
1947 |
+
frame2,
|
1948 |
+
text="Top Down Predict\nRule",
|
1949 |
+
background="#90f090",
|
1950 |
+
foreground="black",
|
1951 |
+
command=self.top_down_predict,
|
1952 |
+
).pack(side="left")
|
1953 |
+
Frame(frame2, width=20).pack(side="left")
|
1954 |
+
|
1955 |
+
Button(
|
1956 |
+
frame2,
|
1957 |
+
text="Bottom Up Predict\nRule",
|
1958 |
+
background="#90f090",
|
1959 |
+
foreground="black",
|
1960 |
+
command=self.bottom_up,
|
1961 |
+
).pack(side="left")
|
1962 |
+
Frame(frame2, width=20).pack(side="left")
|
1963 |
+
|
1964 |
+
Button(
|
1965 |
+
frame2,
|
1966 |
+
text="Bottom Up Left-Corner\nPredict Rule",
|
1967 |
+
background="#90f090",
|
1968 |
+
foreground="black",
|
1969 |
+
command=self.bottom_up_leftcorner,
|
1970 |
+
).pack(side="left")
|
1971 |
+
Frame(frame2, width=20).pack(side="left")
|
1972 |
+
|
1973 |
+
Button(
|
1974 |
+
frame2,
|
1975 |
+
text="Fundamental\nRule",
|
1976 |
+
background="#90f090",
|
1977 |
+
foreground="black",
|
1978 |
+
command=self.fundamental,
|
1979 |
+
).pack(side="left")
|
1980 |
+
|
1981 |
+
def _init_bindings(self):
|
1982 |
+
self._root.bind("<Up>", self._cv.scroll_up)
|
1983 |
+
self._root.bind("<Down>", self._cv.scroll_down)
|
1984 |
+
self._root.bind("<Prior>", self._cv.page_up)
|
1985 |
+
self._root.bind("<Next>", self._cv.page_down)
|
1986 |
+
self._root.bind("<Control-q>", self.destroy)
|
1987 |
+
self._root.bind("<Control-x>", self.destroy)
|
1988 |
+
self._root.bind("<F1>", self.help)
|
1989 |
+
|
1990 |
+
self._root.bind("<Control-s>", self.save_chart)
|
1991 |
+
self._root.bind("<Control-o>", self.load_chart)
|
1992 |
+
self._root.bind("<Control-r>", self.reset)
|
1993 |
+
|
1994 |
+
self._root.bind("t", self.top_down_strategy)
|
1995 |
+
self._root.bind("b", self.bottom_up_strategy)
|
1996 |
+
self._root.bind("c", self.bottom_up_leftcorner_strategy)
|
1997 |
+
self._root.bind("<space>", self._stop_animation)
|
1998 |
+
|
1999 |
+
self._root.bind("<Control-g>", self.edit_grammar)
|
2000 |
+
self._root.bind("<Control-t>", self.edit_sentence)
|
2001 |
+
|
2002 |
+
# Animation speed control
|
2003 |
+
self._root.bind("-", lambda e, a=self._animate: a.set(1))
|
2004 |
+
self._root.bind("=", lambda e, a=self._animate: a.set(2))
|
2005 |
+
self._root.bind("+", lambda e, a=self._animate: a.set(3))
|
2006 |
+
|
2007 |
+
# Step control
|
2008 |
+
self._root.bind("s", lambda e, s=self._step: s.set(not s.get()))
|
2009 |
+
|
2010 |
+
def _init_menubar(self):
|
2011 |
+
menubar = Menu(self._root)
|
2012 |
+
|
2013 |
+
filemenu = Menu(menubar, tearoff=0)
|
2014 |
+
filemenu.add_command(
|
2015 |
+
label="Save Chart",
|
2016 |
+
underline=0,
|
2017 |
+
command=self.save_chart,
|
2018 |
+
accelerator="Ctrl-s",
|
2019 |
+
)
|
2020 |
+
filemenu.add_command(
|
2021 |
+
label="Load Chart",
|
2022 |
+
underline=0,
|
2023 |
+
command=self.load_chart,
|
2024 |
+
accelerator="Ctrl-o",
|
2025 |
+
)
|
2026 |
+
filemenu.add_command(
|
2027 |
+
label="Reset Chart", underline=0, command=self.reset, accelerator="Ctrl-r"
|
2028 |
+
)
|
2029 |
+
filemenu.add_separator()
|
2030 |
+
filemenu.add_command(label="Save Grammar", command=self.save_grammar)
|
2031 |
+
filemenu.add_command(label="Load Grammar", command=self.load_grammar)
|
2032 |
+
filemenu.add_separator()
|
2033 |
+
filemenu.add_command(
|
2034 |
+
label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-x"
|
2035 |
+
)
|
2036 |
+
menubar.add_cascade(label="File", underline=0, menu=filemenu)
|
2037 |
+
|
2038 |
+
editmenu = Menu(menubar, tearoff=0)
|
2039 |
+
editmenu.add_command(
|
2040 |
+
label="Edit Grammar",
|
2041 |
+
underline=5,
|
2042 |
+
command=self.edit_grammar,
|
2043 |
+
accelerator="Ctrl-g",
|
2044 |
+
)
|
2045 |
+
editmenu.add_command(
|
2046 |
+
label="Edit Text",
|
2047 |
+
underline=5,
|
2048 |
+
command=self.edit_sentence,
|
2049 |
+
accelerator="Ctrl-t",
|
2050 |
+
)
|
2051 |
+
menubar.add_cascade(label="Edit", underline=0, menu=editmenu)
|
2052 |
+
|
2053 |
+
viewmenu = Menu(menubar, tearoff=0)
|
2054 |
+
viewmenu.add_command(
|
2055 |
+
label="Chart Matrix", underline=6, command=self.view_matrix
|
2056 |
+
)
|
2057 |
+
viewmenu.add_command(label="Results", underline=0, command=self.view_results)
|
2058 |
+
menubar.add_cascade(label="View", underline=0, menu=viewmenu)
|
2059 |
+
|
2060 |
+
rulemenu = Menu(menubar, tearoff=0)
|
2061 |
+
rulemenu.add_command(
|
2062 |
+
label="Top Down Strategy",
|
2063 |
+
underline=0,
|
2064 |
+
command=self.top_down_strategy,
|
2065 |
+
accelerator="t",
|
2066 |
+
)
|
2067 |
+
rulemenu.add_command(
|
2068 |
+
label="Bottom Up Strategy",
|
2069 |
+
underline=0,
|
2070 |
+
command=self.bottom_up_strategy,
|
2071 |
+
accelerator="b",
|
2072 |
+
)
|
2073 |
+
rulemenu.add_command(
|
2074 |
+
label="Bottom Up Left-Corner Strategy",
|
2075 |
+
underline=0,
|
2076 |
+
command=self.bottom_up_leftcorner_strategy,
|
2077 |
+
accelerator="c",
|
2078 |
+
)
|
2079 |
+
rulemenu.add_separator()
|
2080 |
+
rulemenu.add_command(label="Bottom Up Rule", command=self.bottom_up)
|
2081 |
+
rulemenu.add_command(
|
2082 |
+
label="Bottom Up Left-Corner Rule", command=self.bottom_up_leftcorner
|
2083 |
+
)
|
2084 |
+
rulemenu.add_command(label="Top Down Init Rule", command=self.top_down_init)
|
2085 |
+
rulemenu.add_command(
|
2086 |
+
label="Top Down Predict Rule", command=self.top_down_predict
|
2087 |
+
)
|
2088 |
+
rulemenu.add_command(label="Fundamental Rule", command=self.fundamental)
|
2089 |
+
menubar.add_cascade(label="Apply", underline=0, menu=rulemenu)
|
2090 |
+
|
2091 |
+
animatemenu = Menu(menubar, tearoff=0)
|
2092 |
+
animatemenu.add_checkbutton(
|
2093 |
+
label="Step", underline=0, variable=self._step, accelerator="s"
|
2094 |
+
)
|
2095 |
+
animatemenu.add_separator()
|
2096 |
+
animatemenu.add_radiobutton(
|
2097 |
+
label="No Animation", underline=0, variable=self._animate, value=0
|
2098 |
+
)
|
2099 |
+
animatemenu.add_radiobutton(
|
2100 |
+
label="Slow Animation",
|
2101 |
+
underline=0,
|
2102 |
+
variable=self._animate,
|
2103 |
+
value=1,
|
2104 |
+
accelerator="-",
|
2105 |
+
)
|
2106 |
+
animatemenu.add_radiobutton(
|
2107 |
+
label="Normal Animation",
|
2108 |
+
underline=0,
|
2109 |
+
variable=self._animate,
|
2110 |
+
value=2,
|
2111 |
+
accelerator="=",
|
2112 |
+
)
|
2113 |
+
animatemenu.add_radiobutton(
|
2114 |
+
label="Fast Animation",
|
2115 |
+
underline=0,
|
2116 |
+
variable=self._animate,
|
2117 |
+
value=3,
|
2118 |
+
accelerator="+",
|
2119 |
+
)
|
2120 |
+
menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)
|
2121 |
+
|
2122 |
+
zoommenu = Menu(menubar, tearoff=0)
|
2123 |
+
zoommenu.add_radiobutton(
|
2124 |
+
label="Tiny",
|
2125 |
+
variable=self._size,
|
2126 |
+
underline=0,
|
2127 |
+
value=10,
|
2128 |
+
command=self.resize,
|
2129 |
+
)
|
2130 |
+
zoommenu.add_radiobutton(
|
2131 |
+
label="Small",
|
2132 |
+
variable=self._size,
|
2133 |
+
underline=0,
|
2134 |
+
value=12,
|
2135 |
+
command=self.resize,
|
2136 |
+
)
|
2137 |
+
zoommenu.add_radiobutton(
|
2138 |
+
label="Medium",
|
2139 |
+
variable=self._size,
|
2140 |
+
underline=0,
|
2141 |
+
value=14,
|
2142 |
+
command=self.resize,
|
2143 |
+
)
|
2144 |
+
zoommenu.add_radiobutton(
|
2145 |
+
label="Large",
|
2146 |
+
variable=self._size,
|
2147 |
+
underline=0,
|
2148 |
+
value=18,
|
2149 |
+
command=self.resize,
|
2150 |
+
)
|
2151 |
+
zoommenu.add_radiobutton(
|
2152 |
+
label="Huge",
|
2153 |
+
variable=self._size,
|
2154 |
+
underline=0,
|
2155 |
+
value=24,
|
2156 |
+
command=self.resize,
|
2157 |
+
)
|
2158 |
+
menubar.add_cascade(label="Zoom", underline=0, menu=zoommenu)
|
2159 |
+
|
2160 |
+
helpmenu = Menu(menubar, tearoff=0)
|
2161 |
+
helpmenu.add_command(label="About", underline=0, command=self.about)
|
2162 |
+
helpmenu.add_command(
|
2163 |
+
label="Instructions", underline=0, command=self.help, accelerator="F1"
|
2164 |
+
)
|
2165 |
+
menubar.add_cascade(label="Help", underline=0, menu=helpmenu)
|
2166 |
+
|
2167 |
+
self._root.config(menu=menubar)
|
2168 |
+
|
2169 |
+
# ////////////////////////////////////////////////////////////
|
2170 |
+
# Selection Handling
|
2171 |
+
# ////////////////////////////////////////////////////////////
|
2172 |
+
|
2173 |
+
def _click_cv_edge(self, edge):
|
2174 |
+
if edge != self._selection:
|
2175 |
+
# Clicking on a new edge selects it.
|
2176 |
+
self._select_edge(edge)
|
2177 |
+
else:
|
2178 |
+
# Repeated clicks on one edge cycle its trees.
|
2179 |
+
self._cv.cycle_tree()
|
2180 |
+
# [XX] this can get confused if animation is running
|
2181 |
+
# faster than the callbacks...
|
2182 |
+
|
2183 |
+
def _select_matrix_edge(self, edge):
|
2184 |
+
self._select_edge(edge)
|
2185 |
+
self._cv.view_edge(edge)
|
2186 |
+
|
2187 |
+
def _select_edge(self, edge):
|
2188 |
+
self._selection = edge
|
2189 |
+
# Update the chart view.
|
2190 |
+
self._cv.markonly_edge(edge, "#f00")
|
2191 |
+
self._cv.draw_tree(edge)
|
2192 |
+
# Update the matrix view.
|
2193 |
+
if self._matrix:
|
2194 |
+
self._matrix.markonly_edge(edge)
|
2195 |
+
if self._matrix:
|
2196 |
+
self._matrix.view_edge(edge)
|
2197 |
+
|
2198 |
+
def _deselect_edge(self):
|
2199 |
+
self._selection = None
|
2200 |
+
# Update the chart view.
|
2201 |
+
self._cv.unmark_edge()
|
2202 |
+
self._cv.erase_tree()
|
2203 |
+
# Update the matrix view
|
2204 |
+
if self._matrix:
|
2205 |
+
self._matrix.unmark_edge()
|
2206 |
+
|
2207 |
+
def _show_new_edge(self, edge):
|
2208 |
+
self._display_rule(self._cp.current_chartrule())
|
2209 |
+
# Update the chart view.
|
2210 |
+
self._cv.update()
|
2211 |
+
self._cv.draw_tree(edge)
|
2212 |
+
self._cv.markonly_edge(edge, "#0df")
|
2213 |
+
self._cv.view_edge(edge)
|
2214 |
+
# Update the matrix view.
|
2215 |
+
if self._matrix:
|
2216 |
+
self._matrix.update()
|
2217 |
+
if self._matrix:
|
2218 |
+
self._matrix.markonly_edge(edge)
|
2219 |
+
if self._matrix:
|
2220 |
+
self._matrix.view_edge(edge)
|
2221 |
+
# Update the results view.
|
2222 |
+
if self._results:
|
2223 |
+
self._results.update(edge)
|
2224 |
+
|
2225 |
+
# ////////////////////////////////////////////////////////////
|
2226 |
+
# Help/usage
|
2227 |
+
# ////////////////////////////////////////////////////////////
|
2228 |
+
|
2229 |
+
def help(self, *e):
|
2230 |
+
self._animating = 0
|
2231 |
+
# The default font's not very legible; try using 'fixed' instead.
|
2232 |
+
try:
|
2233 |
+
ShowText(
|
2234 |
+
self._root,
|
2235 |
+
"Help: Chart Parser Application",
|
2236 |
+
(__doc__ or "").strip(),
|
2237 |
+
width=75,
|
2238 |
+
font="fixed",
|
2239 |
+
)
|
2240 |
+
except:
|
2241 |
+
ShowText(
|
2242 |
+
self._root,
|
2243 |
+
"Help: Chart Parser Application",
|
2244 |
+
(__doc__ or "").strip(),
|
2245 |
+
width=75,
|
2246 |
+
)
|
2247 |
+
|
2248 |
+
def about(self, *e):
|
2249 |
+
ABOUT = "NLTK Chart Parser Application\n" + "Written by Edward Loper"
|
2250 |
+
showinfo("About: Chart Parser Application", ABOUT)
|
2251 |
+
|
2252 |
+
# ////////////////////////////////////////////////////////////
|
2253 |
+
# File Menu
|
2254 |
+
# ////////////////////////////////////////////////////////////
|
2255 |
+
|
2256 |
+
CHART_FILE_TYPES = [("Pickle file", ".pickle"), ("All files", "*")]
|
2257 |
+
GRAMMAR_FILE_TYPES = [
|
2258 |
+
("Plaintext grammar file", ".cfg"),
|
2259 |
+
("Pickle file", ".pickle"),
|
2260 |
+
("All files", "*"),
|
2261 |
+
]
|
2262 |
+
|
2263 |
+
def load_chart(self, *args):
|
2264 |
+
"Load a chart from a pickle file"
|
2265 |
+
filename = askopenfilename(
|
2266 |
+
filetypes=self.CHART_FILE_TYPES, defaultextension=".pickle"
|
2267 |
+
)
|
2268 |
+
if not filename:
|
2269 |
+
return
|
2270 |
+
try:
|
2271 |
+
with open(filename, "rb") as infile:
|
2272 |
+
chart = pickle.load(infile)
|
2273 |
+
self._chart = chart
|
2274 |
+
self._cv.update(chart)
|
2275 |
+
if self._matrix:
|
2276 |
+
self._matrix.set_chart(chart)
|
2277 |
+
if self._matrix:
|
2278 |
+
self._matrix.deselect_cell()
|
2279 |
+
if self._results:
|
2280 |
+
self._results.set_chart(chart)
|
2281 |
+
self._cp.set_chart(chart)
|
2282 |
+
except Exception as e:
|
2283 |
+
raise
|
2284 |
+
showerror("Error Loading Chart", "Unable to open file: %r" % filename)
|
2285 |
+
|
2286 |
+
def save_chart(self, *args):
|
2287 |
+
"Save a chart to a pickle file"
|
2288 |
+
filename = asksaveasfilename(
|
2289 |
+
filetypes=self.CHART_FILE_TYPES, defaultextension=".pickle"
|
2290 |
+
)
|
2291 |
+
if not filename:
|
2292 |
+
return
|
2293 |
+
try:
|
2294 |
+
with open(filename, "wb") as outfile:
|
2295 |
+
pickle.dump(self._chart, outfile)
|
2296 |
+
except Exception as e:
|
2297 |
+
raise
|
2298 |
+
showerror("Error Saving Chart", "Unable to open file: %r" % filename)
|
2299 |
+
|
2300 |
+
def load_grammar(self, *args):
|
2301 |
+
"Load a grammar from a pickle file"
|
2302 |
+
filename = askopenfilename(
|
2303 |
+
filetypes=self.GRAMMAR_FILE_TYPES, defaultextension=".cfg"
|
2304 |
+
)
|
2305 |
+
if not filename:
|
2306 |
+
return
|
2307 |
+
try:
|
2308 |
+
if filename.endswith(".pickle"):
|
2309 |
+
with open(filename, "rb") as infile:
|
2310 |
+
grammar = pickle.load(infile)
|
2311 |
+
else:
|
2312 |
+
with open(filename) as infile:
|
2313 |
+
grammar = CFG.fromstring(infile.read())
|
2314 |
+
self.set_grammar(grammar)
|
2315 |
+
except Exception as e:
|
2316 |
+
showerror("Error Loading Grammar", "Unable to open file: %r" % filename)
|
2317 |
+
|
2318 |
+
def save_grammar(self, *args):
|
2319 |
+
filename = asksaveasfilename(
|
2320 |
+
filetypes=self.GRAMMAR_FILE_TYPES, defaultextension=".cfg"
|
2321 |
+
)
|
2322 |
+
if not filename:
|
2323 |
+
return
|
2324 |
+
try:
|
2325 |
+
if filename.endswith(".pickle"):
|
2326 |
+
with open(filename, "wb") as outfile:
|
2327 |
+
pickle.dump((self._chart, self._tokens), outfile)
|
2328 |
+
else:
|
2329 |
+
with open(filename, "w") as outfile:
|
2330 |
+
prods = self._grammar.productions()
|
2331 |
+
start = [p for p in prods if p.lhs() == self._grammar.start()]
|
2332 |
+
rest = [p for p in prods if p.lhs() != self._grammar.start()]
|
2333 |
+
for prod in start:
|
2334 |
+
outfile.write("%s\n" % prod)
|
2335 |
+
for prod in rest:
|
2336 |
+
outfile.write("%s\n" % prod)
|
2337 |
+
except Exception as e:
|
2338 |
+
showerror("Error Saving Grammar", "Unable to open file: %r" % filename)
|
2339 |
+
|
2340 |
+
def reset(self, *args):
|
2341 |
+
self._animating = 0
|
2342 |
+
self._reset_parser()
|
2343 |
+
self._cv.update(self._chart)
|
2344 |
+
if self._matrix:
|
2345 |
+
self._matrix.set_chart(self._chart)
|
2346 |
+
if self._matrix:
|
2347 |
+
self._matrix.deselect_cell()
|
2348 |
+
if self._results:
|
2349 |
+
self._results.set_chart(self._chart)
|
2350 |
+
|
2351 |
+
# ////////////////////////////////////////////////////////////
|
2352 |
+
# Edit
|
2353 |
+
# ////////////////////////////////////////////////////////////
|
2354 |
+
|
2355 |
+
def edit_grammar(self, *e):
|
2356 |
+
CFGEditor(self._root, self._grammar, self.set_grammar)
|
2357 |
+
|
2358 |
+
def set_grammar(self, grammar):
|
2359 |
+
self._grammar = grammar
|
2360 |
+
self._cp.set_grammar(grammar)
|
2361 |
+
if self._results:
|
2362 |
+
self._results.set_grammar(grammar)
|
2363 |
+
|
2364 |
+
def edit_sentence(self, *e):
|
2365 |
+
sentence = " ".join(self._tokens)
|
2366 |
+
title = "Edit Text"
|
2367 |
+
instr = "Enter a new sentence to parse."
|
2368 |
+
EntryDialog(self._root, sentence, instr, self.set_sentence, title)
|
2369 |
+
|
2370 |
+
def set_sentence(self, sentence):
|
2371 |
+
self._tokens = list(sentence.split())
|
2372 |
+
self.reset()
|
2373 |
+
|
2374 |
+
# ////////////////////////////////////////////////////////////
|
2375 |
+
# View Menu
|
2376 |
+
# ////////////////////////////////////////////////////////////
|
2377 |
+
|
2378 |
+
def view_matrix(self, *e):
|
2379 |
+
if self._matrix is not None:
|
2380 |
+
self._matrix.destroy()
|
2381 |
+
self._matrix = ChartMatrixView(self._root, self._chart)
|
2382 |
+
self._matrix.add_callback("select", self._select_matrix_edge)
|
2383 |
+
|
2384 |
+
def view_results(self, *e):
|
2385 |
+
if self._results is not None:
|
2386 |
+
self._results.destroy()
|
2387 |
+
self._results = ChartResultsView(self._root, self._chart, self._grammar)
|
2388 |
+
|
2389 |
+
# ////////////////////////////////////////////////////////////
|
2390 |
+
# Zoom Menu
|
2391 |
+
# ////////////////////////////////////////////////////////////
|
2392 |
+
|
2393 |
+
def resize(self):
|
2394 |
+
self._animating = 0
|
2395 |
+
self.set_font_size(self._size.get())
|
2396 |
+
|
2397 |
+
def set_font_size(self, size):
|
2398 |
+
self._cv.set_font_size(size)
|
2399 |
+
self._font.configure(size=-abs(size))
|
2400 |
+
self._boldfont.configure(size=-abs(size))
|
2401 |
+
self._sysfont.configure(size=-abs(size))
|
2402 |
+
|
2403 |
+
def get_font_size(self):
|
2404 |
+
return abs(self._size.get())
|
2405 |
+
|
2406 |
+
# ////////////////////////////////////////////////////////////
|
2407 |
+
# Parsing
|
2408 |
+
# ////////////////////////////////////////////////////////////
|
2409 |
+
|
2410 |
+
def apply_strategy(self, strategy, edge_strategy=None):
|
2411 |
+
# If we're animating, then stop.
|
2412 |
+
if self._animating:
|
2413 |
+
self._animating = 0
|
2414 |
+
return
|
2415 |
+
|
2416 |
+
# Clear the rule display & mark.
|
2417 |
+
self._display_rule(None)
|
2418 |
+
# self._cv.unmark_edge()
|
2419 |
+
|
2420 |
+
if self._step.get():
|
2421 |
+
selection = self._selection
|
2422 |
+
if (selection is not None) and (edge_strategy is not None):
|
2423 |
+
# Apply the given strategy to the selected edge.
|
2424 |
+
self._cp.set_strategy([edge_strategy(selection)])
|
2425 |
+
newedge = self._apply_strategy()
|
2426 |
+
|
2427 |
+
# If it failed, then clear the selection.
|
2428 |
+
if newedge is None:
|
2429 |
+
self._cv.unmark_edge()
|
2430 |
+
self._selection = None
|
2431 |
+
else:
|
2432 |
+
self._cp.set_strategy(strategy)
|
2433 |
+
self._apply_strategy()
|
2434 |
+
|
2435 |
+
else:
|
2436 |
+
self._cp.set_strategy(strategy)
|
2437 |
+
if self._animate.get():
|
2438 |
+
self._animating = 1
|
2439 |
+
self._animate_strategy()
|
2440 |
+
else:
|
2441 |
+
for edge in self._cpstep:
|
2442 |
+
if edge is None:
|
2443 |
+
break
|
2444 |
+
self._cv.update()
|
2445 |
+
if self._matrix:
|
2446 |
+
self._matrix.update()
|
2447 |
+
if self._results:
|
2448 |
+
self._results.update()
|
2449 |
+
|
2450 |
+
def _stop_animation(self, *e):
|
2451 |
+
self._animating = 0
|
2452 |
+
|
2453 |
+
def _animate_strategy(self, speed=1):
|
2454 |
+
if self._animating == 0:
|
2455 |
+
return
|
2456 |
+
if self._apply_strategy() is not None:
|
2457 |
+
if self._animate.get() == 0 or self._step.get() == 1:
|
2458 |
+
return
|
2459 |
+
if self._animate.get() == 1:
|
2460 |
+
self._root.after(3000, self._animate_strategy)
|
2461 |
+
elif self._animate.get() == 2:
|
2462 |
+
self._root.after(1000, self._animate_strategy)
|
2463 |
+
else:
|
2464 |
+
self._root.after(20, self._animate_strategy)
|
2465 |
+
|
2466 |
+
def _apply_strategy(self):
|
2467 |
+
new_edge = next(self._cpstep)
|
2468 |
+
|
2469 |
+
if new_edge is not None:
|
2470 |
+
self._show_new_edge(new_edge)
|
2471 |
+
return new_edge
|
2472 |
+
|
2473 |
+
def _display_rule(self, rule):
|
2474 |
+
if rule is None:
|
2475 |
+
self._rulelabel2["text"] = ""
|
2476 |
+
else:
|
2477 |
+
name = str(rule)
|
2478 |
+
self._rulelabel2["text"] = name
|
2479 |
+
size = self._cv.get_font_size()
|
2480 |
+
|
2481 |
+
# ////////////////////////////////////////////////////////////
|
2482 |
+
# Parsing Strategies
|
2483 |
+
# ////////////////////////////////////////////////////////////
|
2484 |
+
|
2485 |
+
# Basic rules:
|
2486 |
+
_TD_INIT = [TopDownInitRule()]
|
2487 |
+
_TD_PREDICT = [TopDownPredictRule()]
|
2488 |
+
_BU_RULE = [BottomUpPredictRule()]
|
2489 |
+
_BU_LC_RULE = [BottomUpPredictCombineRule()]
|
2490 |
+
_FUNDAMENTAL = [SingleEdgeFundamentalRule()]
|
2491 |
+
|
2492 |
+
# Complete strategies:
|
2493 |
+
_TD_STRATEGY = _TD_INIT + _TD_PREDICT + _FUNDAMENTAL
|
2494 |
+
_BU_STRATEGY = _BU_RULE + _FUNDAMENTAL
|
2495 |
+
_BU_LC_STRATEGY = _BU_LC_RULE + _FUNDAMENTAL
|
2496 |
+
|
2497 |
+
# Button callback functions:
|
2498 |
+
def top_down_init(self, *e):
|
2499 |
+
self.apply_strategy(self._TD_INIT, None)
|
2500 |
+
|
2501 |
+
def top_down_predict(self, *e):
|
2502 |
+
self.apply_strategy(self._TD_PREDICT, TopDownPredictEdgeRule)
|
2503 |
+
|
2504 |
+
def bottom_up(self, *e):
|
2505 |
+
self.apply_strategy(self._BU_RULE, BottomUpEdgeRule)
|
2506 |
+
|
2507 |
+
def bottom_up_leftcorner(self, *e):
|
2508 |
+
self.apply_strategy(self._BU_LC_RULE, BottomUpLeftCornerEdgeRule)
|
2509 |
+
|
2510 |
+
def fundamental(self, *e):
|
2511 |
+
self.apply_strategy(self._FUNDAMENTAL, FundamentalEdgeRule)
|
2512 |
+
|
2513 |
+
def bottom_up_strategy(self, *e):
|
2514 |
+
self.apply_strategy(self._BU_STRATEGY, BottomUpEdgeRule)
|
2515 |
+
|
2516 |
+
def bottom_up_leftcorner_strategy(self, *e):
|
2517 |
+
self.apply_strategy(self._BU_LC_STRATEGY, BottomUpLeftCornerEdgeRule)
|
2518 |
+
|
2519 |
+
def top_down_strategy(self, *e):
|
2520 |
+
self.apply_strategy(self._TD_STRATEGY, TopDownPredictEdgeRule)
|
2521 |
+
|
2522 |
+
|
2523 |
+
def app():
|
2524 |
+
grammar = CFG.fromstring(
|
2525 |
+
"""
|
2526 |
+
# Grammatical productions.
|
2527 |
+
S -> NP VP
|
2528 |
+
VP -> VP PP | V NP | V
|
2529 |
+
NP -> Det N | NP PP
|
2530 |
+
PP -> P NP
|
2531 |
+
# Lexical productions.
|
2532 |
+
NP -> 'John' | 'I'
|
2533 |
+
Det -> 'the' | 'my' | 'a'
|
2534 |
+
N -> 'dog' | 'cookie' | 'table' | 'cake' | 'fork'
|
2535 |
+
V -> 'ate' | 'saw'
|
2536 |
+
P -> 'on' | 'under' | 'with'
|
2537 |
+
"""
|
2538 |
+
)
|
2539 |
+
|
2540 |
+
sent = "John ate the cake on the table with a fork"
|
2541 |
+
sent = "John ate the cake on the table"
|
2542 |
+
tokens = list(sent.split())
|
2543 |
+
|
2544 |
+
print("grammar= (")
|
2545 |
+
for rule in grammar.productions():
|
2546 |
+
print((" ", repr(rule) + ","))
|
2547 |
+
print(")")
|
2548 |
+
print("tokens = %r" % tokens)
|
2549 |
+
print('Calling "ChartParserApp(grammar, tokens)"...')
|
2550 |
+
ChartParserApp(grammar, tokens).mainloop()
|
2551 |
+
|
2552 |
+
|
2553 |
+
if __name__ == "__main__":
|
2554 |
+
app()
|
2555 |
+
|
2556 |
+
# Chart comparer:
|
2557 |
+
# charts = ['/tmp/earley.pickle',
|
2558 |
+
# '/tmp/topdown.pickle',
|
2559 |
+
# '/tmp/bottomup.pickle']
|
2560 |
+
# ChartComparer(*charts).mainloop()
|
2561 |
+
|
2562 |
+
# import profile
|
2563 |
+
# profile.run('demo2()', '/tmp/profile.out')
|
2564 |
+
# import pstats
|
2565 |
+
# p = pstats.Stats('/tmp/profile.out')
|
2566 |
+
# p.strip_dirs().sort_stats('time', 'cum').print_stats(60)
|
2567 |
+
# p.strip_dirs().sort_stats('cum', 'time').print_stats(60)
|
2568 |
+
|
2569 |
+
__all__ = ["app"]
|
env-llmeval/lib/python3.10/site-packages/nltk/app/chunkparser_app.py
ADDED
@@ -0,0 +1,1500 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Regexp Chunk Parser Application
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Edward Loper <[email protected]>
|
5 |
+
# URL: <https://www.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 |
+
import random
|
19 |
+
import re
|
20 |
+
import textwrap
|
21 |
+
import time
|
22 |
+
from tkinter import (
|
23 |
+
Button,
|
24 |
+
Canvas,
|
25 |
+
Checkbutton,
|
26 |
+
Frame,
|
27 |
+
IntVar,
|
28 |
+
Label,
|
29 |
+
Menu,
|
30 |
+
Scrollbar,
|
31 |
+
Text,
|
32 |
+
Tk,
|
33 |
+
)
|
34 |
+
from tkinter.filedialog import askopenfilename, asksaveasfilename
|
35 |
+
from tkinter.font import Font
|
36 |
+
|
37 |
+
from nltk.chunk import ChunkScore, RegexpChunkParser
|
38 |
+
from nltk.chunk.regexp import RegexpChunkRule
|
39 |
+
from nltk.corpus import conll2000, treebank_chunk
|
40 |
+
from nltk.draw.util import ShowText
|
41 |
+
from nltk.tree import Tree
|
42 |
+
from nltk.util import in_idle
|
43 |
+
|
44 |
+
|
45 |
+
class RegexpChunkApp:
|
46 |
+
"""
|
47 |
+
A graphical tool for exploring the regular expression based chunk
|
48 |
+
parser ``nltk.chunk.RegexpChunkParser``.
|
49 |
+
|
50 |
+
See ``HELP`` for instructional text.
|
51 |
+
"""
|
52 |
+
|
53 |
+
##/////////////////////////////////////////////////////////////////
|
54 |
+
## Help Text
|
55 |
+
##/////////////////////////////////////////////////////////////////
|
56 |
+
|
57 |
+
#: A dictionary mapping from part of speech tags to descriptions,
|
58 |
+
#: which is used in the help text. (This should probably live with
|
59 |
+
#: the conll and/or treebank corpus instead.)
|
60 |
+
TAGSET = {
|
61 |
+
"CC": "Coordinating conjunction",
|
62 |
+
"PRP$": "Possessive pronoun",
|
63 |
+
"CD": "Cardinal number",
|
64 |
+
"RB": "Adverb",
|
65 |
+
"DT": "Determiner",
|
66 |
+
"RBR": "Adverb, comparative",
|
67 |
+
"EX": "Existential there",
|
68 |
+
"RBS": "Adverb, superlative",
|
69 |
+
"FW": "Foreign word",
|
70 |
+
"RP": "Particle",
|
71 |
+
"JJ": "Adjective",
|
72 |
+
"TO": "to",
|
73 |
+
"JJR": "Adjective, comparative",
|
74 |
+
"UH": "Interjection",
|
75 |
+
"JJS": "Adjective, superlative",
|
76 |
+
"VB": "Verb, base form",
|
77 |
+
"LS": "List item marker",
|
78 |
+
"VBD": "Verb, past tense",
|
79 |
+
"MD": "Modal",
|
80 |
+
"NNS": "Noun, plural",
|
81 |
+
"NN": "Noun, singular or masps",
|
82 |
+
"VBN": "Verb, past participle",
|
83 |
+
"VBZ": "Verb,3rd ps. sing. present",
|
84 |
+
"NNP": "Proper noun, singular",
|
85 |
+
"NNPS": "Proper noun plural",
|
86 |
+
"WDT": "wh-determiner",
|
87 |
+
"PDT": "Predeterminer",
|
88 |
+
"WP": "wh-pronoun",
|
89 |
+
"POS": "Possessive ending",
|
90 |
+
"WP$": "Possessive wh-pronoun",
|
91 |
+
"PRP": "Personal pronoun",
|
92 |
+
"WRB": "wh-adverb",
|
93 |
+
"(": "open parenthesis",
|
94 |
+
")": "close parenthesis",
|
95 |
+
"``": "open quote",
|
96 |
+
",": "comma",
|
97 |
+
"''": "close quote",
|
98 |
+
".": "period",
|
99 |
+
"#": "pound sign (currency marker)",
|
100 |
+
"$": "dollar sign (currency marker)",
|
101 |
+
"IN": "Preposition/subord. conjunction",
|
102 |
+
"SYM": "Symbol (mathematical or scientific)",
|
103 |
+
"VBG": "Verb, gerund/present participle",
|
104 |
+
"VBP": "Verb, non-3rd ps. sing. present",
|
105 |
+
":": "colon",
|
106 |
+
}
|
107 |
+
|
108 |
+
#: Contents for the help box. This is a list of tuples, one for
|
109 |
+
#: each help page, where each tuple has four elements:
|
110 |
+
#: - A title (displayed as a tab)
|
111 |
+
#: - A string description of tabstops (see Tkinter.Text for details)
|
112 |
+
#: - The text contents for the help page. You can use expressions
|
113 |
+
#: like <red>...</red> to colorize the text; see ``HELP_AUTOTAG``
|
114 |
+
#: for a list of tags you can use for colorizing.
|
115 |
+
HELP = [
|
116 |
+
(
|
117 |
+
"Help",
|
118 |
+
"20",
|
119 |
+
"Welcome to the regular expression chunk-parser grammar editor. "
|
120 |
+
"You can use this editor to develop and test chunk parser grammars "
|
121 |
+
"based on NLTK's RegexpChunkParser class.\n\n"
|
122 |
+
# Help box.
|
123 |
+
"Use this box ('Help') to learn more about the editor; click on the "
|
124 |
+
"tabs for help on specific topics:"
|
125 |
+
"<indent>\n"
|
126 |
+
"Rules: grammar rule types\n"
|
127 |
+
"Regexps: regular expression syntax\n"
|
128 |
+
"Tags: part of speech tags\n</indent>\n"
|
129 |
+
# Grammar.
|
130 |
+
"Use the upper-left box ('Grammar') to edit your grammar. "
|
131 |
+
"Each line of your grammar specifies a single 'rule', "
|
132 |
+
"which performs an action such as creating a chunk or merging "
|
133 |
+
"two chunks.\n\n"
|
134 |
+
# Dev set.
|
135 |
+
"The lower-left box ('Development Set') runs your grammar on the "
|
136 |
+
"development set, and displays the results. "
|
137 |
+
"Your grammar's chunks are <highlight>highlighted</highlight>, and "
|
138 |
+
"the correct (gold standard) chunks are "
|
139 |
+
"<underline>underlined</underline>. If they "
|
140 |
+
"match, they are displayed in <green>green</green>; otherwise, "
|
141 |
+
"they are displayed in <red>red</red>. The box displays a single "
|
142 |
+
"sentence from the development set at a time; use the scrollbar or "
|
143 |
+
"the next/previous buttons view additional sentences.\n\n"
|
144 |
+
# Performance
|
145 |
+
"The lower-right box ('Evaluation') tracks the performance of "
|
146 |
+
"your grammar on the development set. The 'precision' axis "
|
147 |
+
"indicates how many of your grammar's chunks are correct; and "
|
148 |
+
"the 'recall' axis indicates how many of the gold standard "
|
149 |
+
"chunks your system generated. Typically, you should try to "
|
150 |
+
"design a grammar that scores high on both metrics. The "
|
151 |
+
"exact precision and recall of the current grammar, as well "
|
152 |
+
"as their harmonic mean (the 'f-score'), are displayed in "
|
153 |
+
"the status bar at the bottom of the window.",
|
154 |
+
),
|
155 |
+
(
|
156 |
+
"Rules",
|
157 |
+
"10",
|
158 |
+
"<h1>{...regexp...}</h1>"
|
159 |
+
"<indent>\nChunk rule: creates new chunks from words matching "
|
160 |
+
"regexp.</indent>\n\n"
|
161 |
+
"<h1>}...regexp...{</h1>"
|
162 |
+
"<indent>\nStrip rule: removes words matching regexp from existing "
|
163 |
+
"chunks.</indent>\n\n"
|
164 |
+
"<h1>...regexp1...}{...regexp2...</h1>"
|
165 |
+
"<indent>\nSplit rule: splits chunks that match regexp1 followed by "
|
166 |
+
"regexp2 in two.</indent>\n\n"
|
167 |
+
"<h1>...regexp...{}...regexp...</h1>"
|
168 |
+
"<indent>\nMerge rule: joins consecutive chunks that match regexp1 "
|
169 |
+
"and regexp2</indent>\n",
|
170 |
+
),
|
171 |
+
(
|
172 |
+
"Regexps",
|
173 |
+
"10 60",
|
174 |
+
# "Regular Expression Syntax Summary:\n\n"
|
175 |
+
"<h1>Pattern\t\tMatches...</h1>\n"
|
176 |
+
"<hangindent>"
|
177 |
+
"\t<<var>T</var>>\ta word with tag <var>T</var> "
|
178 |
+
"(where <var>T</var> may be a regexp).\n"
|
179 |
+
"\t<var>x</var>?\tan optional <var>x</var>\n"
|
180 |
+
"\t<var>x</var>+\ta sequence of 1 or more <var>x</var>'s\n"
|
181 |
+
"\t<var>x</var>*\ta sequence of 0 or more <var>x</var>'s\n"
|
182 |
+
"\t<var>x</var>|<var>y</var>\t<var>x</var> or <var>y</var>\n"
|
183 |
+
"\t.\tmatches any character\n"
|
184 |
+
"\t(<var>x</var>)\tTreats <var>x</var> as a group\n"
|
185 |
+
"\t# <var>x...</var>\tTreats <var>x...</var> "
|
186 |
+
"(to the end of the line) as a comment\n"
|
187 |
+
"\t\\<var>C</var>\tmatches character <var>C</var> "
|
188 |
+
"(useful when <var>C</var> is a special character "
|
189 |
+
"like + or #)\n"
|
190 |
+
"</hangindent>"
|
191 |
+
"\n<h1>Examples:</h1>\n"
|
192 |
+
"<hangindent>"
|
193 |
+
"\t<regexp><NN></regexp>\n"
|
194 |
+
'\t\tMatches <match>"cow/NN"</match>\n'
|
195 |
+
'\t\tMatches <match>"green/NN"</match>\n'
|
196 |
+
"\t<regexp><VB.*></regexp>\n"
|
197 |
+
'\t\tMatches <match>"eating/VBG"</match>\n'
|
198 |
+
'\t\tMatches <match>"ate/VBD"</match>\n'
|
199 |
+
"\t<regexp><IN><DT><NN></regexp>\n"
|
200 |
+
'\t\tMatches <match>"on/IN the/DT car/NN"</match>\n'
|
201 |
+
"\t<regexp><RB>?<VBD></regexp>\n"
|
202 |
+
'\t\tMatches <match>"ran/VBD"</match>\n'
|
203 |
+
'\t\tMatches <match>"slowly/RB ate/VBD"</match>\n'
|
204 |
+
r"\t<regexp><\#><CD> # This is a comment...</regexp>\n"
|
205 |
+
'\t\tMatches <match>"#/# 100/CD"</match>\n'
|
206 |
+
"</hangindent>",
|
207 |
+
),
|
208 |
+
(
|
209 |
+
"Tags",
|
210 |
+
"10 60",
|
211 |
+
"<h1>Part of Speech Tags:</h1>\n"
|
212 |
+
+ "<hangindent>"
|
213 |
+
+ "<<TAGSET>>"
|
214 |
+
+ "</hangindent>\n", # this gets auto-substituted w/ self.TAGSET
|
215 |
+
),
|
216 |
+
]
|
217 |
+
|
218 |
+
HELP_AUTOTAG = [
|
219 |
+
("red", dict(foreground="#a00")),
|
220 |
+
("green", dict(foreground="#080")),
|
221 |
+
("highlight", dict(background="#ddd")),
|
222 |
+
("underline", dict(underline=True)),
|
223 |
+
("h1", dict(underline=True)),
|
224 |
+
("indent", dict(lmargin1=20, lmargin2=20)),
|
225 |
+
("hangindent", dict(lmargin1=0, lmargin2=60)),
|
226 |
+
("var", dict(foreground="#88f")),
|
227 |
+
("regexp", dict(foreground="#ba7")),
|
228 |
+
("match", dict(foreground="#6a6")),
|
229 |
+
]
|
230 |
+
|
231 |
+
##/////////////////////////////////////////////////////////////////
|
232 |
+
## Config Parameters
|
233 |
+
##/////////////////////////////////////////////////////////////////
|
234 |
+
|
235 |
+
_EVAL_DELAY = 1
|
236 |
+
"""If the user has not pressed any key for this amount of time (in
|
237 |
+
seconds), and the current grammar has not been evaluated, then
|
238 |
+
the eval demon will evaluate it."""
|
239 |
+
|
240 |
+
_EVAL_CHUNK = 15
|
241 |
+
"""The number of sentences that should be evaluated by the eval
|
242 |
+
demon each time it runs."""
|
243 |
+
_EVAL_FREQ = 0.2
|
244 |
+
"""The frequency (in seconds) at which the eval demon is run"""
|
245 |
+
_EVAL_DEMON_MIN = 0.02
|
246 |
+
"""The minimum amount of time that the eval demon should take each time
|
247 |
+
it runs -- if it takes less than this time, _EVAL_CHUNK will be
|
248 |
+
modified upwards."""
|
249 |
+
_EVAL_DEMON_MAX = 0.04
|
250 |
+
"""The maximum amount of time that the eval demon should take each time
|
251 |
+
it runs -- if it takes more than this time, _EVAL_CHUNK will be
|
252 |
+
modified downwards."""
|
253 |
+
|
254 |
+
_GRAMMARBOX_PARAMS = dict(
|
255 |
+
width=40,
|
256 |
+
height=12,
|
257 |
+
background="#efe",
|
258 |
+
highlightbackground="#efe",
|
259 |
+
highlightthickness=1,
|
260 |
+
relief="groove",
|
261 |
+
border=2,
|
262 |
+
wrap="word",
|
263 |
+
)
|
264 |
+
_HELPBOX_PARAMS = dict(
|
265 |
+
width=15,
|
266 |
+
height=15,
|
267 |
+
background="#efe",
|
268 |
+
highlightbackground="#efe",
|
269 |
+
foreground="#555",
|
270 |
+
highlightthickness=1,
|
271 |
+
relief="groove",
|
272 |
+
border=2,
|
273 |
+
wrap="word",
|
274 |
+
)
|
275 |
+
_DEVSETBOX_PARAMS = dict(
|
276 |
+
width=70,
|
277 |
+
height=10,
|
278 |
+
background="#eef",
|
279 |
+
highlightbackground="#eef",
|
280 |
+
highlightthickness=1,
|
281 |
+
relief="groove",
|
282 |
+
border=2,
|
283 |
+
wrap="word",
|
284 |
+
tabs=(30,),
|
285 |
+
)
|
286 |
+
_STATUS_PARAMS = dict(background="#9bb", relief="groove", border=2)
|
287 |
+
_FONT_PARAMS = dict(family="helvetica", size=-20)
|
288 |
+
_FRAME_PARAMS = dict(background="#777", padx=2, pady=2, border=3)
|
289 |
+
_EVALBOX_PARAMS = dict(
|
290 |
+
background="#eef",
|
291 |
+
highlightbackground="#eef",
|
292 |
+
highlightthickness=1,
|
293 |
+
relief="groove",
|
294 |
+
border=2,
|
295 |
+
width=300,
|
296 |
+
height=280,
|
297 |
+
)
|
298 |
+
_BUTTON_PARAMS = dict(
|
299 |
+
background="#777", activebackground="#777", highlightbackground="#777"
|
300 |
+
)
|
301 |
+
_HELPTAB_BG_COLOR = "#aba"
|
302 |
+
_HELPTAB_FG_COLOR = "#efe"
|
303 |
+
|
304 |
+
_HELPTAB_FG_PARAMS = dict(background="#efe")
|
305 |
+
_HELPTAB_BG_PARAMS = dict(background="#aba")
|
306 |
+
_HELPTAB_SPACER = 6
|
307 |
+
|
308 |
+
def normalize_grammar(self, grammar):
|
309 |
+
# Strip comments
|
310 |
+
grammar = re.sub(r"((\\.|[^#])*)(#.*)?", r"\1", grammar)
|
311 |
+
# Normalize whitespace
|
312 |
+
grammar = re.sub(" +", " ", grammar)
|
313 |
+
grammar = re.sub(r"\n\s+", r"\n", grammar)
|
314 |
+
grammar = grammar.strip()
|
315 |
+
# [xx] Hack: automatically backslash $!
|
316 |
+
grammar = re.sub(r"([^\\])\$", r"\1\\$", grammar)
|
317 |
+
return grammar
|
318 |
+
|
319 |
+
def __init__(
|
320 |
+
self,
|
321 |
+
devset_name="conll2000",
|
322 |
+
devset=None,
|
323 |
+
grammar="",
|
324 |
+
chunk_label="NP",
|
325 |
+
tagset=None,
|
326 |
+
):
|
327 |
+
"""
|
328 |
+
:param devset_name: The name of the development set; used for
|
329 |
+
display & for save files. If either the name 'treebank'
|
330 |
+
or the name 'conll2000' is used, and devset is None, then
|
331 |
+
devset will be set automatically.
|
332 |
+
:param devset: A list of chunked sentences
|
333 |
+
:param grammar: The initial grammar to display.
|
334 |
+
:param tagset: Dictionary from tags to string descriptions, used
|
335 |
+
for the help page. Defaults to ``self.TAGSET``.
|
336 |
+
"""
|
337 |
+
self._chunk_label = chunk_label
|
338 |
+
|
339 |
+
if tagset is None:
|
340 |
+
tagset = self.TAGSET
|
341 |
+
self.tagset = tagset
|
342 |
+
|
343 |
+
# Named development sets:
|
344 |
+
if devset is None:
|
345 |
+
if devset_name == "conll2000":
|
346 |
+
devset = conll2000.chunked_sents("train.txt") # [:100]
|
347 |
+
elif devset == "treebank":
|
348 |
+
devset = treebank_chunk.chunked_sents() # [:100]
|
349 |
+
else:
|
350 |
+
raise ValueError("Unknown development set %s" % devset_name)
|
351 |
+
|
352 |
+
self.chunker = None
|
353 |
+
"""The chunker built from the grammar string"""
|
354 |
+
|
355 |
+
self.grammar = grammar
|
356 |
+
"""The unparsed grammar string"""
|
357 |
+
|
358 |
+
self.normalized_grammar = None
|
359 |
+
"""A normalized version of ``self.grammar``."""
|
360 |
+
|
361 |
+
self.grammar_changed = 0
|
362 |
+
"""The last time() that the grammar was changed."""
|
363 |
+
|
364 |
+
self.devset = devset
|
365 |
+
"""The development set -- a list of chunked sentences."""
|
366 |
+
|
367 |
+
self.devset_name = devset_name
|
368 |
+
"""The name of the development set (for save files)."""
|
369 |
+
|
370 |
+
self.devset_index = -1
|
371 |
+
"""The index into the development set of the first instance
|
372 |
+
that's currently being viewed."""
|
373 |
+
|
374 |
+
self._last_keypress = 0
|
375 |
+
"""The time() when a key was most recently pressed"""
|
376 |
+
|
377 |
+
self._history = []
|
378 |
+
"""A list of (grammar, precision, recall, fscore) tuples for
|
379 |
+
grammars that the user has already tried."""
|
380 |
+
|
381 |
+
self._history_index = 0
|
382 |
+
"""When the user is scrolling through previous grammars, this
|
383 |
+
is used to keep track of which grammar they're looking at."""
|
384 |
+
|
385 |
+
self._eval_grammar = None
|
386 |
+
"""The grammar that is being currently evaluated by the eval
|
387 |
+
demon."""
|
388 |
+
|
389 |
+
self._eval_normalized_grammar = None
|
390 |
+
"""A normalized copy of ``_eval_grammar``."""
|
391 |
+
|
392 |
+
self._eval_index = 0
|
393 |
+
"""The index of the next sentence in the development set that
|
394 |
+
should be looked at by the eval demon."""
|
395 |
+
|
396 |
+
self._eval_score = ChunkScore(chunk_label=chunk_label)
|
397 |
+
"""The ``ChunkScore`` object that's used to keep track of the score
|
398 |
+
of the current grammar on the development set."""
|
399 |
+
|
400 |
+
# Set up the main window.
|
401 |
+
top = self.top = Tk()
|
402 |
+
top.geometry("+50+50")
|
403 |
+
top.title("Regexp Chunk Parser App")
|
404 |
+
top.bind("<Control-q>", self.destroy)
|
405 |
+
|
406 |
+
# Variable that restricts how much of the devset we look at.
|
407 |
+
self._devset_size = IntVar(top)
|
408 |
+
self._devset_size.set(100)
|
409 |
+
|
410 |
+
# Set up all the tkinter widgets
|
411 |
+
self._init_fonts(top)
|
412 |
+
self._init_widgets(top)
|
413 |
+
self._init_bindings(top)
|
414 |
+
self._init_menubar(top)
|
415 |
+
self.grammarbox.focus()
|
416 |
+
|
417 |
+
# If a grammar was given, then display it.
|
418 |
+
if grammar:
|
419 |
+
self.grammarbox.insert("end", grammar + "\n")
|
420 |
+
self.grammarbox.mark_set("insert", "1.0")
|
421 |
+
|
422 |
+
# Display the first item in the development set
|
423 |
+
self.show_devset(0)
|
424 |
+
self.update()
|
425 |
+
|
426 |
+
def _init_bindings(self, top):
|
427 |
+
top.bind("<Control-n>", self._devset_next)
|
428 |
+
top.bind("<Control-p>", self._devset_prev)
|
429 |
+
top.bind("<Control-t>", self.toggle_show_trace)
|
430 |
+
top.bind("<KeyPress>", self.update)
|
431 |
+
top.bind("<Control-s>", lambda e: self.save_grammar())
|
432 |
+
top.bind("<Control-o>", lambda e: self.load_grammar())
|
433 |
+
self.grammarbox.bind("<Control-t>", self.toggle_show_trace)
|
434 |
+
self.grammarbox.bind("<Control-n>", self._devset_next)
|
435 |
+
self.grammarbox.bind("<Control-p>", self._devset_prev)
|
436 |
+
|
437 |
+
# Redraw the eval graph when the window size changes
|
438 |
+
self.evalbox.bind("<Configure>", self._eval_plot)
|
439 |
+
|
440 |
+
def _init_fonts(self, top):
|
441 |
+
# TWhat's our font size (default=same as sysfont)
|
442 |
+
self._size = IntVar(top)
|
443 |
+
self._size.set(20)
|
444 |
+
self._font = Font(family="helvetica", size=-self._size.get())
|
445 |
+
self._smallfont = Font(
|
446 |
+
family="helvetica", size=-(int(self._size.get() * 14 // 20))
|
447 |
+
)
|
448 |
+
|
449 |
+
def _init_menubar(self, parent):
|
450 |
+
menubar = Menu(parent)
|
451 |
+
|
452 |
+
filemenu = Menu(menubar, tearoff=0)
|
453 |
+
filemenu.add_command(label="Reset Application", underline=0, command=self.reset)
|
454 |
+
filemenu.add_command(
|
455 |
+
label="Save Current Grammar",
|
456 |
+
underline=0,
|
457 |
+
accelerator="Ctrl-s",
|
458 |
+
command=self.save_grammar,
|
459 |
+
)
|
460 |
+
filemenu.add_command(
|
461 |
+
label="Load Grammar",
|
462 |
+
underline=0,
|
463 |
+
accelerator="Ctrl-o",
|
464 |
+
command=self.load_grammar,
|
465 |
+
)
|
466 |
+
|
467 |
+
filemenu.add_command(
|
468 |
+
label="Save Grammar History", underline=13, command=self.save_history
|
469 |
+
)
|
470 |
+
|
471 |
+
filemenu.add_command(
|
472 |
+
label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-q"
|
473 |
+
)
|
474 |
+
menubar.add_cascade(label="File", underline=0, menu=filemenu)
|
475 |
+
|
476 |
+
viewmenu = Menu(menubar, tearoff=0)
|
477 |
+
viewmenu.add_radiobutton(
|
478 |
+
label="Tiny",
|
479 |
+
variable=self._size,
|
480 |
+
underline=0,
|
481 |
+
value=10,
|
482 |
+
command=self.resize,
|
483 |
+
)
|
484 |
+
viewmenu.add_radiobutton(
|
485 |
+
label="Small",
|
486 |
+
variable=self._size,
|
487 |
+
underline=0,
|
488 |
+
value=16,
|
489 |
+
command=self.resize,
|
490 |
+
)
|
491 |
+
viewmenu.add_radiobutton(
|
492 |
+
label="Medium",
|
493 |
+
variable=self._size,
|
494 |
+
underline=0,
|
495 |
+
value=20,
|
496 |
+
command=self.resize,
|
497 |
+
)
|
498 |
+
viewmenu.add_radiobutton(
|
499 |
+
label="Large",
|
500 |
+
variable=self._size,
|
501 |
+
underline=0,
|
502 |
+
value=24,
|
503 |
+
command=self.resize,
|
504 |
+
)
|
505 |
+
viewmenu.add_radiobutton(
|
506 |
+
label="Huge",
|
507 |
+
variable=self._size,
|
508 |
+
underline=0,
|
509 |
+
value=34,
|
510 |
+
command=self.resize,
|
511 |
+
)
|
512 |
+
menubar.add_cascade(label="View", underline=0, menu=viewmenu)
|
513 |
+
|
514 |
+
devsetmenu = Menu(menubar, tearoff=0)
|
515 |
+
devsetmenu.add_radiobutton(
|
516 |
+
label="50 sentences",
|
517 |
+
variable=self._devset_size,
|
518 |
+
value=50,
|
519 |
+
command=self.set_devset_size,
|
520 |
+
)
|
521 |
+
devsetmenu.add_radiobutton(
|
522 |
+
label="100 sentences",
|
523 |
+
variable=self._devset_size,
|
524 |
+
value=100,
|
525 |
+
command=self.set_devset_size,
|
526 |
+
)
|
527 |
+
devsetmenu.add_radiobutton(
|
528 |
+
label="200 sentences",
|
529 |
+
variable=self._devset_size,
|
530 |
+
value=200,
|
531 |
+
command=self.set_devset_size,
|
532 |
+
)
|
533 |
+
devsetmenu.add_radiobutton(
|
534 |
+
label="500 sentences",
|
535 |
+
variable=self._devset_size,
|
536 |
+
value=500,
|
537 |
+
command=self.set_devset_size,
|
538 |
+
)
|
539 |
+
menubar.add_cascade(label="Development-Set", underline=0, menu=devsetmenu)
|
540 |
+
|
541 |
+
helpmenu = Menu(menubar, tearoff=0)
|
542 |
+
helpmenu.add_command(label="About", underline=0, command=self.about)
|
543 |
+
menubar.add_cascade(label="Help", underline=0, menu=helpmenu)
|
544 |
+
|
545 |
+
parent.config(menu=menubar)
|
546 |
+
|
547 |
+
def toggle_show_trace(self, *e):
|
548 |
+
if self._showing_trace:
|
549 |
+
self.show_devset()
|
550 |
+
else:
|
551 |
+
self.show_trace()
|
552 |
+
return "break"
|
553 |
+
|
554 |
+
_SCALE_N = 5 # center on the last 5 examples.
|
555 |
+
_DRAW_LINES = False
|
556 |
+
|
557 |
+
def _eval_plot(self, *e, **config):
|
558 |
+
width = config.get("width", self.evalbox.winfo_width())
|
559 |
+
height = config.get("height", self.evalbox.winfo_height())
|
560 |
+
|
561 |
+
# Clear the canvas
|
562 |
+
self.evalbox.delete("all")
|
563 |
+
|
564 |
+
# Draw the precision & recall labels.
|
565 |
+
tag = self.evalbox.create_text(
|
566 |
+
10, height // 2 - 10, justify="left", anchor="w", text="Precision"
|
567 |
+
)
|
568 |
+
left, right = self.evalbox.bbox(tag)[2] + 5, width - 10
|
569 |
+
tag = self.evalbox.create_text(
|
570 |
+
left + (width - left) // 2,
|
571 |
+
height - 10,
|
572 |
+
anchor="s",
|
573 |
+
text="Recall",
|
574 |
+
justify="center",
|
575 |
+
)
|
576 |
+
top, bot = 10, self.evalbox.bbox(tag)[1] - 10
|
577 |
+
|
578 |
+
# Draw masks for clipping the plot.
|
579 |
+
bg = self._EVALBOX_PARAMS["background"]
|
580 |
+
self.evalbox.lower(
|
581 |
+
self.evalbox.create_rectangle(0, 0, left - 1, 5000, fill=bg, outline=bg)
|
582 |
+
)
|
583 |
+
self.evalbox.lower(
|
584 |
+
self.evalbox.create_rectangle(0, bot + 1, 5000, 5000, fill=bg, outline=bg)
|
585 |
+
)
|
586 |
+
|
587 |
+
# Calculate the plot's scale.
|
588 |
+
if self._autoscale.get() and len(self._history) > 1:
|
589 |
+
max_precision = max_recall = 0
|
590 |
+
min_precision = min_recall = 1
|
591 |
+
for i in range(1, min(len(self._history), self._SCALE_N + 1)):
|
592 |
+
grammar, precision, recall, fmeasure = self._history[-i]
|
593 |
+
min_precision = min(precision, min_precision)
|
594 |
+
min_recall = min(recall, min_recall)
|
595 |
+
max_precision = max(precision, max_precision)
|
596 |
+
max_recall = max(recall, max_recall)
|
597 |
+
# if max_precision-min_precision > max_recall-min_recall:
|
598 |
+
# min_recall -= (max_precision-min_precision)/2
|
599 |
+
# max_recall += (max_precision-min_precision)/2
|
600 |
+
# else:
|
601 |
+
# min_precision -= (max_recall-min_recall)/2
|
602 |
+
# max_precision += (max_recall-min_recall)/2
|
603 |
+
# if min_recall < 0:
|
604 |
+
# max_recall -= min_recall
|
605 |
+
# min_recall = 0
|
606 |
+
# if min_precision < 0:
|
607 |
+
# max_precision -= min_precision
|
608 |
+
# min_precision = 0
|
609 |
+
min_precision = max(min_precision - 0.01, 0)
|
610 |
+
min_recall = max(min_recall - 0.01, 0)
|
611 |
+
max_precision = min(max_precision + 0.01, 1)
|
612 |
+
max_recall = min(max_recall + 0.01, 1)
|
613 |
+
else:
|
614 |
+
min_precision = min_recall = 0
|
615 |
+
max_precision = max_recall = 1
|
616 |
+
|
617 |
+
# Draw the axis lines & grid lines
|
618 |
+
for i in range(11):
|
619 |
+
x = left + (right - left) * (
|
620 |
+
(i / 10.0 - min_recall) / (max_recall - min_recall)
|
621 |
+
)
|
622 |
+
y = bot - (bot - top) * (
|
623 |
+
(i / 10.0 - min_precision) / (max_precision - min_precision)
|
624 |
+
)
|
625 |
+
if left < x < right:
|
626 |
+
self.evalbox.create_line(x, top, x, bot, fill="#888")
|
627 |
+
if top < y < bot:
|
628 |
+
self.evalbox.create_line(left, y, right, y, fill="#888")
|
629 |
+
self.evalbox.create_line(left, top, left, bot)
|
630 |
+
self.evalbox.create_line(left, bot, right, bot)
|
631 |
+
|
632 |
+
# Display the plot's scale
|
633 |
+
self.evalbox.create_text(
|
634 |
+
left - 3,
|
635 |
+
bot,
|
636 |
+
justify="right",
|
637 |
+
anchor="se",
|
638 |
+
text="%d%%" % (100 * min_precision),
|
639 |
+
)
|
640 |
+
self.evalbox.create_text(
|
641 |
+
left - 3,
|
642 |
+
top,
|
643 |
+
justify="right",
|
644 |
+
anchor="ne",
|
645 |
+
text="%d%%" % (100 * max_precision),
|
646 |
+
)
|
647 |
+
self.evalbox.create_text(
|
648 |
+
left,
|
649 |
+
bot + 3,
|
650 |
+
justify="center",
|
651 |
+
anchor="nw",
|
652 |
+
text="%d%%" % (100 * min_recall),
|
653 |
+
)
|
654 |
+
self.evalbox.create_text(
|
655 |
+
right,
|
656 |
+
bot + 3,
|
657 |
+
justify="center",
|
658 |
+
anchor="ne",
|
659 |
+
text="%d%%" % (100 * max_recall),
|
660 |
+
)
|
661 |
+
|
662 |
+
# Display the scores.
|
663 |
+
prev_x = prev_y = None
|
664 |
+
for i, (_, precision, recall, fscore) in enumerate(self._history):
|
665 |
+
x = left + (right - left) * (
|
666 |
+
(recall - min_recall) / (max_recall - min_recall)
|
667 |
+
)
|
668 |
+
y = bot - (bot - top) * (
|
669 |
+
(precision - min_precision) / (max_precision - min_precision)
|
670 |
+
)
|
671 |
+
if i == self._history_index:
|
672 |
+
self.evalbox.create_oval(
|
673 |
+
x - 2, y - 2, x + 2, y + 2, fill="#0f0", outline="#000"
|
674 |
+
)
|
675 |
+
self.status["text"] = (
|
676 |
+
"Precision: %.2f%%\t" % (precision * 100)
|
677 |
+
+ "Recall: %.2f%%\t" % (recall * 100)
|
678 |
+
+ "F-score: %.2f%%" % (fscore * 100)
|
679 |
+
)
|
680 |
+
else:
|
681 |
+
self.evalbox.lower(
|
682 |
+
self.evalbox.create_oval(
|
683 |
+
x - 2, y - 2, x + 2, y + 2, fill="#afa", outline="#8c8"
|
684 |
+
)
|
685 |
+
)
|
686 |
+
if prev_x is not None and self._eval_lines.get():
|
687 |
+
self.evalbox.lower(
|
688 |
+
self.evalbox.create_line(prev_x, prev_y, x, y, fill="#8c8")
|
689 |
+
)
|
690 |
+
prev_x, prev_y = x, y
|
691 |
+
|
692 |
+
_eval_demon_running = False
|
693 |
+
|
694 |
+
def _eval_demon(self):
|
695 |
+
if self.top is None:
|
696 |
+
return
|
697 |
+
if self.chunker is None:
|
698 |
+
self._eval_demon_running = False
|
699 |
+
return
|
700 |
+
|
701 |
+
# Note our starting time.
|
702 |
+
t0 = time.time()
|
703 |
+
|
704 |
+
# If are still typing, then wait for them to finish.
|
705 |
+
if (
|
706 |
+
time.time() - self._last_keypress < self._EVAL_DELAY
|
707 |
+
and self.normalized_grammar != self._eval_normalized_grammar
|
708 |
+
):
|
709 |
+
self._eval_demon_running = True
|
710 |
+
return self.top.after(int(self._EVAL_FREQ * 1000), self._eval_demon)
|
711 |
+
|
712 |
+
# If the grammar changed, restart the evaluation.
|
713 |
+
if self.normalized_grammar != self._eval_normalized_grammar:
|
714 |
+
# Check if we've seen this grammar already. If so, then
|
715 |
+
# just use the old evaluation values.
|
716 |
+
for (g, p, r, f) in self._history:
|
717 |
+
if self.normalized_grammar == self.normalize_grammar(g):
|
718 |
+
self._history.append((g, p, r, f))
|
719 |
+
self._history_index = len(self._history) - 1
|
720 |
+
self._eval_plot()
|
721 |
+
self._eval_demon_running = False
|
722 |
+
self._eval_normalized_grammar = None
|
723 |
+
return
|
724 |
+
self._eval_index = 0
|
725 |
+
self._eval_score = ChunkScore(chunk_label=self._chunk_label)
|
726 |
+
self._eval_grammar = self.grammar
|
727 |
+
self._eval_normalized_grammar = self.normalized_grammar
|
728 |
+
|
729 |
+
# If the grammar is empty, the don't bother evaluating it, or
|
730 |
+
# recording it in history -- the score will just be 0.
|
731 |
+
if self.normalized_grammar.strip() == "":
|
732 |
+
# self._eval_index = self._devset_size.get()
|
733 |
+
self._eval_demon_running = False
|
734 |
+
return
|
735 |
+
|
736 |
+
# Score the next set of examples
|
737 |
+
for gold in self.devset[
|
738 |
+
self._eval_index : min(
|
739 |
+
self._eval_index + self._EVAL_CHUNK, self._devset_size.get()
|
740 |
+
)
|
741 |
+
]:
|
742 |
+
guess = self._chunkparse(gold.leaves())
|
743 |
+
self._eval_score.score(gold, guess)
|
744 |
+
|
745 |
+
# update our index in the devset.
|
746 |
+
self._eval_index += self._EVAL_CHUNK
|
747 |
+
|
748 |
+
# Check if we're done
|
749 |
+
if self._eval_index >= self._devset_size.get():
|
750 |
+
self._history.append(
|
751 |
+
(
|
752 |
+
self._eval_grammar,
|
753 |
+
self._eval_score.precision(),
|
754 |
+
self._eval_score.recall(),
|
755 |
+
self._eval_score.f_measure(),
|
756 |
+
)
|
757 |
+
)
|
758 |
+
self._history_index = len(self._history) - 1
|
759 |
+
self._eval_plot()
|
760 |
+
self._eval_demon_running = False
|
761 |
+
self._eval_normalized_grammar = None
|
762 |
+
else:
|
763 |
+
progress = 100 * self._eval_index / self._devset_size.get()
|
764 |
+
self.status["text"] = "Evaluating on Development Set (%d%%)" % progress
|
765 |
+
self._eval_demon_running = True
|
766 |
+
self._adaptively_modify_eval_chunk(time.time() - t0)
|
767 |
+
self.top.after(int(self._EVAL_FREQ * 1000), self._eval_demon)
|
768 |
+
|
769 |
+
def _adaptively_modify_eval_chunk(self, t):
|
770 |
+
"""
|
771 |
+
Modify _EVAL_CHUNK to try to keep the amount of time that the
|
772 |
+
eval demon takes between _EVAL_DEMON_MIN and _EVAL_DEMON_MAX.
|
773 |
+
|
774 |
+
:param t: The amount of time that the eval demon took.
|
775 |
+
"""
|
776 |
+
if t > self._EVAL_DEMON_MAX and self._EVAL_CHUNK > 5:
|
777 |
+
self._EVAL_CHUNK = min(
|
778 |
+
self._EVAL_CHUNK - 1,
|
779 |
+
max(
|
780 |
+
int(self._EVAL_CHUNK * (self._EVAL_DEMON_MAX / t)),
|
781 |
+
self._EVAL_CHUNK - 10,
|
782 |
+
),
|
783 |
+
)
|
784 |
+
elif t < self._EVAL_DEMON_MIN:
|
785 |
+
self._EVAL_CHUNK = max(
|
786 |
+
self._EVAL_CHUNK + 1,
|
787 |
+
min(
|
788 |
+
int(self._EVAL_CHUNK * (self._EVAL_DEMON_MIN / t)),
|
789 |
+
self._EVAL_CHUNK + 10,
|
790 |
+
),
|
791 |
+
)
|
792 |
+
|
793 |
+
def _init_widgets(self, top):
|
794 |
+
frame0 = Frame(top, **self._FRAME_PARAMS)
|
795 |
+
frame0.grid_columnconfigure(0, weight=4)
|
796 |
+
frame0.grid_columnconfigure(3, weight=2)
|
797 |
+
frame0.grid_rowconfigure(1, weight=1)
|
798 |
+
frame0.grid_rowconfigure(5, weight=1)
|
799 |
+
|
800 |
+
# The grammar
|
801 |
+
self.grammarbox = Text(frame0, font=self._font, **self._GRAMMARBOX_PARAMS)
|
802 |
+
self.grammarlabel = Label(
|
803 |
+
frame0,
|
804 |
+
font=self._font,
|
805 |
+
text="Grammar:",
|
806 |
+
highlightcolor="black",
|
807 |
+
background=self._GRAMMARBOX_PARAMS["background"],
|
808 |
+
)
|
809 |
+
self.grammarlabel.grid(column=0, row=0, sticky="SW")
|
810 |
+
self.grammarbox.grid(column=0, row=1, sticky="NEWS")
|
811 |
+
|
812 |
+
# Scroll bar for grammar
|
813 |
+
grammar_scrollbar = Scrollbar(frame0, command=self.grammarbox.yview)
|
814 |
+
grammar_scrollbar.grid(column=1, row=1, sticky="NWS")
|
815 |
+
self.grammarbox.config(yscrollcommand=grammar_scrollbar.set)
|
816 |
+
|
817 |
+
# grammar buttons
|
818 |
+
bg = self._FRAME_PARAMS["background"]
|
819 |
+
frame3 = Frame(frame0, background=bg)
|
820 |
+
frame3.grid(column=0, row=2, sticky="EW")
|
821 |
+
Button(
|
822 |
+
frame3,
|
823 |
+
text="Prev Grammar",
|
824 |
+
command=self._history_prev,
|
825 |
+
**self._BUTTON_PARAMS,
|
826 |
+
).pack(side="left")
|
827 |
+
Button(
|
828 |
+
frame3,
|
829 |
+
text="Next Grammar",
|
830 |
+
command=self._history_next,
|
831 |
+
**self._BUTTON_PARAMS,
|
832 |
+
).pack(side="left")
|
833 |
+
|
834 |
+
# Help box
|
835 |
+
self.helpbox = Text(frame0, font=self._smallfont, **self._HELPBOX_PARAMS)
|
836 |
+
self.helpbox.grid(column=3, row=1, sticky="NEWS")
|
837 |
+
self.helptabs = {}
|
838 |
+
bg = self._FRAME_PARAMS["background"]
|
839 |
+
helptab_frame = Frame(frame0, background=bg)
|
840 |
+
helptab_frame.grid(column=3, row=0, sticky="SW")
|
841 |
+
for i, (tab, tabstops, text) in enumerate(self.HELP):
|
842 |
+
label = Label(helptab_frame, text=tab, font=self._smallfont)
|
843 |
+
label.grid(column=i * 2, row=0, sticky="S")
|
844 |
+
# help_frame.grid_columnconfigure(i, weight=1)
|
845 |
+
# label.pack(side='left')
|
846 |
+
label.bind("<ButtonPress>", lambda e, tab=tab: self.show_help(tab))
|
847 |
+
self.helptabs[tab] = label
|
848 |
+
Frame(
|
849 |
+
helptab_frame, height=1, width=self._HELPTAB_SPACER, background=bg
|
850 |
+
).grid(column=i * 2 + 1, row=0)
|
851 |
+
self.helptabs[self.HELP[0][0]].configure(font=self._font)
|
852 |
+
self.helpbox.tag_config("elide", elide=True)
|
853 |
+
for (tag, params) in self.HELP_AUTOTAG:
|
854 |
+
self.helpbox.tag_config("tag-%s" % tag, **params)
|
855 |
+
self.show_help(self.HELP[0][0])
|
856 |
+
|
857 |
+
# Scroll bar for helpbox
|
858 |
+
help_scrollbar = Scrollbar(frame0, command=self.helpbox.yview)
|
859 |
+
self.helpbox.config(yscrollcommand=help_scrollbar.set)
|
860 |
+
help_scrollbar.grid(column=4, row=1, sticky="NWS")
|
861 |
+
|
862 |
+
# The dev set
|
863 |
+
frame4 = Frame(frame0, background=self._FRAME_PARAMS["background"])
|
864 |
+
self.devsetbox = Text(frame4, font=self._font, **self._DEVSETBOX_PARAMS)
|
865 |
+
self.devsetbox.pack(expand=True, fill="both")
|
866 |
+
self.devsetlabel = Label(
|
867 |
+
frame0,
|
868 |
+
font=self._font,
|
869 |
+
text="Development Set:",
|
870 |
+
justify="right",
|
871 |
+
background=self._DEVSETBOX_PARAMS["background"],
|
872 |
+
)
|
873 |
+
self.devsetlabel.grid(column=0, row=4, sticky="SW")
|
874 |
+
frame4.grid(column=0, row=5, sticky="NEWS")
|
875 |
+
|
876 |
+
# dev set scrollbars
|
877 |
+
self.devset_scroll = Scrollbar(frame0, command=self._devset_scroll)
|
878 |
+
self.devset_scroll.grid(column=1, row=5, sticky="NWS")
|
879 |
+
self.devset_xscroll = Scrollbar(
|
880 |
+
frame4, command=self.devsetbox.xview, orient="horiz"
|
881 |
+
)
|
882 |
+
self.devsetbox["xscrollcommand"] = self.devset_xscroll.set
|
883 |
+
self.devset_xscroll.pack(side="bottom", fill="x")
|
884 |
+
|
885 |
+
# dev set buttons
|
886 |
+
bg = self._FRAME_PARAMS["background"]
|
887 |
+
frame1 = Frame(frame0, background=bg)
|
888 |
+
frame1.grid(column=0, row=7, sticky="EW")
|
889 |
+
Button(
|
890 |
+
frame1,
|
891 |
+
text="Prev Example (Ctrl-p)",
|
892 |
+
command=self._devset_prev,
|
893 |
+
**self._BUTTON_PARAMS,
|
894 |
+
).pack(side="left")
|
895 |
+
Button(
|
896 |
+
frame1,
|
897 |
+
text="Next Example (Ctrl-n)",
|
898 |
+
command=self._devset_next,
|
899 |
+
**self._BUTTON_PARAMS,
|
900 |
+
).pack(side="left")
|
901 |
+
self.devset_button = Button(
|
902 |
+
frame1,
|
903 |
+
text="Show example",
|
904 |
+
command=self.show_devset,
|
905 |
+
state="disabled",
|
906 |
+
**self._BUTTON_PARAMS,
|
907 |
+
)
|
908 |
+
self.devset_button.pack(side="right")
|
909 |
+
self.trace_button = Button(
|
910 |
+
frame1, text="Show trace", command=self.show_trace, **self._BUTTON_PARAMS
|
911 |
+
)
|
912 |
+
self.trace_button.pack(side="right")
|
913 |
+
|
914 |
+
# evaluation box
|
915 |
+
self.evalbox = Canvas(frame0, **self._EVALBOX_PARAMS)
|
916 |
+
label = Label(
|
917 |
+
frame0,
|
918 |
+
font=self._font,
|
919 |
+
text="Evaluation:",
|
920 |
+
justify="right",
|
921 |
+
background=self._EVALBOX_PARAMS["background"],
|
922 |
+
)
|
923 |
+
label.grid(column=3, row=4, sticky="SW")
|
924 |
+
self.evalbox.grid(column=3, row=5, sticky="NEWS", columnspan=2)
|
925 |
+
|
926 |
+
# evaluation box buttons
|
927 |
+
bg = self._FRAME_PARAMS["background"]
|
928 |
+
frame2 = Frame(frame0, background=bg)
|
929 |
+
frame2.grid(column=3, row=7, sticky="EW")
|
930 |
+
self._autoscale = IntVar(self.top)
|
931 |
+
self._autoscale.set(False)
|
932 |
+
Checkbutton(
|
933 |
+
frame2,
|
934 |
+
variable=self._autoscale,
|
935 |
+
command=self._eval_plot,
|
936 |
+
text="Zoom",
|
937 |
+
**self._BUTTON_PARAMS,
|
938 |
+
).pack(side="left")
|
939 |
+
self._eval_lines = IntVar(self.top)
|
940 |
+
self._eval_lines.set(False)
|
941 |
+
Checkbutton(
|
942 |
+
frame2,
|
943 |
+
variable=self._eval_lines,
|
944 |
+
command=self._eval_plot,
|
945 |
+
text="Lines",
|
946 |
+
**self._BUTTON_PARAMS,
|
947 |
+
).pack(side="left")
|
948 |
+
Button(frame2, text="History", **self._BUTTON_PARAMS).pack(side="right")
|
949 |
+
|
950 |
+
# The status label
|
951 |
+
self.status = Label(frame0, font=self._font, **self._STATUS_PARAMS)
|
952 |
+
self.status.grid(column=0, row=9, sticky="NEW", padx=3, pady=2, columnspan=5)
|
953 |
+
|
954 |
+
# Help box & devset box can't be edited.
|
955 |
+
self.helpbox["state"] = "disabled"
|
956 |
+
self.devsetbox["state"] = "disabled"
|
957 |
+
|
958 |
+
# Spacers
|
959 |
+
bg = self._FRAME_PARAMS["background"]
|
960 |
+
Frame(frame0, height=10, width=0, background=bg).grid(column=0, row=3)
|
961 |
+
Frame(frame0, height=0, width=10, background=bg).grid(column=2, row=0)
|
962 |
+
Frame(frame0, height=6, width=0, background=bg).grid(column=0, row=8)
|
963 |
+
|
964 |
+
# pack the frame.
|
965 |
+
frame0.pack(fill="both", expand=True)
|
966 |
+
|
967 |
+
# Set up colors for the devset box
|
968 |
+
self.devsetbox.tag_config("true-pos", background="#afa", underline="True")
|
969 |
+
self.devsetbox.tag_config("false-neg", underline="True", foreground="#800")
|
970 |
+
self.devsetbox.tag_config("false-pos", background="#faa")
|
971 |
+
self.devsetbox.tag_config("trace", foreground="#666", wrap="none")
|
972 |
+
self.devsetbox.tag_config("wrapindent", lmargin2=30, wrap="none")
|
973 |
+
self.devsetbox.tag_config("error", foreground="#800")
|
974 |
+
|
975 |
+
# And for the grammarbox
|
976 |
+
self.grammarbox.tag_config("error", background="#fec")
|
977 |
+
self.grammarbox.tag_config("comment", foreground="#840")
|
978 |
+
self.grammarbox.tag_config("angle", foreground="#00f")
|
979 |
+
self.grammarbox.tag_config("brace", foreground="#0a0")
|
980 |
+
self.grammarbox.tag_config("hangindent", lmargin1=0, lmargin2=40)
|
981 |
+
|
982 |
+
_showing_trace = False
|
983 |
+
|
984 |
+
def show_trace(self, *e):
|
985 |
+
self._showing_trace = True
|
986 |
+
self.trace_button["state"] = "disabled"
|
987 |
+
self.devset_button["state"] = "normal"
|
988 |
+
|
989 |
+
self.devsetbox["state"] = "normal"
|
990 |
+
# self.devsetbox['wrap'] = 'none'
|
991 |
+
self.devsetbox.delete("1.0", "end")
|
992 |
+
self.devsetlabel["text"] = "Development Set (%d/%d)" % (
|
993 |
+
(self.devset_index + 1, self._devset_size.get())
|
994 |
+
)
|
995 |
+
|
996 |
+
if self.chunker is None:
|
997 |
+
self.devsetbox.insert("1.0", "Trace: waiting for a valid grammar.")
|
998 |
+
self.devsetbox.tag_add("error", "1.0", "end")
|
999 |
+
return # can't do anything more
|
1000 |
+
|
1001 |
+
gold_tree = self.devset[self.devset_index]
|
1002 |
+
rules = self.chunker.rules()
|
1003 |
+
|
1004 |
+
# Calculate the tag sequence
|
1005 |
+
tagseq = "\t"
|
1006 |
+
charnum = [1]
|
1007 |
+
for wordnum, (word, pos) in enumerate(gold_tree.leaves()):
|
1008 |
+
tagseq += "%s " % pos
|
1009 |
+
charnum.append(len(tagseq))
|
1010 |
+
self.charnum = {
|
1011 |
+
(i, j): charnum[j]
|
1012 |
+
for i in range(len(rules) + 1)
|
1013 |
+
for j in range(len(charnum))
|
1014 |
+
}
|
1015 |
+
self.linenum = {i: i * 2 + 2 for i in range(len(rules) + 1)}
|
1016 |
+
|
1017 |
+
for i in range(len(rules) + 1):
|
1018 |
+
if i == 0:
|
1019 |
+
self.devsetbox.insert("end", "Start:\n")
|
1020 |
+
self.devsetbox.tag_add("trace", "end -2c linestart", "end -2c")
|
1021 |
+
else:
|
1022 |
+
self.devsetbox.insert("end", "Apply %s:\n" % rules[i - 1])
|
1023 |
+
self.devsetbox.tag_add("trace", "end -2c linestart", "end -2c")
|
1024 |
+
# Display the tag sequence.
|
1025 |
+
self.devsetbox.insert("end", tagseq + "\n")
|
1026 |
+
self.devsetbox.tag_add("wrapindent", "end -2c linestart", "end -2c")
|
1027 |
+
# Run a partial parser, and extract gold & test chunks
|
1028 |
+
chunker = RegexpChunkParser(rules[:i])
|
1029 |
+
test_tree = self._chunkparse(gold_tree.leaves())
|
1030 |
+
gold_chunks = self._chunks(gold_tree)
|
1031 |
+
test_chunks = self._chunks(test_tree)
|
1032 |
+
# Compare them.
|
1033 |
+
for chunk in gold_chunks.intersection(test_chunks):
|
1034 |
+
self._color_chunk(i, chunk, "true-pos")
|
1035 |
+
for chunk in gold_chunks - test_chunks:
|
1036 |
+
self._color_chunk(i, chunk, "false-neg")
|
1037 |
+
for chunk in test_chunks - gold_chunks:
|
1038 |
+
self._color_chunk(i, chunk, "false-pos")
|
1039 |
+
self.devsetbox.insert("end", "Finished.\n")
|
1040 |
+
self.devsetbox.tag_add("trace", "end -2c linestart", "end -2c")
|
1041 |
+
|
1042 |
+
# This is a hack, because the x-scrollbar isn't updating its
|
1043 |
+
# position right -- I'm not sure what the underlying cause is
|
1044 |
+
# though. (This is on OS X w/ python 2.5)
|
1045 |
+
self.top.after(100, self.devset_xscroll.set, 0, 0.3)
|
1046 |
+
|
1047 |
+
def show_help(self, tab):
|
1048 |
+
self.helpbox["state"] = "normal"
|
1049 |
+
self.helpbox.delete("1.0", "end")
|
1050 |
+
for (name, tabstops, text) in self.HELP:
|
1051 |
+
if name == tab:
|
1052 |
+
text = text.replace(
|
1053 |
+
"<<TAGSET>>",
|
1054 |
+
"\n".join(
|
1055 |
+
"\t%s\t%s" % item
|
1056 |
+
for item in sorted(
|
1057 |
+
list(self.tagset.items()),
|
1058 |
+
key=lambda t_w: re.match(r"\w+", t_w[0])
|
1059 |
+
and (0, t_w[0])
|
1060 |
+
or (1, t_w[0]),
|
1061 |
+
)
|
1062 |
+
),
|
1063 |
+
)
|
1064 |
+
|
1065 |
+
self.helptabs[name].config(**self._HELPTAB_FG_PARAMS)
|
1066 |
+
self.helpbox.config(tabs=tabstops)
|
1067 |
+
self.helpbox.insert("1.0", text + "\n" * 20)
|
1068 |
+
C = "1.0 + %d chars"
|
1069 |
+
for (tag, params) in self.HELP_AUTOTAG:
|
1070 |
+
pattern = f"(?s)(<{tag}>)(.*?)(</{tag}>)"
|
1071 |
+
for m in re.finditer(pattern, text):
|
1072 |
+
self.helpbox.tag_add("elide", C % m.start(1), C % m.end(1))
|
1073 |
+
self.helpbox.tag_add(
|
1074 |
+
"tag-%s" % tag, C % m.start(2), C % m.end(2)
|
1075 |
+
)
|
1076 |
+
self.helpbox.tag_add("elide", C % m.start(3), C % m.end(3))
|
1077 |
+
else:
|
1078 |
+
self.helptabs[name].config(**self._HELPTAB_BG_PARAMS)
|
1079 |
+
self.helpbox["state"] = "disabled"
|
1080 |
+
|
1081 |
+
def _history_prev(self, *e):
|
1082 |
+
self._view_history(self._history_index - 1)
|
1083 |
+
return "break"
|
1084 |
+
|
1085 |
+
def _history_next(self, *e):
|
1086 |
+
self._view_history(self._history_index + 1)
|
1087 |
+
return "break"
|
1088 |
+
|
1089 |
+
def _view_history(self, index):
|
1090 |
+
# Bounds & sanity checking:
|
1091 |
+
index = max(0, min(len(self._history) - 1, index))
|
1092 |
+
if not self._history:
|
1093 |
+
return
|
1094 |
+
# Already viewing the requested history item?
|
1095 |
+
if index == self._history_index:
|
1096 |
+
return
|
1097 |
+
# Show the requested grammar. It will get added to _history
|
1098 |
+
# only if they edit it (causing self.update() to get run.)
|
1099 |
+
self.grammarbox["state"] = "normal"
|
1100 |
+
self.grammarbox.delete("1.0", "end")
|
1101 |
+
self.grammarbox.insert("end", self._history[index][0])
|
1102 |
+
self.grammarbox.mark_set("insert", "1.0")
|
1103 |
+
self._history_index = index
|
1104 |
+
self._syntax_highlight_grammar(self._history[index][0])
|
1105 |
+
# Record the normalized grammar & regenerate the chunker.
|
1106 |
+
self.normalized_grammar = self.normalize_grammar(self._history[index][0])
|
1107 |
+
if self.normalized_grammar:
|
1108 |
+
rules = [
|
1109 |
+
RegexpChunkRule.fromstring(line)
|
1110 |
+
for line in self.normalized_grammar.split("\n")
|
1111 |
+
]
|
1112 |
+
else:
|
1113 |
+
rules = []
|
1114 |
+
self.chunker = RegexpChunkParser(rules)
|
1115 |
+
# Show the score.
|
1116 |
+
self._eval_plot()
|
1117 |
+
# Update the devset box
|
1118 |
+
self._highlight_devset()
|
1119 |
+
if self._showing_trace:
|
1120 |
+
self.show_trace()
|
1121 |
+
# Update the grammar label
|
1122 |
+
if self._history_index < len(self._history) - 1:
|
1123 |
+
self.grammarlabel["text"] = "Grammar {}/{}:".format(
|
1124 |
+
self._history_index + 1,
|
1125 |
+
len(self._history),
|
1126 |
+
)
|
1127 |
+
else:
|
1128 |
+
self.grammarlabel["text"] = "Grammar:"
|
1129 |
+
|
1130 |
+
def _devset_next(self, *e):
|
1131 |
+
self._devset_scroll("scroll", 1, "page")
|
1132 |
+
return "break"
|
1133 |
+
|
1134 |
+
def _devset_prev(self, *e):
|
1135 |
+
self._devset_scroll("scroll", -1, "page")
|
1136 |
+
return "break"
|
1137 |
+
|
1138 |
+
def destroy(self, *e):
|
1139 |
+
if self.top is None:
|
1140 |
+
return
|
1141 |
+
self.top.destroy()
|
1142 |
+
self.top = None
|
1143 |
+
|
1144 |
+
def _devset_scroll(self, command, *args):
|
1145 |
+
N = 1 # size of a page -- one sentence.
|
1146 |
+
showing_trace = self._showing_trace
|
1147 |
+
if command == "scroll" and args[1].startswith("unit"):
|
1148 |
+
self.show_devset(self.devset_index + int(args[0]))
|
1149 |
+
elif command == "scroll" and args[1].startswith("page"):
|
1150 |
+
self.show_devset(self.devset_index + N * int(args[0]))
|
1151 |
+
elif command == "moveto":
|
1152 |
+
self.show_devset(int(float(args[0]) * self._devset_size.get()))
|
1153 |
+
else:
|
1154 |
+
assert 0, f"bad scroll command {command} {args}"
|
1155 |
+
if showing_trace:
|
1156 |
+
self.show_trace()
|
1157 |
+
|
1158 |
+
def show_devset(self, index=None):
|
1159 |
+
if index is None:
|
1160 |
+
index = self.devset_index
|
1161 |
+
|
1162 |
+
# Bounds checking
|
1163 |
+
index = min(max(0, index), self._devset_size.get() - 1)
|
1164 |
+
|
1165 |
+
if index == self.devset_index and not self._showing_trace:
|
1166 |
+
return
|
1167 |
+
self.devset_index = index
|
1168 |
+
|
1169 |
+
self._showing_trace = False
|
1170 |
+
self.trace_button["state"] = "normal"
|
1171 |
+
self.devset_button["state"] = "disabled"
|
1172 |
+
|
1173 |
+
# Clear the text box.
|
1174 |
+
self.devsetbox["state"] = "normal"
|
1175 |
+
self.devsetbox["wrap"] = "word"
|
1176 |
+
self.devsetbox.delete("1.0", "end")
|
1177 |
+
self.devsetlabel["text"] = "Development Set (%d/%d)" % (
|
1178 |
+
(self.devset_index + 1, self._devset_size.get())
|
1179 |
+
)
|
1180 |
+
|
1181 |
+
# Add the sentences
|
1182 |
+
sample = self.devset[self.devset_index : self.devset_index + 1]
|
1183 |
+
self.charnum = {}
|
1184 |
+
self.linenum = {0: 1}
|
1185 |
+
for sentnum, sent in enumerate(sample):
|
1186 |
+
linestr = ""
|
1187 |
+
for wordnum, (word, pos) in enumerate(sent.leaves()):
|
1188 |
+
self.charnum[sentnum, wordnum] = len(linestr)
|
1189 |
+
linestr += f"{word}/{pos} "
|
1190 |
+
self.charnum[sentnum, wordnum + 1] = len(linestr)
|
1191 |
+
self.devsetbox.insert("end", linestr[:-1] + "\n\n")
|
1192 |
+
|
1193 |
+
# Highlight chunks in the dev set
|
1194 |
+
if self.chunker is not None:
|
1195 |
+
self._highlight_devset()
|
1196 |
+
self.devsetbox["state"] = "disabled"
|
1197 |
+
|
1198 |
+
# Update the scrollbar
|
1199 |
+
first = self.devset_index / self._devset_size.get()
|
1200 |
+
last = (self.devset_index + 2) / self._devset_size.get()
|
1201 |
+
self.devset_scroll.set(first, last)
|
1202 |
+
|
1203 |
+
def _chunks(self, tree):
|
1204 |
+
chunks = set()
|
1205 |
+
wordnum = 0
|
1206 |
+
for child in tree:
|
1207 |
+
if isinstance(child, Tree):
|
1208 |
+
if child.label() == self._chunk_label:
|
1209 |
+
chunks.add((wordnum, wordnum + len(child)))
|
1210 |
+
wordnum += len(child)
|
1211 |
+
else:
|
1212 |
+
wordnum += 1
|
1213 |
+
return chunks
|
1214 |
+
|
1215 |
+
def _syntax_highlight_grammar(self, grammar):
|
1216 |
+
if self.top is None:
|
1217 |
+
return
|
1218 |
+
self.grammarbox.tag_remove("comment", "1.0", "end")
|
1219 |
+
self.grammarbox.tag_remove("angle", "1.0", "end")
|
1220 |
+
self.grammarbox.tag_remove("brace", "1.0", "end")
|
1221 |
+
self.grammarbox.tag_add("hangindent", "1.0", "end")
|
1222 |
+
for lineno, line in enumerate(grammar.split("\n")):
|
1223 |
+
if not line.strip():
|
1224 |
+
continue
|
1225 |
+
m = re.match(r"(\\.|[^#])*(#.*)?", line)
|
1226 |
+
comment_start = None
|
1227 |
+
if m.group(2):
|
1228 |
+
comment_start = m.start(2)
|
1229 |
+
s = "%d.%d" % (lineno + 1, m.start(2))
|
1230 |
+
e = "%d.%d" % (lineno + 1, m.end(2))
|
1231 |
+
self.grammarbox.tag_add("comment", s, e)
|
1232 |
+
for m in re.finditer("[<>{}]", line):
|
1233 |
+
if comment_start is not None and m.start() >= comment_start:
|
1234 |
+
break
|
1235 |
+
s = "%d.%d" % (lineno + 1, m.start())
|
1236 |
+
e = "%d.%d" % (lineno + 1, m.end())
|
1237 |
+
if m.group() in "<>":
|
1238 |
+
self.grammarbox.tag_add("angle", s, e)
|
1239 |
+
else:
|
1240 |
+
self.grammarbox.tag_add("brace", s, e)
|
1241 |
+
|
1242 |
+
def _grammarcheck(self, grammar):
|
1243 |
+
if self.top is None:
|
1244 |
+
return
|
1245 |
+
self.grammarbox.tag_remove("error", "1.0", "end")
|
1246 |
+
self._grammarcheck_errs = []
|
1247 |
+
for lineno, line in enumerate(grammar.split("\n")):
|
1248 |
+
line = re.sub(r"((\\.|[^#])*)(#.*)?", r"\1", line)
|
1249 |
+
line = line.strip()
|
1250 |
+
if line:
|
1251 |
+
try:
|
1252 |
+
RegexpChunkRule.fromstring(line)
|
1253 |
+
except ValueError as e:
|
1254 |
+
self.grammarbox.tag_add(
|
1255 |
+
"error", "%s.0" % (lineno + 1), "%s.0 lineend" % (lineno + 1)
|
1256 |
+
)
|
1257 |
+
self.status["text"] = ""
|
1258 |
+
|
1259 |
+
def update(self, *event):
|
1260 |
+
# Record when update was called (for grammarcheck)
|
1261 |
+
if event:
|
1262 |
+
self._last_keypress = time.time()
|
1263 |
+
|
1264 |
+
# Read the grammar from the Text box.
|
1265 |
+
self.grammar = grammar = self.grammarbox.get("1.0", "end")
|
1266 |
+
|
1267 |
+
# If the grammar hasn't changed, do nothing:
|
1268 |
+
normalized_grammar = self.normalize_grammar(grammar)
|
1269 |
+
if normalized_grammar == self.normalized_grammar:
|
1270 |
+
return
|
1271 |
+
else:
|
1272 |
+
self.normalized_grammar = normalized_grammar
|
1273 |
+
|
1274 |
+
# If the grammar has changed, and we're looking at history,
|
1275 |
+
# then stop looking at history.
|
1276 |
+
if self._history_index < len(self._history) - 1:
|
1277 |
+
self.grammarlabel["text"] = "Grammar:"
|
1278 |
+
|
1279 |
+
self._syntax_highlight_grammar(grammar)
|
1280 |
+
|
1281 |
+
# The grammar has changed; try parsing it. If it doesn't
|
1282 |
+
# parse, do nothing. (flag error location?)
|
1283 |
+
try:
|
1284 |
+
# Note: the normalized grammar has no blank lines.
|
1285 |
+
if normalized_grammar:
|
1286 |
+
rules = [
|
1287 |
+
RegexpChunkRule.fromstring(line)
|
1288 |
+
for line in normalized_grammar.split("\n")
|
1289 |
+
]
|
1290 |
+
else:
|
1291 |
+
rules = []
|
1292 |
+
except ValueError as e:
|
1293 |
+
# Use the un-normalized grammar for error highlighting.
|
1294 |
+
self._grammarcheck(grammar)
|
1295 |
+
self.chunker = None
|
1296 |
+
return
|
1297 |
+
|
1298 |
+
self.chunker = RegexpChunkParser(rules)
|
1299 |
+
self.grammarbox.tag_remove("error", "1.0", "end")
|
1300 |
+
self.grammar_changed = time.time()
|
1301 |
+
# Display the results
|
1302 |
+
if self._showing_trace:
|
1303 |
+
self.show_trace()
|
1304 |
+
else:
|
1305 |
+
self._highlight_devset()
|
1306 |
+
# Start the eval demon
|
1307 |
+
if not self._eval_demon_running:
|
1308 |
+
self._eval_demon()
|
1309 |
+
|
1310 |
+
def _highlight_devset(self, sample=None):
|
1311 |
+
if sample is None:
|
1312 |
+
sample = self.devset[self.devset_index : self.devset_index + 1]
|
1313 |
+
|
1314 |
+
self.devsetbox.tag_remove("true-pos", "1.0", "end")
|
1315 |
+
self.devsetbox.tag_remove("false-neg", "1.0", "end")
|
1316 |
+
self.devsetbox.tag_remove("false-pos", "1.0", "end")
|
1317 |
+
|
1318 |
+
# Run the grammar on the test cases.
|
1319 |
+
for sentnum, gold_tree in enumerate(sample):
|
1320 |
+
# Run the chunk parser
|
1321 |
+
test_tree = self._chunkparse(gold_tree.leaves())
|
1322 |
+
# Extract gold & test chunks
|
1323 |
+
gold_chunks = self._chunks(gold_tree)
|
1324 |
+
test_chunks = self._chunks(test_tree)
|
1325 |
+
# Compare them.
|
1326 |
+
for chunk in gold_chunks.intersection(test_chunks):
|
1327 |
+
self._color_chunk(sentnum, chunk, "true-pos")
|
1328 |
+
for chunk in gold_chunks - test_chunks:
|
1329 |
+
self._color_chunk(sentnum, chunk, "false-neg")
|
1330 |
+
for chunk in test_chunks - gold_chunks:
|
1331 |
+
self._color_chunk(sentnum, chunk, "false-pos")
|
1332 |
+
|
1333 |
+
def _chunkparse(self, words):
|
1334 |
+
try:
|
1335 |
+
return self.chunker.parse(words)
|
1336 |
+
except (ValueError, IndexError) as e:
|
1337 |
+
# There's an error somewhere in the grammar, but we're not sure
|
1338 |
+
# exactly where, so just mark the whole grammar as bad.
|
1339 |
+
# E.g., this is caused by: "({<NN>})"
|
1340 |
+
self.grammarbox.tag_add("error", "1.0", "end")
|
1341 |
+
# Treat it as tagging nothing:
|
1342 |
+
return words
|
1343 |
+
|
1344 |
+
def _color_chunk(self, sentnum, chunk, tag):
|
1345 |
+
start, end = chunk
|
1346 |
+
self.devsetbox.tag_add(
|
1347 |
+
tag,
|
1348 |
+
f"{self.linenum[sentnum]}.{self.charnum[sentnum, start]}",
|
1349 |
+
f"{self.linenum[sentnum]}.{self.charnum[sentnum, end] - 1}",
|
1350 |
+
)
|
1351 |
+
|
1352 |
+
def reset(self):
|
1353 |
+
# Clear various variables
|
1354 |
+
self.chunker = None
|
1355 |
+
self.grammar = None
|
1356 |
+
self.normalized_grammar = None
|
1357 |
+
self.grammar_changed = 0
|
1358 |
+
self._history = []
|
1359 |
+
self._history_index = 0
|
1360 |
+
# Update the on-screen display.
|
1361 |
+
self.grammarbox.delete("1.0", "end")
|
1362 |
+
self.show_devset(0)
|
1363 |
+
self.update()
|
1364 |
+
# self._eval_plot()
|
1365 |
+
|
1366 |
+
SAVE_GRAMMAR_TEMPLATE = (
|
1367 |
+
"# Regexp Chunk Parsing Grammar\n"
|
1368 |
+
"# Saved %(date)s\n"
|
1369 |
+
"#\n"
|
1370 |
+
"# Development set: %(devset)s\n"
|
1371 |
+
"# Precision: %(precision)s\n"
|
1372 |
+
"# Recall: %(recall)s\n"
|
1373 |
+
"# F-score: %(fscore)s\n\n"
|
1374 |
+
"%(grammar)s\n"
|
1375 |
+
)
|
1376 |
+
|
1377 |
+
def save_grammar(self, filename=None):
|
1378 |
+
if not filename:
|
1379 |
+
ftypes = [("Chunk Gramamr", ".chunk"), ("All files", "*")]
|
1380 |
+
filename = asksaveasfilename(filetypes=ftypes, defaultextension=".chunk")
|
1381 |
+
if not filename:
|
1382 |
+
return
|
1383 |
+
if self._history and self.normalized_grammar == self.normalize_grammar(
|
1384 |
+
self._history[-1][0]
|
1385 |
+
):
|
1386 |
+
precision, recall, fscore = (
|
1387 |
+
"%.2f%%" % (100 * v) for v in self._history[-1][1:]
|
1388 |
+
)
|
1389 |
+
elif self.chunker is None:
|
1390 |
+
precision = recall = fscore = "Grammar not well formed"
|
1391 |
+
else:
|
1392 |
+
precision = recall = fscore = "Not finished evaluation yet"
|
1393 |
+
|
1394 |
+
with open(filename, "w") as outfile:
|
1395 |
+
outfile.write(
|
1396 |
+
self.SAVE_GRAMMAR_TEMPLATE
|
1397 |
+
% dict(
|
1398 |
+
date=time.ctime(),
|
1399 |
+
devset=self.devset_name,
|
1400 |
+
precision=precision,
|
1401 |
+
recall=recall,
|
1402 |
+
fscore=fscore,
|
1403 |
+
grammar=self.grammar.strip(),
|
1404 |
+
)
|
1405 |
+
)
|
1406 |
+
|
1407 |
+
def load_grammar(self, filename=None):
|
1408 |
+
if not filename:
|
1409 |
+
ftypes = [("Chunk Gramamr", ".chunk"), ("All files", "*")]
|
1410 |
+
filename = askopenfilename(filetypes=ftypes, defaultextension=".chunk")
|
1411 |
+
if not filename:
|
1412 |
+
return
|
1413 |
+
self.grammarbox.delete("1.0", "end")
|
1414 |
+
self.update()
|
1415 |
+
with open(filename) as infile:
|
1416 |
+
grammar = infile.read()
|
1417 |
+
grammar = re.sub(
|
1418 |
+
r"^\# Regexp Chunk Parsing Grammar[\s\S]*" "F-score:.*\n", "", grammar
|
1419 |
+
).lstrip()
|
1420 |
+
self.grammarbox.insert("1.0", grammar)
|
1421 |
+
self.update()
|
1422 |
+
|
1423 |
+
def save_history(self, filename=None):
|
1424 |
+
if not filename:
|
1425 |
+
ftypes = [("Chunk Gramamr History", ".txt"), ("All files", "*")]
|
1426 |
+
filename = asksaveasfilename(filetypes=ftypes, defaultextension=".txt")
|
1427 |
+
if not filename:
|
1428 |
+
return
|
1429 |
+
|
1430 |
+
with open(filename, "w") as outfile:
|
1431 |
+
outfile.write("# Regexp Chunk Parsing Grammar History\n")
|
1432 |
+
outfile.write("# Saved %s\n" % time.ctime())
|
1433 |
+
outfile.write("# Development set: %s\n" % self.devset_name)
|
1434 |
+
for i, (g, p, r, f) in enumerate(self._history):
|
1435 |
+
hdr = (
|
1436 |
+
"Grammar %d/%d (precision=%.2f%%, recall=%.2f%%, "
|
1437 |
+
"fscore=%.2f%%)"
|
1438 |
+
% (i + 1, len(self._history), p * 100, r * 100, f * 100)
|
1439 |
+
)
|
1440 |
+
outfile.write("\n%s\n" % hdr)
|
1441 |
+
outfile.write("".join(" %s\n" % line for line in g.strip().split()))
|
1442 |
+
|
1443 |
+
if not (
|
1444 |
+
self._history
|
1445 |
+
and self.normalized_grammar
|
1446 |
+
== self.normalize_grammar(self._history[-1][0])
|
1447 |
+
):
|
1448 |
+
if self.chunker is None:
|
1449 |
+
outfile.write("\nCurrent Grammar (not well-formed)\n")
|
1450 |
+
else:
|
1451 |
+
outfile.write("\nCurrent Grammar (not evaluated)\n")
|
1452 |
+
outfile.write(
|
1453 |
+
"".join(" %s\n" % line for line in self.grammar.strip().split())
|
1454 |
+
)
|
1455 |
+
|
1456 |
+
def about(self, *e):
|
1457 |
+
ABOUT = "NLTK RegExp Chunk Parser Application\n" + "Written by Edward Loper"
|
1458 |
+
TITLE = "About: Regular Expression Chunk Parser Application"
|
1459 |
+
try:
|
1460 |
+
from tkinter.messagebox import Message
|
1461 |
+
|
1462 |
+
Message(message=ABOUT, title=TITLE).show()
|
1463 |
+
except:
|
1464 |
+
ShowText(self.top, TITLE, ABOUT)
|
1465 |
+
|
1466 |
+
def set_devset_size(self, size=None):
|
1467 |
+
if size is not None:
|
1468 |
+
self._devset_size.set(size)
|
1469 |
+
self._devset_size.set(min(len(self.devset), self._devset_size.get()))
|
1470 |
+
self.show_devset(1)
|
1471 |
+
self.show_devset(0)
|
1472 |
+
# what about history? Evaluated at diff dev set sizes!
|
1473 |
+
|
1474 |
+
def resize(self, size=None):
|
1475 |
+
if size is not None:
|
1476 |
+
self._size.set(size)
|
1477 |
+
size = self._size.get()
|
1478 |
+
self._font.configure(size=-(abs(size)))
|
1479 |
+
self._smallfont.configure(size=min(-10, -(abs(size)) * 14 // 20))
|
1480 |
+
|
1481 |
+
def mainloop(self, *args, **kwargs):
|
1482 |
+
"""
|
1483 |
+
Enter the Tkinter mainloop. This function must be called if
|
1484 |
+
this demo is created from a non-interactive program (e.g.
|
1485 |
+
from a secript); otherwise, the demo will close as soon as
|
1486 |
+
the script completes.
|
1487 |
+
"""
|
1488 |
+
if in_idle():
|
1489 |
+
return
|
1490 |
+
self.top.mainloop(*args, **kwargs)
|
1491 |
+
|
1492 |
+
|
1493 |
+
def app():
|
1494 |
+
RegexpChunkApp().mainloop()
|
1495 |
+
|
1496 |
+
|
1497 |
+
if __name__ == "__main__":
|
1498 |
+
app()
|
1499 |
+
|
1500 |
+
__all__ = ["app"]
|
env-llmeval/lib/python3.10/site-packages/nltk/app/collocations_app.py
ADDED
@@ -0,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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Collocations Application
|
2 |
+
# Much of the GUI code is imported from concordance.py; We intend to merge these tools together
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Sumukh Ghodke <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
#
|
8 |
+
|
9 |
+
|
10 |
+
import queue as q
|
11 |
+
import threading
|
12 |
+
from tkinter import (
|
13 |
+
END,
|
14 |
+
LEFT,
|
15 |
+
SUNKEN,
|
16 |
+
Button,
|
17 |
+
Frame,
|
18 |
+
IntVar,
|
19 |
+
Label,
|
20 |
+
Menu,
|
21 |
+
OptionMenu,
|
22 |
+
Scrollbar,
|
23 |
+
StringVar,
|
24 |
+
Text,
|
25 |
+
Tk,
|
26 |
+
)
|
27 |
+
from tkinter.font import Font
|
28 |
+
|
29 |
+
from nltk.corpus import (
|
30 |
+
alpino,
|
31 |
+
brown,
|
32 |
+
cess_cat,
|
33 |
+
cess_esp,
|
34 |
+
floresta,
|
35 |
+
indian,
|
36 |
+
mac_morpho,
|
37 |
+
machado,
|
38 |
+
nps_chat,
|
39 |
+
sinica_treebank,
|
40 |
+
treebank,
|
41 |
+
)
|
42 |
+
from nltk.probability import FreqDist
|
43 |
+
from nltk.util import in_idle
|
44 |
+
|
45 |
+
CORPUS_LOADED_EVENT = "<<CL_EVENT>>"
|
46 |
+
ERROR_LOADING_CORPUS_EVENT = "<<ELC_EVENT>>"
|
47 |
+
POLL_INTERVAL = 100
|
48 |
+
|
49 |
+
_DEFAULT = "English: Brown Corpus (Humor)"
|
50 |
+
_CORPORA = {
|
51 |
+
"Catalan: CESS-CAT Corpus": lambda: cess_cat.words(),
|
52 |
+
"English: Brown Corpus": lambda: brown.words(),
|
53 |
+
"English: Brown Corpus (Press)": lambda: brown.words(
|
54 |
+
categories=["news", "editorial", "reviews"]
|
55 |
+
),
|
56 |
+
"English: Brown Corpus (Religion)": lambda: brown.words(categories="religion"),
|
57 |
+
"English: Brown Corpus (Learned)": lambda: brown.words(categories="learned"),
|
58 |
+
"English: Brown Corpus (Science Fiction)": lambda: brown.words(
|
59 |
+
categories="science_fiction"
|
60 |
+
),
|
61 |
+
"English: Brown Corpus (Romance)": lambda: brown.words(categories="romance"),
|
62 |
+
"English: Brown Corpus (Humor)": lambda: brown.words(categories="humor"),
|
63 |
+
"English: NPS Chat Corpus": lambda: nps_chat.words(),
|
64 |
+
"English: Wall Street Journal Corpus": lambda: treebank.words(),
|
65 |
+
"Chinese: Sinica Corpus": lambda: sinica_treebank.words(),
|
66 |
+
"Dutch: Alpino Corpus": lambda: alpino.words(),
|
67 |
+
"Hindi: Indian Languages Corpus": lambda: indian.words(files="hindi.pos"),
|
68 |
+
"Portuguese: Floresta Corpus (Portugal)": lambda: floresta.words(),
|
69 |
+
"Portuguese: MAC-MORPHO Corpus (Brazil)": lambda: mac_morpho.words(),
|
70 |
+
"Portuguese: Machado Corpus (Brazil)": lambda: machado.words(),
|
71 |
+
"Spanish: CESS-ESP Corpus": lambda: cess_esp.words(),
|
72 |
+
}
|
73 |
+
|
74 |
+
|
75 |
+
class CollocationsView:
|
76 |
+
_BACKGROUND_COLOUR = "#FFF" # white
|
77 |
+
|
78 |
+
def __init__(self):
|
79 |
+
self.queue = q.Queue()
|
80 |
+
self.model = CollocationsModel(self.queue)
|
81 |
+
self.top = Tk()
|
82 |
+
self._init_top(self.top)
|
83 |
+
self._init_menubar()
|
84 |
+
self._init_widgets(self.top)
|
85 |
+
self.load_corpus(self.model.DEFAULT_CORPUS)
|
86 |
+
self.after = self.top.after(POLL_INTERVAL, self._poll)
|
87 |
+
|
88 |
+
def _init_top(self, top):
|
89 |
+
top.geometry("550x650+50+50")
|
90 |
+
top.title("NLTK Collocations List")
|
91 |
+
top.bind("<Control-q>", self.destroy)
|
92 |
+
top.protocol("WM_DELETE_WINDOW", self.destroy)
|
93 |
+
top.minsize(550, 650)
|
94 |
+
|
95 |
+
def _init_widgets(self, parent):
|
96 |
+
self.main_frame = Frame(
|
97 |
+
parent, dict(background=self._BACKGROUND_COLOUR, padx=1, pady=1, border=1)
|
98 |
+
)
|
99 |
+
self._init_corpus_select(self.main_frame)
|
100 |
+
self._init_results_box(self.main_frame)
|
101 |
+
self._init_paging(self.main_frame)
|
102 |
+
self._init_status(self.main_frame)
|
103 |
+
self.main_frame.pack(fill="both", expand=True)
|
104 |
+
|
105 |
+
def _init_corpus_select(self, parent):
|
106 |
+
innerframe = Frame(parent, background=self._BACKGROUND_COLOUR)
|
107 |
+
self.var = StringVar(innerframe)
|
108 |
+
self.var.set(self.model.DEFAULT_CORPUS)
|
109 |
+
Label(
|
110 |
+
innerframe,
|
111 |
+
justify=LEFT,
|
112 |
+
text=" Corpus: ",
|
113 |
+
background=self._BACKGROUND_COLOUR,
|
114 |
+
padx=2,
|
115 |
+
pady=1,
|
116 |
+
border=0,
|
117 |
+
).pack(side="left")
|
118 |
+
|
119 |
+
other_corpora = list(self.model.CORPORA.keys()).remove(
|
120 |
+
self.model.DEFAULT_CORPUS
|
121 |
+
)
|
122 |
+
om = OptionMenu(
|
123 |
+
innerframe,
|
124 |
+
self.var,
|
125 |
+
self.model.DEFAULT_CORPUS,
|
126 |
+
command=self.corpus_selected,
|
127 |
+
*self.model.non_default_corpora()
|
128 |
+
)
|
129 |
+
om["borderwidth"] = 0
|
130 |
+
om["highlightthickness"] = 1
|
131 |
+
om.pack(side="left")
|
132 |
+
innerframe.pack(side="top", fill="x", anchor="n")
|
133 |
+
|
134 |
+
def _init_status(self, parent):
|
135 |
+
self.status = Label(
|
136 |
+
parent,
|
137 |
+
justify=LEFT,
|
138 |
+
relief=SUNKEN,
|
139 |
+
background=self._BACKGROUND_COLOUR,
|
140 |
+
border=0,
|
141 |
+
padx=1,
|
142 |
+
pady=0,
|
143 |
+
)
|
144 |
+
self.status.pack(side="top", anchor="sw")
|
145 |
+
|
146 |
+
def _init_menubar(self):
|
147 |
+
self._result_size = IntVar(self.top)
|
148 |
+
menubar = Menu(self.top)
|
149 |
+
|
150 |
+
filemenu = Menu(menubar, tearoff=0, borderwidth=0)
|
151 |
+
filemenu.add_command(
|
152 |
+
label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-q"
|
153 |
+
)
|
154 |
+
menubar.add_cascade(label="File", underline=0, menu=filemenu)
|
155 |
+
|
156 |
+
editmenu = Menu(menubar, tearoff=0)
|
157 |
+
rescntmenu = Menu(editmenu, tearoff=0)
|
158 |
+
rescntmenu.add_radiobutton(
|
159 |
+
label="20",
|
160 |
+
variable=self._result_size,
|
161 |
+
underline=0,
|
162 |
+
value=20,
|
163 |
+
command=self.set_result_size,
|
164 |
+
)
|
165 |
+
rescntmenu.add_radiobutton(
|
166 |
+
label="50",
|
167 |
+
variable=self._result_size,
|
168 |
+
underline=0,
|
169 |
+
value=50,
|
170 |
+
command=self.set_result_size,
|
171 |
+
)
|
172 |
+
rescntmenu.add_radiobutton(
|
173 |
+
label="100",
|
174 |
+
variable=self._result_size,
|
175 |
+
underline=0,
|
176 |
+
value=100,
|
177 |
+
command=self.set_result_size,
|
178 |
+
)
|
179 |
+
rescntmenu.invoke(1)
|
180 |
+
editmenu.add_cascade(label="Result Count", underline=0, menu=rescntmenu)
|
181 |
+
|
182 |
+
menubar.add_cascade(label="Edit", underline=0, menu=editmenu)
|
183 |
+
self.top.config(menu=menubar)
|
184 |
+
|
185 |
+
def set_result_size(self, **kwargs):
|
186 |
+
self.model.result_count = self._result_size.get()
|
187 |
+
|
188 |
+
def _init_results_box(self, parent):
|
189 |
+
innerframe = Frame(parent)
|
190 |
+
i1 = Frame(innerframe)
|
191 |
+
i2 = Frame(innerframe)
|
192 |
+
vscrollbar = Scrollbar(i1, borderwidth=1)
|
193 |
+
hscrollbar = Scrollbar(i2, borderwidth=1, orient="horiz")
|
194 |
+
self.results_box = Text(
|
195 |
+
i1,
|
196 |
+
font=Font(family="courier", size="16"),
|
197 |
+
state="disabled",
|
198 |
+
borderwidth=1,
|
199 |
+
yscrollcommand=vscrollbar.set,
|
200 |
+
xscrollcommand=hscrollbar.set,
|
201 |
+
wrap="none",
|
202 |
+
width="40",
|
203 |
+
height="20",
|
204 |
+
exportselection=1,
|
205 |
+
)
|
206 |
+
self.results_box.pack(side="left", fill="both", expand=True)
|
207 |
+
vscrollbar.pack(side="left", fill="y", anchor="e")
|
208 |
+
vscrollbar.config(command=self.results_box.yview)
|
209 |
+
hscrollbar.pack(side="left", fill="x", expand=True, anchor="w")
|
210 |
+
hscrollbar.config(command=self.results_box.xview)
|
211 |
+
# there is no other way of avoiding the overlap of scrollbars while using pack layout manager!!!
|
212 |
+
Label(i2, text=" ", background=self._BACKGROUND_COLOUR).pack(
|
213 |
+
side="left", anchor="e"
|
214 |
+
)
|
215 |
+
i1.pack(side="top", fill="both", expand=True, anchor="n")
|
216 |
+
i2.pack(side="bottom", fill="x", anchor="s")
|
217 |
+
innerframe.pack(side="top", fill="both", expand=True)
|
218 |
+
|
219 |
+
def _init_paging(self, parent):
|
220 |
+
innerframe = Frame(parent, background=self._BACKGROUND_COLOUR)
|
221 |
+
self.prev = prev = Button(
|
222 |
+
innerframe,
|
223 |
+
text="Previous",
|
224 |
+
command=self.previous,
|
225 |
+
width="10",
|
226 |
+
borderwidth=1,
|
227 |
+
highlightthickness=1,
|
228 |
+
state="disabled",
|
229 |
+
)
|
230 |
+
prev.pack(side="left", anchor="center")
|
231 |
+
self.next = next = Button(
|
232 |
+
innerframe,
|
233 |
+
text="Next",
|
234 |
+
command=self.__next__,
|
235 |
+
width="10",
|
236 |
+
borderwidth=1,
|
237 |
+
highlightthickness=1,
|
238 |
+
state="disabled",
|
239 |
+
)
|
240 |
+
next.pack(side="right", anchor="center")
|
241 |
+
innerframe.pack(side="top", fill="y")
|
242 |
+
self.reset_current_page()
|
243 |
+
|
244 |
+
def reset_current_page(self):
|
245 |
+
self.current_page = -1
|
246 |
+
|
247 |
+
def _poll(self):
|
248 |
+
try:
|
249 |
+
event = self.queue.get(block=False)
|
250 |
+
except q.Empty:
|
251 |
+
pass
|
252 |
+
else:
|
253 |
+
if event == CORPUS_LOADED_EVENT:
|
254 |
+
self.handle_corpus_loaded(event)
|
255 |
+
elif event == ERROR_LOADING_CORPUS_EVENT:
|
256 |
+
self.handle_error_loading_corpus(event)
|
257 |
+
self.after = self.top.after(POLL_INTERVAL, self._poll)
|
258 |
+
|
259 |
+
def handle_error_loading_corpus(self, event):
|
260 |
+
self.status["text"] = "Error in loading " + self.var.get()
|
261 |
+
self.unfreeze_editable()
|
262 |
+
self.clear_results_box()
|
263 |
+
self.freeze_editable()
|
264 |
+
self.reset_current_page()
|
265 |
+
|
266 |
+
def handle_corpus_loaded(self, event):
|
267 |
+
self.status["text"] = self.var.get() + " is loaded"
|
268 |
+
self.unfreeze_editable()
|
269 |
+
self.clear_results_box()
|
270 |
+
self.reset_current_page()
|
271 |
+
# self.next()
|
272 |
+
collocations = self.model.next(self.current_page + 1)
|
273 |
+
self.write_results(collocations)
|
274 |
+
self.current_page += 1
|
275 |
+
|
276 |
+
def corpus_selected(self, *args):
|
277 |
+
new_selection = self.var.get()
|
278 |
+
self.load_corpus(new_selection)
|
279 |
+
|
280 |
+
def previous(self):
|
281 |
+
self.freeze_editable()
|
282 |
+
collocations = self.model.prev(self.current_page - 1)
|
283 |
+
self.current_page = self.current_page - 1
|
284 |
+
self.clear_results_box()
|
285 |
+
self.write_results(collocations)
|
286 |
+
self.unfreeze_editable()
|
287 |
+
|
288 |
+
def __next__(self):
|
289 |
+
self.freeze_editable()
|
290 |
+
collocations = self.model.next(self.current_page + 1)
|
291 |
+
self.clear_results_box()
|
292 |
+
self.write_results(collocations)
|
293 |
+
self.current_page += 1
|
294 |
+
self.unfreeze_editable()
|
295 |
+
|
296 |
+
def load_corpus(self, selection):
|
297 |
+
if self.model.selected_corpus != selection:
|
298 |
+
self.status["text"] = "Loading " + selection + "..."
|
299 |
+
self.freeze_editable()
|
300 |
+
self.model.load_corpus(selection)
|
301 |
+
|
302 |
+
def freeze_editable(self):
|
303 |
+
self.prev["state"] = "disabled"
|
304 |
+
self.next["state"] = "disabled"
|
305 |
+
|
306 |
+
def clear_results_box(self):
|
307 |
+
self.results_box["state"] = "normal"
|
308 |
+
self.results_box.delete("1.0", END)
|
309 |
+
self.results_box["state"] = "disabled"
|
310 |
+
|
311 |
+
def fire_event(self, event):
|
312 |
+
# Firing an event so that rendering of widgets happen in the mainloop thread
|
313 |
+
self.top.event_generate(event, when="tail")
|
314 |
+
|
315 |
+
def destroy(self, *e):
|
316 |
+
if self.top is None:
|
317 |
+
return
|
318 |
+
self.top.after_cancel(self.after)
|
319 |
+
self.top.destroy()
|
320 |
+
self.top = None
|
321 |
+
|
322 |
+
def mainloop(self, *args, **kwargs):
|
323 |
+
if in_idle():
|
324 |
+
return
|
325 |
+
self.top.mainloop(*args, **kwargs)
|
326 |
+
|
327 |
+
def unfreeze_editable(self):
|
328 |
+
self.set_paging_button_states()
|
329 |
+
|
330 |
+
def set_paging_button_states(self):
|
331 |
+
if self.current_page == -1 or self.current_page == 0:
|
332 |
+
self.prev["state"] = "disabled"
|
333 |
+
else:
|
334 |
+
self.prev["state"] = "normal"
|
335 |
+
if self.model.is_last_page(self.current_page):
|
336 |
+
self.next["state"] = "disabled"
|
337 |
+
else:
|
338 |
+
self.next["state"] = "normal"
|
339 |
+
|
340 |
+
def write_results(self, results):
|
341 |
+
self.results_box["state"] = "normal"
|
342 |
+
row = 1
|
343 |
+
for each in results:
|
344 |
+
self.results_box.insert(str(row) + ".0", each[0] + " " + each[1] + "\n")
|
345 |
+
row += 1
|
346 |
+
self.results_box["state"] = "disabled"
|
347 |
+
|
348 |
+
|
349 |
+
class CollocationsModel:
|
350 |
+
def __init__(self, queue):
|
351 |
+
self.result_count = None
|
352 |
+
self.selected_corpus = None
|
353 |
+
self.collocations = None
|
354 |
+
self.CORPORA = _CORPORA
|
355 |
+
self.DEFAULT_CORPUS = _DEFAULT
|
356 |
+
self.queue = queue
|
357 |
+
self.reset_results()
|
358 |
+
|
359 |
+
def reset_results(self):
|
360 |
+
self.result_pages = []
|
361 |
+
self.results_returned = 0
|
362 |
+
|
363 |
+
def load_corpus(self, name):
|
364 |
+
self.selected_corpus = name
|
365 |
+
self.collocations = None
|
366 |
+
runner_thread = self.LoadCorpus(name, self)
|
367 |
+
runner_thread.start()
|
368 |
+
self.reset_results()
|
369 |
+
|
370 |
+
def non_default_corpora(self):
|
371 |
+
copy = []
|
372 |
+
copy.extend(list(self.CORPORA.keys()))
|
373 |
+
copy.remove(self.DEFAULT_CORPUS)
|
374 |
+
copy.sort()
|
375 |
+
return copy
|
376 |
+
|
377 |
+
def is_last_page(self, number):
|
378 |
+
if number < len(self.result_pages):
|
379 |
+
return False
|
380 |
+
return self.results_returned + (
|
381 |
+
number - len(self.result_pages)
|
382 |
+
) * self.result_count >= len(self.collocations)
|
383 |
+
|
384 |
+
def next(self, page):
|
385 |
+
if (len(self.result_pages) - 1) < page:
|
386 |
+
for i in range(page - (len(self.result_pages) - 1)):
|
387 |
+
self.result_pages.append(
|
388 |
+
self.collocations[
|
389 |
+
self.results_returned : self.results_returned
|
390 |
+
+ self.result_count
|
391 |
+
]
|
392 |
+
)
|
393 |
+
self.results_returned += self.result_count
|
394 |
+
return self.result_pages[page]
|
395 |
+
|
396 |
+
def prev(self, page):
|
397 |
+
if page == -1:
|
398 |
+
return []
|
399 |
+
return self.result_pages[page]
|
400 |
+
|
401 |
+
class LoadCorpus(threading.Thread):
|
402 |
+
def __init__(self, name, model):
|
403 |
+
threading.Thread.__init__(self)
|
404 |
+
self.model, self.name = model, name
|
405 |
+
|
406 |
+
def run(self):
|
407 |
+
try:
|
408 |
+
words = self.model.CORPORA[self.name]()
|
409 |
+
from operator import itemgetter
|
410 |
+
|
411 |
+
text = [w for w in words if len(w) > 2]
|
412 |
+
fd = FreqDist(tuple(text[i : i + 2]) for i in range(len(text) - 1))
|
413 |
+
vocab = FreqDist(text)
|
414 |
+
scored = [
|
415 |
+
((w1, w2), fd[(w1, w2)] ** 3 / (vocab[w1] * vocab[w2]))
|
416 |
+
for w1, w2 in fd
|
417 |
+
]
|
418 |
+
scored.sort(key=itemgetter(1), reverse=True)
|
419 |
+
self.model.collocations = list(map(itemgetter(0), scored))
|
420 |
+
self.model.queue.put(CORPUS_LOADED_EVENT)
|
421 |
+
except Exception as e:
|
422 |
+
print(e)
|
423 |
+
self.model.queue.put(ERROR_LOADING_CORPUS_EVENT)
|
424 |
+
|
425 |
+
|
426 |
+
# def collocations():
|
427 |
+
# colloc_strings = [w1 + ' ' + w2 for w1, w2 in self._collocations[:num]]
|
428 |
+
|
429 |
+
|
430 |
+
def app():
|
431 |
+
c = CollocationsView()
|
432 |
+
c.mainloop()
|
433 |
+
|
434 |
+
|
435 |
+
if __name__ == "__main__":
|
436 |
+
app()
|
437 |
+
|
438 |
+
__all__ = ["app"]
|
env-llmeval/lib/python3.10/site-packages/nltk/app/concordance_app.py
ADDED
@@ -0,0 +1,709 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Sumukh Ghodke <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
|
8 |
+
import queue as q
|
9 |
+
import re
|
10 |
+
import threading
|
11 |
+
from tkinter import (
|
12 |
+
END,
|
13 |
+
LEFT,
|
14 |
+
SUNKEN,
|
15 |
+
Button,
|
16 |
+
Entry,
|
17 |
+
Frame,
|
18 |
+
IntVar,
|
19 |
+
Label,
|
20 |
+
Menu,
|
21 |
+
OptionMenu,
|
22 |
+
Scrollbar,
|
23 |
+
StringVar,
|
24 |
+
Text,
|
25 |
+
Tk,
|
26 |
+
)
|
27 |
+
from tkinter.font import Font
|
28 |
+
|
29 |
+
from nltk.corpus import (
|
30 |
+
alpino,
|
31 |
+
brown,
|
32 |
+
cess_cat,
|
33 |
+
cess_esp,
|
34 |
+
floresta,
|
35 |
+
indian,
|
36 |
+
mac_morpho,
|
37 |
+
nps_chat,
|
38 |
+
sinica_treebank,
|
39 |
+
treebank,
|
40 |
+
)
|
41 |
+
from nltk.draw.util import ShowText
|
42 |
+
from nltk.util import in_idle
|
43 |
+
|
44 |
+
WORD_OR_TAG = "[^/ ]+"
|
45 |
+
BOUNDARY = r"\b"
|
46 |
+
|
47 |
+
CORPUS_LOADED_EVENT = "<<CL_EVENT>>"
|
48 |
+
SEARCH_TERMINATED_EVENT = "<<ST_EVENT>>"
|
49 |
+
SEARCH_ERROR_EVENT = "<<SE_EVENT>>"
|
50 |
+
ERROR_LOADING_CORPUS_EVENT = "<<ELC_EVENT>>"
|
51 |
+
|
52 |
+
POLL_INTERVAL = 50
|
53 |
+
|
54 |
+
# NB All corpora must be specified in a lambda expression so as not to be
|
55 |
+
# loaded when the module is imported.
|
56 |
+
|
57 |
+
_DEFAULT = "English: Brown Corpus (Humor, simplified)"
|
58 |
+
_CORPORA = {
|
59 |
+
"Catalan: CESS-CAT Corpus (simplified)": lambda: cess_cat.tagged_sents(
|
60 |
+
tagset="universal"
|
61 |
+
),
|
62 |
+
"English: Brown Corpus": lambda: brown.tagged_sents(),
|
63 |
+
"English: Brown Corpus (simplified)": lambda: brown.tagged_sents(
|
64 |
+
tagset="universal"
|
65 |
+
),
|
66 |
+
"English: Brown Corpus (Press, simplified)": lambda: brown.tagged_sents(
|
67 |
+
categories=["news", "editorial", "reviews"], tagset="universal"
|
68 |
+
),
|
69 |
+
"English: Brown Corpus (Religion, simplified)": lambda: brown.tagged_sents(
|
70 |
+
categories="religion", tagset="universal"
|
71 |
+
),
|
72 |
+
"English: Brown Corpus (Learned, simplified)": lambda: brown.tagged_sents(
|
73 |
+
categories="learned", tagset="universal"
|
74 |
+
),
|
75 |
+
"English: Brown Corpus (Science Fiction, simplified)": lambda: brown.tagged_sents(
|
76 |
+
categories="science_fiction", tagset="universal"
|
77 |
+
),
|
78 |
+
"English: Brown Corpus (Romance, simplified)": lambda: brown.tagged_sents(
|
79 |
+
categories="romance", tagset="universal"
|
80 |
+
),
|
81 |
+
"English: Brown Corpus (Humor, simplified)": lambda: brown.tagged_sents(
|
82 |
+
categories="humor", tagset="universal"
|
83 |
+
),
|
84 |
+
"English: NPS Chat Corpus": lambda: nps_chat.tagged_posts(),
|
85 |
+
"English: NPS Chat Corpus (simplified)": lambda: nps_chat.tagged_posts(
|
86 |
+
tagset="universal"
|
87 |
+
),
|
88 |
+
"English: Wall Street Journal Corpus": lambda: treebank.tagged_sents(),
|
89 |
+
"English: Wall Street Journal Corpus (simplified)": lambda: treebank.tagged_sents(
|
90 |
+
tagset="universal"
|
91 |
+
),
|
92 |
+
"Chinese: Sinica Corpus": lambda: sinica_treebank.tagged_sents(),
|
93 |
+
"Chinese: Sinica Corpus (simplified)": lambda: sinica_treebank.tagged_sents(
|
94 |
+
tagset="universal"
|
95 |
+
),
|
96 |
+
"Dutch: Alpino Corpus": lambda: alpino.tagged_sents(),
|
97 |
+
"Dutch: Alpino Corpus (simplified)": lambda: alpino.tagged_sents(
|
98 |
+
tagset="universal"
|
99 |
+
),
|
100 |
+
"Hindi: Indian Languages Corpus": lambda: indian.tagged_sents(files="hindi.pos"),
|
101 |
+
"Hindi: Indian Languages Corpus (simplified)": lambda: indian.tagged_sents(
|
102 |
+
files="hindi.pos", tagset="universal"
|
103 |
+
),
|
104 |
+
"Portuguese: Floresta Corpus (Portugal)": lambda: floresta.tagged_sents(),
|
105 |
+
"Portuguese: Floresta Corpus (Portugal, simplified)": lambda: floresta.tagged_sents(
|
106 |
+
tagset="universal"
|
107 |
+
),
|
108 |
+
"Portuguese: MAC-MORPHO Corpus (Brazil)": lambda: mac_morpho.tagged_sents(),
|
109 |
+
"Portuguese: MAC-MORPHO Corpus (Brazil, simplified)": lambda: mac_morpho.tagged_sents(
|
110 |
+
tagset="universal"
|
111 |
+
),
|
112 |
+
"Spanish: CESS-ESP Corpus (simplified)": lambda: cess_esp.tagged_sents(
|
113 |
+
tagset="universal"
|
114 |
+
),
|
115 |
+
}
|
116 |
+
|
117 |
+
|
118 |
+
class ConcordanceSearchView:
|
119 |
+
_BACKGROUND_COLOUR = "#FFF" # white
|
120 |
+
|
121 |
+
# Colour of highlighted results
|
122 |
+
_HIGHLIGHT_WORD_COLOUR = "#F00" # red
|
123 |
+
_HIGHLIGHT_WORD_TAG = "HL_WRD_TAG"
|
124 |
+
|
125 |
+
_HIGHLIGHT_LABEL_COLOUR = "#C0C0C0" # dark grey
|
126 |
+
_HIGHLIGHT_LABEL_TAG = "HL_LBL_TAG"
|
127 |
+
|
128 |
+
# Percentage of text left of the scrollbar position
|
129 |
+
_FRACTION_LEFT_TEXT = 0.30
|
130 |
+
|
131 |
+
def __init__(self):
|
132 |
+
self.queue = q.Queue()
|
133 |
+
self.model = ConcordanceSearchModel(self.queue)
|
134 |
+
self.top = Tk()
|
135 |
+
self._init_top(self.top)
|
136 |
+
self._init_menubar()
|
137 |
+
self._init_widgets(self.top)
|
138 |
+
self.load_corpus(self.model.DEFAULT_CORPUS)
|
139 |
+
self.after = self.top.after(POLL_INTERVAL, self._poll)
|
140 |
+
|
141 |
+
def _init_top(self, top):
|
142 |
+
top.geometry("950x680+50+50")
|
143 |
+
top.title("NLTK Concordance Search")
|
144 |
+
top.bind("<Control-q>", self.destroy)
|
145 |
+
top.protocol("WM_DELETE_WINDOW", self.destroy)
|
146 |
+
top.minsize(950, 680)
|
147 |
+
|
148 |
+
def _init_widgets(self, parent):
|
149 |
+
self.main_frame = Frame(
|
150 |
+
parent, dict(background=self._BACKGROUND_COLOUR, padx=1, pady=1, border=1)
|
151 |
+
)
|
152 |
+
self._init_corpus_select(self.main_frame)
|
153 |
+
self._init_query_box(self.main_frame)
|
154 |
+
self._init_results_box(self.main_frame)
|
155 |
+
self._init_paging(self.main_frame)
|
156 |
+
self._init_status(self.main_frame)
|
157 |
+
self.main_frame.pack(fill="both", expand=True)
|
158 |
+
|
159 |
+
def _init_menubar(self):
|
160 |
+
self._result_size = IntVar(self.top)
|
161 |
+
self._cntx_bf_len = IntVar(self.top)
|
162 |
+
self._cntx_af_len = IntVar(self.top)
|
163 |
+
menubar = Menu(self.top)
|
164 |
+
|
165 |
+
filemenu = Menu(menubar, tearoff=0, borderwidth=0)
|
166 |
+
filemenu.add_command(
|
167 |
+
label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-q"
|
168 |
+
)
|
169 |
+
menubar.add_cascade(label="File", underline=0, menu=filemenu)
|
170 |
+
|
171 |
+
editmenu = Menu(menubar, tearoff=0)
|
172 |
+
rescntmenu = Menu(editmenu, tearoff=0)
|
173 |
+
rescntmenu.add_radiobutton(
|
174 |
+
label="20",
|
175 |
+
variable=self._result_size,
|
176 |
+
underline=0,
|
177 |
+
value=20,
|
178 |
+
command=self.set_result_size,
|
179 |
+
)
|
180 |
+
rescntmenu.add_radiobutton(
|
181 |
+
label="50",
|
182 |
+
variable=self._result_size,
|
183 |
+
underline=0,
|
184 |
+
value=50,
|
185 |
+
command=self.set_result_size,
|
186 |
+
)
|
187 |
+
rescntmenu.add_radiobutton(
|
188 |
+
label="100",
|
189 |
+
variable=self._result_size,
|
190 |
+
underline=0,
|
191 |
+
value=100,
|
192 |
+
command=self.set_result_size,
|
193 |
+
)
|
194 |
+
rescntmenu.invoke(1)
|
195 |
+
editmenu.add_cascade(label="Result Count", underline=0, menu=rescntmenu)
|
196 |
+
|
197 |
+
cntxmenu = Menu(editmenu, tearoff=0)
|
198 |
+
cntxbfmenu = Menu(cntxmenu, tearoff=0)
|
199 |
+
cntxbfmenu.add_radiobutton(
|
200 |
+
label="60 characters",
|
201 |
+
variable=self._cntx_bf_len,
|
202 |
+
underline=0,
|
203 |
+
value=60,
|
204 |
+
command=self.set_cntx_bf_len,
|
205 |
+
)
|
206 |
+
cntxbfmenu.add_radiobutton(
|
207 |
+
label="80 characters",
|
208 |
+
variable=self._cntx_bf_len,
|
209 |
+
underline=0,
|
210 |
+
value=80,
|
211 |
+
command=self.set_cntx_bf_len,
|
212 |
+
)
|
213 |
+
cntxbfmenu.add_radiobutton(
|
214 |
+
label="100 characters",
|
215 |
+
variable=self._cntx_bf_len,
|
216 |
+
underline=0,
|
217 |
+
value=100,
|
218 |
+
command=self.set_cntx_bf_len,
|
219 |
+
)
|
220 |
+
cntxbfmenu.invoke(1)
|
221 |
+
cntxmenu.add_cascade(label="Before", underline=0, menu=cntxbfmenu)
|
222 |
+
|
223 |
+
cntxafmenu = Menu(cntxmenu, tearoff=0)
|
224 |
+
cntxafmenu.add_radiobutton(
|
225 |
+
label="70 characters",
|
226 |
+
variable=self._cntx_af_len,
|
227 |
+
underline=0,
|
228 |
+
value=70,
|
229 |
+
command=self.set_cntx_af_len,
|
230 |
+
)
|
231 |
+
cntxafmenu.add_radiobutton(
|
232 |
+
label="90 characters",
|
233 |
+
variable=self._cntx_af_len,
|
234 |
+
underline=0,
|
235 |
+
value=90,
|
236 |
+
command=self.set_cntx_af_len,
|
237 |
+
)
|
238 |
+
cntxafmenu.add_radiobutton(
|
239 |
+
label="110 characters",
|
240 |
+
variable=self._cntx_af_len,
|
241 |
+
underline=0,
|
242 |
+
value=110,
|
243 |
+
command=self.set_cntx_af_len,
|
244 |
+
)
|
245 |
+
cntxafmenu.invoke(1)
|
246 |
+
cntxmenu.add_cascade(label="After", underline=0, menu=cntxafmenu)
|
247 |
+
|
248 |
+
editmenu.add_cascade(label="Context", underline=0, menu=cntxmenu)
|
249 |
+
|
250 |
+
menubar.add_cascade(label="Edit", underline=0, menu=editmenu)
|
251 |
+
|
252 |
+
self.top.config(menu=menubar)
|
253 |
+
|
254 |
+
def set_result_size(self, **kwargs):
|
255 |
+
self.model.result_count = self._result_size.get()
|
256 |
+
|
257 |
+
def set_cntx_af_len(self, **kwargs):
|
258 |
+
self._char_after = self._cntx_af_len.get()
|
259 |
+
|
260 |
+
def set_cntx_bf_len(self, **kwargs):
|
261 |
+
self._char_before = self._cntx_bf_len.get()
|
262 |
+
|
263 |
+
def _init_corpus_select(self, parent):
|
264 |
+
innerframe = Frame(parent, background=self._BACKGROUND_COLOUR)
|
265 |
+
self.var = StringVar(innerframe)
|
266 |
+
self.var.set(self.model.DEFAULT_CORPUS)
|
267 |
+
Label(
|
268 |
+
innerframe,
|
269 |
+
justify=LEFT,
|
270 |
+
text=" Corpus: ",
|
271 |
+
background=self._BACKGROUND_COLOUR,
|
272 |
+
padx=2,
|
273 |
+
pady=1,
|
274 |
+
border=0,
|
275 |
+
).pack(side="left")
|
276 |
+
|
277 |
+
other_corpora = list(self.model.CORPORA.keys()).remove(
|
278 |
+
self.model.DEFAULT_CORPUS
|
279 |
+
)
|
280 |
+
om = OptionMenu(
|
281 |
+
innerframe,
|
282 |
+
self.var,
|
283 |
+
self.model.DEFAULT_CORPUS,
|
284 |
+
command=self.corpus_selected,
|
285 |
+
*self.model.non_default_corpora()
|
286 |
+
)
|
287 |
+
om["borderwidth"] = 0
|
288 |
+
om["highlightthickness"] = 1
|
289 |
+
om.pack(side="left")
|
290 |
+
innerframe.pack(side="top", fill="x", anchor="n")
|
291 |
+
|
292 |
+
def _init_status(self, parent):
|
293 |
+
self.status = Label(
|
294 |
+
parent,
|
295 |
+
justify=LEFT,
|
296 |
+
relief=SUNKEN,
|
297 |
+
background=self._BACKGROUND_COLOUR,
|
298 |
+
border=0,
|
299 |
+
padx=1,
|
300 |
+
pady=0,
|
301 |
+
)
|
302 |
+
self.status.pack(side="top", anchor="sw")
|
303 |
+
|
304 |
+
def _init_query_box(self, parent):
|
305 |
+
innerframe = Frame(parent, background=self._BACKGROUND_COLOUR)
|
306 |
+
another = Frame(innerframe, background=self._BACKGROUND_COLOUR)
|
307 |
+
self.query_box = Entry(another, width=60)
|
308 |
+
self.query_box.pack(side="left", fill="x", pady=25, anchor="center")
|
309 |
+
self.search_button = Button(
|
310 |
+
another,
|
311 |
+
text="Search",
|
312 |
+
command=self.search,
|
313 |
+
borderwidth=1,
|
314 |
+
highlightthickness=1,
|
315 |
+
)
|
316 |
+
self.search_button.pack(side="left", fill="x", pady=25, anchor="center")
|
317 |
+
self.query_box.bind("<KeyPress-Return>", self.search_enter_keypress_handler)
|
318 |
+
another.pack()
|
319 |
+
innerframe.pack(side="top", fill="x", anchor="n")
|
320 |
+
|
321 |
+
def search_enter_keypress_handler(self, *event):
|
322 |
+
self.search()
|
323 |
+
|
324 |
+
def _init_results_box(self, parent):
|
325 |
+
innerframe = Frame(parent)
|
326 |
+
i1 = Frame(innerframe)
|
327 |
+
i2 = Frame(innerframe)
|
328 |
+
vscrollbar = Scrollbar(i1, borderwidth=1)
|
329 |
+
hscrollbar = Scrollbar(i2, borderwidth=1, orient="horiz")
|
330 |
+
self.results_box = Text(
|
331 |
+
i1,
|
332 |
+
font=Font(family="courier", size="16"),
|
333 |
+
state="disabled",
|
334 |
+
borderwidth=1,
|
335 |
+
yscrollcommand=vscrollbar.set,
|
336 |
+
xscrollcommand=hscrollbar.set,
|
337 |
+
wrap="none",
|
338 |
+
width="40",
|
339 |
+
height="20",
|
340 |
+
exportselection=1,
|
341 |
+
)
|
342 |
+
self.results_box.pack(side="left", fill="both", expand=True)
|
343 |
+
self.results_box.tag_config(
|
344 |
+
self._HIGHLIGHT_WORD_TAG, foreground=self._HIGHLIGHT_WORD_COLOUR
|
345 |
+
)
|
346 |
+
self.results_box.tag_config(
|
347 |
+
self._HIGHLIGHT_LABEL_TAG, foreground=self._HIGHLIGHT_LABEL_COLOUR
|
348 |
+
)
|
349 |
+
vscrollbar.pack(side="left", fill="y", anchor="e")
|
350 |
+
vscrollbar.config(command=self.results_box.yview)
|
351 |
+
hscrollbar.pack(side="left", fill="x", expand=True, anchor="w")
|
352 |
+
hscrollbar.config(command=self.results_box.xview)
|
353 |
+
# there is no other way of avoiding the overlap of scrollbars while using pack layout manager!!!
|
354 |
+
Label(i2, text=" ", background=self._BACKGROUND_COLOUR).pack(
|
355 |
+
side="left", anchor="e"
|
356 |
+
)
|
357 |
+
i1.pack(side="top", fill="both", expand=True, anchor="n")
|
358 |
+
i2.pack(side="bottom", fill="x", anchor="s")
|
359 |
+
innerframe.pack(side="top", fill="both", expand=True)
|
360 |
+
|
361 |
+
def _init_paging(self, parent):
|
362 |
+
innerframe = Frame(parent, background=self._BACKGROUND_COLOUR)
|
363 |
+
self.prev = prev = Button(
|
364 |
+
innerframe,
|
365 |
+
text="Previous",
|
366 |
+
command=self.previous,
|
367 |
+
width="10",
|
368 |
+
borderwidth=1,
|
369 |
+
highlightthickness=1,
|
370 |
+
state="disabled",
|
371 |
+
)
|
372 |
+
prev.pack(side="left", anchor="center")
|
373 |
+
self.next = next = Button(
|
374 |
+
innerframe,
|
375 |
+
text="Next",
|
376 |
+
command=self.__next__,
|
377 |
+
width="10",
|
378 |
+
borderwidth=1,
|
379 |
+
highlightthickness=1,
|
380 |
+
state="disabled",
|
381 |
+
)
|
382 |
+
next.pack(side="right", anchor="center")
|
383 |
+
innerframe.pack(side="top", fill="y")
|
384 |
+
self.current_page = 0
|
385 |
+
|
386 |
+
def previous(self):
|
387 |
+
self.clear_results_box()
|
388 |
+
self.freeze_editable()
|
389 |
+
self.model.prev(self.current_page - 1)
|
390 |
+
|
391 |
+
def __next__(self):
|
392 |
+
self.clear_results_box()
|
393 |
+
self.freeze_editable()
|
394 |
+
self.model.next(self.current_page + 1)
|
395 |
+
|
396 |
+
def about(self, *e):
|
397 |
+
ABOUT = "NLTK Concordance Search Demo\n"
|
398 |
+
TITLE = "About: NLTK Concordance Search Demo"
|
399 |
+
try:
|
400 |
+
from tkinter.messagebox import Message
|
401 |
+
|
402 |
+
Message(message=ABOUT, title=TITLE, parent=self.main_frame).show()
|
403 |
+
except:
|
404 |
+
ShowText(self.top, TITLE, ABOUT)
|
405 |
+
|
406 |
+
def _bind_event_handlers(self):
|
407 |
+
self.top.bind(CORPUS_LOADED_EVENT, self.handle_corpus_loaded)
|
408 |
+
self.top.bind(SEARCH_TERMINATED_EVENT, self.handle_search_terminated)
|
409 |
+
self.top.bind(SEARCH_ERROR_EVENT, self.handle_search_error)
|
410 |
+
self.top.bind(ERROR_LOADING_CORPUS_EVENT, self.handle_error_loading_corpus)
|
411 |
+
|
412 |
+
def _poll(self):
|
413 |
+
try:
|
414 |
+
event = self.queue.get(block=False)
|
415 |
+
except q.Empty:
|
416 |
+
pass
|
417 |
+
else:
|
418 |
+
if event == CORPUS_LOADED_EVENT:
|
419 |
+
self.handle_corpus_loaded(event)
|
420 |
+
elif event == SEARCH_TERMINATED_EVENT:
|
421 |
+
self.handle_search_terminated(event)
|
422 |
+
elif event == SEARCH_ERROR_EVENT:
|
423 |
+
self.handle_search_error(event)
|
424 |
+
elif event == ERROR_LOADING_CORPUS_EVENT:
|
425 |
+
self.handle_error_loading_corpus(event)
|
426 |
+
self.after = self.top.after(POLL_INTERVAL, self._poll)
|
427 |
+
|
428 |
+
def handle_error_loading_corpus(self, event):
|
429 |
+
self.status["text"] = "Error in loading " + self.var.get()
|
430 |
+
self.unfreeze_editable()
|
431 |
+
self.clear_all()
|
432 |
+
self.freeze_editable()
|
433 |
+
|
434 |
+
def handle_corpus_loaded(self, event):
|
435 |
+
self.status["text"] = self.var.get() + " is loaded"
|
436 |
+
self.unfreeze_editable()
|
437 |
+
self.clear_all()
|
438 |
+
self.query_box.focus_set()
|
439 |
+
|
440 |
+
def handle_search_terminated(self, event):
|
441 |
+
# todo: refactor the model such that it is less state sensitive
|
442 |
+
results = self.model.get_results()
|
443 |
+
self.write_results(results)
|
444 |
+
self.status["text"] = ""
|
445 |
+
if len(results) == 0:
|
446 |
+
self.status["text"] = "No results found for " + self.model.query
|
447 |
+
else:
|
448 |
+
self.current_page = self.model.last_requested_page
|
449 |
+
self.unfreeze_editable()
|
450 |
+
self.results_box.xview_moveto(self._FRACTION_LEFT_TEXT)
|
451 |
+
|
452 |
+
def handle_search_error(self, event):
|
453 |
+
self.status["text"] = "Error in query " + self.model.query
|
454 |
+
self.unfreeze_editable()
|
455 |
+
|
456 |
+
def corpus_selected(self, *args):
|
457 |
+
new_selection = self.var.get()
|
458 |
+
self.load_corpus(new_selection)
|
459 |
+
|
460 |
+
def load_corpus(self, selection):
|
461 |
+
if self.model.selected_corpus != selection:
|
462 |
+
self.status["text"] = "Loading " + selection + "..."
|
463 |
+
self.freeze_editable()
|
464 |
+
self.model.load_corpus(selection)
|
465 |
+
|
466 |
+
def search(self):
|
467 |
+
self.current_page = 0
|
468 |
+
self.clear_results_box()
|
469 |
+
self.model.reset_results()
|
470 |
+
query = self.query_box.get()
|
471 |
+
if len(query.strip()) == 0:
|
472 |
+
return
|
473 |
+
self.status["text"] = "Searching for " + query
|
474 |
+
self.freeze_editable()
|
475 |
+
self.model.search(query, self.current_page + 1)
|
476 |
+
|
477 |
+
def write_results(self, results):
|
478 |
+
self.results_box["state"] = "normal"
|
479 |
+
row = 1
|
480 |
+
for each in results:
|
481 |
+
sent, pos1, pos2 = each[0].strip(), each[1], each[2]
|
482 |
+
if len(sent) != 0:
|
483 |
+
if pos1 < self._char_before:
|
484 |
+
sent, pos1, pos2 = self.pad(sent, pos1, pos2)
|
485 |
+
sentence = sent[pos1 - self._char_before : pos1 + self._char_after]
|
486 |
+
if not row == len(results):
|
487 |
+
sentence += "\n"
|
488 |
+
self.results_box.insert(str(row) + ".0", sentence)
|
489 |
+
word_markers, label_markers = self.words_and_labels(sent, pos1, pos2)
|
490 |
+
for marker in word_markers:
|
491 |
+
self.results_box.tag_add(
|
492 |
+
self._HIGHLIGHT_WORD_TAG,
|
493 |
+
str(row) + "." + str(marker[0]),
|
494 |
+
str(row) + "." + str(marker[1]),
|
495 |
+
)
|
496 |
+
for marker in label_markers:
|
497 |
+
self.results_box.tag_add(
|
498 |
+
self._HIGHLIGHT_LABEL_TAG,
|
499 |
+
str(row) + "." + str(marker[0]),
|
500 |
+
str(row) + "." + str(marker[1]),
|
501 |
+
)
|
502 |
+
row += 1
|
503 |
+
self.results_box["state"] = "disabled"
|
504 |
+
|
505 |
+
def words_and_labels(self, sentence, pos1, pos2):
|
506 |
+
search_exp = sentence[pos1:pos2]
|
507 |
+
words, labels = [], []
|
508 |
+
labeled_words = search_exp.split(" ")
|
509 |
+
index = 0
|
510 |
+
for each in labeled_words:
|
511 |
+
if each == "":
|
512 |
+
index += 1
|
513 |
+
else:
|
514 |
+
word, label = each.split("/")
|
515 |
+
words.append(
|
516 |
+
(self._char_before + index, self._char_before + index + len(word))
|
517 |
+
)
|
518 |
+
index += len(word) + 1
|
519 |
+
labels.append(
|
520 |
+
(self._char_before + index, self._char_before + index + len(label))
|
521 |
+
)
|
522 |
+
index += len(label)
|
523 |
+
index += 1
|
524 |
+
return words, labels
|
525 |
+
|
526 |
+
def pad(self, sent, hstart, hend):
|
527 |
+
if hstart >= self._char_before:
|
528 |
+
return sent, hstart, hend
|
529 |
+
d = self._char_before - hstart
|
530 |
+
sent = "".join([" "] * d) + sent
|
531 |
+
return sent, hstart + d, hend + d
|
532 |
+
|
533 |
+
def destroy(self, *e):
|
534 |
+
if self.top is None:
|
535 |
+
return
|
536 |
+
self.top.after_cancel(self.after)
|
537 |
+
self.top.destroy()
|
538 |
+
self.top = None
|
539 |
+
|
540 |
+
def clear_all(self):
|
541 |
+
self.query_box.delete(0, END)
|
542 |
+
self.model.reset_query()
|
543 |
+
self.clear_results_box()
|
544 |
+
|
545 |
+
def clear_results_box(self):
|
546 |
+
self.results_box["state"] = "normal"
|
547 |
+
self.results_box.delete("1.0", END)
|
548 |
+
self.results_box["state"] = "disabled"
|
549 |
+
|
550 |
+
def freeze_editable(self):
|
551 |
+
self.query_box["state"] = "disabled"
|
552 |
+
self.search_button["state"] = "disabled"
|
553 |
+
self.prev["state"] = "disabled"
|
554 |
+
self.next["state"] = "disabled"
|
555 |
+
|
556 |
+
def unfreeze_editable(self):
|
557 |
+
self.query_box["state"] = "normal"
|
558 |
+
self.search_button["state"] = "normal"
|
559 |
+
self.set_paging_button_states()
|
560 |
+
|
561 |
+
def set_paging_button_states(self):
|
562 |
+
if self.current_page == 0 or self.current_page == 1:
|
563 |
+
self.prev["state"] = "disabled"
|
564 |
+
else:
|
565 |
+
self.prev["state"] = "normal"
|
566 |
+
if self.model.has_more_pages(self.current_page):
|
567 |
+
self.next["state"] = "normal"
|
568 |
+
else:
|
569 |
+
self.next["state"] = "disabled"
|
570 |
+
|
571 |
+
def fire_event(self, event):
|
572 |
+
# Firing an event so that rendering of widgets happen in the mainloop thread
|
573 |
+
self.top.event_generate(event, when="tail")
|
574 |
+
|
575 |
+
def mainloop(self, *args, **kwargs):
|
576 |
+
if in_idle():
|
577 |
+
return
|
578 |
+
self.top.mainloop(*args, **kwargs)
|
579 |
+
|
580 |
+
|
581 |
+
class ConcordanceSearchModel:
|
582 |
+
def __init__(self, queue):
|
583 |
+
self.queue = queue
|
584 |
+
self.CORPORA = _CORPORA
|
585 |
+
self.DEFAULT_CORPUS = _DEFAULT
|
586 |
+
self.selected_corpus = None
|
587 |
+
self.reset_query()
|
588 |
+
self.reset_results()
|
589 |
+
self.result_count = None
|
590 |
+
self.last_sent_searched = 0
|
591 |
+
|
592 |
+
def non_default_corpora(self):
|
593 |
+
copy = []
|
594 |
+
copy.extend(list(self.CORPORA.keys()))
|
595 |
+
copy.remove(self.DEFAULT_CORPUS)
|
596 |
+
copy.sort()
|
597 |
+
return copy
|
598 |
+
|
599 |
+
def load_corpus(self, name):
|
600 |
+
self.selected_corpus = name
|
601 |
+
self.tagged_sents = []
|
602 |
+
runner_thread = self.LoadCorpus(name, self)
|
603 |
+
runner_thread.start()
|
604 |
+
|
605 |
+
def search(self, query, page):
|
606 |
+
self.query = query
|
607 |
+
self.last_requested_page = page
|
608 |
+
self.SearchCorpus(self, page, self.result_count).start()
|
609 |
+
|
610 |
+
def next(self, page):
|
611 |
+
self.last_requested_page = page
|
612 |
+
if len(self.results) < page:
|
613 |
+
self.search(self.query, page)
|
614 |
+
else:
|
615 |
+
self.queue.put(SEARCH_TERMINATED_EVENT)
|
616 |
+
|
617 |
+
def prev(self, page):
|
618 |
+
self.last_requested_page = page
|
619 |
+
self.queue.put(SEARCH_TERMINATED_EVENT)
|
620 |
+
|
621 |
+
def reset_results(self):
|
622 |
+
self.last_sent_searched = 0
|
623 |
+
self.results = []
|
624 |
+
self.last_page = None
|
625 |
+
|
626 |
+
def reset_query(self):
|
627 |
+
self.query = None
|
628 |
+
|
629 |
+
def set_results(self, page, resultset):
|
630 |
+
self.results.insert(page - 1, resultset)
|
631 |
+
|
632 |
+
def get_results(self):
|
633 |
+
return self.results[self.last_requested_page - 1]
|
634 |
+
|
635 |
+
def has_more_pages(self, page):
|
636 |
+
if self.results == [] or self.results[0] == []:
|
637 |
+
return False
|
638 |
+
if self.last_page is None:
|
639 |
+
return True
|
640 |
+
return page < self.last_page
|
641 |
+
|
642 |
+
class LoadCorpus(threading.Thread):
|
643 |
+
def __init__(self, name, model):
|
644 |
+
threading.Thread.__init__(self)
|
645 |
+
self.model, self.name = model, name
|
646 |
+
|
647 |
+
def run(self):
|
648 |
+
try:
|
649 |
+
ts = self.model.CORPORA[self.name]()
|
650 |
+
self.model.tagged_sents = [
|
651 |
+
" ".join(w + "/" + t for (w, t) in sent) for sent in ts
|
652 |
+
]
|
653 |
+
self.model.queue.put(CORPUS_LOADED_EVENT)
|
654 |
+
except Exception as e:
|
655 |
+
print(e)
|
656 |
+
self.model.queue.put(ERROR_LOADING_CORPUS_EVENT)
|
657 |
+
|
658 |
+
class SearchCorpus(threading.Thread):
|
659 |
+
def __init__(self, model, page, count):
|
660 |
+
self.model, self.count, self.page = model, count, page
|
661 |
+
threading.Thread.__init__(self)
|
662 |
+
|
663 |
+
def run(self):
|
664 |
+
q = self.processed_query()
|
665 |
+
sent_pos, i, sent_count = [], 0, 0
|
666 |
+
for sent in self.model.tagged_sents[self.model.last_sent_searched :]:
|
667 |
+
try:
|
668 |
+
m = re.search(q, sent)
|
669 |
+
except re.error:
|
670 |
+
self.model.reset_results()
|
671 |
+
self.model.queue.put(SEARCH_ERROR_EVENT)
|
672 |
+
return
|
673 |
+
if m:
|
674 |
+
sent_pos.append((sent, m.start(), m.end()))
|
675 |
+
i += 1
|
676 |
+
if i > self.count:
|
677 |
+
self.model.last_sent_searched += sent_count - 1
|
678 |
+
break
|
679 |
+
sent_count += 1
|
680 |
+
if self.count >= len(sent_pos):
|
681 |
+
self.model.last_sent_searched += sent_count - 1
|
682 |
+
self.model.last_page = self.page
|
683 |
+
self.model.set_results(self.page, sent_pos)
|
684 |
+
else:
|
685 |
+
self.model.set_results(self.page, sent_pos[:-1])
|
686 |
+
self.model.queue.put(SEARCH_TERMINATED_EVENT)
|
687 |
+
|
688 |
+
def processed_query(self):
|
689 |
+
new = []
|
690 |
+
for term in self.model.query.split():
|
691 |
+
term = re.sub(r"\.", r"[^/ ]", term)
|
692 |
+
if re.match("[A-Z]+$", term):
|
693 |
+
new.append(BOUNDARY + WORD_OR_TAG + "/" + term + BOUNDARY)
|
694 |
+
elif "/" in term:
|
695 |
+
new.append(BOUNDARY + term + BOUNDARY)
|
696 |
+
else:
|
697 |
+
new.append(BOUNDARY + term + "/" + WORD_OR_TAG + BOUNDARY)
|
698 |
+
return " ".join(new)
|
699 |
+
|
700 |
+
|
701 |
+
def app():
|
702 |
+
d = ConcordanceSearchView()
|
703 |
+
d.mainloop()
|
704 |
+
|
705 |
+
|
706 |
+
if __name__ == "__main__":
|
707 |
+
app()
|
708 |
+
|
709 |
+
__all__ = ["app"]
|
env-llmeval/lib/python3.10/site-packages/nltk/app/nemo_app.py
ADDED
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Finding (and Replacing) Nemo, Version 1.1, Aristide Grange 2006/06/06
|
2 |
+
# https://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496783
|
3 |
+
|
4 |
+
"""
|
5 |
+
Finding (and Replacing) Nemo
|
6 |
+
|
7 |
+
Instant Regular Expressions
|
8 |
+
Created by Aristide Grange
|
9 |
+
"""
|
10 |
+
import itertools
|
11 |
+
import re
|
12 |
+
from tkinter import SEL_FIRST, SEL_LAST, Frame, Label, PhotoImage, Scrollbar, Text, Tk
|
13 |
+
|
14 |
+
windowTitle = "Finding (and Replacing) Nemo"
|
15 |
+
initialFind = r"n(.*?)e(.*?)m(.*?)o"
|
16 |
+
initialRepl = r"M\1A\2K\3I"
|
17 |
+
initialText = """\
|
18 |
+
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
|
19 |
+
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
|
20 |
+
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
|
21 |
+
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
|
22 |
+
"""
|
23 |
+
images = {
|
24 |
+
"FIND": "R0lGODlhMAAiAPcAMf/////37//35//n1v97Off///f/9/f37/fexvfOvfeEQvd7QvdrQvdrKfdaKfdSMfdSIe/v9+/v7+/v5+/n3u/e1u/Wxu/Gre+1lO+tnO+thO+Ua+97Y+97Oe97Me9rOe9rMe9jOe9jMe9jIe9aMefe5+fe3ufezuece+eEWudzQudaIedSIedKMedKIedCKedCId7e1t7Wzt7Oxt7Gvd69vd69rd61pd6ljN6UjN6Ue96EY95zY95rUt5rQt5jMd5SId5KIdbn59be3tbGztbGvda1rdaEa9Z7a9Z7WtZzQtZzOdZzMdZjMdZaQtZSOdZSMdZKMdZCKdZCGNY5Ic7W1s7Oxs7Gtc69xs69tc69rc6tpc6llM6clM6cjM6Ue86EY85zWs5rSs5SKc5KKc5KGMa1tcatrcalvcalnMaUpcZ7c8ZzMcZrUsZrOcZrMcZaQsZSOcZSMcZKMcZCKcZCGMYxIcYxGL3Gxr21tb21rb2lpb2crb2cjL2UnL2UlL2UhL2Ec717Wr17Ur1zWr1rMb1jUr1KMb1KIb1CI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hUVlhESDgqlBp0rAn5nVpBMDxeZDRQbHBgWFBSWDgtLBnFjKwRYCI9VqQsPs0YKEcMXFq0UEalFDWx4BAO2IwPjppAKDkrTWKYUGd7fEJJFEZpM00cOzCgh4EE8SaoWxKNixQooBRMyZMBwAYIRBhUgLDGS4MoBJeoANMhAgQsaCRZm/5lqaCUJhA4cNHjDoKEDBlJUHqkBlYBTiQUZNGjYMMxDhY3VWk6R4MEDBoMUak5AqoYBqANIBo4wcGGDUKIeLlzVZmWJggsVIkwAZaQSA3kdZzlKkIiEAAlDvW5oOkEBs488JTw44oeUIwdvVTFTUK7uiAAPgubt8GFDhQepqETAQCFU1UMGzlqAgFhUsAcCS0AO6lUDhw8xNRSbENGDhgWSHjWUe6ACbKITizmopZoBa6KvOwj9uuHDhwxyj3xekgDDhw5EvWKo0IB4iQLCOCC/njc7ZQ8UeGvza+ABZZgcxJNc4FO1gc0cOsCUrHevc8tdIMTIAhc4F198G2Qwwd8CBIQUAwEINABBBJUwR9R5wElgVRLwWODBBx4cGB8GEzDQIAo33CGJA8gh+JoH/clUgQU0YvDhdfmJdwEFC6Sjgg8yEPAABsPkh2F22cl2AQbn6QdTghTQ5eAJAQyQAAQV0MSBB9gRVZ4GE1mw5JZOAmiAVi1UWcAZDrDyZXYTeaOhA/bIVuIBPtKQ4h7ViYekUPdcEAEbzTzCRp5CADmAAwj+ORGPBcgwAAHo9ABGCYtm0ChwFHShlRiXhmHlkAcCiOeUodqQw5W0oXLAiamy4MOkjOyAaqxUymApDCEAADs=",
|
28 |
+
}
|
29 |
+
colors = ["#FF7B39", "#80F121"]
|
30 |
+
emphColors = ["#DAFC33", "#F42548"]
|
31 |
+
fieldParams = {
|
32 |
+
"height": 3,
|
33 |
+
"width": 70,
|
34 |
+
"font": ("monaco", 14),
|
35 |
+
"highlightthickness": 0,
|
36 |
+
"borderwidth": 0,
|
37 |
+
"background": "white",
|
38 |
+
}
|
39 |
+
textParams = {
|
40 |
+
"bg": "#F7E0D4",
|
41 |
+
"fg": "#2321F1",
|
42 |
+
"highlightthickness": 0,
|
43 |
+
"width": 1,
|
44 |
+
"height": 10,
|
45 |
+
"font": ("verdana", 16),
|
46 |
+
"wrap": "word",
|
47 |
+
}
|
48 |
+
|
49 |
+
|
50 |
+
class Zone:
|
51 |
+
def __init__(self, image, initialField, initialText):
|
52 |
+
frm = Frame(root)
|
53 |
+
frm.config(background="white")
|
54 |
+
self.image = PhotoImage(format="gif", data=images[image.upper()])
|
55 |
+
self.imageDimmed = PhotoImage(format="gif", data=images[image])
|
56 |
+
self.img = Label(frm)
|
57 |
+
self.img.config(borderwidth=0)
|
58 |
+
self.img.pack(side="left")
|
59 |
+
self.fld = Text(frm, **fieldParams)
|
60 |
+
self.initScrollText(frm, self.fld, initialField)
|
61 |
+
frm = Frame(root)
|
62 |
+
self.txt = Text(frm, **textParams)
|
63 |
+
self.initScrollText(frm, self.txt, initialText)
|
64 |
+
for i in range(2):
|
65 |
+
self.txt.tag_config(colors[i], background=colors[i])
|
66 |
+
self.txt.tag_config("emph" + colors[i], foreground=emphColors[i])
|
67 |
+
|
68 |
+
def initScrollText(self, frm, txt, contents):
|
69 |
+
scl = Scrollbar(frm)
|
70 |
+
scl.config(command=txt.yview)
|
71 |
+
scl.pack(side="right", fill="y")
|
72 |
+
txt.pack(side="left", expand=True, fill="x")
|
73 |
+
txt.config(yscrollcommand=scl.set)
|
74 |
+
txt.insert("1.0", contents)
|
75 |
+
frm.pack(fill="x")
|
76 |
+
Frame(height=2, bd=1, relief="ridge").pack(fill="x")
|
77 |
+
|
78 |
+
def refresh(self):
|
79 |
+
self.colorCycle = itertools.cycle(colors)
|
80 |
+
try:
|
81 |
+
self.substitute()
|
82 |
+
self.img.config(image=self.image)
|
83 |
+
except re.error:
|
84 |
+
self.img.config(image=self.imageDimmed)
|
85 |
+
|
86 |
+
|
87 |
+
class FindZone(Zone):
|
88 |
+
def addTags(self, m):
|
89 |
+
color = next(self.colorCycle)
|
90 |
+
self.txt.tag_add(color, "1.0+%sc" % m.start(), "1.0+%sc" % m.end())
|
91 |
+
try:
|
92 |
+
self.txt.tag_add(
|
93 |
+
"emph" + color, "1.0+%sc" % m.start("emph"), "1.0+%sc" % m.end("emph")
|
94 |
+
)
|
95 |
+
except:
|
96 |
+
pass
|
97 |
+
|
98 |
+
def substitute(self, *args):
|
99 |
+
for color in colors:
|
100 |
+
self.txt.tag_remove(color, "1.0", "end")
|
101 |
+
self.txt.tag_remove("emph" + color, "1.0", "end")
|
102 |
+
self.rex = re.compile("") # default value in case of malformed regexp
|
103 |
+
self.rex = re.compile(self.fld.get("1.0", "end")[:-1], re.MULTILINE)
|
104 |
+
try:
|
105 |
+
re.compile("(?P<emph>%s)" % self.fld.get(SEL_FIRST, SEL_LAST))
|
106 |
+
self.rexSel = re.compile(
|
107 |
+
"%s(?P<emph>%s)%s"
|
108 |
+
% (
|
109 |
+
self.fld.get("1.0", SEL_FIRST),
|
110 |
+
self.fld.get(SEL_FIRST, SEL_LAST),
|
111 |
+
self.fld.get(SEL_LAST, "end")[:-1],
|
112 |
+
),
|
113 |
+
re.MULTILINE,
|
114 |
+
)
|
115 |
+
except:
|
116 |
+
self.rexSel = self.rex
|
117 |
+
self.rexSel.sub(self.addTags, self.txt.get("1.0", "end"))
|
118 |
+
|
119 |
+
|
120 |
+
class ReplaceZone(Zone):
|
121 |
+
def addTags(self, m):
|
122 |
+
s = sz.rex.sub(self.repl, m.group())
|
123 |
+
self.txt.delete(
|
124 |
+
"1.0+%sc" % (m.start() + self.diff), "1.0+%sc" % (m.end() + self.diff)
|
125 |
+
)
|
126 |
+
self.txt.insert("1.0+%sc" % (m.start() + self.diff), s, next(self.colorCycle))
|
127 |
+
self.diff += len(s) - (m.end() - m.start())
|
128 |
+
|
129 |
+
def substitute(self):
|
130 |
+
self.txt.delete("1.0", "end")
|
131 |
+
self.txt.insert("1.0", sz.txt.get("1.0", "end")[:-1])
|
132 |
+
self.diff = 0
|
133 |
+
self.repl = rex0.sub(r"\\g<\1>", self.fld.get("1.0", "end")[:-1])
|
134 |
+
sz.rex.sub(self.addTags, sz.txt.get("1.0", "end")[:-1])
|
135 |
+
|
136 |
+
|
137 |
+
def launchRefresh(_):
|
138 |
+
sz.fld.after_idle(sz.refresh)
|
139 |
+
rz.fld.after_idle(rz.refresh)
|
140 |
+
|
141 |
+
|
142 |
+
def app():
|
143 |
+
global root, sz, rz, rex0
|
144 |
+
root = Tk()
|
145 |
+
root.resizable(height=False, width=True)
|
146 |
+
root.title(windowTitle)
|
147 |
+
root.minsize(width=250, height=0)
|
148 |
+
sz = FindZone("find", initialFind, initialText)
|
149 |
+
sz.fld.bind("<Button-1>", launchRefresh)
|
150 |
+
sz.fld.bind("<ButtonRelease-1>", launchRefresh)
|
151 |
+
sz.fld.bind("<B1-Motion>", launchRefresh)
|
152 |
+
sz.rexSel = re.compile("")
|
153 |
+
rz = ReplaceZone("repl", initialRepl, "")
|
154 |
+
rex0 = re.compile(r"(?<!\\)\\([0-9]+)")
|
155 |
+
root.bind_all("<Key>", launchRefresh)
|
156 |
+
launchRefresh(None)
|
157 |
+
root.mainloop()
|
158 |
+
|
159 |
+
|
160 |
+
if __name__ == "__main__":
|
161 |
+
app()
|
162 |
+
|
163 |
+
__all__ = ["app"]
|
env-llmeval/lib/python3.10/site-packages/nltk/app/rdparser_app.py
ADDED
@@ -0,0 +1,1052 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Recursive Descent Parser Application
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Edward Loper <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
|
8 |
+
"""
|
9 |
+
A graphical tool for exploring the recursive descent parser.
|
10 |
+
|
11 |
+
The recursive descent parser maintains a tree, which records the
|
12 |
+
structure of the portion of the text that has been parsed. It uses
|
13 |
+
CFG productions to expand the fringe of the tree, and matches its
|
14 |
+
leaves against the text. Initially, the tree contains the start
|
15 |
+
symbol ("S"). It is shown in the main canvas, to the right of the
|
16 |
+
list of available expansions.
|
17 |
+
|
18 |
+
The parser builds up a tree structure for the text using three
|
19 |
+
operations:
|
20 |
+
|
21 |
+
- "expand" uses a CFG production to add children to a node on the
|
22 |
+
fringe of the tree.
|
23 |
+
- "match" compares a leaf in the tree to a text token.
|
24 |
+
- "backtrack" returns the tree to its state before the most recent
|
25 |
+
expand or match operation.
|
26 |
+
|
27 |
+
The parser maintains a list of tree locations called a "frontier" to
|
28 |
+
remember which nodes have not yet been expanded and which leaves have
|
29 |
+
not yet been matched against the text. The leftmost frontier node is
|
30 |
+
shown in green, and the other frontier nodes are shown in blue. The
|
31 |
+
parser always performs expand and match operations on the leftmost
|
32 |
+
element of the frontier.
|
33 |
+
|
34 |
+
You can control the parser's operation by using the "expand," "match,"
|
35 |
+
and "backtrack" buttons; or you can use the "step" button to let the
|
36 |
+
parser automatically decide which operation to apply. The parser uses
|
37 |
+
the following rules to decide which operation to apply:
|
38 |
+
|
39 |
+
- If the leftmost frontier element is a token, try matching it.
|
40 |
+
- If the leftmost frontier element is a node, try expanding it with
|
41 |
+
the first untried expansion.
|
42 |
+
- Otherwise, backtrack.
|
43 |
+
|
44 |
+
The "expand" button applies the untried expansion whose CFG production
|
45 |
+
is listed earliest in the grammar. To manually choose which expansion
|
46 |
+
to apply, click on a CFG production from the list of available
|
47 |
+
expansions, on the left side of the main window.
|
48 |
+
|
49 |
+
The "autostep" button will let the parser continue applying
|
50 |
+
applications to the tree until it reaches a complete parse. You can
|
51 |
+
cancel an autostep in progress at any time by clicking on the
|
52 |
+
"autostep" button again.
|
53 |
+
|
54 |
+
Keyboard Shortcuts::
|
55 |
+
[Space]\t Perform the next expand, match, or backtrack operation
|
56 |
+
[a]\t Step through operations until the next complete parse
|
57 |
+
[e]\t Perform an expand operation
|
58 |
+
[m]\t Perform a match operation
|
59 |
+
[b]\t Perform a backtrack operation
|
60 |
+
[Delete]\t Reset the parser
|
61 |
+
[g]\t Show/hide available expansions list
|
62 |
+
[h]\t Help
|
63 |
+
[Ctrl-p]\t Print
|
64 |
+
[q]\t Quit
|
65 |
+
"""
|
66 |
+
|
67 |
+
from tkinter import Button, Frame, IntVar, Label, Listbox, Menu, Scrollbar, Tk
|
68 |
+
from tkinter.font import Font
|
69 |
+
|
70 |
+
from nltk.draw import CFGEditor, TreeSegmentWidget, tree_to_treesegment
|
71 |
+
from nltk.draw.util import CanvasFrame, EntryDialog, ShowText, TextWidget
|
72 |
+
from nltk.parse import SteppingRecursiveDescentParser
|
73 |
+
from nltk.tree import Tree
|
74 |
+
from nltk.util import in_idle
|
75 |
+
|
76 |
+
|
77 |
+
class RecursiveDescentApp:
|
78 |
+
"""
|
79 |
+
A graphical tool for exploring the recursive descent parser. The tool
|
80 |
+
displays the parser's tree and the remaining text, and allows the
|
81 |
+
user to control the parser's operation. In particular, the user
|
82 |
+
can expand subtrees on the frontier, match tokens on the frontier
|
83 |
+
against the text, and backtrack. A "step" button simply steps
|
84 |
+
through the parsing process, performing the operations that
|
85 |
+
``RecursiveDescentParser`` would use.
|
86 |
+
"""
|
87 |
+
|
88 |
+
def __init__(self, grammar, sent, trace=0):
|
89 |
+
self._sent = sent
|
90 |
+
self._parser = SteppingRecursiveDescentParser(grammar, trace)
|
91 |
+
|
92 |
+
# Set up the main window.
|
93 |
+
self._top = Tk()
|
94 |
+
self._top.title("Recursive Descent Parser Application")
|
95 |
+
|
96 |
+
# Set up key bindings.
|
97 |
+
self._init_bindings()
|
98 |
+
|
99 |
+
# Initialize the fonts.
|
100 |
+
self._init_fonts(self._top)
|
101 |
+
|
102 |
+
# Animations. animating_lock is a lock to prevent the demo
|
103 |
+
# from performing new operations while it's animating.
|
104 |
+
self._animation_frames = IntVar(self._top)
|
105 |
+
self._animation_frames.set(5)
|
106 |
+
self._animating_lock = 0
|
107 |
+
self._autostep = 0
|
108 |
+
|
109 |
+
# The user can hide the grammar.
|
110 |
+
self._show_grammar = IntVar(self._top)
|
111 |
+
self._show_grammar.set(1)
|
112 |
+
|
113 |
+
# Create the basic frames.
|
114 |
+
self._init_menubar(self._top)
|
115 |
+
self._init_buttons(self._top)
|
116 |
+
self._init_feedback(self._top)
|
117 |
+
self._init_grammar(self._top)
|
118 |
+
self._init_canvas(self._top)
|
119 |
+
|
120 |
+
# Initialize the parser.
|
121 |
+
self._parser.initialize(self._sent)
|
122 |
+
|
123 |
+
# Resize callback
|
124 |
+
self._canvas.bind("<Configure>", self._configure)
|
125 |
+
|
126 |
+
#########################################
|
127 |
+
## Initialization Helpers
|
128 |
+
#########################################
|
129 |
+
|
130 |
+
def _init_fonts(self, root):
|
131 |
+
# See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
|
132 |
+
self._sysfont = Font(font=Button()["font"])
|
133 |
+
root.option_add("*Font", self._sysfont)
|
134 |
+
|
135 |
+
# TWhat's our font size (default=same as sysfont)
|
136 |
+
self._size = IntVar(root)
|
137 |
+
self._size.set(self._sysfont.cget("size"))
|
138 |
+
|
139 |
+
self._boldfont = Font(family="helvetica", weight="bold", size=self._size.get())
|
140 |
+
self._font = Font(family="helvetica", size=self._size.get())
|
141 |
+
if self._size.get() < 0:
|
142 |
+
big = self._size.get() - 2
|
143 |
+
else:
|
144 |
+
big = self._size.get() + 2
|
145 |
+
self._bigfont = Font(family="helvetica", weight="bold", size=big)
|
146 |
+
|
147 |
+
def _init_grammar(self, parent):
|
148 |
+
# Grammar view.
|
149 |
+
self._prodframe = listframe = Frame(parent)
|
150 |
+
self._prodframe.pack(fill="both", side="left", padx=2)
|
151 |
+
self._prodlist_label = Label(
|
152 |
+
self._prodframe, font=self._boldfont, text="Available Expansions"
|
153 |
+
)
|
154 |
+
self._prodlist_label.pack()
|
155 |
+
self._prodlist = Listbox(
|
156 |
+
self._prodframe,
|
157 |
+
selectmode="single",
|
158 |
+
relief="groove",
|
159 |
+
background="white",
|
160 |
+
foreground="#909090",
|
161 |
+
font=self._font,
|
162 |
+
selectforeground="#004040",
|
163 |
+
selectbackground="#c0f0c0",
|
164 |
+
)
|
165 |
+
|
166 |
+
self._prodlist.pack(side="right", fill="both", expand=1)
|
167 |
+
|
168 |
+
self._productions = list(self._parser.grammar().productions())
|
169 |
+
for production in self._productions:
|
170 |
+
self._prodlist.insert("end", (" %s" % production))
|
171 |
+
self._prodlist.config(height=min(len(self._productions), 25))
|
172 |
+
|
173 |
+
# Add a scrollbar if there are more than 25 productions.
|
174 |
+
if len(self._productions) > 25:
|
175 |
+
listscroll = Scrollbar(self._prodframe, orient="vertical")
|
176 |
+
self._prodlist.config(yscrollcommand=listscroll.set)
|
177 |
+
listscroll.config(command=self._prodlist.yview)
|
178 |
+
listscroll.pack(side="left", fill="y")
|
179 |
+
|
180 |
+
# If they select a production, apply it.
|
181 |
+
self._prodlist.bind("<<ListboxSelect>>", self._prodlist_select)
|
182 |
+
|
183 |
+
def _init_bindings(self):
|
184 |
+
# Key bindings are a good thing.
|
185 |
+
self._top.bind("<Control-q>", self.destroy)
|
186 |
+
self._top.bind("<Control-x>", self.destroy)
|
187 |
+
self._top.bind("<Escape>", self.destroy)
|
188 |
+
self._top.bind("e", self.expand)
|
189 |
+
# self._top.bind('<Alt-e>', self.expand)
|
190 |
+
# self._top.bind('<Control-e>', self.expand)
|
191 |
+
self._top.bind("m", self.match)
|
192 |
+
self._top.bind("<Alt-m>", self.match)
|
193 |
+
self._top.bind("<Control-m>", self.match)
|
194 |
+
self._top.bind("b", self.backtrack)
|
195 |
+
self._top.bind("<Alt-b>", self.backtrack)
|
196 |
+
self._top.bind("<Control-b>", self.backtrack)
|
197 |
+
self._top.bind("<Control-z>", self.backtrack)
|
198 |
+
self._top.bind("<BackSpace>", self.backtrack)
|
199 |
+
self._top.bind("a", self.autostep)
|
200 |
+
# self._top.bind('<Control-a>', self.autostep)
|
201 |
+
self._top.bind("<Control-space>", self.autostep)
|
202 |
+
self._top.bind("<Control-c>", self.cancel_autostep)
|
203 |
+
self._top.bind("<space>", self.step)
|
204 |
+
self._top.bind("<Delete>", self.reset)
|
205 |
+
self._top.bind("<Control-p>", self.postscript)
|
206 |
+
# self._top.bind('<h>', self.help)
|
207 |
+
# self._top.bind('<Alt-h>', self.help)
|
208 |
+
self._top.bind("<Control-h>", self.help)
|
209 |
+
self._top.bind("<F1>", self.help)
|
210 |
+
# self._top.bind('<g>', self.toggle_grammar)
|
211 |
+
# self._top.bind('<Alt-g>', self.toggle_grammar)
|
212 |
+
# self._top.bind('<Control-g>', self.toggle_grammar)
|
213 |
+
self._top.bind("<Control-g>", self.edit_grammar)
|
214 |
+
self._top.bind("<Control-t>", self.edit_sentence)
|
215 |
+
|
216 |
+
def _init_buttons(self, parent):
|
217 |
+
# Set up the frames.
|
218 |
+
self._buttonframe = buttonframe = Frame(parent)
|
219 |
+
buttonframe.pack(fill="none", side="bottom", padx=3, pady=2)
|
220 |
+
Button(
|
221 |
+
buttonframe,
|
222 |
+
text="Step",
|
223 |
+
background="#90c0d0",
|
224 |
+
foreground="black",
|
225 |
+
command=self.step,
|
226 |
+
).pack(side="left")
|
227 |
+
Button(
|
228 |
+
buttonframe,
|
229 |
+
text="Autostep",
|
230 |
+
background="#90c0d0",
|
231 |
+
foreground="black",
|
232 |
+
command=self.autostep,
|
233 |
+
).pack(side="left")
|
234 |
+
Button(
|
235 |
+
buttonframe,
|
236 |
+
text="Expand",
|
237 |
+
underline=0,
|
238 |
+
background="#90f090",
|
239 |
+
foreground="black",
|
240 |
+
command=self.expand,
|
241 |
+
).pack(side="left")
|
242 |
+
Button(
|
243 |
+
buttonframe,
|
244 |
+
text="Match",
|
245 |
+
underline=0,
|
246 |
+
background="#90f090",
|
247 |
+
foreground="black",
|
248 |
+
command=self.match,
|
249 |
+
).pack(side="left")
|
250 |
+
Button(
|
251 |
+
buttonframe,
|
252 |
+
text="Backtrack",
|
253 |
+
underline=0,
|
254 |
+
background="#f0a0a0",
|
255 |
+
foreground="black",
|
256 |
+
command=self.backtrack,
|
257 |
+
).pack(side="left")
|
258 |
+
# Replace autostep...
|
259 |
+
|
260 |
+
# self._autostep_button = Button(buttonframe, text='Autostep',
|
261 |
+
# underline=0, command=self.autostep)
|
262 |
+
# self._autostep_button.pack(side='left')
|
263 |
+
|
264 |
+
def _configure(self, event):
|
265 |
+
self._autostep = 0
|
266 |
+
(x1, y1, x2, y2) = self._cframe.scrollregion()
|
267 |
+
y2 = event.height - 6
|
268 |
+
self._canvas["scrollregion"] = "%d %d %d %d" % (x1, y1, x2, y2)
|
269 |
+
self._redraw()
|
270 |
+
|
271 |
+
def _init_feedback(self, parent):
|
272 |
+
self._feedbackframe = feedbackframe = Frame(parent)
|
273 |
+
feedbackframe.pack(fill="x", side="bottom", padx=3, pady=3)
|
274 |
+
self._lastoper_label = Label(
|
275 |
+
feedbackframe, text="Last Operation:", font=self._font
|
276 |
+
)
|
277 |
+
self._lastoper_label.pack(side="left")
|
278 |
+
lastoperframe = Frame(feedbackframe, relief="sunken", border=1)
|
279 |
+
lastoperframe.pack(fill="x", side="right", expand=1, padx=5)
|
280 |
+
self._lastoper1 = Label(
|
281 |
+
lastoperframe, foreground="#007070", background="#f0f0f0", font=self._font
|
282 |
+
)
|
283 |
+
self._lastoper2 = Label(
|
284 |
+
lastoperframe,
|
285 |
+
anchor="w",
|
286 |
+
width=30,
|
287 |
+
foreground="#004040",
|
288 |
+
background="#f0f0f0",
|
289 |
+
font=self._font,
|
290 |
+
)
|
291 |
+
self._lastoper1.pack(side="left")
|
292 |
+
self._lastoper2.pack(side="left", fill="x", expand=1)
|
293 |
+
|
294 |
+
def _init_canvas(self, parent):
|
295 |
+
self._cframe = CanvasFrame(
|
296 |
+
parent,
|
297 |
+
background="white",
|
298 |
+
# width=525, height=250,
|
299 |
+
closeenough=10,
|
300 |
+
border=2,
|
301 |
+
relief="sunken",
|
302 |
+
)
|
303 |
+
self._cframe.pack(expand=1, fill="both", side="top", pady=2)
|
304 |
+
canvas = self._canvas = self._cframe.canvas()
|
305 |
+
|
306 |
+
# Initially, there's no tree or text
|
307 |
+
self._tree = None
|
308 |
+
self._textwidgets = []
|
309 |
+
self._textline = None
|
310 |
+
|
311 |
+
def _init_menubar(self, parent):
|
312 |
+
menubar = Menu(parent)
|
313 |
+
|
314 |
+
filemenu = Menu(menubar, tearoff=0)
|
315 |
+
filemenu.add_command(
|
316 |
+
label="Reset Parser", underline=0, command=self.reset, accelerator="Del"
|
317 |
+
)
|
318 |
+
filemenu.add_command(
|
319 |
+
label="Print to Postscript",
|
320 |
+
underline=0,
|
321 |
+
command=self.postscript,
|
322 |
+
accelerator="Ctrl-p",
|
323 |
+
)
|
324 |
+
filemenu.add_command(
|
325 |
+
label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-x"
|
326 |
+
)
|
327 |
+
menubar.add_cascade(label="File", underline=0, menu=filemenu)
|
328 |
+
|
329 |
+
editmenu = Menu(menubar, tearoff=0)
|
330 |
+
editmenu.add_command(
|
331 |
+
label="Edit Grammar",
|
332 |
+
underline=5,
|
333 |
+
command=self.edit_grammar,
|
334 |
+
accelerator="Ctrl-g",
|
335 |
+
)
|
336 |
+
editmenu.add_command(
|
337 |
+
label="Edit Text",
|
338 |
+
underline=5,
|
339 |
+
command=self.edit_sentence,
|
340 |
+
accelerator="Ctrl-t",
|
341 |
+
)
|
342 |
+
menubar.add_cascade(label="Edit", underline=0, menu=editmenu)
|
343 |
+
|
344 |
+
rulemenu = Menu(menubar, tearoff=0)
|
345 |
+
rulemenu.add_command(
|
346 |
+
label="Step", underline=1, command=self.step, accelerator="Space"
|
347 |
+
)
|
348 |
+
rulemenu.add_separator()
|
349 |
+
rulemenu.add_command(
|
350 |
+
label="Match", underline=0, command=self.match, accelerator="Ctrl-m"
|
351 |
+
)
|
352 |
+
rulemenu.add_command(
|
353 |
+
label="Expand", underline=0, command=self.expand, accelerator="Ctrl-e"
|
354 |
+
)
|
355 |
+
rulemenu.add_separator()
|
356 |
+
rulemenu.add_command(
|
357 |
+
label="Backtrack", underline=0, command=self.backtrack, accelerator="Ctrl-b"
|
358 |
+
)
|
359 |
+
menubar.add_cascade(label="Apply", underline=0, menu=rulemenu)
|
360 |
+
|
361 |
+
viewmenu = Menu(menubar, tearoff=0)
|
362 |
+
viewmenu.add_checkbutton(
|
363 |
+
label="Show Grammar",
|
364 |
+
underline=0,
|
365 |
+
variable=self._show_grammar,
|
366 |
+
command=self._toggle_grammar,
|
367 |
+
)
|
368 |
+
viewmenu.add_separator()
|
369 |
+
viewmenu.add_radiobutton(
|
370 |
+
label="Tiny",
|
371 |
+
variable=self._size,
|
372 |
+
underline=0,
|
373 |
+
value=10,
|
374 |
+
command=self.resize,
|
375 |
+
)
|
376 |
+
viewmenu.add_radiobutton(
|
377 |
+
label="Small",
|
378 |
+
variable=self._size,
|
379 |
+
underline=0,
|
380 |
+
value=12,
|
381 |
+
command=self.resize,
|
382 |
+
)
|
383 |
+
viewmenu.add_radiobutton(
|
384 |
+
label="Medium",
|
385 |
+
variable=self._size,
|
386 |
+
underline=0,
|
387 |
+
value=14,
|
388 |
+
command=self.resize,
|
389 |
+
)
|
390 |
+
viewmenu.add_radiobutton(
|
391 |
+
label="Large",
|
392 |
+
variable=self._size,
|
393 |
+
underline=0,
|
394 |
+
value=18,
|
395 |
+
command=self.resize,
|
396 |
+
)
|
397 |
+
viewmenu.add_radiobutton(
|
398 |
+
label="Huge",
|
399 |
+
variable=self._size,
|
400 |
+
underline=0,
|
401 |
+
value=24,
|
402 |
+
command=self.resize,
|
403 |
+
)
|
404 |
+
menubar.add_cascade(label="View", underline=0, menu=viewmenu)
|
405 |
+
|
406 |
+
animatemenu = Menu(menubar, tearoff=0)
|
407 |
+
animatemenu.add_radiobutton(
|
408 |
+
label="No Animation", underline=0, variable=self._animation_frames, value=0
|
409 |
+
)
|
410 |
+
animatemenu.add_radiobutton(
|
411 |
+
label="Slow Animation",
|
412 |
+
underline=0,
|
413 |
+
variable=self._animation_frames,
|
414 |
+
value=10,
|
415 |
+
accelerator="-",
|
416 |
+
)
|
417 |
+
animatemenu.add_radiobutton(
|
418 |
+
label="Normal Animation",
|
419 |
+
underline=0,
|
420 |
+
variable=self._animation_frames,
|
421 |
+
value=5,
|
422 |
+
accelerator="=",
|
423 |
+
)
|
424 |
+
animatemenu.add_radiobutton(
|
425 |
+
label="Fast Animation",
|
426 |
+
underline=0,
|
427 |
+
variable=self._animation_frames,
|
428 |
+
value=2,
|
429 |
+
accelerator="+",
|
430 |
+
)
|
431 |
+
menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)
|
432 |
+
|
433 |
+
helpmenu = Menu(menubar, tearoff=0)
|
434 |
+
helpmenu.add_command(label="About", underline=0, command=self.about)
|
435 |
+
helpmenu.add_command(
|
436 |
+
label="Instructions", underline=0, command=self.help, accelerator="F1"
|
437 |
+
)
|
438 |
+
menubar.add_cascade(label="Help", underline=0, menu=helpmenu)
|
439 |
+
|
440 |
+
parent.config(menu=menubar)
|
441 |
+
|
442 |
+
#########################################
|
443 |
+
## Helper
|
444 |
+
#########################################
|
445 |
+
|
446 |
+
def _get(self, widget, treeloc):
|
447 |
+
for i in treeloc:
|
448 |
+
widget = widget.subtrees()[i]
|
449 |
+
if isinstance(widget, TreeSegmentWidget):
|
450 |
+
widget = widget.label()
|
451 |
+
return widget
|
452 |
+
|
453 |
+
#########################################
|
454 |
+
## Main draw procedure
|
455 |
+
#########################################
|
456 |
+
|
457 |
+
def _redraw(self):
|
458 |
+
canvas = self._canvas
|
459 |
+
|
460 |
+
# Delete the old tree, widgets, etc.
|
461 |
+
if self._tree is not None:
|
462 |
+
self._cframe.destroy_widget(self._tree)
|
463 |
+
for twidget in self._textwidgets:
|
464 |
+
self._cframe.destroy_widget(twidget)
|
465 |
+
if self._textline is not None:
|
466 |
+
self._canvas.delete(self._textline)
|
467 |
+
|
468 |
+
# Draw the tree.
|
469 |
+
helv = ("helvetica", -self._size.get())
|
470 |
+
bold = ("helvetica", -self._size.get(), "bold")
|
471 |
+
attribs = {
|
472 |
+
"tree_color": "#000000",
|
473 |
+
"tree_width": 2,
|
474 |
+
"node_font": bold,
|
475 |
+
"leaf_font": helv,
|
476 |
+
}
|
477 |
+
tree = self._parser.tree()
|
478 |
+
self._tree = tree_to_treesegment(canvas, tree, **attribs)
|
479 |
+
self._cframe.add_widget(self._tree, 30, 5)
|
480 |
+
|
481 |
+
# Draw the text.
|
482 |
+
helv = ("helvetica", -self._size.get())
|
483 |
+
bottom = y = self._cframe.scrollregion()[3]
|
484 |
+
self._textwidgets = [
|
485 |
+
TextWidget(canvas, word, font=self._font) for word in self._sent
|
486 |
+
]
|
487 |
+
for twidget in self._textwidgets:
|
488 |
+
self._cframe.add_widget(twidget, 0, 0)
|
489 |
+
twidget.move(0, bottom - twidget.bbox()[3] - 5)
|
490 |
+
y = min(y, twidget.bbox()[1])
|
491 |
+
|
492 |
+
# Draw a line over the text, to separate it from the tree.
|
493 |
+
self._textline = canvas.create_line(-5000, y - 5, 5000, y - 5, dash=".")
|
494 |
+
|
495 |
+
# Highlight appropriate nodes.
|
496 |
+
self._highlight_nodes()
|
497 |
+
self._highlight_prodlist()
|
498 |
+
|
499 |
+
# Make sure the text lines up.
|
500 |
+
self._position_text()
|
501 |
+
|
502 |
+
def _redraw_quick(self):
|
503 |
+
# This should be more-or-less sufficient after an animation.
|
504 |
+
self._highlight_nodes()
|
505 |
+
self._highlight_prodlist()
|
506 |
+
self._position_text()
|
507 |
+
|
508 |
+
def _highlight_nodes(self):
|
509 |
+
# Highlight the list of nodes to be checked.
|
510 |
+
bold = ("helvetica", -self._size.get(), "bold")
|
511 |
+
for treeloc in self._parser.frontier()[:1]:
|
512 |
+
self._get(self._tree, treeloc)["color"] = "#20a050"
|
513 |
+
self._get(self._tree, treeloc)["font"] = bold
|
514 |
+
for treeloc in self._parser.frontier()[1:]:
|
515 |
+
self._get(self._tree, treeloc)["color"] = "#008080"
|
516 |
+
|
517 |
+
def _highlight_prodlist(self):
|
518 |
+
# Highlight the productions that can be expanded.
|
519 |
+
# Boy, too bad tkinter doesn't implement Listbox.itemconfig;
|
520 |
+
# that would be pretty useful here.
|
521 |
+
self._prodlist.delete(0, "end")
|
522 |
+
expandable = self._parser.expandable_productions()
|
523 |
+
untried = self._parser.untried_expandable_productions()
|
524 |
+
productions = self._productions
|
525 |
+
for index in range(len(productions)):
|
526 |
+
if productions[index] in expandable:
|
527 |
+
if productions[index] in untried:
|
528 |
+
self._prodlist.insert(index, " %s" % productions[index])
|
529 |
+
else:
|
530 |
+
self._prodlist.insert(index, " %s (TRIED)" % productions[index])
|
531 |
+
self._prodlist.selection_set(index)
|
532 |
+
else:
|
533 |
+
self._prodlist.insert(index, " %s" % productions[index])
|
534 |
+
|
535 |
+
def _position_text(self):
|
536 |
+
# Line up the text widgets that are matched against the tree
|
537 |
+
numwords = len(self._sent)
|
538 |
+
num_matched = numwords - len(self._parser.remaining_text())
|
539 |
+
leaves = self._tree_leaves()[:num_matched]
|
540 |
+
xmax = self._tree.bbox()[0]
|
541 |
+
for i in range(0, len(leaves)):
|
542 |
+
widget = self._textwidgets[i]
|
543 |
+
leaf = leaves[i]
|
544 |
+
widget["color"] = "#006040"
|
545 |
+
leaf["color"] = "#006040"
|
546 |
+
widget.move(leaf.bbox()[0] - widget.bbox()[0], 0)
|
547 |
+
xmax = widget.bbox()[2] + 10
|
548 |
+
|
549 |
+
# Line up the text widgets that are not matched against the tree.
|
550 |
+
for i in range(len(leaves), numwords):
|
551 |
+
widget = self._textwidgets[i]
|
552 |
+
widget["color"] = "#a0a0a0"
|
553 |
+
widget.move(xmax - widget.bbox()[0], 0)
|
554 |
+
xmax = widget.bbox()[2] + 10
|
555 |
+
|
556 |
+
# If we have a complete parse, make everything green :)
|
557 |
+
if self._parser.currently_complete():
|
558 |
+
for twidget in self._textwidgets:
|
559 |
+
twidget["color"] = "#00a000"
|
560 |
+
|
561 |
+
# Move the matched leaves down to the text.
|
562 |
+
for i in range(0, len(leaves)):
|
563 |
+
widget = self._textwidgets[i]
|
564 |
+
leaf = leaves[i]
|
565 |
+
dy = widget.bbox()[1] - leaf.bbox()[3] - 10.0
|
566 |
+
dy = max(dy, leaf.parent().label().bbox()[3] - leaf.bbox()[3] + 10)
|
567 |
+
leaf.move(0, dy)
|
568 |
+
|
569 |
+
def _tree_leaves(self, tree=None):
|
570 |
+
if tree is None:
|
571 |
+
tree = self._tree
|
572 |
+
if isinstance(tree, TreeSegmentWidget):
|
573 |
+
leaves = []
|
574 |
+
for child in tree.subtrees():
|
575 |
+
leaves += self._tree_leaves(child)
|
576 |
+
return leaves
|
577 |
+
else:
|
578 |
+
return [tree]
|
579 |
+
|
580 |
+
#########################################
|
581 |
+
## Button Callbacks
|
582 |
+
#########################################
|
583 |
+
|
584 |
+
def destroy(self, *e):
|
585 |
+
self._autostep = 0
|
586 |
+
if self._top is None:
|
587 |
+
return
|
588 |
+
self._top.destroy()
|
589 |
+
self._top = None
|
590 |
+
|
591 |
+
def reset(self, *e):
|
592 |
+
self._autostep = 0
|
593 |
+
self._parser.initialize(self._sent)
|
594 |
+
self._lastoper1["text"] = "Reset Application"
|
595 |
+
self._lastoper2["text"] = ""
|
596 |
+
self._redraw()
|
597 |
+
|
598 |
+
def autostep(self, *e):
|
599 |
+
if self._animation_frames.get() == 0:
|
600 |
+
self._animation_frames.set(2)
|
601 |
+
if self._autostep:
|
602 |
+
self._autostep = 0
|
603 |
+
else:
|
604 |
+
self._autostep = 1
|
605 |
+
self._step()
|
606 |
+
|
607 |
+
def cancel_autostep(self, *e):
|
608 |
+
# self._autostep_button['text'] = 'Autostep'
|
609 |
+
self._autostep = 0
|
610 |
+
|
611 |
+
# Make sure to stop auto-stepping if we get any user input.
|
612 |
+
def step(self, *e):
|
613 |
+
self._autostep = 0
|
614 |
+
self._step()
|
615 |
+
|
616 |
+
def match(self, *e):
|
617 |
+
self._autostep = 0
|
618 |
+
self._match()
|
619 |
+
|
620 |
+
def expand(self, *e):
|
621 |
+
self._autostep = 0
|
622 |
+
self._expand()
|
623 |
+
|
624 |
+
def backtrack(self, *e):
|
625 |
+
self._autostep = 0
|
626 |
+
self._backtrack()
|
627 |
+
|
628 |
+
def _step(self):
|
629 |
+
if self._animating_lock:
|
630 |
+
return
|
631 |
+
|
632 |
+
# Try expanding, matching, and backtracking (in that order)
|
633 |
+
if self._expand():
|
634 |
+
pass
|
635 |
+
elif self._parser.untried_match() and self._match():
|
636 |
+
pass
|
637 |
+
elif self._backtrack():
|
638 |
+
pass
|
639 |
+
else:
|
640 |
+
self._lastoper1["text"] = "Finished"
|
641 |
+
self._lastoper2["text"] = ""
|
642 |
+
self._autostep = 0
|
643 |
+
|
644 |
+
# Check if we just completed a parse.
|
645 |
+
if self._parser.currently_complete():
|
646 |
+
self._autostep = 0
|
647 |
+
self._lastoper2["text"] += " [COMPLETE PARSE]"
|
648 |
+
|
649 |
+
def _expand(self, *e):
|
650 |
+
if self._animating_lock:
|
651 |
+
return
|
652 |
+
old_frontier = self._parser.frontier()
|
653 |
+
rv = self._parser.expand()
|
654 |
+
if rv is not None:
|
655 |
+
self._lastoper1["text"] = "Expand:"
|
656 |
+
self._lastoper2["text"] = rv
|
657 |
+
self._prodlist.selection_clear(0, "end")
|
658 |
+
index = self._productions.index(rv)
|
659 |
+
self._prodlist.selection_set(index)
|
660 |
+
self._animate_expand(old_frontier[0])
|
661 |
+
return True
|
662 |
+
else:
|
663 |
+
self._lastoper1["text"] = "Expand:"
|
664 |
+
self._lastoper2["text"] = "(all expansions tried)"
|
665 |
+
return False
|
666 |
+
|
667 |
+
def _match(self, *e):
|
668 |
+
if self._animating_lock:
|
669 |
+
return
|
670 |
+
old_frontier = self._parser.frontier()
|
671 |
+
rv = self._parser.match()
|
672 |
+
if rv is not None:
|
673 |
+
self._lastoper1["text"] = "Match:"
|
674 |
+
self._lastoper2["text"] = rv
|
675 |
+
self._animate_match(old_frontier[0])
|
676 |
+
return True
|
677 |
+
else:
|
678 |
+
self._lastoper1["text"] = "Match:"
|
679 |
+
self._lastoper2["text"] = "(failed)"
|
680 |
+
return False
|
681 |
+
|
682 |
+
def _backtrack(self, *e):
|
683 |
+
if self._animating_lock:
|
684 |
+
return
|
685 |
+
if self._parser.backtrack():
|
686 |
+
elt = self._parser.tree()
|
687 |
+
for i in self._parser.frontier()[0]:
|
688 |
+
elt = elt[i]
|
689 |
+
self._lastoper1["text"] = "Backtrack"
|
690 |
+
self._lastoper2["text"] = ""
|
691 |
+
if isinstance(elt, Tree):
|
692 |
+
self._animate_backtrack(self._parser.frontier()[0])
|
693 |
+
else:
|
694 |
+
self._animate_match_backtrack(self._parser.frontier()[0])
|
695 |
+
return True
|
696 |
+
else:
|
697 |
+
self._autostep = 0
|
698 |
+
self._lastoper1["text"] = "Finished"
|
699 |
+
self._lastoper2["text"] = ""
|
700 |
+
return False
|
701 |
+
|
702 |
+
def about(self, *e):
|
703 |
+
ABOUT = (
|
704 |
+
"NLTK Recursive Descent Parser Application\n" + "Written by Edward Loper"
|
705 |
+
)
|
706 |
+
TITLE = "About: Recursive Descent Parser Application"
|
707 |
+
try:
|
708 |
+
from tkinter.messagebox import Message
|
709 |
+
|
710 |
+
Message(message=ABOUT, title=TITLE).show()
|
711 |
+
except:
|
712 |
+
ShowText(self._top, TITLE, ABOUT)
|
713 |
+
|
714 |
+
def help(self, *e):
|
715 |
+
self._autostep = 0
|
716 |
+
# The default font's not very legible; try using 'fixed' instead.
|
717 |
+
try:
|
718 |
+
ShowText(
|
719 |
+
self._top,
|
720 |
+
"Help: Recursive Descent Parser Application",
|
721 |
+
(__doc__ or "").strip(),
|
722 |
+
width=75,
|
723 |
+
font="fixed",
|
724 |
+
)
|
725 |
+
except:
|
726 |
+
ShowText(
|
727 |
+
self._top,
|
728 |
+
"Help: Recursive Descent Parser Application",
|
729 |
+
(__doc__ or "").strip(),
|
730 |
+
width=75,
|
731 |
+
)
|
732 |
+
|
733 |
+
def postscript(self, *e):
|
734 |
+
self._autostep = 0
|
735 |
+
self._cframe.print_to_file()
|
736 |
+
|
737 |
+
def mainloop(self, *args, **kwargs):
|
738 |
+
"""
|
739 |
+
Enter the Tkinter mainloop. This function must be called if
|
740 |
+
this demo is created from a non-interactive program (e.g.
|
741 |
+
from a secript); otherwise, the demo will close as soon as
|
742 |
+
the script completes.
|
743 |
+
"""
|
744 |
+
if in_idle():
|
745 |
+
return
|
746 |
+
self._top.mainloop(*args, **kwargs)
|
747 |
+
|
748 |
+
def resize(self, size=None):
|
749 |
+
if size is not None:
|
750 |
+
self._size.set(size)
|
751 |
+
size = self._size.get()
|
752 |
+
self._font.configure(size=-(abs(size)))
|
753 |
+
self._boldfont.configure(size=-(abs(size)))
|
754 |
+
self._sysfont.configure(size=-(abs(size)))
|
755 |
+
self._bigfont.configure(size=-(abs(size + 2)))
|
756 |
+
self._redraw()
|
757 |
+
|
758 |
+
#########################################
|
759 |
+
## Expand Production Selection
|
760 |
+
#########################################
|
761 |
+
|
762 |
+
def _toggle_grammar(self, *e):
|
763 |
+
if self._show_grammar.get():
|
764 |
+
self._prodframe.pack(
|
765 |
+
fill="both", side="left", padx=2, after=self._feedbackframe
|
766 |
+
)
|
767 |
+
self._lastoper1["text"] = "Show Grammar"
|
768 |
+
else:
|
769 |
+
self._prodframe.pack_forget()
|
770 |
+
self._lastoper1["text"] = "Hide Grammar"
|
771 |
+
self._lastoper2["text"] = ""
|
772 |
+
|
773 |
+
# def toggle_grammar(self, *e):
|
774 |
+
# self._show_grammar = not self._show_grammar
|
775 |
+
# if self._show_grammar:
|
776 |
+
# self._prodframe.pack(fill='both', expand='y', side='left',
|
777 |
+
# after=self._feedbackframe)
|
778 |
+
# self._lastoper1['text'] = 'Show Grammar'
|
779 |
+
# else:
|
780 |
+
# self._prodframe.pack_forget()
|
781 |
+
# self._lastoper1['text'] = 'Hide Grammar'
|
782 |
+
# self._lastoper2['text'] = ''
|
783 |
+
|
784 |
+
def _prodlist_select(self, event):
|
785 |
+
selection = self._prodlist.curselection()
|
786 |
+
if len(selection) != 1:
|
787 |
+
return
|
788 |
+
index = int(selection[0])
|
789 |
+
old_frontier = self._parser.frontier()
|
790 |
+
production = self._parser.expand(self._productions[index])
|
791 |
+
|
792 |
+
if production:
|
793 |
+
self._lastoper1["text"] = "Expand:"
|
794 |
+
self._lastoper2["text"] = production
|
795 |
+
self._prodlist.selection_clear(0, "end")
|
796 |
+
self._prodlist.selection_set(index)
|
797 |
+
self._animate_expand(old_frontier[0])
|
798 |
+
else:
|
799 |
+
# Reset the production selections.
|
800 |
+
self._prodlist.selection_clear(0, "end")
|
801 |
+
for prod in self._parser.expandable_productions():
|
802 |
+
index = self._productions.index(prod)
|
803 |
+
self._prodlist.selection_set(index)
|
804 |
+
|
805 |
+
#########################################
|
806 |
+
## Animation
|
807 |
+
#########################################
|
808 |
+
|
809 |
+
def _animate_expand(self, treeloc):
|
810 |
+
oldwidget = self._get(self._tree, treeloc)
|
811 |
+
oldtree = oldwidget.parent()
|
812 |
+
top = not isinstance(oldtree.parent(), TreeSegmentWidget)
|
813 |
+
|
814 |
+
tree = self._parser.tree()
|
815 |
+
for i in treeloc:
|
816 |
+
tree = tree[i]
|
817 |
+
|
818 |
+
widget = tree_to_treesegment(
|
819 |
+
self._canvas,
|
820 |
+
tree,
|
821 |
+
node_font=self._boldfont,
|
822 |
+
leaf_color="white",
|
823 |
+
tree_width=2,
|
824 |
+
tree_color="white",
|
825 |
+
node_color="white",
|
826 |
+
leaf_font=self._font,
|
827 |
+
)
|
828 |
+
widget.label()["color"] = "#20a050"
|
829 |
+
|
830 |
+
(oldx, oldy) = oldtree.label().bbox()[:2]
|
831 |
+
(newx, newy) = widget.label().bbox()[:2]
|
832 |
+
widget.move(oldx - newx, oldy - newy)
|
833 |
+
|
834 |
+
if top:
|
835 |
+
self._cframe.add_widget(widget, 0, 5)
|
836 |
+
widget.move(30 - widget.label().bbox()[0], 0)
|
837 |
+
self._tree = widget
|
838 |
+
else:
|
839 |
+
oldtree.parent().replace_child(oldtree, widget)
|
840 |
+
|
841 |
+
# Move the children over so they don't overlap.
|
842 |
+
# Line the children up in a strange way.
|
843 |
+
if widget.subtrees():
|
844 |
+
dx = (
|
845 |
+
oldx
|
846 |
+
+ widget.label().width() / 2
|
847 |
+
- widget.subtrees()[0].bbox()[0] / 2
|
848 |
+
- widget.subtrees()[0].bbox()[2] / 2
|
849 |
+
)
|
850 |
+
for subtree in widget.subtrees():
|
851 |
+
subtree.move(dx, 0)
|
852 |
+
|
853 |
+
self._makeroom(widget)
|
854 |
+
|
855 |
+
if top:
|
856 |
+
self._cframe.destroy_widget(oldtree)
|
857 |
+
else:
|
858 |
+
oldtree.destroy()
|
859 |
+
|
860 |
+
colors = [
|
861 |
+
"gray%d" % (10 * int(10 * x / self._animation_frames.get()))
|
862 |
+
for x in range(self._animation_frames.get(), 0, -1)
|
863 |
+
]
|
864 |
+
|
865 |
+
# Move the text string down, if necessary.
|
866 |
+
dy = widget.bbox()[3] + 30 - self._canvas.coords(self._textline)[1]
|
867 |
+
if dy > 0:
|
868 |
+
for twidget in self._textwidgets:
|
869 |
+
twidget.move(0, dy)
|
870 |
+
self._canvas.move(self._textline, 0, dy)
|
871 |
+
|
872 |
+
self._animate_expand_frame(widget, colors)
|
873 |
+
|
874 |
+
def _makeroom(self, treeseg):
|
875 |
+
"""
|
876 |
+
Make sure that no sibling tree bbox's overlap.
|
877 |
+
"""
|
878 |
+
parent = treeseg.parent()
|
879 |
+
if not isinstance(parent, TreeSegmentWidget):
|
880 |
+
return
|
881 |
+
|
882 |
+
index = parent.subtrees().index(treeseg)
|
883 |
+
|
884 |
+
# Handle siblings to the right
|
885 |
+
rsiblings = parent.subtrees()[index + 1 :]
|
886 |
+
if rsiblings:
|
887 |
+
dx = treeseg.bbox()[2] - rsiblings[0].bbox()[0] + 10
|
888 |
+
for sibling in rsiblings:
|
889 |
+
sibling.move(dx, 0)
|
890 |
+
|
891 |
+
# Handle siblings to the left
|
892 |
+
if index > 0:
|
893 |
+
lsibling = parent.subtrees()[index - 1]
|
894 |
+
dx = max(0, lsibling.bbox()[2] - treeseg.bbox()[0] + 10)
|
895 |
+
treeseg.move(dx, 0)
|
896 |
+
|
897 |
+
# Keep working up the tree.
|
898 |
+
self._makeroom(parent)
|
899 |
+
|
900 |
+
def _animate_expand_frame(self, widget, colors):
|
901 |
+
if len(colors) > 0:
|
902 |
+
self._animating_lock = 1
|
903 |
+
widget["color"] = colors[0]
|
904 |
+
for subtree in widget.subtrees():
|
905 |
+
if isinstance(subtree, TreeSegmentWidget):
|
906 |
+
subtree.label()["color"] = colors[0]
|
907 |
+
else:
|
908 |
+
subtree["color"] = colors[0]
|
909 |
+
self._top.after(50, self._animate_expand_frame, widget, colors[1:])
|
910 |
+
else:
|
911 |
+
widget["color"] = "black"
|
912 |
+
for subtree in widget.subtrees():
|
913 |
+
if isinstance(subtree, TreeSegmentWidget):
|
914 |
+
subtree.label()["color"] = "black"
|
915 |
+
else:
|
916 |
+
subtree["color"] = "black"
|
917 |
+
self._redraw_quick()
|
918 |
+
widget.label()["color"] = "black"
|
919 |
+
self._animating_lock = 0
|
920 |
+
if self._autostep:
|
921 |
+
self._step()
|
922 |
+
|
923 |
+
def _animate_backtrack(self, treeloc):
|
924 |
+
# Flash red first, if we're animating.
|
925 |
+
if self._animation_frames.get() == 0:
|
926 |
+
colors = []
|
927 |
+
else:
|
928 |
+
colors = ["#a00000", "#000000", "#a00000"]
|
929 |
+
colors += [
|
930 |
+
"gray%d" % (10 * int(10 * x / (self._animation_frames.get())))
|
931 |
+
for x in range(1, self._animation_frames.get() + 1)
|
932 |
+
]
|
933 |
+
|
934 |
+
widgets = [self._get(self._tree, treeloc).parent()]
|
935 |
+
for subtree in widgets[0].subtrees():
|
936 |
+
if isinstance(subtree, TreeSegmentWidget):
|
937 |
+
widgets.append(subtree.label())
|
938 |
+
else:
|
939 |
+
widgets.append(subtree)
|
940 |
+
|
941 |
+
self._animate_backtrack_frame(widgets, colors)
|
942 |
+
|
943 |
+
def _animate_backtrack_frame(self, widgets, colors):
|
944 |
+
if len(colors) > 0:
|
945 |
+
self._animating_lock = 1
|
946 |
+
for widget in widgets:
|
947 |
+
widget["color"] = colors[0]
|
948 |
+
self._top.after(50, self._animate_backtrack_frame, widgets, colors[1:])
|
949 |
+
else:
|
950 |
+
for widget in widgets[0].subtrees():
|
951 |
+
widgets[0].remove_child(widget)
|
952 |
+
widget.destroy()
|
953 |
+
self._redraw_quick()
|
954 |
+
self._animating_lock = 0
|
955 |
+
if self._autostep:
|
956 |
+
self._step()
|
957 |
+
|
958 |
+
def _animate_match_backtrack(self, treeloc):
|
959 |
+
widget = self._get(self._tree, treeloc)
|
960 |
+
node = widget.parent().label()
|
961 |
+
dy = (node.bbox()[3] - widget.bbox()[1] + 14) / max(
|
962 |
+
1, self._animation_frames.get()
|
963 |
+
)
|
964 |
+
self._animate_match_backtrack_frame(self._animation_frames.get(), widget, dy)
|
965 |
+
|
966 |
+
def _animate_match(self, treeloc):
|
967 |
+
widget = self._get(self._tree, treeloc)
|
968 |
+
|
969 |
+
dy = (self._textwidgets[0].bbox()[1] - widget.bbox()[3] - 10.0) / max(
|
970 |
+
1, self._animation_frames.get()
|
971 |
+
)
|
972 |
+
self._animate_match_frame(self._animation_frames.get(), widget, dy)
|
973 |
+
|
974 |
+
def _animate_match_frame(self, frame, widget, dy):
|
975 |
+
if frame > 0:
|
976 |
+
self._animating_lock = 1
|
977 |
+
widget.move(0, dy)
|
978 |
+
self._top.after(10, self._animate_match_frame, frame - 1, widget, dy)
|
979 |
+
else:
|
980 |
+
widget["color"] = "#006040"
|
981 |
+
self._redraw_quick()
|
982 |
+
self._animating_lock = 0
|
983 |
+
if self._autostep:
|
984 |
+
self._step()
|
985 |
+
|
986 |
+
def _animate_match_backtrack_frame(self, frame, widget, dy):
|
987 |
+
if frame > 0:
|
988 |
+
self._animating_lock = 1
|
989 |
+
widget.move(0, dy)
|
990 |
+
self._top.after(
|
991 |
+
10, self._animate_match_backtrack_frame, frame - 1, widget, dy
|
992 |
+
)
|
993 |
+
else:
|
994 |
+
widget.parent().remove_child(widget)
|
995 |
+
widget.destroy()
|
996 |
+
self._animating_lock = 0
|
997 |
+
if self._autostep:
|
998 |
+
self._step()
|
999 |
+
|
1000 |
+
def edit_grammar(self, *e):
|
1001 |
+
CFGEditor(self._top, self._parser.grammar(), self.set_grammar)
|
1002 |
+
|
1003 |
+
def set_grammar(self, grammar):
|
1004 |
+
self._parser.set_grammar(grammar)
|
1005 |
+
self._productions = list(grammar.productions())
|
1006 |
+
self._prodlist.delete(0, "end")
|
1007 |
+
for production in self._productions:
|
1008 |
+
self._prodlist.insert("end", (" %s" % production))
|
1009 |
+
|
1010 |
+
def edit_sentence(self, *e):
|
1011 |
+
sentence = " ".join(self._sent)
|
1012 |
+
title = "Edit Text"
|
1013 |
+
instr = "Enter a new sentence to parse."
|
1014 |
+
EntryDialog(self._top, sentence, instr, self.set_sentence, title)
|
1015 |
+
|
1016 |
+
def set_sentence(self, sentence):
|
1017 |
+
self._sent = sentence.split() # [XX] use tagged?
|
1018 |
+
self.reset()
|
1019 |
+
|
1020 |
+
|
1021 |
+
def app():
|
1022 |
+
"""
|
1023 |
+
Create a recursive descent parser demo, using a simple grammar and
|
1024 |
+
text.
|
1025 |
+
"""
|
1026 |
+
from nltk.grammar import CFG
|
1027 |
+
|
1028 |
+
grammar = CFG.fromstring(
|
1029 |
+
"""
|
1030 |
+
# Grammatical productions.
|
1031 |
+
S -> NP VP
|
1032 |
+
NP -> Det N PP | Det N
|
1033 |
+
VP -> V NP PP | V NP | V
|
1034 |
+
PP -> P NP
|
1035 |
+
# Lexical productions.
|
1036 |
+
NP -> 'I'
|
1037 |
+
Det -> 'the' | 'a'
|
1038 |
+
N -> 'man' | 'park' | 'dog' | 'telescope'
|
1039 |
+
V -> 'ate' | 'saw'
|
1040 |
+
P -> 'in' | 'under' | 'with'
|
1041 |
+
"""
|
1042 |
+
)
|
1043 |
+
|
1044 |
+
sent = "the dog saw a man in the park".split()
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Shift-Reduce Parser Application
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Edward Loper <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
|
8 |
+
"""
|
9 |
+
A graphical tool for exploring the shift-reduce parser.
|
10 |
+
|
11 |
+
The shift-reduce parser maintains a stack, which records the structure
|
12 |
+
of the portion of the text that has been parsed. The stack is
|
13 |
+
initially empty. Its contents are shown on the left side of the main
|
14 |
+
canvas.
|
15 |
+
|
16 |
+
On the right side of the main canvas is the remaining text. This is
|
17 |
+
the portion of the text which has not yet been considered by the
|
18 |
+
parser.
|
19 |
+
|
20 |
+
The parser builds up a tree structure for the text using two
|
21 |
+
operations:
|
22 |
+
|
23 |
+
- "shift" moves the first token from the remaining text to the top
|
24 |
+
of the stack. In the demo, the top of the stack is its right-hand
|
25 |
+
side.
|
26 |
+
- "reduce" uses a grammar production to combine the rightmost stack
|
27 |
+
elements into a single tree token.
|
28 |
+
|
29 |
+
You can control the parser's operation by using the "shift" and
|
30 |
+
"reduce" buttons; or you can use the "step" button to let the parser
|
31 |
+
automatically decide which operation to apply. The parser uses the
|
32 |
+
following rules to decide which operation to apply:
|
33 |
+
|
34 |
+
- Only shift if no reductions are available.
|
35 |
+
- If multiple reductions are available, then apply the reduction
|
36 |
+
whose CFG production is listed earliest in the grammar.
|
37 |
+
|
38 |
+
The "reduce" button applies the reduction whose CFG production is
|
39 |
+
listed earliest in the grammar. There are two ways to manually choose
|
40 |
+
which reduction to apply:
|
41 |
+
|
42 |
+
- Click on a CFG production from the list of available reductions,
|
43 |
+
on the left side of the main window. The reduction based on that
|
44 |
+
production will be applied to the top of the stack.
|
45 |
+
- Click on one of the stack elements. A popup window will appear,
|
46 |
+
containing all available reductions. Select one, and it will be
|
47 |
+
applied to the top of the stack.
|
48 |
+
|
49 |
+
Note that reductions can only be applied to the top of the stack.
|
50 |
+
|
51 |
+
Keyboard Shortcuts::
|
52 |
+
[Space]\t Perform the next shift or reduce operation
|
53 |
+
[s]\t Perform a shift operation
|
54 |
+
[r]\t Perform a reduction operation
|
55 |
+
[Ctrl-z]\t Undo most recent operation
|
56 |
+
[Delete]\t Reset the parser
|
57 |
+
[g]\t Show/hide available production list
|
58 |
+
[Ctrl-a]\t Toggle animations
|
59 |
+
[h]\t Help
|
60 |
+
[Ctrl-p]\t Print
|
61 |
+
[q]\t Quit
|
62 |
+
|
63 |
+
"""
|
64 |
+
|
65 |
+
from tkinter import Button, Frame, IntVar, Label, Listbox, Menu, Scrollbar, Tk
|
66 |
+
from tkinter.font import Font
|
67 |
+
|
68 |
+
from nltk.draw import CFGEditor, TreeSegmentWidget, tree_to_treesegment
|
69 |
+
from nltk.draw.util import CanvasFrame, EntryDialog, ShowText, TextWidget
|
70 |
+
from nltk.parse import SteppingShiftReduceParser
|
71 |
+
from nltk.tree import Tree
|
72 |
+
from nltk.util import in_idle
|
73 |
+
|
74 |
+
"""
|
75 |
+
Possible future improvements:
|
76 |
+
- button/window to change and/or select text. Just pop up a window
|
77 |
+
with an entry, and let them modify the text; and then retokenize
|
78 |
+
it? Maybe give a warning if it contains tokens whose types are
|
79 |
+
not in the grammar.
|
80 |
+
- button/window to change and/or select grammar. Select from
|
81 |
+
several alternative grammars? Or actually change the grammar? If
|
82 |
+
the later, then I'd want to define nltk.draw.cfg, which would be
|
83 |
+
responsible for that.
|
84 |
+
"""
|
85 |
+
|
86 |
+
|
87 |
+
class ShiftReduceApp:
|
88 |
+
"""
|
89 |
+
A graphical tool for exploring the shift-reduce parser. The tool
|
90 |
+
displays the parser's stack and the remaining text, and allows the
|
91 |
+
user to control the parser's operation. In particular, the user
|
92 |
+
can shift tokens onto the stack, and can perform reductions on the
|
93 |
+
top elements of the stack. A "step" button simply steps through
|
94 |
+
the parsing process, performing the operations that
|
95 |
+
``nltk.parse.ShiftReduceParser`` would use.
|
96 |
+
"""
|
97 |
+
|
98 |
+
def __init__(self, grammar, sent, trace=0):
|
99 |
+
self._sent = sent
|
100 |
+
self._parser = SteppingShiftReduceParser(grammar, trace)
|
101 |
+
|
102 |
+
# Set up the main window.
|
103 |
+
self._top = Tk()
|
104 |
+
self._top.title("Shift Reduce Parser Application")
|
105 |
+
|
106 |
+
# Animations. animating_lock is a lock to prevent the demo
|
107 |
+
# from performing new operations while it's animating.
|
108 |
+
self._animating_lock = 0
|
109 |
+
self._animate = IntVar(self._top)
|
110 |
+
self._animate.set(10) # = medium
|
111 |
+
|
112 |
+
# The user can hide the grammar.
|
113 |
+
self._show_grammar = IntVar(self._top)
|
114 |
+
self._show_grammar.set(1)
|
115 |
+
|
116 |
+
# Initialize fonts.
|
117 |
+
self._init_fonts(self._top)
|
118 |
+
|
119 |
+
# Set up key bindings.
|
120 |
+
self._init_bindings()
|
121 |
+
|
122 |
+
# Create the basic frames.
|
123 |
+
self._init_menubar(self._top)
|
124 |
+
self._init_buttons(self._top)
|
125 |
+
self._init_feedback(self._top)
|
126 |
+
self._init_grammar(self._top)
|
127 |
+
self._init_canvas(self._top)
|
128 |
+
|
129 |
+
# A popup menu for reducing.
|
130 |
+
self._reduce_menu = Menu(self._canvas, tearoff=0)
|
131 |
+
|
132 |
+
# Reset the demo, and set the feedback frame to empty.
|
133 |
+
self.reset()
|
134 |
+
self._lastoper1["text"] = ""
|
135 |
+
|
136 |
+
#########################################
|
137 |
+
## Initialization Helpers
|
138 |
+
#########################################
|
139 |
+
|
140 |
+
def _init_fonts(self, root):
|
141 |
+
# See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
|
142 |
+
self._sysfont = Font(font=Button()["font"])
|
143 |
+
root.option_add("*Font", self._sysfont)
|
144 |
+
|
145 |
+
# TWhat's our font size (default=same as sysfont)
|
146 |
+
self._size = IntVar(root)
|
147 |
+
self._size.set(self._sysfont.cget("size"))
|
148 |
+
|
149 |
+
self._boldfont = Font(family="helvetica", weight="bold", size=self._size.get())
|
150 |
+
self._font = Font(family="helvetica", size=self._size.get())
|
151 |
+
|
152 |
+
def _init_grammar(self, parent):
|
153 |
+
# Grammar view.
|
154 |
+
self._prodframe = listframe = Frame(parent)
|
155 |
+
self._prodframe.pack(fill="both", side="left", padx=2)
|
156 |
+
self._prodlist_label = Label(
|
157 |
+
self._prodframe, font=self._boldfont, text="Available Reductions"
|
158 |
+
)
|
159 |
+
self._prodlist_label.pack()
|
160 |
+
self._prodlist = Listbox(
|
161 |
+
self._prodframe,
|
162 |
+
selectmode="single",
|
163 |
+
relief="groove",
|
164 |
+
background="white",
|
165 |
+
foreground="#909090",
|
166 |
+
font=self._font,
|
167 |
+
selectforeground="#004040",
|
168 |
+
selectbackground="#c0f0c0",
|
169 |
+
)
|
170 |
+
|
171 |
+
self._prodlist.pack(side="right", fill="both", expand=1)
|
172 |
+
|
173 |
+
self._productions = list(self._parser.grammar().productions())
|
174 |
+
for production in self._productions:
|
175 |
+
self._prodlist.insert("end", (" %s" % production))
|
176 |
+
self._prodlist.config(height=min(len(self._productions), 25))
|
177 |
+
|
178 |
+
# Add a scrollbar if there are more than 25 productions.
|
179 |
+
if 1: # len(self._productions) > 25:
|
180 |
+
listscroll = Scrollbar(self._prodframe, orient="vertical")
|
181 |
+
self._prodlist.config(yscrollcommand=listscroll.set)
|
182 |
+
listscroll.config(command=self._prodlist.yview)
|
183 |
+
listscroll.pack(side="left", fill="y")
|
184 |
+
|
185 |
+
# If they select a production, apply it.
|
186 |
+
self._prodlist.bind("<<ListboxSelect>>", self._prodlist_select)
|
187 |
+
|
188 |
+
# When they hover over a production, highlight it.
|
189 |
+
self._hover = -1
|
190 |
+
self._prodlist.bind("<Motion>", self._highlight_hover)
|
191 |
+
self._prodlist.bind("<Leave>", self._clear_hover)
|
192 |
+
|
193 |
+
def _init_bindings(self):
|
194 |
+
# Quit
|
195 |
+
self._top.bind("<Control-q>", self.destroy)
|
196 |
+
self._top.bind("<Control-x>", self.destroy)
|
197 |
+
self._top.bind("<Alt-q>", self.destroy)
|
198 |
+
self._top.bind("<Alt-x>", self.destroy)
|
199 |
+
|
200 |
+
# Ops (step, shift, reduce, undo)
|
201 |
+
self._top.bind("<space>", self.step)
|
202 |
+
self._top.bind("<s>", self.shift)
|
203 |
+
self._top.bind("<Alt-s>", self.shift)
|
204 |
+
self._top.bind("<Control-s>", self.shift)
|
205 |
+
self._top.bind("<r>", self.reduce)
|
206 |
+
self._top.bind("<Alt-r>", self.reduce)
|
207 |
+
self._top.bind("<Control-r>", self.reduce)
|
208 |
+
self._top.bind("<Delete>", self.reset)
|
209 |
+
self._top.bind("<u>", self.undo)
|
210 |
+
self._top.bind("<Alt-u>", self.undo)
|
211 |
+
self._top.bind("<Control-u>", self.undo)
|
212 |
+
self._top.bind("<Control-z>", self.undo)
|
213 |
+
self._top.bind("<BackSpace>", self.undo)
|
214 |
+
|
215 |
+
# Misc
|
216 |
+
self._top.bind("<Control-p>", self.postscript)
|
217 |
+
self._top.bind("<Control-h>", self.help)
|
218 |
+
self._top.bind("<F1>", self.help)
|
219 |
+
self._top.bind("<Control-g>", self.edit_grammar)
|
220 |
+
self._top.bind("<Control-t>", self.edit_sentence)
|
221 |
+
|
222 |
+
# Animation speed control
|
223 |
+
self._top.bind("-", lambda e, a=self._animate: a.set(20))
|
224 |
+
self._top.bind("=", lambda e, a=self._animate: a.set(10))
|
225 |
+
self._top.bind("+", lambda e, a=self._animate: a.set(4))
|
226 |
+
|
227 |
+
def _init_buttons(self, parent):
|
228 |
+
# Set up the frames.
|
229 |
+
self._buttonframe = buttonframe = Frame(parent)
|
230 |
+
buttonframe.pack(fill="none", side="bottom")
|
231 |
+
Button(
|
232 |
+
buttonframe,
|
233 |
+
text="Step",
|
234 |
+
background="#90c0d0",
|
235 |
+
foreground="black",
|
236 |
+
command=self.step,
|
237 |
+
).pack(side="left")
|
238 |
+
Button(
|
239 |
+
buttonframe,
|
240 |
+
text="Shift",
|
241 |
+
underline=0,
|
242 |
+
background="#90f090",
|
243 |
+
foreground="black",
|
244 |
+
command=self.shift,
|
245 |
+
).pack(side="left")
|
246 |
+
Button(
|
247 |
+
buttonframe,
|
248 |
+
text="Reduce",
|
249 |
+
underline=0,
|
250 |
+
background="#90f090",
|
251 |
+
foreground="black",
|
252 |
+
command=self.reduce,
|
253 |
+
).pack(side="left")
|
254 |
+
Button(
|
255 |
+
buttonframe,
|
256 |
+
text="Undo",
|
257 |
+
underline=0,
|
258 |
+
background="#f0a0a0",
|
259 |
+
foreground="black",
|
260 |
+
command=self.undo,
|
261 |
+
).pack(side="left")
|
262 |
+
|
263 |
+
def _init_menubar(self, parent):
|
264 |
+
menubar = Menu(parent)
|
265 |
+
|
266 |
+
filemenu = Menu(menubar, tearoff=0)
|
267 |
+
filemenu.add_command(
|
268 |
+
label="Reset Parser", underline=0, command=self.reset, accelerator="Del"
|
269 |
+
)
|
270 |
+
filemenu.add_command(
|
271 |
+
label="Print to Postscript",
|
272 |
+
underline=0,
|
273 |
+
command=self.postscript,
|
274 |
+
accelerator="Ctrl-p",
|
275 |
+
)
|
276 |
+
filemenu.add_command(
|
277 |
+
label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-x"
|
278 |
+
)
|
279 |
+
menubar.add_cascade(label="File", underline=0, menu=filemenu)
|
280 |
+
|
281 |
+
editmenu = Menu(menubar, tearoff=0)
|
282 |
+
editmenu.add_command(
|
283 |
+
label="Edit Grammar",
|
284 |
+
underline=5,
|
285 |
+
command=self.edit_grammar,
|
286 |
+
accelerator="Ctrl-g",
|
287 |
+
)
|
288 |
+
editmenu.add_command(
|
289 |
+
label="Edit Text",
|
290 |
+
underline=5,
|
291 |
+
command=self.edit_sentence,
|
292 |
+
accelerator="Ctrl-t",
|
293 |
+
)
|
294 |
+
menubar.add_cascade(label="Edit", underline=0, menu=editmenu)
|
295 |
+
|
296 |
+
rulemenu = Menu(menubar, tearoff=0)
|
297 |
+
rulemenu.add_command(
|
298 |
+
label="Step", underline=1, command=self.step, accelerator="Space"
|
299 |
+
)
|
300 |
+
rulemenu.add_separator()
|
301 |
+
rulemenu.add_command(
|
302 |
+
label="Shift", underline=0, command=self.shift, accelerator="Ctrl-s"
|
303 |
+
)
|
304 |
+
rulemenu.add_command(
|
305 |
+
label="Reduce", underline=0, command=self.reduce, accelerator="Ctrl-r"
|
306 |
+
)
|
307 |
+
rulemenu.add_separator()
|
308 |
+
rulemenu.add_command(
|
309 |
+
label="Undo", underline=0, command=self.undo, accelerator="Ctrl-u"
|
310 |
+
)
|
311 |
+
menubar.add_cascade(label="Apply", underline=0, menu=rulemenu)
|
312 |
+
|
313 |
+
viewmenu = Menu(menubar, tearoff=0)
|
314 |
+
viewmenu.add_checkbutton(
|
315 |
+
label="Show Grammar",
|
316 |
+
underline=0,
|
317 |
+
variable=self._show_grammar,
|
318 |
+
command=self._toggle_grammar,
|
319 |
+
)
|
320 |
+
viewmenu.add_separator()
|
321 |
+
viewmenu.add_radiobutton(
|
322 |
+
label="Tiny",
|
323 |
+
variable=self._size,
|
324 |
+
underline=0,
|
325 |
+
value=10,
|
326 |
+
command=self.resize,
|
327 |
+
)
|
328 |
+
viewmenu.add_radiobutton(
|
329 |
+
label="Small",
|
330 |
+
variable=self._size,
|
331 |
+
underline=0,
|
332 |
+
value=12,
|
333 |
+
command=self.resize,
|
334 |
+
)
|
335 |
+
viewmenu.add_radiobutton(
|
336 |
+
label="Medium",
|
337 |
+
variable=self._size,
|
338 |
+
underline=0,
|
339 |
+
value=14,
|
340 |
+
command=self.resize,
|
341 |
+
)
|
342 |
+
viewmenu.add_radiobutton(
|
343 |
+
label="Large",
|
344 |
+
variable=self._size,
|
345 |
+
underline=0,
|
346 |
+
value=18,
|
347 |
+
command=self.resize,
|
348 |
+
)
|
349 |
+
viewmenu.add_radiobutton(
|
350 |
+
label="Huge",
|
351 |
+
variable=self._size,
|
352 |
+
underline=0,
|
353 |
+
value=24,
|
354 |
+
command=self.resize,
|
355 |
+
)
|
356 |
+
menubar.add_cascade(label="View", underline=0, menu=viewmenu)
|
357 |
+
|
358 |
+
animatemenu = Menu(menubar, tearoff=0)
|
359 |
+
animatemenu.add_radiobutton(
|
360 |
+
label="No Animation", underline=0, variable=self._animate, value=0
|
361 |
+
)
|
362 |
+
animatemenu.add_radiobutton(
|
363 |
+
label="Slow Animation",
|
364 |
+
underline=0,
|
365 |
+
variable=self._animate,
|
366 |
+
value=20,
|
367 |
+
accelerator="-",
|
368 |
+
)
|
369 |
+
animatemenu.add_radiobutton(
|
370 |
+
label="Normal Animation",
|
371 |
+
underline=0,
|
372 |
+
variable=self._animate,
|
373 |
+
value=10,
|
374 |
+
accelerator="=",
|
375 |
+
)
|
376 |
+
animatemenu.add_radiobutton(
|
377 |
+
label="Fast Animation",
|
378 |
+
underline=0,
|
379 |
+
variable=self._animate,
|
380 |
+
value=4,
|
381 |
+
accelerator="+",
|
382 |
+
)
|
383 |
+
menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)
|
384 |
+
|
385 |
+
helpmenu = Menu(menubar, tearoff=0)
|
386 |
+
helpmenu.add_command(label="About", underline=0, command=self.about)
|
387 |
+
helpmenu.add_command(
|
388 |
+
label="Instructions", underline=0, command=self.help, accelerator="F1"
|
389 |
+
)
|
390 |
+
menubar.add_cascade(label="Help", underline=0, menu=helpmenu)
|
391 |
+
|
392 |
+
parent.config(menu=menubar)
|
393 |
+
|
394 |
+
def _init_feedback(self, parent):
|
395 |
+
self._feedbackframe = feedbackframe = Frame(parent)
|
396 |
+
feedbackframe.pack(fill="x", side="bottom", padx=3, pady=3)
|
397 |
+
self._lastoper_label = Label(
|
398 |
+
feedbackframe, text="Last Operation:", font=self._font
|
399 |
+
)
|
400 |
+
self._lastoper_label.pack(side="left")
|
401 |
+
lastoperframe = Frame(feedbackframe, relief="sunken", border=1)
|
402 |
+
lastoperframe.pack(fill="x", side="right", expand=1, padx=5)
|
403 |
+
self._lastoper1 = Label(
|
404 |
+
lastoperframe, foreground="#007070", background="#f0f0f0", font=self._font
|
405 |
+
)
|
406 |
+
self._lastoper2 = Label(
|
407 |
+
lastoperframe,
|
408 |
+
anchor="w",
|
409 |
+
width=30,
|
410 |
+
foreground="#004040",
|
411 |
+
background="#f0f0f0",
|
412 |
+
font=self._font,
|
413 |
+
)
|
414 |
+
self._lastoper1.pack(side="left")
|
415 |
+
self._lastoper2.pack(side="left", fill="x", expand=1)
|
416 |
+
|
417 |
+
def _init_canvas(self, parent):
|
418 |
+
self._cframe = CanvasFrame(
|
419 |
+
parent,
|
420 |
+
background="white",
|
421 |
+
width=525,
|
422 |
+
closeenough=10,
|
423 |
+
border=2,
|
424 |
+
relief="sunken",
|
425 |
+
)
|
426 |
+
self._cframe.pack(expand=1, fill="both", side="top", pady=2)
|
427 |
+
canvas = self._canvas = self._cframe.canvas()
|
428 |
+
|
429 |
+
self._stackwidgets = []
|
430 |
+
self._rtextwidgets = []
|
431 |
+
self._titlebar = canvas.create_rectangle(
|
432 |
+
0, 0, 0, 0, fill="#c0f0f0", outline="black"
|
433 |
+
)
|
434 |
+
self._exprline = canvas.create_line(0, 0, 0, 0, dash=".")
|
435 |
+
self._stacktop = canvas.create_line(0, 0, 0, 0, fill="#408080")
|
436 |
+
size = self._size.get() + 4
|
437 |
+
self._stacklabel = TextWidget(
|
438 |
+
canvas, "Stack", color="#004040", font=self._boldfont
|
439 |
+
)
|
440 |
+
self._rtextlabel = TextWidget(
|
441 |
+
canvas, "Remaining Text", color="#004040", font=self._boldfont
|
442 |
+
)
|
443 |
+
self._cframe.add_widget(self._stacklabel)
|
444 |
+
self._cframe.add_widget(self._rtextlabel)
|
445 |
+
|
446 |
+
#########################################
|
447 |
+
## Main draw procedure
|
448 |
+
#########################################
|
449 |
+
|
450 |
+
def _redraw(self):
|
451 |
+
scrollregion = self._canvas["scrollregion"].split()
|
452 |
+
(cx1, cy1, cx2, cy2) = (int(c) for c in scrollregion)
|
453 |
+
|
454 |
+
# Delete the old stack & rtext widgets.
|
455 |
+
for stackwidget in self._stackwidgets:
|
456 |
+
self._cframe.destroy_widget(stackwidget)
|
457 |
+
self._stackwidgets = []
|
458 |
+
for rtextwidget in self._rtextwidgets:
|
459 |
+
self._cframe.destroy_widget(rtextwidget)
|
460 |
+
self._rtextwidgets = []
|
461 |
+
|
462 |
+
# Position the titlebar & exprline
|
463 |
+
(x1, y1, x2, y2) = self._stacklabel.bbox()
|
464 |
+
y = y2 - y1 + 10
|
465 |
+
self._canvas.coords(self._titlebar, -5000, 0, 5000, y - 4)
|
466 |
+
self._canvas.coords(self._exprline, 0, y * 2 - 10, 5000, y * 2 - 10)
|
467 |
+
|
468 |
+
# Position the titlebar labels..
|
469 |
+
(x1, y1, x2, y2) = self._stacklabel.bbox()
|
470 |
+
self._stacklabel.move(5 - x1, 3 - y1)
|
471 |
+
(x1, y1, x2, y2) = self._rtextlabel.bbox()
|
472 |
+
self._rtextlabel.move(cx2 - x2 - 5, 3 - y1)
|
473 |
+
|
474 |
+
# Draw the stack.
|
475 |
+
stackx = 5
|
476 |
+
for tok in self._parser.stack():
|
477 |
+
if isinstance(tok, Tree):
|
478 |
+
attribs = {
|
479 |
+
"tree_color": "#4080a0",
|
480 |
+
"tree_width": 2,
|
481 |
+
"node_font": self._boldfont,
|
482 |
+
"node_color": "#006060",
|
483 |
+
"leaf_color": "#006060",
|
484 |
+
"leaf_font": self._font,
|
485 |
+
}
|
486 |
+
widget = tree_to_treesegment(self._canvas, tok, **attribs)
|
487 |
+
widget.label()["color"] = "#000000"
|
488 |
+
else:
|
489 |
+
widget = TextWidget(self._canvas, tok, color="#000000", font=self._font)
|
490 |
+
widget.bind_click(self._popup_reduce)
|
491 |
+
self._stackwidgets.append(widget)
|
492 |
+
self._cframe.add_widget(widget, stackx, y)
|
493 |
+
stackx = widget.bbox()[2] + 10
|
494 |
+
|
495 |
+
# Draw the remaining text.
|
496 |
+
rtextwidth = 0
|
497 |
+
for tok in self._parser.remaining_text():
|
498 |
+
widget = TextWidget(self._canvas, tok, color="#000000", font=self._font)
|
499 |
+
self._rtextwidgets.append(widget)
|
500 |
+
self._cframe.add_widget(widget, rtextwidth, y)
|
501 |
+
rtextwidth = widget.bbox()[2] + 4
|
502 |
+
|
503 |
+
# Allow enough room to shift the next token (for animations)
|
504 |
+
if len(self._rtextwidgets) > 0:
|
505 |
+
stackx += self._rtextwidgets[0].width()
|
506 |
+
|
507 |
+
# Move the remaining text to the correct location (keep it
|
508 |
+
# right-justified, when possible); and move the remaining text
|
509 |
+
# label, if necessary.
|
510 |
+
stackx = max(stackx, self._stacklabel.width() + 25)
|
511 |
+
rlabelwidth = self._rtextlabel.width() + 10
|
512 |
+
if stackx >= cx2 - max(rtextwidth, rlabelwidth):
|
513 |
+
cx2 = stackx + max(rtextwidth, rlabelwidth)
|
514 |
+
for rtextwidget in self._rtextwidgets:
|
515 |
+
rtextwidget.move(4 + cx2 - rtextwidth, 0)
|
516 |
+
self._rtextlabel.move(cx2 - self._rtextlabel.bbox()[2] - 5, 0)
|
517 |
+
|
518 |
+
midx = (stackx + cx2 - max(rtextwidth, rlabelwidth)) / 2
|
519 |
+
self._canvas.coords(self._stacktop, midx, 0, midx, 5000)
|
520 |
+
(x1, y1, x2, y2) = self._stacklabel.bbox()
|
521 |
+
|
522 |
+
# Set up binding to allow them to shift a token by dragging it.
|
523 |
+
if len(self._rtextwidgets) > 0:
|
524 |
+
|
525 |
+
def drag_shift(widget, midx=midx, self=self):
|
526 |
+
if widget.bbox()[0] < midx:
|
527 |
+
self.shift()
|
528 |
+
else:
|
529 |
+
self._redraw()
|
530 |
+
|
531 |
+
self._rtextwidgets[0].bind_drag(drag_shift)
|
532 |
+
self._rtextwidgets[0].bind_click(self.shift)
|
533 |
+
|
534 |
+
# Draw the stack top.
|
535 |
+
self._highlight_productions()
|
536 |
+
|
537 |
+
def _draw_stack_top(self, widget):
|
538 |
+
# hack..
|
539 |
+
midx = widget.bbox()[2] + 50
|
540 |
+
self._canvas.coords(self._stacktop, midx, 0, midx, 5000)
|
541 |
+
|
542 |
+
def _highlight_productions(self):
|
543 |
+
# Highlight the productions that can be reduced.
|
544 |
+
self._prodlist.selection_clear(0, "end")
|
545 |
+
for prod in self._parser.reducible_productions():
|
546 |
+
index = self._productions.index(prod)
|
547 |
+
self._prodlist.selection_set(index)
|
548 |
+
|
549 |
+
#########################################
|
550 |
+
## Button Callbacks
|
551 |
+
#########################################
|
552 |
+
|
553 |
+
def destroy(self, *e):
|
554 |
+
if self._top is None:
|
555 |
+
return
|
556 |
+
self._top.destroy()
|
557 |
+
self._top = None
|
558 |
+
|
559 |
+
def reset(self, *e):
|
560 |
+
self._parser.initialize(self._sent)
|
561 |
+
self._lastoper1["text"] = "Reset App"
|
562 |
+
self._lastoper2["text"] = ""
|
563 |
+
self._redraw()
|
564 |
+
|
565 |
+
def step(self, *e):
|
566 |
+
if self.reduce():
|
567 |
+
return True
|
568 |
+
elif self.shift():
|
569 |
+
return True
|
570 |
+
else:
|
571 |
+
if list(self._parser.parses()):
|
572 |
+
self._lastoper1["text"] = "Finished:"
|
573 |
+
self._lastoper2["text"] = "Success"
|
574 |
+
else:
|
575 |
+
self._lastoper1["text"] = "Finished:"
|
576 |
+
self._lastoper2["text"] = "Failure"
|
577 |
+
|
578 |
+
def shift(self, *e):
|
579 |
+
if self._animating_lock:
|
580 |
+
return
|
581 |
+
if self._parser.shift():
|
582 |
+
tok = self._parser.stack()[-1]
|
583 |
+
self._lastoper1["text"] = "Shift:"
|
584 |
+
self._lastoper2["text"] = "%r" % tok
|
585 |
+
if self._animate.get():
|
586 |
+
self._animate_shift()
|
587 |
+
else:
|
588 |
+
self._redraw()
|
589 |
+
return True
|
590 |
+
return False
|
591 |
+
|
592 |
+
def reduce(self, *e):
|
593 |
+
if self._animating_lock:
|
594 |
+
return
|
595 |
+
production = self._parser.reduce()
|
596 |
+
if production:
|
597 |
+
self._lastoper1["text"] = "Reduce:"
|
598 |
+
self._lastoper2["text"] = "%s" % production
|
599 |
+
if self._animate.get():
|
600 |
+
self._animate_reduce()
|
601 |
+
else:
|
602 |
+
self._redraw()
|
603 |
+
return production
|
604 |
+
|
605 |
+
def undo(self, *e):
|
606 |
+
if self._animating_lock:
|
607 |
+
return
|
608 |
+
if self._parser.undo():
|
609 |
+
self._redraw()
|
610 |
+
|
611 |
+
def postscript(self, *e):
|
612 |
+
self._cframe.print_to_file()
|
613 |
+
|
614 |
+
def mainloop(self, *args, **kwargs):
|
615 |
+
"""
|
616 |
+
Enter the Tkinter mainloop. This function must be called if
|
617 |
+
this demo is created from a non-interactive program (e.g.
|
618 |
+
from a secript); otherwise, the demo will close as soon as
|
619 |
+
the script completes.
|
620 |
+
"""
|
621 |
+
if in_idle():
|
622 |
+
return
|
623 |
+
self._top.mainloop(*args, **kwargs)
|
624 |
+
|
625 |
+
#########################################
|
626 |
+
## Menubar callbacks
|
627 |
+
#########################################
|
628 |
+
|
629 |
+
def resize(self, size=None):
|
630 |
+
if size is not None:
|
631 |
+
self._size.set(size)
|
632 |
+
size = self._size.get()
|
633 |
+
self._font.configure(size=-(abs(size)))
|
634 |
+
self._boldfont.configure(size=-(abs(size)))
|
635 |
+
self._sysfont.configure(size=-(abs(size)))
|
636 |
+
|
637 |
+
# self._stacklabel['font'] = ('helvetica', -size-4, 'bold')
|
638 |
+
# self._rtextlabel['font'] = ('helvetica', -size-4, 'bold')
|
639 |
+
# self._lastoper_label['font'] = ('helvetica', -size)
|
640 |
+
# self._lastoper1['font'] = ('helvetica', -size)
|
641 |
+
# self._lastoper2['font'] = ('helvetica', -size)
|
642 |
+
# self._prodlist['font'] = ('helvetica', -size)
|
643 |
+
# self._prodlist_label['font'] = ('helvetica', -size-2, 'bold')
|
644 |
+
self._redraw()
|
645 |
+
|
646 |
+
def help(self, *e):
|
647 |
+
# The default font's not very legible; try using 'fixed' instead.
|
648 |
+
try:
|
649 |
+
ShowText(
|
650 |
+
self._top,
|
651 |
+
"Help: Shift-Reduce Parser Application",
|
652 |
+
(__doc__ or "").strip(),
|
653 |
+
width=75,
|
654 |
+
font="fixed",
|
655 |
+
)
|
656 |
+
except:
|
657 |
+
ShowText(
|
658 |
+
self._top,
|
659 |
+
"Help: Shift-Reduce Parser Application",
|
660 |
+
(__doc__ or "").strip(),
|
661 |
+
width=75,
|
662 |
+
)
|
663 |
+
|
664 |
+
def about(self, *e):
|
665 |
+
ABOUT = "NLTK Shift-Reduce Parser Application\n" + "Written by Edward Loper"
|
666 |
+
TITLE = "About: Shift-Reduce Parser Application"
|
667 |
+
try:
|
668 |
+
from tkinter.messagebox import Message
|
669 |
+
|
670 |
+
Message(message=ABOUT, title=TITLE).show()
|
671 |
+
except:
|
672 |
+
ShowText(self._top, TITLE, ABOUT)
|
673 |
+
|
674 |
+
def edit_grammar(self, *e):
|
675 |
+
CFGEditor(self._top, self._parser.grammar(), self.set_grammar)
|
676 |
+
|
677 |
+
def set_grammar(self, grammar):
|
678 |
+
self._parser.set_grammar(grammar)
|
679 |
+
self._productions = list(grammar.productions())
|
680 |
+
self._prodlist.delete(0, "end")
|
681 |
+
for production in self._productions:
|
682 |
+
self._prodlist.insert("end", (" %s" % production))
|
683 |
+
|
684 |
+
def edit_sentence(self, *e):
|
685 |
+
sentence = " ".join(self._sent)
|
686 |
+
title = "Edit Text"
|
687 |
+
instr = "Enter a new sentence to parse."
|
688 |
+
EntryDialog(self._top, sentence, instr, self.set_sentence, title)
|
689 |
+
|
690 |
+
def set_sentence(self, sent):
|
691 |
+
self._sent = sent.split() # [XX] use tagged?
|
692 |
+
self.reset()
|
693 |
+
|
694 |
+
#########################################
|
695 |
+
## Reduce Production Selection
|
696 |
+
#########################################
|
697 |
+
|
698 |
+
def _toggle_grammar(self, *e):
|
699 |
+
if self._show_grammar.get():
|
700 |
+
self._prodframe.pack(
|
701 |
+
fill="both", side="left", padx=2, after=self._feedbackframe
|
702 |
+
)
|
703 |
+
self._lastoper1["text"] = "Show Grammar"
|
704 |
+
else:
|
705 |
+
self._prodframe.pack_forget()
|
706 |
+
self._lastoper1["text"] = "Hide Grammar"
|
707 |
+
self._lastoper2["text"] = ""
|
708 |
+
|
709 |
+
def _prodlist_select(self, event):
|
710 |
+
selection = self._prodlist.curselection()
|
711 |
+
if len(selection) != 1:
|
712 |
+
return
|
713 |
+
index = int(selection[0])
|
714 |
+
production = self._parser.reduce(self._productions[index])
|
715 |
+
if production:
|
716 |
+
self._lastoper1["text"] = "Reduce:"
|
717 |
+
self._lastoper2["text"] = "%s" % production
|
718 |
+
if self._animate.get():
|
719 |
+
self._animate_reduce()
|
720 |
+
else:
|
721 |
+
self._redraw()
|
722 |
+
else:
|
723 |
+
# Reset the production selections.
|
724 |
+
self._prodlist.selection_clear(0, "end")
|
725 |
+
for prod in self._parser.reducible_productions():
|
726 |
+
index = self._productions.index(prod)
|
727 |
+
self._prodlist.selection_set(index)
|
728 |
+
|
729 |
+
def _popup_reduce(self, widget):
|
730 |
+
# Remove old commands.
|
731 |
+
productions = self._parser.reducible_productions()
|
732 |
+
if len(productions) == 0:
|
733 |
+
return
|
734 |
+
|
735 |
+
self._reduce_menu.delete(0, "end")
|
736 |
+
for production in productions:
|
737 |
+
self._reduce_menu.add_command(label=str(production), command=self.reduce)
|
738 |
+
self._reduce_menu.post(
|
739 |
+
self._canvas.winfo_pointerx(), self._canvas.winfo_pointery()
|
740 |
+
)
|
741 |
+
|
742 |
+
#########################################
|
743 |
+
## Animations
|
744 |
+
#########################################
|
745 |
+
|
746 |
+
def _animate_shift(self):
|
747 |
+
# What widget are we shifting?
|
748 |
+
widget = self._rtextwidgets[0]
|
749 |
+
|
750 |
+
# Where are we shifting from & to?
|
751 |
+
right = widget.bbox()[0]
|
752 |
+
if len(self._stackwidgets) == 0:
|
753 |
+
left = 5
|
754 |
+
else:
|
755 |
+
left = self._stackwidgets[-1].bbox()[2] + 10
|
756 |
+
|
757 |
+
# Start animating.
|
758 |
+
dt = self._animate.get()
|
759 |
+
dx = (left - right) * 1.0 / dt
|
760 |
+
self._animate_shift_frame(dt, widget, dx)
|
761 |
+
|
762 |
+
def _animate_shift_frame(self, frame, widget, dx):
|
763 |
+
if frame > 0:
|
764 |
+
self._animating_lock = 1
|
765 |
+
widget.move(dx, 0)
|
766 |
+
self._top.after(10, self._animate_shift_frame, frame - 1, widget, dx)
|
767 |
+
else:
|
768 |
+
# but: stacktop??
|
769 |
+
|
770 |
+
# Shift the widget to the stack.
|
771 |
+
del self._rtextwidgets[0]
|
772 |
+
self._stackwidgets.append(widget)
|
773 |
+
self._animating_lock = 0
|
774 |
+
|
775 |
+
# Display the available productions.
|
776 |
+
self._draw_stack_top(widget)
|
777 |
+
self._highlight_productions()
|
778 |
+
|
779 |
+
def _animate_reduce(self):
|
780 |
+
# What widgets are we shifting?
|
781 |
+
numwidgets = len(self._parser.stack()[-1]) # number of children
|
782 |
+
widgets = self._stackwidgets[-numwidgets:]
|
783 |
+
|
784 |
+
# How far are we moving?
|
785 |
+
if isinstance(widgets[0], TreeSegmentWidget):
|
786 |
+
ydist = 15 + widgets[0].label().height()
|
787 |
+
else:
|
788 |
+
ydist = 15 + widgets[0].height()
|
789 |
+
|
790 |
+
# Start animating.
|
791 |
+
dt = self._animate.get()
|
792 |
+
dy = ydist * 2.0 / dt
|
793 |
+
self._animate_reduce_frame(dt / 2, widgets, dy)
|
794 |
+
|
795 |
+
def _animate_reduce_frame(self, frame, widgets, dy):
|
796 |
+
if frame > 0:
|
797 |
+
self._animating_lock = 1
|
798 |
+
for widget in widgets:
|
799 |
+
widget.move(0, dy)
|
800 |
+
self._top.after(10, self._animate_reduce_frame, frame - 1, widgets, dy)
|
801 |
+
else:
|
802 |
+
del self._stackwidgets[-len(widgets) :]
|
803 |
+
for widget in widgets:
|
804 |
+
self._cframe.remove_widget(widget)
|
805 |
+
tok = self._parser.stack()[-1]
|
806 |
+
if not isinstance(tok, Tree):
|
807 |
+
raise ValueError()
|
808 |
+
label = TextWidget(
|
809 |
+
self._canvas, str(tok.label()), color="#006060", font=self._boldfont
|
810 |
+
)
|
811 |
+
widget = TreeSegmentWidget(self._canvas, label, widgets, width=2)
|
812 |
+
(x1, y1, x2, y2) = self._stacklabel.bbox()
|
813 |
+
y = y2 - y1 + 10
|
814 |
+
if not self._stackwidgets:
|
815 |
+
x = 5
|
816 |
+
else:
|
817 |
+
x = self._stackwidgets[-1].bbox()[2] + 10
|
818 |
+
self._cframe.add_widget(widget, x, y)
|
819 |
+
self._stackwidgets.append(widget)
|
820 |
+
|
821 |
+
# Display the available productions.
|
822 |
+
self._draw_stack_top(widget)
|
823 |
+
self._highlight_productions()
|
824 |
+
|
825 |
+
# # Delete the old widgets..
|
826 |
+
# del self._stackwidgets[-len(widgets):]
|
827 |
+
# for widget in widgets:
|
828 |
+
# self._cframe.destroy_widget(widget)
|
829 |
+
#
|
830 |
+
# # Make a new one.
|
831 |
+
# tok = self._parser.stack()[-1]
|
832 |
+
# if isinstance(tok, Tree):
|
833 |
+
# attribs = {'tree_color': '#4080a0', 'tree_width': 2,
|
834 |
+
# 'node_font': bold, 'node_color': '#006060',
|
835 |
+
# 'leaf_color': '#006060', 'leaf_font':self._font}
|
836 |
+
# widget = tree_to_treesegment(self._canvas, tok.type(),
|
837 |
+
# **attribs)
|
838 |
+
# widget.node()['color'] = '#000000'
|
839 |
+
# else:
|
840 |
+
# widget = TextWidget(self._canvas, tok.type(),
|
841 |
+
# color='#000000', font=self._font)
|
842 |
+
# widget.bind_click(self._popup_reduce)
|
843 |
+
# (x1, y1, x2, y2) = self._stacklabel.bbox()
|
844 |
+
# y = y2-y1+10
|
845 |
+
# if not self._stackwidgets: x = 5
|
846 |
+
# else: x = self._stackwidgets[-1].bbox()[2] + 10
|
847 |
+
# self._cframe.add_widget(widget, x, y)
|
848 |
+
# self._stackwidgets.append(widget)
|
849 |
+
|
850 |
+
# self._redraw()
|
851 |
+
self._animating_lock = 0
|
852 |
+
|
853 |
+
#########################################
|
854 |
+
## Hovering.
|
855 |
+
#########################################
|
856 |
+
|
857 |
+
def _highlight_hover(self, event):
|
858 |
+
# What production are we hovering over?
|
859 |
+
index = self._prodlist.nearest(event.y)
|
860 |
+
if self._hover == index:
|
861 |
+
return
|
862 |
+
|
863 |
+
# Clear any previous hover highlighting.
|
864 |
+
self._clear_hover()
|
865 |
+
|
866 |
+
# If the production corresponds to an available reduction,
|
867 |
+
# highlight the stack.
|
868 |
+
selection = [int(s) for s in self._prodlist.curselection()]
|
869 |
+
if index in selection:
|
870 |
+
rhslen = len(self._productions[index].rhs())
|
871 |
+
for stackwidget in self._stackwidgets[-rhslen:]:
|
872 |
+
if isinstance(stackwidget, TreeSegmentWidget):
|
873 |
+
stackwidget.label()["color"] = "#00a000"
|
874 |
+
else:
|
875 |
+
stackwidget["color"] = "#00a000"
|
876 |
+
|
877 |
+
# Remember what production we're hovering over.
|
878 |
+
self._hover = index
|
879 |
+
|
880 |
+
def _clear_hover(self, *event):
|
881 |
+
# Clear any previous hover highlighting.
|
882 |
+
if self._hover == -1:
|
883 |
+
return
|
884 |
+
self._hover = -1
|
885 |
+
for stackwidget in self._stackwidgets:
|
886 |
+
if isinstance(stackwidget, TreeSegmentWidget):
|
887 |
+
stackwidget.label()["color"] = "black"
|
888 |
+
else:
|
889 |
+
stackwidget["color"] = "black"
|
890 |
+
|
891 |
+
|
892 |
+
def app():
|
893 |
+
"""
|
894 |
+
Create a shift reduce parser app, using a simple grammar and
|
895 |
+
text.
|
896 |
+
"""
|
897 |
+
|
898 |
+
from nltk.grammar import CFG, Nonterminal, Production
|
899 |
+
|
900 |
+
nonterminals = "S VP NP PP P N Name V Det"
|
901 |
+
(S, VP, NP, PP, P, N, Name, V, Det) = (Nonterminal(s) for s in nonterminals.split())
|
902 |
+
|
903 |
+
productions = (
|
904 |
+
# Syntactic Productions
|
905 |
+
Production(S, [NP, VP]),
|
906 |
+
Production(NP, [Det, N]),
|
907 |
+
Production(NP, [NP, PP]),
|
908 |
+
Production(VP, [VP, PP]),
|
909 |
+
Production(VP, [V, NP, PP]),
|
910 |
+
Production(VP, [V, NP]),
|
911 |
+
Production(PP, [P, NP]),
|
912 |
+
# Lexical Productions
|
913 |
+
Production(NP, ["I"]),
|
914 |
+
Production(Det, ["the"]),
|
915 |
+
Production(Det, ["a"]),
|
916 |
+
Production(N, ["man"]),
|
917 |
+
Production(V, ["saw"]),
|
918 |
+
Production(P, ["in"]),
|
919 |
+
Production(P, ["with"]),
|
920 |
+
Production(N, ["park"]),
|
921 |
+
Production(N, ["dog"]),
|
922 |
+
Production(N, ["statue"]),
|
923 |
+
Production(Det, ["my"]),
|
924 |
+
)
|
925 |
+
|
926 |
+
grammar = CFG(S, productions)
|
927 |
+
|
928 |
+
# tokenize the sentence
|
929 |
+
sent = "my dog saw a man in the park with a statue".split()
|
930 |
+
|
931 |
+
ShiftReduceApp(grammar, sent).mainloop()
|
932 |
+
|
933 |
+
|
934 |
+
if __name__ == "__main__":
|
935 |
+
app()
|
936 |
+
|
937 |
+
__all__ = ["app"]
|
env-llmeval/lib/python3.10/site-packages/nltk/app/wordfreq_app.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Wordfreq Application
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Sumukh Ghodke <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
|
8 |
+
from matplotlib import pylab
|
9 |
+
|
10 |
+
from nltk.corpus import gutenberg
|
11 |
+
from nltk.text import Text
|
12 |
+
|
13 |
+
|
14 |
+
def plot_word_freq_dist(text):
|
15 |
+
fd = text.vocab()
|
16 |
+
|
17 |
+
samples = [item for item, _ in fd.most_common(50)]
|
18 |
+
values = [fd[sample] for sample in samples]
|
19 |
+
values = [sum(values[: i + 1]) * 100.0 / fd.N() for i in range(len(values))]
|
20 |
+
pylab.title(text.name)
|
21 |
+
pylab.xlabel("Samples")
|
22 |
+
pylab.ylabel("Cumulative Percentage")
|
23 |
+
pylab.plot(values)
|
24 |
+
pylab.xticks(range(len(samples)), [str(s) for s in samples], rotation=90)
|
25 |
+
pylab.show()
|
26 |
+
|
27 |
+
|
28 |
+
def app():
|
29 |
+
t1 = Text(gutenberg.words("melville-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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: WordNet Browser Application
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Jussi Salmela <[email protected]>
|
5 |
+
# Paul Bone <[email protected]>
|
6 |
+
# URL: <https://www.nltk.org/>
|
7 |
+
# For license information, see LICENSE.TXT
|
8 |
+
|
9 |
+
"""
|
10 |
+
A WordNet Browser application which launches the default browser
|
11 |
+
(if it is not already running) and opens a new tab with a connection
|
12 |
+
to http://localhost:port/ . It also starts an HTTP server on the
|
13 |
+
specified port and begins serving browser requests. The default
|
14 |
+
port is 8000. (For command-line help, run "python wordnet -h")
|
15 |
+
This application requires that the user's web browser supports
|
16 |
+
Javascript.
|
17 |
+
|
18 |
+
BrowServer is a server for browsing the NLTK Wordnet database It first
|
19 |
+
launches a browser client to be used for browsing and then starts
|
20 |
+
serving the requests of that and maybe other clients
|
21 |
+
|
22 |
+
Usage::
|
23 |
+
|
24 |
+
browserver.py -h
|
25 |
+
browserver.py [-s] [-p <port>]
|
26 |
+
|
27 |
+
Options::
|
28 |
+
|
29 |
+
-h or --help
|
30 |
+
Display this help message.
|
31 |
+
|
32 |
+
-l <file> or --log-file <file>
|
33 |
+
Logs messages to the given file, If this option is not specified
|
34 |
+
messages are silently dropped.
|
35 |
+
|
36 |
+
-p <port> or --port <port>
|
37 |
+
Run the web server on this TCP port, defaults to 8000.
|
38 |
+
|
39 |
+
-s or --server-mode
|
40 |
+
Do not start a web browser, and do not allow a user to
|
41 |
+
shutdown the server through the web interface.
|
42 |
+
"""
|
43 |
+
# TODO: throughout this package variable names and docstrings need
|
44 |
+
# modifying to be compliant with NLTK's coding standards. Tests also
|
45 |
+
# need to be develop to ensure this continues to work in the face of
|
46 |
+
# changes to other NLTK packages.
|
47 |
+
|
48 |
+
import base64
|
49 |
+
import copy
|
50 |
+
import getopt
|
51 |
+
import io
|
52 |
+
import os
|
53 |
+
import pickle
|
54 |
+
import sys
|
55 |
+
import threading
|
56 |
+
import time
|
57 |
+
import webbrowser
|
58 |
+
from collections import defaultdict
|
59 |
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
60 |
+
|
61 |
+
# Allow this program to run inside the NLTK source tree.
|
62 |
+
from sys import argv
|
63 |
+
from urllib.parse import unquote_plus
|
64 |
+
|
65 |
+
from nltk.corpus import wordnet as wn
|
66 |
+
from nltk.corpus.reader.wordnet import Lemma, Synset
|
67 |
+
|
68 |
+
firstClient = True
|
69 |
+
|
70 |
+
# True if we're not also running a web browser. The value f server_mode
|
71 |
+
# gets set by demo().
|
72 |
+
server_mode = None
|
73 |
+
|
74 |
+
# If set this is a file object for writing log messages.
|
75 |
+
logfile = None
|
76 |
+
|
77 |
+
|
78 |
+
class MyServerHandler(BaseHTTPRequestHandler):
|
79 |
+
def do_HEAD(self):
|
80 |
+
self.send_head()
|
81 |
+
|
82 |
+
def do_GET(self):
|
83 |
+
global firstClient
|
84 |
+
sp = self.path[1:]
|
85 |
+
if unquote_plus(sp) == "SHUTDOWN THE SERVER":
|
86 |
+
if server_mode:
|
87 |
+
page = "Server must be killed with SIGTERM."
|
88 |
+
type = "text/plain"
|
89 |
+
else:
|
90 |
+
print("Server shutting down!")
|
91 |
+
os._exit(0)
|
92 |
+
|
93 |
+
elif sp == "": # First request.
|
94 |
+
type = "text/html"
|
95 |
+
if not server_mode and firstClient:
|
96 |
+
firstClient = False
|
97 |
+
page = get_static_index_page(True)
|
98 |
+
else:
|
99 |
+
page = get_static_index_page(False)
|
100 |
+
word = "green"
|
101 |
+
|
102 |
+
elif sp.endswith(".html"): # Trying to fetch a HTML file TODO:
|
103 |
+
type = "text/html"
|
104 |
+
usp = unquote_plus(sp)
|
105 |
+
if usp == "NLTK Wordnet Browser Database Info.html":
|
106 |
+
word = "* Database Info *"
|
107 |
+
if os.path.isfile(usp):
|
108 |
+
with open(usp) as infile:
|
109 |
+
page = infile.read()
|
110 |
+
else:
|
111 |
+
page = (
|
112 |
+
(html_header % word) + "<p>The database info file:"
|
113 |
+
"<p><b>"
|
114 |
+
+ usp
|
115 |
+
+ "</b>"
|
116 |
+
+ "<p>was not found. Run this:"
|
117 |
+
+ "<p><b>python dbinfo_html.py</b>"
|
118 |
+
+ "<p>to produce it."
|
119 |
+
+ html_trailer
|
120 |
+
)
|
121 |
+
else:
|
122 |
+
# Handle files here.
|
123 |
+
word = sp
|
124 |
+
try:
|
125 |
+
page = get_static_page_by_path(usp)
|
126 |
+
except FileNotFoundError:
|
127 |
+
page = "Internal error: Path for static page '%s' is unknown" % usp
|
128 |
+
# Set type to plain to prevent XSS by printing the path as HTML
|
129 |
+
type = "text/plain"
|
130 |
+
elif sp.startswith("search"):
|
131 |
+
# This doesn't seem to work with MWEs.
|
132 |
+
type = "text/html"
|
133 |
+
parts = (sp.split("?")[1]).split("&")
|
134 |
+
word = [
|
135 |
+
p.split("=")[1].replace("+", " ")
|
136 |
+
for p in parts
|
137 |
+
if p.startswith("nextWord")
|
138 |
+
][0]
|
139 |
+
page, word = page_from_word(word)
|
140 |
+
elif sp.startswith("lookup_"):
|
141 |
+
# TODO add a variation of this that takes a non ecoded word or MWE.
|
142 |
+
type = "text/html"
|
143 |
+
sp = sp[len("lookup_") :]
|
144 |
+
page, word = page_from_href(sp)
|
145 |
+
elif sp == "start_page":
|
146 |
+
# if this is the first request we should display help
|
147 |
+
# information, and possibly set a default word.
|
148 |
+
type = "text/html"
|
149 |
+
page, word = page_from_word("wordnet")
|
150 |
+
else:
|
151 |
+
type = "text/plain"
|
152 |
+
page = "Could not parse request: '%s'" % sp
|
153 |
+
|
154 |
+
# Send result.
|
155 |
+
self.send_head(type)
|
156 |
+
self.wfile.write(page.encode("utf8"))
|
157 |
+
|
158 |
+
def send_head(self, type=None):
|
159 |
+
self.send_response(200)
|
160 |
+
self.send_header("Content-type", type)
|
161 |
+
self.end_headers()
|
162 |
+
|
163 |
+
def log_message(self, format, *args):
|
164 |
+
global logfile
|
165 |
+
|
166 |
+
if logfile:
|
167 |
+
logfile.write(
|
168 |
+
"%s - - [%s] %s\n"
|
169 |
+
% (self.address_string(), self.log_date_time_string(), format % args)
|
170 |
+
)
|
171 |
+
|
172 |
+
|
173 |
+
def get_unique_counter_from_url(sp):
|
174 |
+
"""
|
175 |
+
Extract the unique counter from the URL if it has one. Otherwise return
|
176 |
+
null.
|
177 |
+
"""
|
178 |
+
pos = sp.rfind("%23")
|
179 |
+
if pos != -1:
|
180 |
+
return int(sp[(pos + 3) :])
|
181 |
+
else:
|
182 |
+
return None
|
183 |
+
|
184 |
+
|
185 |
+
def wnb(port=8000, runBrowser=True, logfilename=None):
|
186 |
+
"""
|
187 |
+
Run NLTK Wordnet Browser Server.
|
188 |
+
|
189 |
+
:param port: The port number for the server to listen on, defaults to
|
190 |
+
8000
|
191 |
+
:type port: int
|
192 |
+
|
193 |
+
:param runBrowser: True to start a web browser and point it at the web
|
194 |
+
server.
|
195 |
+
:type runBrowser: bool
|
196 |
+
"""
|
197 |
+
# The webbrowser module is unpredictable, typically it blocks if it uses
|
198 |
+
# a console web browser, and doesn't block if it uses a GUI webbrowser,
|
199 |
+
# so we need to force it to have a clear correct behaviour.
|
200 |
+
#
|
201 |
+
# Normally the server should run for as long as the user wants. they
|
202 |
+
# should idealy be able to control this from the UI by closing the
|
203 |
+
# window or tab. Second best would be clicking a button to say
|
204 |
+
# 'Shutdown' that first shutsdown the server and closes the window or
|
205 |
+
# tab, or exits the text-mode browser. Both of these are unfreasable.
|
206 |
+
#
|
207 |
+
# The next best alternative is to start the server, have it close when
|
208 |
+
# it receives SIGTERM (default), and run the browser as well. The user
|
209 |
+
# may have to shutdown both programs.
|
210 |
+
#
|
211 |
+
# Since webbrowser may block, and the webserver will block, we must run
|
212 |
+
# them in separate threads.
|
213 |
+
#
|
214 |
+
global server_mode, logfile
|
215 |
+
server_mode = not runBrowser
|
216 |
+
|
217 |
+
# Setup logging.
|
218 |
+
if logfilename:
|
219 |
+
try:
|
220 |
+
logfile = open(logfilename, "a", 1) # 1 means 'line buffering'
|
221 |
+
except OSError as e:
|
222 |
+
sys.stderr.write("Couldn't open %s for writing: %s", logfilename, e)
|
223 |
+
sys.exit(1)
|
224 |
+
else:
|
225 |
+
logfile = None
|
226 |
+
|
227 |
+
# Compute URL and start web browser
|
228 |
+
url = "http://localhost:" + str(port)
|
229 |
+
|
230 |
+
server_ready = None
|
231 |
+
browser_thread = None
|
232 |
+
|
233 |
+
if runBrowser:
|
234 |
+
server_ready = threading.Event()
|
235 |
+
browser_thread = startBrowser(url, server_ready)
|
236 |
+
|
237 |
+
# Start the server.
|
238 |
+
server = HTTPServer(("", port), MyServerHandler)
|
239 |
+
if logfile:
|
240 |
+
logfile.write("NLTK Wordnet browser server running serving: %s\n" % url)
|
241 |
+
if runBrowser:
|
242 |
+
server_ready.set()
|
243 |
+
|
244 |
+
try:
|
245 |
+
server.serve_forever()
|
246 |
+
except KeyboardInterrupt:
|
247 |
+
pass
|
248 |
+
|
249 |
+
if runBrowser:
|
250 |
+
browser_thread.join()
|
251 |
+
|
252 |
+
if logfile:
|
253 |
+
logfile.close()
|
254 |
+
|
255 |
+
|
256 |
+
def startBrowser(url, server_ready):
|
257 |
+
def run():
|
258 |
+
server_ready.wait()
|
259 |
+
time.sleep(1) # Wait a little bit more, there's still the chance of
|
260 |
+
# a race condition.
|
261 |
+
webbrowser.open(url, new=2, autoraise=1)
|
262 |
+
|
263 |
+
t = threading.Thread(target=run)
|
264 |
+
t.start()
|
265 |
+
return t
|
266 |
+
|
267 |
+
|
268 |
+
#####################################################################
|
269 |
+
# Utilities
|
270 |
+
#####################################################################
|
271 |
+
|
272 |
+
|
273 |
+
"""
|
274 |
+
WordNet Browser Utilities.
|
275 |
+
|
276 |
+
This provides a backend to both wxbrowse and browserver.py.
|
277 |
+
"""
|
278 |
+
|
279 |
+
################################################################################
|
280 |
+
#
|
281 |
+
# Main logic for wordnet browser.
|
282 |
+
#
|
283 |
+
|
284 |
+
# This is wrapped inside a function since wn is only available if the
|
285 |
+
# WordNet corpus is installed.
|
286 |
+
def _pos_tuples():
|
287 |
+
return [
|
288 |
+
(wn.NOUN, "N", "noun"),
|
289 |
+
(wn.VERB, "V", "verb"),
|
290 |
+
(wn.ADJ, "J", "adj"),
|
291 |
+
(wn.ADV, "R", "adv"),
|
292 |
+
]
|
293 |
+
|
294 |
+
|
295 |
+
def _pos_match(pos_tuple):
|
296 |
+
"""
|
297 |
+
This function returns the complete pos tuple for the partial pos
|
298 |
+
tuple given to it. It attempts to match it against the first
|
299 |
+
non-null component of the given pos tuple.
|
300 |
+
"""
|
301 |
+
if pos_tuple[0] == "s":
|
302 |
+
pos_tuple = ("a", pos_tuple[1], pos_tuple[2])
|
303 |
+
for n, x in enumerate(pos_tuple):
|
304 |
+
if x is not None:
|
305 |
+
break
|
306 |
+
for pt in _pos_tuples():
|
307 |
+
if pt[n] == pos_tuple[n]:
|
308 |
+
return pt
|
309 |
+
return None
|
310 |
+
|
311 |
+
|
312 |
+
HYPONYM = 0
|
313 |
+
HYPERNYM = 1
|
314 |
+
CLASS_REGIONAL = 2
|
315 |
+
PART_HOLONYM = 3
|
316 |
+
PART_MERONYM = 4
|
317 |
+
ATTRIBUTE = 5
|
318 |
+
SUBSTANCE_HOLONYM = 6
|
319 |
+
SUBSTANCE_MERONYM = 7
|
320 |
+
MEMBER_HOLONYM = 8
|
321 |
+
MEMBER_MERONYM = 9
|
322 |
+
VERB_GROUP = 10
|
323 |
+
INSTANCE_HYPONYM = 12
|
324 |
+
INSTANCE_HYPERNYM = 13
|
325 |
+
CAUSE = 14
|
326 |
+
ALSO_SEE = 15
|
327 |
+
SIMILAR = 16
|
328 |
+
ENTAILMENT = 17
|
329 |
+
ANTONYM = 18
|
330 |
+
FRAMES = 19
|
331 |
+
PERTAINYM = 20
|
332 |
+
|
333 |
+
CLASS_CATEGORY = 21
|
334 |
+
CLASS_USAGE = 22
|
335 |
+
CLASS_REGIONAL = 23
|
336 |
+
CLASS_USAGE = 24
|
337 |
+
CLASS_CATEGORY = 11
|
338 |
+
|
339 |
+
DERIVATIONALLY_RELATED_FORM = 25
|
340 |
+
|
341 |
+
INDIRECT_HYPERNYMS = 26
|
342 |
+
|
343 |
+
|
344 |
+
def lemma_property(word, synset, func):
|
345 |
+
def flattern(l):
|
346 |
+
if l == []:
|
347 |
+
return []
|
348 |
+
else:
|
349 |
+
return l[0] + flattern(l[1:])
|
350 |
+
|
351 |
+
return flattern([func(l) for l in synset.lemmas() if l.name == word])
|
352 |
+
|
353 |
+
|
354 |
+
def rebuild_tree(orig_tree):
|
355 |
+
node = orig_tree[0]
|
356 |
+
children = orig_tree[1:]
|
357 |
+
return (node, [rebuild_tree(t) for t in children])
|
358 |
+
|
359 |
+
|
360 |
+
def get_relations_data(word, synset):
|
361 |
+
"""
|
362 |
+
Get synset relations data for a synset. Note that this doesn't
|
363 |
+
yet support things such as full hyponym vs direct hyponym.
|
364 |
+
"""
|
365 |
+
if synset.pos() == wn.NOUN:
|
366 |
+
return (
|
367 |
+
(HYPONYM, "Hyponyms", synset.hyponyms()),
|
368 |
+
(INSTANCE_HYPONYM, "Instance hyponyms", synset.instance_hyponyms()),
|
369 |
+
(HYPERNYM, "Direct hypernyms", synset.hypernyms()),
|
370 |
+
(
|
371 |
+
INDIRECT_HYPERNYMS,
|
372 |
+
"Indirect hypernyms",
|
373 |
+
rebuild_tree(synset.tree(lambda x: x.hypernyms()))[1],
|
374 |
+
),
|
375 |
+
# hypernyms', 'Sister terms',
|
376 |
+
(INSTANCE_HYPERNYM, "Instance hypernyms", synset.instance_hypernyms()),
|
377 |
+
# (CLASS_REGIONAL, ['domain term region'], ),
|
378 |
+
(PART_HOLONYM, "Part holonyms", synset.part_holonyms()),
|
379 |
+
(PART_MERONYM, "Part meronyms", synset.part_meronyms()),
|
380 |
+
(SUBSTANCE_HOLONYM, "Substance holonyms", synset.substance_holonyms()),
|
381 |
+
(SUBSTANCE_MERONYM, "Substance meronyms", synset.substance_meronyms()),
|
382 |
+
(MEMBER_HOLONYM, "Member holonyms", synset.member_holonyms()),
|
383 |
+
(MEMBER_MERONYM, "Member meronyms", synset.member_meronyms()),
|
384 |
+
(ATTRIBUTE, "Attributes", synset.attributes()),
|
385 |
+
(ANTONYM, "Antonyms", lemma_property(word, synset, lambda l: l.antonyms())),
|
386 |
+
(
|
387 |
+
DERIVATIONALLY_RELATED_FORM,
|
388 |
+
"Derivationally related form",
|
389 |
+
lemma_property(
|
390 |
+
word, synset, lambda l: l.derivationally_related_forms()
|
391 |
+
),
|
392 |
+
),
|
393 |
+
)
|
394 |
+
elif synset.pos() == wn.VERB:
|
395 |
+
return (
|
396 |
+
(ANTONYM, "Antonym", lemma_property(word, synset, lambda l: l.antonyms())),
|
397 |
+
(HYPONYM, "Hyponym", synset.hyponyms()),
|
398 |
+
(HYPERNYM, "Direct hypernyms", synset.hypernyms()),
|
399 |
+
(
|
400 |
+
INDIRECT_HYPERNYMS,
|
401 |
+
"Indirect hypernyms",
|
402 |
+
rebuild_tree(synset.tree(lambda x: x.hypernyms()))[1],
|
403 |
+
),
|
404 |
+
(ENTAILMENT, "Entailments", synset.entailments()),
|
405 |
+
(CAUSE, "Causes", synset.causes()),
|
406 |
+
(ALSO_SEE, "Also see", synset.also_sees()),
|
407 |
+
(VERB_GROUP, "Verb Groups", synset.verb_groups()),
|
408 |
+
(
|
409 |
+
DERIVATIONALLY_RELATED_FORM,
|
410 |
+
"Derivationally related form",
|
411 |
+
lemma_property(
|
412 |
+
word, synset, lambda l: l.derivationally_related_forms()
|
413 |
+
),
|
414 |
+
),
|
415 |
+
)
|
416 |
+
elif synset.pos() == wn.ADJ or synset.pos == wn.ADJ_SAT:
|
417 |
+
return (
|
418 |
+
(ANTONYM, "Antonym", lemma_property(word, synset, lambda l: l.antonyms())),
|
419 |
+
(SIMILAR, "Similar to", synset.similar_tos()),
|
420 |
+
# Participle of verb - not supported by corpus
|
421 |
+
(
|
422 |
+
PERTAINYM,
|
423 |
+
"Pertainyms",
|
424 |
+
lemma_property(word, synset, lambda l: l.pertainyms()),
|
425 |
+
),
|
426 |
+
(ATTRIBUTE, "Attributes", synset.attributes()),
|
427 |
+
(ALSO_SEE, "Also see", synset.also_sees()),
|
428 |
+
)
|
429 |
+
elif synset.pos() == wn.ADV:
|
430 |
+
# This is weird. adverbs such as 'quick' and 'fast' don't seem
|
431 |
+
# to have antonyms returned by the corpus.a
|
432 |
+
return (
|
433 |
+
(ANTONYM, "Antonym", lemma_property(word, synset, lambda l: l.antonyms())),
|
434 |
+
)
|
435 |
+
# Derived from adjective - not supported by corpus
|
436 |
+
else:
|
437 |
+
raise TypeError("Unhandles synset POS type: " + str(synset.pos()))
|
438 |
+
|
439 |
+
|
440 |
+
html_header = """
|
441 |
+
<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01//EN'
|
442 |
+
'http://www.w3.org/TR/html4/strict.dtd'>
|
443 |
+
<html>
|
444 |
+
<head>
|
445 |
+
<meta name='generator' content=
|
446 |
+
'HTML Tidy for Windows (vers 14 February 2006), see www.w3.org'>
|
447 |
+
<meta http-equiv='Content-Type' content=
|
448 |
+
'text/html; charset=us-ascii'>
|
449 |
+
<title>NLTK Wordnet Browser display of: %s</title></head>
|
450 |
+
<body bgcolor='#F5F5F5' text='#000000'>
|
451 |
+
"""
|
452 |
+
html_trailer = """
|
453 |
+
</body>
|
454 |
+
</html>
|
455 |
+
"""
|
456 |
+
|
457 |
+
explanation = """
|
458 |
+
<h3>Search Help</h3>
|
459 |
+
<ul><li>The display below the line is an example of the output the browser
|
460 |
+
shows you when you enter a search word. The search word was <b>green</b>.</li>
|
461 |
+
<li>The search result shows for different parts of speech the <b>synsets</b>
|
462 |
+
i.e. different meanings for the word.</li>
|
463 |
+
<li>All underlined texts are hypertext links. There are two types of links:
|
464 |
+
word links and others. Clicking a word link carries out a search for the word
|
465 |
+
in the Wordnet database.</li>
|
466 |
+
<li>Clicking a link of the other type opens a display section of data attached
|
467 |
+
to that link. Clicking that link a second time closes the section again.</li>
|
468 |
+
<li>Clicking <u>S:</u> opens a section showing the relations for that synset.
|
469 |
+
</li>
|
470 |
+
<li>Clicking on a relation name opens a section that displays the associated
|
471 |
+
synsets.</li>
|
472 |
+
<li>Type a search word in the <b>Word</b> field and start the search by the
|
473 |
+
<b>Enter/Return</b> key or click the <b>Search</b> button.</li>
|
474 |
+
</ul>
|
475 |
+
<hr width='100%'>
|
476 |
+
"""
|
477 |
+
|
478 |
+
# HTML oriented functions
|
479 |
+
|
480 |
+
|
481 |
+
def _bold(txt):
|
482 |
+
return "<b>%s</b>" % txt
|
483 |
+
|
484 |
+
|
485 |
+
def _center(txt):
|
486 |
+
return "<center>%s</center>" % txt
|
487 |
+
|
488 |
+
|
489 |
+
def _hlev(n, txt):
|
490 |
+
return "<h%d>%s</h%d>" % (n, txt, n)
|
491 |
+
|
492 |
+
|
493 |
+
def _italic(txt):
|
494 |
+
return "<i>%s</i>" % txt
|
495 |
+
|
496 |
+
|
497 |
+
def _li(txt):
|
498 |
+
return "<li>%s</li>" % txt
|
499 |
+
|
500 |
+
|
501 |
+
def pg(word, body):
|
502 |
+
"""
|
503 |
+
Return a HTML page of NLTK Browser format constructed from the
|
504 |
+
word and body
|
505 |
+
|
506 |
+
:param word: The word that the body corresponds to
|
507 |
+
:type word: str
|
508 |
+
:param body: The HTML body corresponding to the word
|
509 |
+
:type body: str
|
510 |
+
:return: a HTML page for the word-body combination
|
511 |
+
:rtype: str
|
512 |
+
"""
|
513 |
+
return (html_header % word) + body + html_trailer
|
514 |
+
|
515 |
+
|
516 |
+
def _ul(txt):
|
517 |
+
return "<ul>" + txt + "</ul>"
|
518 |
+
|
519 |
+
|
520 |
+
def _abbc(txt):
|
521 |
+
"""
|
522 |
+
abbc = asterisks, breaks, bold, center
|
523 |
+
"""
|
524 |
+
return _center(_bold("<br>" * 10 + "*" * 10 + " " + txt + " " + "*" * 10))
|
525 |
+
|
526 |
+
|
527 |
+
full_hyponym_cont_text = _ul(_li(_italic("(has full hyponym continuation)"))) + "\n"
|
528 |
+
|
529 |
+
|
530 |
+
def _get_synset(synset_key):
|
531 |
+
"""
|
532 |
+
The synset key is the unique name of the synset, this can be
|
533 |
+
retrieved via synset.name()
|
534 |
+
"""
|
535 |
+
return wn.synset(synset_key)
|
536 |
+
|
537 |
+
|
538 |
+
def _collect_one_synset(word, synset, synset_relations):
|
539 |
+
"""
|
540 |
+
Returns the HTML string for one synset or word
|
541 |
+
|
542 |
+
:param word: the current word
|
543 |
+
:type word: str
|
544 |
+
:param synset: a synset
|
545 |
+
:type synset: synset
|
546 |
+
:param synset_relations: information about which synset relations
|
547 |
+
to display.
|
548 |
+
:type synset_relations: dict(synset_key, set(relation_id))
|
549 |
+
:return: The HTML string built for this synset
|
550 |
+
:rtype: str
|
551 |
+
"""
|
552 |
+
if isinstance(synset, tuple): # It's a word
|
553 |
+
raise NotImplementedError("word not supported by _collect_one_synset")
|
554 |
+
|
555 |
+
typ = "S"
|
556 |
+
pos_tuple = _pos_match((synset.pos(), None, None))
|
557 |
+
assert pos_tuple is not None, "pos_tuple is null: synset.pos(): %s" % synset.pos()
|
558 |
+
descr = pos_tuple[2]
|
559 |
+
ref = copy.deepcopy(Reference(word, synset_relations))
|
560 |
+
ref.toggle_synset(synset)
|
561 |
+
synset_label = typ + ";"
|
562 |
+
if synset.name() in synset_relations:
|
563 |
+
synset_label = _bold(synset_label)
|
564 |
+
s = f"<li>{make_lookup_link(ref, synset_label)} ({descr}) "
|
565 |
+
|
566 |
+
def format_lemma(w):
|
567 |
+
w = w.replace("_", " ")
|
568 |
+
if w.lower() == word:
|
569 |
+
return _bold(w)
|
570 |
+
else:
|
571 |
+
ref = Reference(w)
|
572 |
+
return make_lookup_link(ref, w)
|
573 |
+
|
574 |
+
s += ", ".join(format_lemma(l.name()) for l in synset.lemmas())
|
575 |
+
|
576 |
+
gl = " ({}) <i>{}</i> ".format(
|
577 |
+
synset.definition(),
|
578 |
+
"; ".join('"%s"' % e for e in synset.examples()),
|
579 |
+
)
|
580 |
+
return s + gl + _synset_relations(word, synset, synset_relations) + "</li>\n"
|
581 |
+
|
582 |
+
|
583 |
+
def _collect_all_synsets(word, pos, synset_relations=dict()):
|
584 |
+
"""
|
585 |
+
Return a HTML unordered list of synsets for the given word and
|
586 |
+
part of speech.
|
587 |
+
"""
|
588 |
+
return "<ul>%s\n</ul>\n" % "".join(
|
589 |
+
_collect_one_synset(word, synset, synset_relations)
|
590 |
+
for synset in wn.synsets(word, pos)
|
591 |
+
)
|
592 |
+
|
593 |
+
|
594 |
+
def _synset_relations(word, synset, synset_relations):
|
595 |
+
"""
|
596 |
+
Builds the HTML string for the relations of a synset
|
597 |
+
|
598 |
+
:param word: The current word
|
599 |
+
:type word: str
|
600 |
+
:param synset: The synset for which we're building the relations.
|
601 |
+
:type synset: Synset
|
602 |
+
:param synset_relations: synset keys and relation types for which to display relations.
|
603 |
+
:type synset_relations: dict(synset_key, set(relation_type))
|
604 |
+
:return: The HTML for a synset's relations
|
605 |
+
:rtype: str
|
606 |
+
"""
|
607 |
+
|
608 |
+
if not synset.name() in synset_relations:
|
609 |
+
return ""
|
610 |
+
ref = Reference(word, synset_relations)
|
611 |
+
|
612 |
+
def relation_html(r):
|
613 |
+
if isinstance(r, Synset):
|
614 |
+
return make_lookup_link(Reference(r.lemma_names()[0]), r.lemma_names()[0])
|
615 |
+
elif isinstance(r, Lemma):
|
616 |
+
return relation_html(r.synset())
|
617 |
+
elif isinstance(r, tuple):
|
618 |
+
# It's probably a tuple containing a Synset and a list of
|
619 |
+
# similar tuples. This forms a tree of synsets.
|
620 |
+
return "{}\n<ul>{}</ul>\n".format(
|
621 |
+
relation_html(r[0]),
|
622 |
+
"".join("<li>%s</li>\n" % relation_html(sr) for sr in r[1]),
|
623 |
+
)
|
624 |
+
else:
|
625 |
+
raise TypeError(
|
626 |
+
"r must be a synset, lemma or list, it was: type(r) = %s, r = %s"
|
627 |
+
% (type(r), r)
|
628 |
+
)
|
629 |
+
|
630 |
+
def make_synset_html(db_name, disp_name, rels):
|
631 |
+
synset_html = "<i>%s</i>\n" % make_lookup_link(
|
632 |
+
copy.deepcopy(ref).toggle_synset_relation(synset, db_name),
|
633 |
+
disp_name,
|
634 |
+
)
|
635 |
+
|
636 |
+
if db_name in ref.synset_relations[synset.name()]:
|
637 |
+
synset_html += "<ul>%s</ul>\n" % "".join(
|
638 |
+
"<li>%s</li>\n" % relation_html(r) for r in rels
|
639 |
+
)
|
640 |
+
|
641 |
+
return synset_html
|
642 |
+
|
643 |
+
html = (
|
644 |
+
"<ul>"
|
645 |
+
+ "\n".join(
|
646 |
+
"<li>%s</li>" % make_synset_html(*rel_data)
|
647 |
+
for rel_data in get_relations_data(word, synset)
|
648 |
+
if rel_data[2] != []
|
649 |
+
)
|
650 |
+
+ "</ul>"
|
651 |
+
)
|
652 |
+
|
653 |
+
return html
|
654 |
+
|
655 |
+
|
656 |
+
class RestrictedUnpickler(pickle.Unpickler):
|
657 |
+
"""
|
658 |
+
Unpickler that prevents any class or function from being used during loading.
|
659 |
+
"""
|
660 |
+
|
661 |
+
def find_class(self, module, name):
|
662 |
+
# Forbid every function
|
663 |
+
raise pickle.UnpicklingError(f"global '{module}.{name}' is forbidden")
|
664 |
+
|
665 |
+
|
666 |
+
class Reference:
|
667 |
+
"""
|
668 |
+
A reference to a page that may be generated by page_word
|
669 |
+
"""
|
670 |
+
|
671 |
+
def __init__(self, word, synset_relations=dict()):
|
672 |
+
"""
|
673 |
+
Build a reference to a new page.
|
674 |
+
|
675 |
+
word is the word or words (separated by commas) for which to
|
676 |
+
search for synsets of
|
677 |
+
|
678 |
+
synset_relations is a dictionary of synset keys to sets of
|
679 |
+
synset relation identifaiers to unfold a list of synset
|
680 |
+
relations for.
|
681 |
+
"""
|
682 |
+
self.word = word
|
683 |
+
self.synset_relations = synset_relations
|
684 |
+
|
685 |
+
def encode(self):
|
686 |
+
"""
|
687 |
+
Encode this reference into a string to be used in a URL.
|
688 |
+
"""
|
689 |
+
# This uses a tuple rather than an object since the python
|
690 |
+
# pickle representation is much smaller and there is no need
|
691 |
+
# to represent the complete object.
|
692 |
+
string = pickle.dumps((self.word, self.synset_relations), -1)
|
693 |
+
return base64.urlsafe_b64encode(string).decode()
|
694 |
+
|
695 |
+
@staticmethod
|
696 |
+
def decode(string):
|
697 |
+
"""
|
698 |
+
Decode a reference encoded with Reference.encode
|
699 |
+
"""
|
700 |
+
string = base64.urlsafe_b64decode(string.encode())
|
701 |
+
word, synset_relations = RestrictedUnpickler(io.BytesIO(string)).load()
|
702 |
+
return Reference(word, synset_relations)
|
703 |
+
|
704 |
+
def toggle_synset_relation(self, synset, relation):
|
705 |
+
"""
|
706 |
+
Toggle the display of the relations for the given synset and
|
707 |
+
relation type.
|
708 |
+
|
709 |
+
This function will throw a KeyError if the synset is currently
|
710 |
+
not being displayed.
|
711 |
+
"""
|
712 |
+
if relation in self.synset_relations[synset.name()]:
|
713 |
+
self.synset_relations[synset.name()].remove(relation)
|
714 |
+
else:
|
715 |
+
self.synset_relations[synset.name()].add(relation)
|
716 |
+
|
717 |
+
return self
|
718 |
+
|
719 |
+
def toggle_synset(self, synset):
|
720 |
+
"""
|
721 |
+
Toggle displaying of the relation types for the given synset
|
722 |
+
"""
|
723 |
+
if synset.name() in self.synset_relations:
|
724 |
+
del self.synset_relations[synset.name()]
|
725 |
+
else:
|
726 |
+
self.synset_relations[synset.name()] = set()
|
727 |
+
|
728 |
+
return self
|
729 |
+
|
730 |
+
|
731 |
+
def make_lookup_link(ref, label):
|
732 |
+
return f'<a href="lookup_{ref.encode()}">{label}</a>'
|
733 |
+
|
734 |
+
|
735 |
+
def page_from_word(word):
|
736 |
+
"""
|
737 |
+
Return a HTML page for the given word.
|
738 |
+
|
739 |
+
:type word: str
|
740 |
+
:param word: The currently active word
|
741 |
+
:return: A tuple (page,word), where page is the new current HTML page
|
742 |
+
to be sent to the browser and
|
743 |
+
word is the new current word
|
744 |
+
:rtype: A tuple (str,str)
|
745 |
+
"""
|
746 |
+
return page_from_reference(Reference(word))
|
747 |
+
|
748 |
+
|
749 |
+
def page_from_href(href):
|
750 |
+
"""
|
751 |
+
Returns a tuple of the HTML page built and the new current word
|
752 |
+
|
753 |
+
:param href: The hypertext reference to be solved
|
754 |
+
:type href: str
|
755 |
+
:return: A tuple (page,word), where page is the new current HTML page
|
756 |
+
to be sent to the browser and
|
757 |
+
word is the new current word
|
758 |
+
:rtype: A tuple (str,str)
|
759 |
+
"""
|
760 |
+
return page_from_reference(Reference.decode(href))
|
761 |
+
|
762 |
+
|
763 |
+
def page_from_reference(href):
|
764 |
+
"""
|
765 |
+
Returns a tuple of the HTML page built and the new current word
|
766 |
+
|
767 |
+
:param href: The hypertext reference to be solved
|
768 |
+
:type href: str
|
769 |
+
:return: A tuple (page,word), where page is the new current HTML page
|
770 |
+
to be sent to the browser and
|
771 |
+
word is the new current word
|
772 |
+
:rtype: A tuple (str,str)
|
773 |
+
"""
|
774 |
+
word = href.word
|
775 |
+
pos_forms = defaultdict(list)
|
776 |
+
words = word.split(",")
|
777 |
+
words = [w for w in [w.strip().lower().replace(" ", "_") for w in words] if w != ""]
|
778 |
+
if len(words) == 0:
|
779 |
+
# No words were found.
|
780 |
+
return "", "Please specify a word to search for."
|
781 |
+
|
782 |
+
# This looks up multiple words at once. This is probably not
|
783 |
+
# necessary and may lead to problems.
|
784 |
+
for w in words:
|
785 |
+
for pos in [wn.NOUN, wn.VERB, wn.ADJ, wn.ADV]:
|
786 |
+
form = wn.morphy(w, pos)
|
787 |
+
if form and form not in pos_forms[pos]:
|
788 |
+
pos_forms[pos].append(form)
|
789 |
+
body = ""
|
790 |
+
for pos, pos_str, name in _pos_tuples():
|
791 |
+
if pos in pos_forms:
|
792 |
+
body += _hlev(3, name) + "\n"
|
793 |
+
for w in pos_forms[pos]:
|
794 |
+
# Not all words of exc files are in the database, skip
|
795 |
+
# to the next word if a KeyError is raised.
|
796 |
+
try:
|
797 |
+
body += _collect_all_synsets(w, pos, href.synset_relations)
|
798 |
+
except KeyError:
|
799 |
+
pass
|
800 |
+
if not body:
|
801 |
+
body = "The word or words '%s' were not found in the dictionary." % word
|
802 |
+
return body, word
|
803 |
+
|
804 |
+
|
805 |
+
#####################################################################
|
806 |
+
# Static pages
|
807 |
+
#####################################################################
|
808 |
+
|
809 |
+
|
810 |
+
def get_static_page_by_path(path):
|
811 |
+
"""
|
812 |
+
Return a static HTML page from the path given.
|
813 |
+
"""
|
814 |
+
if path == "index_2.html":
|
815 |
+
return get_static_index_page(False)
|
816 |
+
elif path == "index.html":
|
817 |
+
return get_static_index_page(True)
|
818 |
+
elif path == "NLTK Wordnet Browser Database Info.html":
|
819 |
+
return "Display of Wordnet Database Statistics is not supported"
|
820 |
+
elif path == "upper_2.html":
|
821 |
+
return get_static_upper_page(False)
|
822 |
+
elif path == "upper.html":
|
823 |
+
return get_static_upper_page(True)
|
824 |
+
elif path == "web_help.html":
|
825 |
+
return get_static_web_help_page()
|
826 |
+
elif path == "wx_help.html":
|
827 |
+
return get_static_wx_help_page()
|
828 |
+
raise FileNotFoundError()
|
829 |
+
|
830 |
+
|
831 |
+
def get_static_web_help_page():
|
832 |
+
"""
|
833 |
+
Return the static web help page.
|
834 |
+
"""
|
835 |
+
return """
|
836 |
+
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
|
837 |
+
<html>
|
838 |
+
<!-- Natural Language Toolkit: Wordnet Interface: Graphical Wordnet Browser
|
839 |
+
Copyright (C) 2001-2023 NLTK Project
|
840 |
+
Author: Jussi Salmela <[email protected]>
|
841 |
+
URL: <https://www.nltk.org/>
|
842 |
+
For license information, see LICENSE.TXT -->
|
843 |
+
<head>
|
844 |
+
<meta http-equiv='Content-Type' content='text/html; charset=us-ascii'>
|
845 |
+
<title>NLTK Wordnet Browser display of: * Help *</title>
|
846 |
+
</head>
|
847 |
+
<body bgcolor='#F5F5F5' text='#000000'>
|
848 |
+
<h2>NLTK Wordnet Browser Help</h2>
|
849 |
+
<p>The NLTK Wordnet Browser is a tool to use in browsing the Wordnet database. It tries to behave like the Wordnet project's web browser but the difference is that the NLTK Wordnet Browser uses a local Wordnet database.
|
850 |
+
<p><b>You are using the Javascript client part of the NLTK Wordnet BrowseServer.</b> We assume your browser is in tab sheets enabled mode.</p>
|
851 |
+
<p>For background information on Wordnet, see the Wordnet project home page: <a href="https://wordnet.princeton.edu/"><b> https://wordnet.princeton.edu/</b></a>. For more information on the NLTK project, see the project home:
|
852 |
+
<a href="https://www.nltk.org/"><b>https://www.nltk.org/</b></a>. To get an idea of what the Wordnet version used by this browser includes choose <b>Show Database Info</b> from the <b>View</b> submenu.</p>
|
853 |
+
<h3>Word search</h3>
|
854 |
+
<p>The word to be searched is typed into the <b>New Word</b> field and the search started with Enter or by clicking the <b>Search</b> button. There is no uppercase/lowercase distinction: the search word is transformed to lowercase before the search.</p>
|
855 |
+
<p>In addition, the word does not have to be in base form. The browser tries to find the possible base form(s) by making certain morphological substitutions. Typing <b>fLIeS</b> as an obscure example gives one <a href="MfLIeS">this</a>. Click the previous link to see what this kind of search looks like and then come back to this page by using the <b>Alt+LeftArrow</b> key combination.</p>
|
856 |
+
<p>The result of a search is a display of one or more
|
857 |
+
<b>synsets</b> for every part of speech in which a form of the
|
858 |
+
search word was found to occur. A synset is a set of words
|
859 |
+
having the same sense or meaning. Each word in a synset that is
|
860 |
+
underlined is a hyperlink which can be clicked to trigger an
|
861 |
+
automatic search for that word.</p>
|
862 |
+
<p>Every synset has a hyperlink <b>S:</b> at the start of its
|
863 |
+
display line. Clicking that symbol shows you the name of every
|
864 |
+
<b>relation</b> that this synset is part of. Every relation name is a hyperlink that opens up a display for that relation. Clicking it another time closes the display again. Clicking another relation name on a line that has an opened relation closes the open relation and opens the clicked relation.</p>
|
865 |
+
<p>It is also possible to give two or more words or collocations to be searched at the same time separating them with a comma like this <a href="Mcheer up,clear up">cheer up,clear up</a>, for example. Click the previous link to see what this kind of search looks like and then come back to this page by using the <b>Alt+LeftArrow</b> key combination. As you could see the search result includes the synsets found in the same order than the forms were given in the search field.</p>
|
866 |
+
<p>
|
867 |
+
There are also word level (lexical) relations recorded in the Wordnet database. Opening this kind of relation displays lines with a hyperlink <b>W:</b> at their beginning. Clicking this link shows more info on the word in question.</p>
|
868 |
+
<h3>The Buttons</h3>
|
869 |
+
<p>The <b>Search</b> and <b>Help</b> buttons need no more explanation. </p>
|
870 |
+
<p>The <b>Show Database Info</b> button shows a collection of Wordnet database statistics.</p>
|
871 |
+
<p>The <b>Shutdown the Server</b> button is shown for the first client of the BrowServer program i.e. for the client that is automatically launched when the BrowServer is started but not for the succeeding clients in order to protect the server from accidental shutdowns.
|
872 |
+
</p></body>
|
873 |
+
</html>
|
874 |
+
"""
|
875 |
+
|
876 |
+
|
877 |
+
def get_static_welcome_message():
|
878 |
+
"""
|
879 |
+
Get the static welcome page.
|
880 |
+
"""
|
881 |
+
return """
|
882 |
+
<h3>Search Help</h3>
|
883 |
+
<ul><li>The display below the line is an example of the output the browser
|
884 |
+
shows you when you enter a search word. The search word was <b>green</b>.</li>
|
885 |
+
<li>The search result shows for different parts of speech the <b>synsets</b>
|
886 |
+
i.e. different meanings for the word.</li>
|
887 |
+
<li>All underlined texts are hypertext links. There are two types of links:
|
888 |
+
word links and others. Clicking a word link carries out a search for the word
|
889 |
+
in the Wordnet database.</li>
|
890 |
+
<li>Clicking a link of the other type opens a display section of data attached
|
891 |
+
to that link. Clicking that link a second time closes the section again.</li>
|
892 |
+
<li>Clicking <u>S:</u> opens a section showing the relations for that synset.</li>
|
893 |
+
<li>Clicking on a relation name opens a section that displays the associated
|
894 |
+
synsets.</li>
|
895 |
+
<li>Type a search word in the <b>Next Word</b> field and start the search by the
|
896 |
+
<b>Enter/Return</b> key or click the <b>Search</b> button.</li>
|
897 |
+
</ul>
|
898 |
+
"""
|
899 |
+
|
900 |
+
|
901 |
+
def get_static_index_page(with_shutdown):
|
902 |
+
"""
|
903 |
+
Get the static index page.
|
904 |
+
"""
|
905 |
+
template = """
|
906 |
+
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
|
907 |
+
<HTML>
|
908 |
+
<!-- Natural Language Toolkit: Wordnet Interface: Graphical Wordnet Browser
|
909 |
+
Copyright (C) 2001-2023 NLTK Project
|
910 |
+
Author: Jussi Salmela <[email protected]>
|
911 |
+
URL: <https://www.nltk.org/>
|
912 |
+
For license information, see LICENSE.TXT -->
|
913 |
+
<HEAD>
|
914 |
+
<TITLE>NLTK Wordnet Browser</TITLE>
|
915 |
+
</HEAD>
|
916 |
+
|
917 |
+
<frameset rows="7%%,93%%">
|
918 |
+
<frame src="%s" name="header">
|
919 |
+
<frame src="start_page" name="body">
|
920 |
+
</frameset>
|
921 |
+
</HTML>
|
922 |
+
"""
|
923 |
+
if with_shutdown:
|
924 |
+
upper_link = "upper.html"
|
925 |
+
else:
|
926 |
+
upper_link = "upper_2.html"
|
927 |
+
|
928 |
+
return template % upper_link
|
929 |
+
|
930 |
+
|
931 |
+
def get_static_upper_page(with_shutdown):
|
932 |
+
"""
|
933 |
+
Return the upper frame page,
|
934 |
+
|
935 |
+
If with_shutdown is True then a 'shutdown' button is also provided
|
936 |
+
to shutdown the server.
|
937 |
+
"""
|
938 |
+
template = """
|
939 |
+
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
|
940 |
+
<html>
|
941 |
+
<!-- Natural Language Toolkit: Wordnet Interface: Graphical Wordnet Browser
|
942 |
+
Copyright (C) 2001-2023 NLTK Project
|
943 |
+
Author: Jussi Salmela <[email protected]>
|
944 |
+
URL: <https://www.nltk.org/>
|
945 |
+
For license information, see LICENSE.TXT -->
|
946 |
+
<head>
|
947 |
+
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
|
948 |
+
<title>Untitled Document</title>
|
949 |
+
</head>
|
950 |
+
<body>
|
951 |
+
<form method="GET" action="search" target="body">
|
952 |
+
Current Word: <input type="text" id="currentWord" size="10" disabled>
|
953 |
+
Next Word: <input type="text" id="nextWord" name="nextWord" size="10">
|
954 |
+
<input name="searchButton" type="submit" value="Search">
|
955 |
+
</form>
|
956 |
+
<a target="body" href="web_help.html">Help</a>
|
957 |
+
%s
|
958 |
+
|
959 |
+
</body>
|
960 |
+
</html>
|
961 |
+
"""
|
962 |
+
if with_shutdown:
|
963 |
+
shutdown_link = '<a href="SHUTDOWN THE SERVER">Shutdown</a>'
|
964 |
+
else:
|
965 |
+
shutdown_link = ""
|
966 |
+
|
967 |
+
return template % shutdown_link
|
968 |
+
|
969 |
+
|
970 |
+
def usage():
|
971 |
+
"""
|
972 |
+
Display the command line help message.
|
973 |
+
"""
|
974 |
+
print(__doc__)
|
975 |
+
|
976 |
+
|
977 |
+
def app():
|
978 |
+
# Parse and interpret options.
|
979 |
+
(opts, _) = getopt.getopt(
|
980 |
+
argv[1:], "l:p:sh", ["logfile=", "port=", "server-mode", "help"]
|
981 |
+
)
|
982 |
+
port = 8000
|
983 |
+
server_mode = False
|
984 |
+
help_mode = False
|
985 |
+
logfilename = None
|
986 |
+
for (opt, value) in opts:
|
987 |
+
if (opt == "-l") or (opt == "--logfile"):
|
988 |
+
logfilename = str(value)
|
989 |
+
elif (opt == "-p") or (opt == "--port"):
|
990 |
+
port = int(value)
|
991 |
+
elif (opt == "-s") or (opt == "--server-mode"):
|
992 |
+
server_mode = True
|
993 |
+
elif (opt == "-h") or (opt == "--help"):
|
994 |
+
help_mode = True
|
995 |
+
|
996 |
+
if help_mode:
|
997 |
+
usage()
|
998 |
+
else:
|
999 |
+
wnb(port, not server_mode, logfilename)
|
1000 |
+
|
1001 |
+
|
1002 |
+
if __name__ == "__main__":
|
1003 |
+
app()
|
1004 |
+
|
1005 |
+
__all__ = ["app"]
|
env-llmeval/lib/python3.10/site-packages/nltk/classify/api.py
ADDED
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Classifier Interface
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Edward Loper <[email protected]>
|
5 |
+
# Steven Bird <[email protected]> (minor additions)
|
6 |
+
# URL: <https://www.nltk.org/>
|
7 |
+
# For license information, see LICENSE.TXT
|
8 |
+
|
9 |
+
"""
|
10 |
+
Interfaces for labeling tokens with category labels (or "class labels").
|
11 |
+
|
12 |
+
``ClassifierI`` is a standard interface for "single-category
|
13 |
+
classification", in which the set of categories is known, the number
|
14 |
+
of categories is finite, and each text belongs to exactly one
|
15 |
+
category.
|
16 |
+
|
17 |
+
``MultiClassifierI`` is a standard interface for "multi-category
|
18 |
+
classification", which is like single-category classification except
|
19 |
+
that each text belongs to zero or more categories.
|
20 |
+
"""
|
21 |
+
from nltk.internals import overridden
|
22 |
+
|
23 |
+
##//////////////////////////////////////////////////////
|
24 |
+
# { Classification Interfaces
|
25 |
+
##//////////////////////////////////////////////////////
|
26 |
+
|
27 |
+
|
28 |
+
class ClassifierI:
|
29 |
+
"""
|
30 |
+
A processing interface for labeling tokens with a single category
|
31 |
+
label (or "class"). Labels are typically strs or
|
32 |
+
ints, but can be any immutable type. The set of labels
|
33 |
+
that the classifier chooses from must be fixed and finite.
|
34 |
+
|
35 |
+
Subclasses must define:
|
36 |
+
- ``labels()``
|
37 |
+
- either ``classify()`` or ``classify_many()`` (or both)
|
38 |
+
|
39 |
+
Subclasses may define:
|
40 |
+
- either ``prob_classify()`` or ``prob_classify_many()`` (or both)
|
41 |
+
"""
|
42 |
+
|
43 |
+
def labels(self):
|
44 |
+
"""
|
45 |
+
:return: the list of category labels used by this classifier.
|
46 |
+
:rtype: list of (immutable)
|
47 |
+
"""
|
48 |
+
raise NotImplementedError()
|
49 |
+
|
50 |
+
def classify(self, featureset):
|
51 |
+
"""
|
52 |
+
:return: the most appropriate label for the given featureset.
|
53 |
+
:rtype: label
|
54 |
+
"""
|
55 |
+
if overridden(self.classify_many):
|
56 |
+
return self.classify_many([featureset])[0]
|
57 |
+
else:
|
58 |
+
raise NotImplementedError()
|
59 |
+
|
60 |
+
def prob_classify(self, featureset):
|
61 |
+
"""
|
62 |
+
:return: a probability distribution over labels for the given
|
63 |
+
featureset.
|
64 |
+
:rtype: ProbDistI
|
65 |
+
"""
|
66 |
+
if overridden(self.prob_classify_many):
|
67 |
+
return self.prob_classify_many([featureset])[0]
|
68 |
+
else:
|
69 |
+
raise NotImplementedError()
|
70 |
+
|
71 |
+
def classify_many(self, featuresets):
|
72 |
+
"""
|
73 |
+
Apply ``self.classify()`` to each element of ``featuresets``. I.e.:
|
74 |
+
|
75 |
+
return [self.classify(fs) for fs in featuresets]
|
76 |
+
|
77 |
+
:rtype: list(label)
|
78 |
+
"""
|
79 |
+
return [self.classify(fs) for fs in featuresets]
|
80 |
+
|
81 |
+
def prob_classify_many(self, featuresets):
|
82 |
+
"""
|
83 |
+
Apply ``self.prob_classify()`` to each element of ``featuresets``. I.e.:
|
84 |
+
|
85 |
+
return [self.prob_classify(fs) for fs in featuresets]
|
86 |
+
|
87 |
+
:rtype: list(ProbDistI)
|
88 |
+
"""
|
89 |
+
return [self.prob_classify(fs) for fs in featuresets]
|
90 |
+
|
91 |
+
|
92 |
+
class MultiClassifierI:
|
93 |
+
"""
|
94 |
+
A processing interface for labeling tokens with zero or more
|
95 |
+
category labels (or "labels"). Labels are typically strs
|
96 |
+
or ints, but can be any immutable type. The set of labels
|
97 |
+
that the multi-classifier chooses from must be fixed and finite.
|
98 |
+
|
99 |
+
Subclasses must define:
|
100 |
+
- ``labels()``
|
101 |
+
- either ``classify()`` or ``classify_many()`` (or both)
|
102 |
+
|
103 |
+
Subclasses may define:
|
104 |
+
- either ``prob_classify()`` or ``prob_classify_many()`` (or both)
|
105 |
+
"""
|
106 |
+
|
107 |
+
def labels(self):
|
108 |
+
"""
|
109 |
+
:return: the list of category labels used by this classifier.
|
110 |
+
:rtype: list of (immutable)
|
111 |
+
"""
|
112 |
+
raise NotImplementedError()
|
113 |
+
|
114 |
+
def classify(self, featureset):
|
115 |
+
"""
|
116 |
+
:return: the most appropriate set of labels for the given featureset.
|
117 |
+
:rtype: set(label)
|
118 |
+
"""
|
119 |
+
if overridden(self.classify_many):
|
120 |
+
return self.classify_many([featureset])[0]
|
121 |
+
else:
|
122 |
+
raise NotImplementedError()
|
123 |
+
|
124 |
+
def prob_classify(self, featureset):
|
125 |
+
"""
|
126 |
+
:return: a probability distribution over sets of labels for the
|
127 |
+
given featureset.
|
128 |
+
:rtype: ProbDistI
|
129 |
+
"""
|
130 |
+
if overridden(self.prob_classify_many):
|
131 |
+
return self.prob_classify_many([featureset])[0]
|
132 |
+
else:
|
133 |
+
raise NotImplementedError()
|
134 |
+
|
135 |
+
def classify_many(self, featuresets):
|
136 |
+
"""
|
137 |
+
Apply ``self.classify()`` to each element of ``featuresets``. I.e.:
|
138 |
+
|
139 |
+
return [self.classify(fs) for fs in featuresets]
|
140 |
+
|
141 |
+
:rtype: list(set(label))
|
142 |
+
"""
|
143 |
+
return [self.classify(fs) for fs in featuresets]
|
144 |
+
|
145 |
+
def prob_classify_many(self, featuresets):
|
146 |
+
"""
|
147 |
+
Apply ``self.prob_classify()`` to each element of ``featuresets``. I.e.:
|
148 |
+
|
149 |
+
return [self.prob_classify(fs) for fs in featuresets]
|
150 |
+
|
151 |
+
:rtype: list(ProbDistI)
|
152 |
+
"""
|
153 |
+
return [self.prob_classify(fs) for fs in featuresets]
|
154 |
+
|
155 |
+
|
156 |
+
# # [XX] IN PROGRESS:
|
157 |
+
# class SequenceClassifierI:
|
158 |
+
# """
|
159 |
+
# A processing interface for labeling sequences of tokens with a
|
160 |
+
# single category label (or "class"). Labels are typically
|
161 |
+
# strs or ints, but can be any immutable type. The set
|
162 |
+
# of labels that the classifier chooses from must be fixed and
|
163 |
+
# finite.
|
164 |
+
# """
|
165 |
+
# def labels(self):
|
166 |
+
# """
|
167 |
+
# :return: the list of category labels used by this classifier.
|
168 |
+
# :rtype: list of (immutable)
|
169 |
+
# """
|
170 |
+
# raise NotImplementedError()
|
171 |
+
|
172 |
+
# def prob_classify(self, featureset):
|
173 |
+
# """
|
174 |
+
# Return a probability distribution over labels for the given
|
175 |
+
# featureset.
|
176 |
+
|
177 |
+
# If ``featureset`` is a list of featuresets, then return a
|
178 |
+
# corresponding list containing the probability distribution
|
179 |
+
# over labels for each of the given featuresets, where the
|
180 |
+
# *i*\ th element of this list is the most appropriate label for
|
181 |
+
# the *i*\ th element of ``featuresets``.
|
182 |
+
# """
|
183 |
+
# raise NotImplementedError()
|
184 |
+
|
185 |
+
# def classify(self, featureset):
|
186 |
+
# """
|
187 |
+
# Return the most appropriate label for the given featureset.
|
188 |
+
|
189 |
+
# If ``featureset`` is a list of featuresets, then return a
|
190 |
+
# corresponding list containing the most appropriate label for
|
191 |
+
# each of the given featuresets, where the *i*\ th element of
|
192 |
+
# this list is the most appropriate label for the *i*\ th element
|
193 |
+
# of ``featuresets``.
|
194 |
+
# """
|
195 |
+
# raise NotImplementedError()
|
env-llmeval/lib/python3.10/site-packages/nltk/classify/decisiontree.py
ADDED
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Decision Tree Classifiers
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Edward Loper <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
|
8 |
+
"""
|
9 |
+
A classifier model that decides which label to assign to a token on
|
10 |
+
the basis of a tree structure, where branches correspond to conditions
|
11 |
+
on feature values, and leaves correspond to label assignments.
|
12 |
+
"""
|
13 |
+
|
14 |
+
from collections import defaultdict
|
15 |
+
|
16 |
+
from nltk.classify.api import ClassifierI
|
17 |
+
from nltk.probability import FreqDist, MLEProbDist, entropy
|
18 |
+
|
19 |
+
|
20 |
+
class DecisionTreeClassifier(ClassifierI):
|
21 |
+
def __init__(self, label, feature_name=None, decisions=None, default=None):
|
22 |
+
"""
|
23 |
+
:param label: The most likely label for tokens that reach
|
24 |
+
this node in the decision tree. If this decision tree
|
25 |
+
has no children, then this label will be assigned to
|
26 |
+
any token that reaches this decision tree.
|
27 |
+
:param feature_name: The name of the feature that this
|
28 |
+
decision tree selects for.
|
29 |
+
:param decisions: A dictionary mapping from feature values
|
30 |
+
for the feature identified by ``feature_name`` to
|
31 |
+
child decision trees.
|
32 |
+
:param default: The child that will be used if the value of
|
33 |
+
feature ``feature_name`` does not match any of the keys in
|
34 |
+
``decisions``. This is used when constructing binary
|
35 |
+
decision trees.
|
36 |
+
"""
|
37 |
+
self._label = label
|
38 |
+
self._fname = feature_name
|
39 |
+
self._decisions = decisions
|
40 |
+
self._default = default
|
41 |
+
|
42 |
+
def labels(self):
|
43 |
+
labels = [self._label]
|
44 |
+
if self._decisions is not None:
|
45 |
+
for dt in self._decisions.values():
|
46 |
+
labels.extend(dt.labels())
|
47 |
+
if self._default is not None:
|
48 |
+
labels.extend(self._default.labels())
|
49 |
+
return list(set(labels))
|
50 |
+
|
51 |
+
def classify(self, featureset):
|
52 |
+
# Decision leaf:
|
53 |
+
if self._fname is None:
|
54 |
+
return self._label
|
55 |
+
|
56 |
+
# Decision tree:
|
57 |
+
fval = featureset.get(self._fname)
|
58 |
+
if fval in self._decisions:
|
59 |
+
return self._decisions[fval].classify(featureset)
|
60 |
+
elif self._default is not None:
|
61 |
+
return self._default.classify(featureset)
|
62 |
+
else:
|
63 |
+
return self._label
|
64 |
+
|
65 |
+
def error(self, labeled_featuresets):
|
66 |
+
errors = 0
|
67 |
+
for featureset, label in labeled_featuresets:
|
68 |
+
if self.classify(featureset) != label:
|
69 |
+
errors += 1
|
70 |
+
return errors / len(labeled_featuresets)
|
71 |
+
|
72 |
+
def pretty_format(self, width=70, prefix="", depth=4):
|
73 |
+
"""
|
74 |
+
Return a string containing a pretty-printed version of this
|
75 |
+
decision tree. Each line in this string corresponds to a
|
76 |
+
single decision tree node or leaf, and indentation is used to
|
77 |
+
display the structure of the decision tree.
|
78 |
+
"""
|
79 |
+
# [xx] display default!!
|
80 |
+
if self._fname is None:
|
81 |
+
n = width - len(prefix) - 15
|
82 |
+
return "{}{} {}\n".format(prefix, "." * n, self._label)
|
83 |
+
s = ""
|
84 |
+
for i, (fval, result) in enumerate(
|
85 |
+
sorted(
|
86 |
+
self._decisions.items(),
|
87 |
+
key=lambda item: (item[0] in [None, False, True], str(item[0]).lower()),
|
88 |
+
)
|
89 |
+
):
|
90 |
+
hdr = f"{prefix}{self._fname}={fval}? "
|
91 |
+
n = width - 15 - len(hdr)
|
92 |
+
s += "{}{} {}\n".format(hdr, "." * (n), result._label)
|
93 |
+
if result._fname is not None and depth > 1:
|
94 |
+
s += result.pretty_format(width, prefix + " ", depth - 1)
|
95 |
+
if self._default is not None:
|
96 |
+
n = width - len(prefix) - 21
|
97 |
+
s += "{}else: {} {}\n".format(prefix, "." * n, self._default._label)
|
98 |
+
if self._default._fname is not None and depth > 1:
|
99 |
+
s += self._default.pretty_format(width, prefix + " ", depth - 1)
|
100 |
+
return s
|
101 |
+
|
102 |
+
def pseudocode(self, prefix="", depth=4):
|
103 |
+
"""
|
104 |
+
Return a string representation of this decision tree that
|
105 |
+
expresses the decisions it makes as a nested set of pseudocode
|
106 |
+
if statements.
|
107 |
+
"""
|
108 |
+
if self._fname is None:
|
109 |
+
return f"{prefix}return {self._label!r}\n"
|
110 |
+
s = ""
|
111 |
+
for (fval, result) in sorted(
|
112 |
+
self._decisions.items(),
|
113 |
+
key=lambda item: (item[0] in [None, False, True], str(item[0]).lower()),
|
114 |
+
):
|
115 |
+
s += f"{prefix}if {self._fname} == {fval!r}: "
|
116 |
+
if result._fname is not None and depth > 1:
|
117 |
+
s += "\n" + result.pseudocode(prefix + " ", depth - 1)
|
118 |
+
else:
|
119 |
+
s += f"return {result._label!r}\n"
|
120 |
+
if self._default is not None:
|
121 |
+
if len(self._decisions) == 1:
|
122 |
+
s += "{}if {} != {!r}: ".format(
|
123 |
+
prefix, self._fname, list(self._decisions.keys())[0]
|
124 |
+
)
|
125 |
+
else:
|
126 |
+
s += f"{prefix}else: "
|
127 |
+
if self._default._fname is not None and depth > 1:
|
128 |
+
s += "\n" + self._default.pseudocode(prefix + " ", depth - 1)
|
129 |
+
else:
|
130 |
+
s += f"return {self._default._label!r}\n"
|
131 |
+
return s
|
132 |
+
|
133 |
+
def __str__(self):
|
134 |
+
return self.pretty_format()
|
135 |
+
|
136 |
+
@staticmethod
|
137 |
+
def train(
|
138 |
+
labeled_featuresets,
|
139 |
+
entropy_cutoff=0.05,
|
140 |
+
depth_cutoff=100,
|
141 |
+
support_cutoff=10,
|
142 |
+
binary=False,
|
143 |
+
feature_values=None,
|
144 |
+
verbose=False,
|
145 |
+
):
|
146 |
+
"""
|
147 |
+
:param binary: If true, then treat all feature/value pairs as
|
148 |
+
individual binary features, rather than using a single n-way
|
149 |
+
branch for each feature.
|
150 |
+
"""
|
151 |
+
# Collect a list of all feature names.
|
152 |
+
feature_names = set()
|
153 |
+
for featureset, label in labeled_featuresets:
|
154 |
+
for fname in featureset:
|
155 |
+
feature_names.add(fname)
|
156 |
+
|
157 |
+
# Collect a list of the values each feature can take.
|
158 |
+
if feature_values is None and binary:
|
159 |
+
feature_values = defaultdict(set)
|
160 |
+
for featureset, label in labeled_featuresets:
|
161 |
+
for fname, fval in featureset.items():
|
162 |
+
feature_values[fname].add(fval)
|
163 |
+
|
164 |
+
# Start with a stump.
|
165 |
+
if not binary:
|
166 |
+
tree = DecisionTreeClassifier.best_stump(
|
167 |
+
feature_names, labeled_featuresets, verbose
|
168 |
+
)
|
169 |
+
else:
|
170 |
+
tree = DecisionTreeClassifier.best_binary_stump(
|
171 |
+
feature_names, labeled_featuresets, feature_values, verbose
|
172 |
+
)
|
173 |
+
|
174 |
+
# Refine the stump.
|
175 |
+
tree.refine(
|
176 |
+
labeled_featuresets,
|
177 |
+
entropy_cutoff,
|
178 |
+
depth_cutoff - 1,
|
179 |
+
support_cutoff,
|
180 |
+
binary,
|
181 |
+
feature_values,
|
182 |
+
verbose,
|
183 |
+
)
|
184 |
+
|
185 |
+
# Return it
|
186 |
+
return tree
|
187 |
+
|
188 |
+
@staticmethod
|
189 |
+
def leaf(labeled_featuresets):
|
190 |
+
label = FreqDist(label for (featureset, label) in labeled_featuresets).max()
|
191 |
+
return DecisionTreeClassifier(label)
|
192 |
+
|
193 |
+
@staticmethod
|
194 |
+
def stump(feature_name, labeled_featuresets):
|
195 |
+
label = FreqDist(label for (featureset, label) in labeled_featuresets).max()
|
196 |
+
|
197 |
+
# Find the best label for each value.
|
198 |
+
freqs = defaultdict(FreqDist) # freq(label|value)
|
199 |
+
for featureset, label in labeled_featuresets:
|
200 |
+
feature_value = featureset.get(feature_name)
|
201 |
+
freqs[feature_value][label] += 1
|
202 |
+
|
203 |
+
decisions = {val: DecisionTreeClassifier(freqs[val].max()) for val in freqs}
|
204 |
+
return DecisionTreeClassifier(label, feature_name, decisions)
|
205 |
+
|
206 |
+
def refine(
|
207 |
+
self,
|
208 |
+
labeled_featuresets,
|
209 |
+
entropy_cutoff,
|
210 |
+
depth_cutoff,
|
211 |
+
support_cutoff,
|
212 |
+
binary=False,
|
213 |
+
feature_values=None,
|
214 |
+
verbose=False,
|
215 |
+
):
|
216 |
+
if len(labeled_featuresets) <= support_cutoff:
|
217 |
+
return
|
218 |
+
if self._fname is None:
|
219 |
+
return
|
220 |
+
if depth_cutoff <= 0:
|
221 |
+
return
|
222 |
+
for fval in self._decisions:
|
223 |
+
fval_featuresets = [
|
224 |
+
(featureset, label)
|
225 |
+
for (featureset, label) in labeled_featuresets
|
226 |
+
if featureset.get(self._fname) == fval
|
227 |
+
]
|
228 |
+
|
229 |
+
label_freqs = FreqDist(label for (featureset, label) in fval_featuresets)
|
230 |
+
if entropy(MLEProbDist(label_freqs)) > entropy_cutoff:
|
231 |
+
self._decisions[fval] = DecisionTreeClassifier.train(
|
232 |
+
fval_featuresets,
|
233 |
+
entropy_cutoff,
|
234 |
+
depth_cutoff,
|
235 |
+
support_cutoff,
|
236 |
+
binary,
|
237 |
+
feature_values,
|
238 |
+
verbose,
|
239 |
+
)
|
240 |
+
if self._default is not None:
|
241 |
+
default_featuresets = [
|
242 |
+
(featureset, label)
|
243 |
+
for (featureset, label) in labeled_featuresets
|
244 |
+
if featureset.get(self._fname) not in self._decisions
|
245 |
+
]
|
246 |
+
label_freqs = FreqDist(label for (featureset, label) in default_featuresets)
|
247 |
+
if entropy(MLEProbDist(label_freqs)) > entropy_cutoff:
|
248 |
+
self._default = DecisionTreeClassifier.train(
|
249 |
+
default_featuresets,
|
250 |
+
entropy_cutoff,
|
251 |
+
depth_cutoff,
|
252 |
+
support_cutoff,
|
253 |
+
binary,
|
254 |
+
feature_values,
|
255 |
+
verbose,
|
256 |
+
)
|
257 |
+
|
258 |
+
@staticmethod
|
259 |
+
def best_stump(feature_names, labeled_featuresets, verbose=False):
|
260 |
+
best_stump = DecisionTreeClassifier.leaf(labeled_featuresets)
|
261 |
+
best_error = best_stump.error(labeled_featuresets)
|
262 |
+
for fname in feature_names:
|
263 |
+
stump = DecisionTreeClassifier.stump(fname, labeled_featuresets)
|
264 |
+
stump_error = stump.error(labeled_featuresets)
|
265 |
+
if stump_error < best_error:
|
266 |
+
best_error = stump_error
|
267 |
+
best_stump = stump
|
268 |
+
if verbose:
|
269 |
+
print(
|
270 |
+
"best stump for {:6d} toks uses {:20} err={:6.4f}".format(
|
271 |
+
len(labeled_featuresets), best_stump._fname, best_error
|
272 |
+
)
|
273 |
+
)
|
274 |
+
return best_stump
|
275 |
+
|
276 |
+
@staticmethod
|
277 |
+
def binary_stump(feature_name, feature_value, labeled_featuresets):
|
278 |
+
label = FreqDist(label for (featureset, label) in labeled_featuresets).max()
|
279 |
+
|
280 |
+
# Find the best label for each value.
|
281 |
+
pos_fdist = FreqDist()
|
282 |
+
neg_fdist = FreqDist()
|
283 |
+
for featureset, label in labeled_featuresets:
|
284 |
+
if featureset.get(feature_name) == feature_value:
|
285 |
+
pos_fdist[label] += 1
|
286 |
+
else:
|
287 |
+
neg_fdist[label] += 1
|
288 |
+
|
289 |
+
decisions = {}
|
290 |
+
default = label
|
291 |
+
# But hopefully we have observations!
|
292 |
+
if pos_fdist.N() > 0:
|
293 |
+
decisions = {feature_value: DecisionTreeClassifier(pos_fdist.max())}
|
294 |
+
if neg_fdist.N() > 0:
|
295 |
+
default = DecisionTreeClassifier(neg_fdist.max())
|
296 |
+
|
297 |
+
return DecisionTreeClassifier(label, feature_name, decisions, default)
|
298 |
+
|
299 |
+
@staticmethod
|
300 |
+
def best_binary_stump(
|
301 |
+
feature_names, labeled_featuresets, feature_values, verbose=False
|
302 |
+
):
|
303 |
+
best_stump = DecisionTreeClassifier.leaf(labeled_featuresets)
|
304 |
+
best_error = best_stump.error(labeled_featuresets)
|
305 |
+
for fname in feature_names:
|
306 |
+
for fval in feature_values[fname]:
|
307 |
+
stump = DecisionTreeClassifier.binary_stump(
|
308 |
+
fname, fval, labeled_featuresets
|
309 |
+
)
|
310 |
+
stump_error = stump.error(labeled_featuresets)
|
311 |
+
if stump_error < best_error:
|
312 |
+
best_error = stump_error
|
313 |
+
best_stump = stump
|
314 |
+
if verbose:
|
315 |
+
if best_stump._decisions:
|
316 |
+
descr = "{}={}".format(
|
317 |
+
best_stump._fname, list(best_stump._decisions.keys())[0]
|
318 |
+
)
|
319 |
+
else:
|
320 |
+
descr = "(default)"
|
321 |
+
print(
|
322 |
+
"best stump for {:6d} toks uses {:20} err={:6.4f}".format(
|
323 |
+
len(labeled_featuresets), descr, best_error
|
324 |
+
)
|
325 |
+
)
|
326 |
+
return best_stump
|
327 |
+
|
328 |
+
|
329 |
+
##//////////////////////////////////////////////////////
|
330 |
+
## Demo
|
331 |
+
##//////////////////////////////////////////////////////
|
332 |
+
|
333 |
+
|
334 |
+
def f(x):
|
335 |
+
return DecisionTreeClassifier.train(x, binary=True, verbose=True)
|
336 |
+
|
337 |
+
|
338 |
+
def demo():
|
339 |
+
from nltk.classify.util import binary_names_demo_features, names_demo
|
340 |
+
|
341 |
+
classifier = names_demo(
|
342 |
+
f, binary_names_demo_features # DecisionTreeClassifier.train,
|
343 |
+
)
|
344 |
+
print(classifier.pretty_format(depth=7))
|
345 |
+
print(classifier.pseudocode(depth=7))
|
346 |
+
|
347 |
+
|
348 |
+
if __name__ == "__main__":
|
349 |
+
demo()
|
env-llmeval/lib/python3.10/site-packages/nltk/classify/maxent.py
ADDED
@@ -0,0 +1,1569 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Maximum Entropy Classifiers
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Edward Loper <[email protected]>
|
5 |
+
# Dmitry Chichkov <[email protected]> (TypedMaxentFeatureEncoding)
|
6 |
+
# URL: <https://www.nltk.org/>
|
7 |
+
# For license information, see LICENSE.TXT
|
8 |
+
|
9 |
+
"""
|
10 |
+
A classifier model based on maximum entropy modeling framework. This
|
11 |
+
framework considers all of the probability distributions that are
|
12 |
+
empirically consistent with the training data; and chooses the
|
13 |
+
distribution with the highest entropy. A probability distribution is
|
14 |
+
"empirically consistent" with a set of training data if its estimated
|
15 |
+
frequency with which a class and a feature vector value co-occur is
|
16 |
+
equal to the actual frequency in the data.
|
17 |
+
|
18 |
+
Terminology: 'feature'
|
19 |
+
======================
|
20 |
+
The term *feature* is usually used to refer to some property of an
|
21 |
+
unlabeled token. For example, when performing word sense
|
22 |
+
disambiguation, we might define a ``'prevword'`` feature whose value is
|
23 |
+
the word preceding the target word. However, in the context of
|
24 |
+
maxent modeling, the term *feature* is typically used to refer to a
|
25 |
+
property of a "labeled" token. In order to prevent confusion, we
|
26 |
+
will introduce two distinct terms to disambiguate these two different
|
27 |
+
concepts:
|
28 |
+
|
29 |
+
- An "input-feature" is a property of an unlabeled token.
|
30 |
+
- A "joint-feature" is a property of a labeled token.
|
31 |
+
|
32 |
+
In the rest of the ``nltk.classify`` module, the term "features" is
|
33 |
+
used to refer to what we will call "input-features" in this module.
|
34 |
+
|
35 |
+
In literature that describes and discusses maximum entropy models,
|
36 |
+
input-features are typically called "contexts", and joint-features
|
37 |
+
are simply referred to as "features".
|
38 |
+
|
39 |
+
Converting Input-Features to Joint-Features
|
40 |
+
-------------------------------------------
|
41 |
+
In maximum entropy models, joint-features are required to have numeric
|
42 |
+
values. Typically, each input-feature ``input_feat`` is mapped to a
|
43 |
+
set of joint-features of the form:
|
44 |
+
|
45 |
+
| joint_feat(token, label) = { 1 if input_feat(token) == feat_val
|
46 |
+
| { and label == some_label
|
47 |
+
| {
|
48 |
+
| { 0 otherwise
|
49 |
+
|
50 |
+
For all values of ``feat_val`` and ``some_label``. This mapping is
|
51 |
+
performed by classes that implement the ``MaxentFeatureEncodingI``
|
52 |
+
interface.
|
53 |
+
"""
|
54 |
+
try:
|
55 |
+
import numpy
|
56 |
+
except ImportError:
|
57 |
+
pass
|
58 |
+
|
59 |
+
import os
|
60 |
+
import tempfile
|
61 |
+
from collections import defaultdict
|
62 |
+
|
63 |
+
from nltk.classify.api import ClassifierI
|
64 |
+
from nltk.classify.megam import call_megam, parse_megam_weights, write_megam_file
|
65 |
+
from nltk.classify.tadm import call_tadm, parse_tadm_weights, write_tadm_file
|
66 |
+
from nltk.classify.util import CutoffChecker, accuracy, log_likelihood
|
67 |
+
from nltk.data import gzip_open_unicode
|
68 |
+
from nltk.probability import DictionaryProbDist
|
69 |
+
from nltk.util import OrderedDict
|
70 |
+
|
71 |
+
__docformat__ = "epytext en"
|
72 |
+
|
73 |
+
######################################################################
|
74 |
+
# { Classifier Model
|
75 |
+
######################################################################
|
76 |
+
|
77 |
+
|
78 |
+
class MaxentClassifier(ClassifierI):
|
79 |
+
"""
|
80 |
+
A maximum entropy classifier (also known as a "conditional
|
81 |
+
exponential classifier"). This classifier is parameterized by a
|
82 |
+
set of "weights", which are used to combine the joint-features
|
83 |
+
that are generated from a featureset by an "encoding". In
|
84 |
+
particular, the encoding maps each ``(featureset, label)`` pair to
|
85 |
+
a vector. The probability of each label is then computed using
|
86 |
+
the following equation::
|
87 |
+
|
88 |
+
dotprod(weights, encode(fs,label))
|
89 |
+
prob(fs|label) = ---------------------------------------------------
|
90 |
+
sum(dotprod(weights, encode(fs,l)) for l in labels)
|
91 |
+
|
92 |
+
Where ``dotprod`` is the dot product::
|
93 |
+
|
94 |
+
dotprod(a,b) = sum(x*y for (x,y) in zip(a,b))
|
95 |
+
"""
|
96 |
+
|
97 |
+
def __init__(self, encoding, weights, logarithmic=True):
|
98 |
+
"""
|
99 |
+
Construct a new maxent classifier model. Typically, new
|
100 |
+
classifier models are created using the ``train()`` method.
|
101 |
+
|
102 |
+
:type encoding: MaxentFeatureEncodingI
|
103 |
+
:param encoding: An encoding that is used to convert the
|
104 |
+
featuresets that are given to the ``classify`` method into
|
105 |
+
joint-feature vectors, which are used by the maxent
|
106 |
+
classifier model.
|
107 |
+
|
108 |
+
:type weights: list of float
|
109 |
+
:param weights: The feature weight vector for this classifier.
|
110 |
+
|
111 |
+
:type logarithmic: bool
|
112 |
+
:param logarithmic: If false, then use non-logarithmic weights.
|
113 |
+
"""
|
114 |
+
self._encoding = encoding
|
115 |
+
self._weights = weights
|
116 |
+
self._logarithmic = logarithmic
|
117 |
+
# self._logarithmic = False
|
118 |
+
assert encoding.length() == len(weights)
|
119 |
+
|
120 |
+
def labels(self):
|
121 |
+
return self._encoding.labels()
|
122 |
+
|
123 |
+
def set_weights(self, new_weights):
|
124 |
+
"""
|
125 |
+
Set the feature weight vector for this classifier.
|
126 |
+
:param new_weights: The new feature weight vector.
|
127 |
+
:type new_weights: list of float
|
128 |
+
"""
|
129 |
+
self._weights = new_weights
|
130 |
+
assert self._encoding.length() == len(new_weights)
|
131 |
+
|
132 |
+
def weights(self):
|
133 |
+
"""
|
134 |
+
:return: The feature weight vector for this classifier.
|
135 |
+
:rtype: list of float
|
136 |
+
"""
|
137 |
+
return self._weights
|
138 |
+
|
139 |
+
def classify(self, featureset):
|
140 |
+
return self.prob_classify(featureset).max()
|
141 |
+
|
142 |
+
def prob_classify(self, featureset):
|
143 |
+
prob_dict = {}
|
144 |
+
for label in self._encoding.labels():
|
145 |
+
feature_vector = self._encoding.encode(featureset, label)
|
146 |
+
|
147 |
+
if self._logarithmic:
|
148 |
+
total = 0.0
|
149 |
+
for (f_id, f_val) in feature_vector:
|
150 |
+
total += self._weights[f_id] * f_val
|
151 |
+
prob_dict[label] = total
|
152 |
+
|
153 |
+
else:
|
154 |
+
prod = 1.0
|
155 |
+
for (f_id, f_val) in feature_vector:
|
156 |
+
prod *= self._weights[f_id] ** f_val
|
157 |
+
prob_dict[label] = prod
|
158 |
+
|
159 |
+
# Normalize the dictionary to give a probability distribution
|
160 |
+
return DictionaryProbDist(prob_dict, log=self._logarithmic, normalize=True)
|
161 |
+
|
162 |
+
def explain(self, featureset, columns=4):
|
163 |
+
"""
|
164 |
+
Print a table showing the effect of each of the features in
|
165 |
+
the given feature set, and how they combine to determine the
|
166 |
+
probabilities of each label for that featureset.
|
167 |
+
"""
|
168 |
+
descr_width = 50
|
169 |
+
TEMPLATE = " %-" + str(descr_width - 2) + "s%s%8.3f"
|
170 |
+
|
171 |
+
pdist = self.prob_classify(featureset)
|
172 |
+
labels = sorted(pdist.samples(), key=pdist.prob, reverse=True)
|
173 |
+
labels = labels[:columns]
|
174 |
+
print(
|
175 |
+
" Feature".ljust(descr_width)
|
176 |
+
+ "".join("%8s" % (("%s" % l)[:7]) for l in labels)
|
177 |
+
)
|
178 |
+
print(" " + "-" * (descr_width - 2 + 8 * len(labels)))
|
179 |
+
sums = defaultdict(int)
|
180 |
+
for i, label in enumerate(labels):
|
181 |
+
feature_vector = self._encoding.encode(featureset, label)
|
182 |
+
feature_vector.sort(
|
183 |
+
key=lambda fid__: abs(self._weights[fid__[0]]), reverse=True
|
184 |
+
)
|
185 |
+
for (f_id, f_val) in feature_vector:
|
186 |
+
if self._logarithmic:
|
187 |
+
score = self._weights[f_id] * f_val
|
188 |
+
else:
|
189 |
+
score = self._weights[f_id] ** f_val
|
190 |
+
descr = self._encoding.describe(f_id)
|
191 |
+
descr = descr.split(" and label is ")[0] # hack
|
192 |
+
descr += " (%s)" % f_val # hack
|
193 |
+
if len(descr) > 47:
|
194 |
+
descr = descr[:44] + "..."
|
195 |
+
print(TEMPLATE % (descr, i * 8 * " ", score))
|
196 |
+
sums[label] += score
|
197 |
+
print(" " + "-" * (descr_width - 1 + 8 * len(labels)))
|
198 |
+
print(
|
199 |
+
" TOTAL:".ljust(descr_width) + "".join("%8.3f" % sums[l] for l in labels)
|
200 |
+
)
|
201 |
+
print(
|
202 |
+
" PROBS:".ljust(descr_width)
|
203 |
+
+ "".join("%8.3f" % pdist.prob(l) for l in labels)
|
204 |
+
)
|
205 |
+
|
206 |
+
def most_informative_features(self, n=10):
|
207 |
+
"""
|
208 |
+
Generates the ranked list of informative features from most to least.
|
209 |
+
"""
|
210 |
+
if hasattr(self, "_most_informative_features"):
|
211 |
+
return self._most_informative_features[:n]
|
212 |
+
else:
|
213 |
+
self._most_informative_features = sorted(
|
214 |
+
list(range(len(self._weights))),
|
215 |
+
key=lambda fid: abs(self._weights[fid]),
|
216 |
+
reverse=True,
|
217 |
+
)
|
218 |
+
return self._most_informative_features[:n]
|
219 |
+
|
220 |
+
def show_most_informative_features(self, n=10, show="all"):
|
221 |
+
"""
|
222 |
+
:param show: all, neg, or pos (for negative-only or positive-only)
|
223 |
+
:type show: str
|
224 |
+
:param n: The no. of top features
|
225 |
+
:type n: int
|
226 |
+
"""
|
227 |
+
# Use None the full list of ranked features.
|
228 |
+
fids = self.most_informative_features(None)
|
229 |
+
if show == "pos":
|
230 |
+
fids = [fid for fid in fids if self._weights[fid] > 0]
|
231 |
+
elif show == "neg":
|
232 |
+
fids = [fid for fid in fids if self._weights[fid] < 0]
|
233 |
+
for fid in fids[:n]:
|
234 |
+
print(f"{self._weights[fid]:8.3f} {self._encoding.describe(fid)}")
|
235 |
+
|
236 |
+
def __repr__(self):
|
237 |
+
return "<ConditionalExponentialClassifier: %d labels, %d features>" % (
|
238 |
+
len(self._encoding.labels()),
|
239 |
+
self._encoding.length(),
|
240 |
+
)
|
241 |
+
|
242 |
+
#: A list of the algorithm names that are accepted for the
|
243 |
+
#: ``train()`` method's ``algorithm`` parameter.
|
244 |
+
ALGORITHMS = ["GIS", "IIS", "MEGAM", "TADM"]
|
245 |
+
|
246 |
+
@classmethod
|
247 |
+
def train(
|
248 |
+
cls,
|
249 |
+
train_toks,
|
250 |
+
algorithm=None,
|
251 |
+
trace=3,
|
252 |
+
encoding=None,
|
253 |
+
labels=None,
|
254 |
+
gaussian_prior_sigma=0,
|
255 |
+
**cutoffs,
|
256 |
+
):
|
257 |
+
"""
|
258 |
+
Train a new maxent classifier based on the given corpus of
|
259 |
+
training samples. This classifier will have its weights
|
260 |
+
chosen to maximize entropy while remaining empirically
|
261 |
+
consistent with the training corpus.
|
262 |
+
|
263 |
+
:rtype: MaxentClassifier
|
264 |
+
:return: The new maxent classifier
|
265 |
+
|
266 |
+
:type train_toks: list
|
267 |
+
:param train_toks: Training data, represented as a list of
|
268 |
+
pairs, the first member of which is a featureset,
|
269 |
+
and the second of which is a classification label.
|
270 |
+
|
271 |
+
:type algorithm: str
|
272 |
+
:param algorithm: A case-insensitive string, specifying which
|
273 |
+
algorithm should be used to train the classifier. The
|
274 |
+
following algorithms are currently available.
|
275 |
+
|
276 |
+
- Iterative Scaling Methods: Generalized Iterative Scaling (``'GIS'``),
|
277 |
+
Improved Iterative Scaling (``'IIS'``)
|
278 |
+
- External Libraries (requiring megam):
|
279 |
+
LM-BFGS algorithm, with training performed by Megam (``'megam'``)
|
280 |
+
|
281 |
+
The default algorithm is ``'IIS'``.
|
282 |
+
|
283 |
+
:type trace: int
|
284 |
+
:param trace: The level of diagnostic tracing output to produce.
|
285 |
+
Higher values produce more verbose output.
|
286 |
+
:type encoding: MaxentFeatureEncodingI
|
287 |
+
:param encoding: A feature encoding, used to convert featuresets
|
288 |
+
into feature vectors. If none is specified, then a
|
289 |
+
``BinaryMaxentFeatureEncoding`` will be built based on the
|
290 |
+
features that are attested in the training corpus.
|
291 |
+
:type labels: list(str)
|
292 |
+
:param labels: The set of possible labels. If none is given, then
|
293 |
+
the set of all labels attested in the training data will be
|
294 |
+
used instead.
|
295 |
+
:param gaussian_prior_sigma: The sigma value for a gaussian
|
296 |
+
prior on model weights. Currently, this is supported by
|
297 |
+
``megam``. For other algorithms, its value is ignored.
|
298 |
+
:param cutoffs: Arguments specifying various conditions under
|
299 |
+
which the training should be halted. (Some of the cutoff
|
300 |
+
conditions are not supported by some algorithms.)
|
301 |
+
|
302 |
+
- ``max_iter=v``: Terminate after ``v`` iterations.
|
303 |
+
- ``min_ll=v``: Terminate after the negative average
|
304 |
+
log-likelihood drops under ``v``.
|
305 |
+
- ``min_lldelta=v``: Terminate if a single iteration improves
|
306 |
+
log likelihood by less than ``v``.
|
307 |
+
"""
|
308 |
+
if algorithm is None:
|
309 |
+
algorithm = "iis"
|
310 |
+
for key in cutoffs:
|
311 |
+
if key not in (
|
312 |
+
"max_iter",
|
313 |
+
"min_ll",
|
314 |
+
"min_lldelta",
|
315 |
+
"max_acc",
|
316 |
+
"min_accdelta",
|
317 |
+
"count_cutoff",
|
318 |
+
"norm",
|
319 |
+
"explicit",
|
320 |
+
"bernoulli",
|
321 |
+
):
|
322 |
+
raise TypeError("Unexpected keyword arg %r" % key)
|
323 |
+
algorithm = algorithm.lower()
|
324 |
+
if algorithm == "iis":
|
325 |
+
return train_maxent_classifier_with_iis(
|
326 |
+
train_toks, trace, encoding, labels, **cutoffs
|
327 |
+
)
|
328 |
+
elif algorithm == "gis":
|
329 |
+
return train_maxent_classifier_with_gis(
|
330 |
+
train_toks, trace, encoding, labels, **cutoffs
|
331 |
+
)
|
332 |
+
elif algorithm == "megam":
|
333 |
+
return train_maxent_classifier_with_megam(
|
334 |
+
train_toks, trace, encoding, labels, gaussian_prior_sigma, **cutoffs
|
335 |
+
)
|
336 |
+
elif algorithm == "tadm":
|
337 |
+
kwargs = cutoffs
|
338 |
+
kwargs["trace"] = trace
|
339 |
+
kwargs["encoding"] = encoding
|
340 |
+
kwargs["labels"] = labels
|
341 |
+
kwargs["gaussian_prior_sigma"] = gaussian_prior_sigma
|
342 |
+
return TadmMaxentClassifier.train(train_toks, **kwargs)
|
343 |
+
else:
|
344 |
+
raise ValueError("Unknown algorithm %s" % algorithm)
|
345 |
+
|
346 |
+
|
347 |
+
#: Alias for MaxentClassifier.
|
348 |
+
ConditionalExponentialClassifier = MaxentClassifier
|
349 |
+
|
350 |
+
|
351 |
+
######################################################################
|
352 |
+
# { Feature Encodings
|
353 |
+
######################################################################
|
354 |
+
|
355 |
+
|
356 |
+
class MaxentFeatureEncodingI:
|
357 |
+
"""
|
358 |
+
A mapping that converts a set of input-feature values to a vector
|
359 |
+
of joint-feature values, given a label. This conversion is
|
360 |
+
necessary to translate featuresets into a format that can be used
|
361 |
+
by maximum entropy models.
|
362 |
+
|
363 |
+
The set of joint-features used by a given encoding is fixed, and
|
364 |
+
each index in the generated joint-feature vectors corresponds to a
|
365 |
+
single joint-feature. The length of the generated joint-feature
|
366 |
+
vectors is therefore constant (for a given encoding).
|
367 |
+
|
368 |
+
Because the joint-feature vectors generated by
|
369 |
+
``MaxentFeatureEncodingI`` are typically very sparse, they are
|
370 |
+
represented as a list of ``(index, value)`` tuples, specifying the
|
371 |
+
value of each non-zero joint-feature.
|
372 |
+
|
373 |
+
Feature encodings are generally created using the ``train()``
|
374 |
+
method, which generates an appropriate encoding based on the
|
375 |
+
input-feature values and labels that are present in a given
|
376 |
+
corpus.
|
377 |
+
"""
|
378 |
+
|
379 |
+
def encode(self, featureset, label):
|
380 |
+
"""
|
381 |
+
Given a (featureset, label) pair, return the corresponding
|
382 |
+
vector of joint-feature values. This vector is represented as
|
383 |
+
a list of ``(index, value)`` tuples, specifying the value of
|
384 |
+
each non-zero joint-feature.
|
385 |
+
|
386 |
+
:type featureset: dict
|
387 |
+
:rtype: list(tuple(int, int))
|
388 |
+
"""
|
389 |
+
raise NotImplementedError()
|
390 |
+
|
391 |
+
def length(self):
|
392 |
+
"""
|
393 |
+
:return: The size of the fixed-length joint-feature vectors
|
394 |
+
that are generated by this encoding.
|
395 |
+
:rtype: int
|
396 |
+
"""
|
397 |
+
raise NotImplementedError()
|
398 |
+
|
399 |
+
def labels(self):
|
400 |
+
"""
|
401 |
+
:return: A list of the \"known labels\" -- i.e., all labels
|
402 |
+
``l`` such that ``self.encode(fs,l)`` can be a nonzero
|
403 |
+
joint-feature vector for some value of ``fs``.
|
404 |
+
:rtype: list
|
405 |
+
"""
|
406 |
+
raise NotImplementedError()
|
407 |
+
|
408 |
+
def describe(self, fid):
|
409 |
+
"""
|
410 |
+
:return: A string describing the value of the joint-feature
|
411 |
+
whose index in the generated feature vectors is ``fid``.
|
412 |
+
:rtype: str
|
413 |
+
"""
|
414 |
+
raise NotImplementedError()
|
415 |
+
|
416 |
+
def train(cls, train_toks):
|
417 |
+
"""
|
418 |
+
Construct and return new feature encoding, based on a given
|
419 |
+
training corpus ``train_toks``.
|
420 |
+
|
421 |
+
:type train_toks: list(tuple(dict, str))
|
422 |
+
:param train_toks: Training data, represented as a list of
|
423 |
+
pairs, the first member of which is a feature dictionary,
|
424 |
+
and the second of which is a classification label.
|
425 |
+
"""
|
426 |
+
raise NotImplementedError()
|
427 |
+
|
428 |
+
|
429 |
+
class FunctionBackedMaxentFeatureEncoding(MaxentFeatureEncodingI):
|
430 |
+
"""
|
431 |
+
A feature encoding that calls a user-supplied function to map a
|
432 |
+
given featureset/label pair to a sparse joint-feature vector.
|
433 |
+
"""
|
434 |
+
|
435 |
+
def __init__(self, func, length, labels):
|
436 |
+
"""
|
437 |
+
Construct a new feature encoding based on the given function.
|
438 |
+
|
439 |
+
:type func: (callable)
|
440 |
+
:param func: A function that takes two arguments, a featureset
|
441 |
+
and a label, and returns the sparse joint feature vector
|
442 |
+
that encodes them::
|
443 |
+
|
444 |
+
func(featureset, label) -> feature_vector
|
445 |
+
|
446 |
+
This sparse joint feature vector (``feature_vector``) is a
|
447 |
+
list of ``(index,value)`` tuples.
|
448 |
+
|
449 |
+
:type length: int
|
450 |
+
:param length: The size of the fixed-length joint-feature
|
451 |
+
vectors that are generated by this encoding.
|
452 |
+
|
453 |
+
:type labels: list
|
454 |
+
:param labels: A list of the \"known labels\" for this
|
455 |
+
encoding -- i.e., all labels ``l`` such that
|
456 |
+
``self.encode(fs,l)`` can be a nonzero joint-feature vector
|
457 |
+
for some value of ``fs``.
|
458 |
+
"""
|
459 |
+
self._length = length
|
460 |
+
self._func = func
|
461 |
+
self._labels = labels
|
462 |
+
|
463 |
+
def encode(self, featureset, label):
|
464 |
+
return self._func(featureset, label)
|
465 |
+
|
466 |
+
def length(self):
|
467 |
+
return self._length
|
468 |
+
|
469 |
+
def labels(self):
|
470 |
+
return self._labels
|
471 |
+
|
472 |
+
def describe(self, fid):
|
473 |
+
return "no description available"
|
474 |
+
|
475 |
+
|
476 |
+
class BinaryMaxentFeatureEncoding(MaxentFeatureEncodingI):
|
477 |
+
"""
|
478 |
+
A feature encoding that generates vectors containing a binary
|
479 |
+
joint-features of the form:
|
480 |
+
|
481 |
+
| joint_feat(fs, l) = { 1 if (fs[fname] == fval) and (l == label)
|
482 |
+
| {
|
483 |
+
| { 0 otherwise
|
484 |
+
|
485 |
+
Where ``fname`` is the name of an input-feature, ``fval`` is a value
|
486 |
+
for that input-feature, and ``label`` is a label.
|
487 |
+
|
488 |
+
Typically, these features are constructed based on a training
|
489 |
+
corpus, using the ``train()`` method. This method will create one
|
490 |
+
feature for each combination of ``fname``, ``fval``, and ``label``
|
491 |
+
that occurs at least once in the training corpus.
|
492 |
+
|
493 |
+
The ``unseen_features`` parameter can be used to add "unseen-value
|
494 |
+
features", which are used whenever an input feature has a value
|
495 |
+
that was not encountered in the training corpus. These features
|
496 |
+
have the form:
|
497 |
+
|
498 |
+
| joint_feat(fs, l) = { 1 if is_unseen(fname, fs[fname])
|
499 |
+
| { and l == label
|
500 |
+
| {
|
501 |
+
| { 0 otherwise
|
502 |
+
|
503 |
+
Where ``is_unseen(fname, fval)`` is true if the encoding does not
|
504 |
+
contain any joint features that are true when ``fs[fname]==fval``.
|
505 |
+
|
506 |
+
The ``alwayson_features`` parameter can be used to add "always-on
|
507 |
+
features", which have the form::
|
508 |
+
|
509 |
+
| joint_feat(fs, l) = { 1 if (l == label)
|
510 |
+
| {
|
511 |
+
| { 0 otherwise
|
512 |
+
|
513 |
+
These always-on features allow the maxent model to directly model
|
514 |
+
the prior probabilities of each label.
|
515 |
+
"""
|
516 |
+
|
517 |
+
def __init__(self, labels, mapping, unseen_features=False, alwayson_features=False):
|
518 |
+
"""
|
519 |
+
:param labels: A list of the \"known labels\" for this encoding.
|
520 |
+
|
521 |
+
:param mapping: A dictionary mapping from ``(fname,fval,label)``
|
522 |
+
tuples to corresponding joint-feature indexes. These
|
523 |
+
indexes must be the set of integers from 0...len(mapping).
|
524 |
+
If ``mapping[fname,fval,label]=id``, then
|
525 |
+
``self.encode(..., fname:fval, ..., label)[id]`` is 1;
|
526 |
+
otherwise, it is 0.
|
527 |
+
|
528 |
+
:param unseen_features: If true, then include unseen value
|
529 |
+
features in the generated joint-feature vectors.
|
530 |
+
|
531 |
+
:param alwayson_features: If true, then include always-on
|
532 |
+
features in the generated joint-feature vectors.
|
533 |
+
"""
|
534 |
+
if set(mapping.values()) != set(range(len(mapping))):
|
535 |
+
raise ValueError(
|
536 |
+
"Mapping values must be exactly the "
|
537 |
+
"set of integers from 0...len(mapping)"
|
538 |
+
)
|
539 |
+
|
540 |
+
self._labels = list(labels)
|
541 |
+
"""A list of attested labels."""
|
542 |
+
|
543 |
+
self._mapping = mapping
|
544 |
+
"""dict mapping from (fname,fval,label) -> fid"""
|
545 |
+
|
546 |
+
self._length = len(mapping)
|
547 |
+
"""The length of generated joint feature vectors."""
|
548 |
+
|
549 |
+
self._alwayson = None
|
550 |
+
"""dict mapping from label -> fid"""
|
551 |
+
|
552 |
+
self._unseen = None
|
553 |
+
"""dict mapping from fname -> fid"""
|
554 |
+
|
555 |
+
if alwayson_features:
|
556 |
+
self._alwayson = {
|
557 |
+
label: i + self._length for (i, label) in enumerate(labels)
|
558 |
+
}
|
559 |
+
self._length += len(self._alwayson)
|
560 |
+
|
561 |
+
if unseen_features:
|
562 |
+
fnames = {fname for (fname, fval, label) in mapping}
|
563 |
+
self._unseen = {fname: i + self._length for (i, fname) in enumerate(fnames)}
|
564 |
+
self._length += len(fnames)
|
565 |
+
|
566 |
+
def encode(self, featureset, label):
|
567 |
+
# Inherit docs.
|
568 |
+
encoding = []
|
569 |
+
|
570 |
+
# Convert input-features to joint-features:
|
571 |
+
for fname, fval in featureset.items():
|
572 |
+
# Known feature name & value:
|
573 |
+
if (fname, fval, label) in self._mapping:
|
574 |
+
encoding.append((self._mapping[fname, fval, label], 1))
|
575 |
+
|
576 |
+
# Otherwise, we might want to fire an "unseen-value feature".
|
577 |
+
elif self._unseen:
|
578 |
+
# Have we seen this fname/fval combination with any label?
|
579 |
+
for label2 in self._labels:
|
580 |
+
if (fname, fval, label2) in self._mapping:
|
581 |
+
break # we've seen this fname/fval combo
|
582 |
+
# We haven't -- fire the unseen-value feature
|
583 |
+
else:
|
584 |
+
if fname in self._unseen:
|
585 |
+
encoding.append((self._unseen[fname], 1))
|
586 |
+
|
587 |
+
# Add always-on features:
|
588 |
+
if self._alwayson and label in self._alwayson:
|
589 |
+
encoding.append((self._alwayson[label], 1))
|
590 |
+
|
591 |
+
return encoding
|
592 |
+
|
593 |
+
def describe(self, f_id):
|
594 |
+
# Inherit docs.
|
595 |
+
if not isinstance(f_id, int):
|
596 |
+
raise TypeError("describe() expected an int")
|
597 |
+
try:
|
598 |
+
self._inv_mapping
|
599 |
+
except AttributeError:
|
600 |
+
self._inv_mapping = [-1] * len(self._mapping)
|
601 |
+
for (info, i) in self._mapping.items():
|
602 |
+
self._inv_mapping[i] = info
|
603 |
+
|
604 |
+
if f_id < len(self._mapping):
|
605 |
+
(fname, fval, label) = self._inv_mapping[f_id]
|
606 |
+
return f"{fname}=={fval!r} and label is {label!r}"
|
607 |
+
elif self._alwayson and f_id in self._alwayson.values():
|
608 |
+
for (label, f_id2) in self._alwayson.items():
|
609 |
+
if f_id == f_id2:
|
610 |
+
return "label is %r" % label
|
611 |
+
elif self._unseen and f_id in self._unseen.values():
|
612 |
+
for (fname, f_id2) in self._unseen.items():
|
613 |
+
if f_id == f_id2:
|
614 |
+
return "%s is unseen" % fname
|
615 |
+
else:
|
616 |
+
raise ValueError("Bad feature id")
|
617 |
+
|
618 |
+
def labels(self):
|
619 |
+
# Inherit docs.
|
620 |
+
return self._labels
|
621 |
+
|
622 |
+
def length(self):
|
623 |
+
# Inherit docs.
|
624 |
+
return self._length
|
625 |
+
|
626 |
+
@classmethod
|
627 |
+
def train(cls, train_toks, count_cutoff=0, labels=None, **options):
|
628 |
+
"""
|
629 |
+
Construct and return new feature encoding, based on a given
|
630 |
+
training corpus ``train_toks``. See the class description
|
631 |
+
``BinaryMaxentFeatureEncoding`` for a description of the
|
632 |
+
joint-features that will be included in this encoding.
|
633 |
+
|
634 |
+
:type train_toks: list(tuple(dict, str))
|
635 |
+
:param train_toks: Training data, represented as a list of
|
636 |
+
pairs, the first member of which is a feature dictionary,
|
637 |
+
and the second of which is a classification label.
|
638 |
+
|
639 |
+
:type count_cutoff: int
|
640 |
+
:param count_cutoff: A cutoff value that is used to discard
|
641 |
+
rare joint-features. If a joint-feature's value is 1
|
642 |
+
fewer than ``count_cutoff`` times in the training corpus,
|
643 |
+
then that joint-feature is not included in the generated
|
644 |
+
encoding.
|
645 |
+
|
646 |
+
:type labels: list
|
647 |
+
:param labels: A list of labels that should be used by the
|
648 |
+
classifier. If not specified, then the set of labels
|
649 |
+
attested in ``train_toks`` will be used.
|
650 |
+
|
651 |
+
:param options: Extra parameters for the constructor, such as
|
652 |
+
``unseen_features`` and ``alwayson_features``.
|
653 |
+
"""
|
654 |
+
mapping = {} # maps (fname, fval, label) -> fid
|
655 |
+
seen_labels = set() # The set of labels we've encountered
|
656 |
+
count = defaultdict(int) # maps (fname, fval) -> count
|
657 |
+
|
658 |
+
for (tok, label) in train_toks:
|
659 |
+
if labels and label not in labels:
|
660 |
+
raise ValueError("Unexpected label %s" % label)
|
661 |
+
seen_labels.add(label)
|
662 |
+
|
663 |
+
# Record each of the features.
|
664 |
+
for (fname, fval) in tok.items():
|
665 |
+
|
666 |
+
# If a count cutoff is given, then only add a joint
|
667 |
+
# feature once the corresponding (fname, fval, label)
|
668 |
+
# tuple exceeds that cutoff.
|
669 |
+
count[fname, fval] += 1
|
670 |
+
if count[fname, fval] >= count_cutoff:
|
671 |
+
if (fname, fval, label) not in mapping:
|
672 |
+
mapping[fname, fval, label] = len(mapping)
|
673 |
+
|
674 |
+
if labels is None:
|
675 |
+
labels = seen_labels
|
676 |
+
return cls(labels, mapping, **options)
|
677 |
+
|
678 |
+
|
679 |
+
class GISEncoding(BinaryMaxentFeatureEncoding):
|
680 |
+
"""
|
681 |
+
A binary feature encoding which adds one new joint-feature to the
|
682 |
+
joint-features defined by ``BinaryMaxentFeatureEncoding``: a
|
683 |
+
correction feature, whose value is chosen to ensure that the
|
684 |
+
sparse vector always sums to a constant non-negative number. This
|
685 |
+
new feature is used to ensure two preconditions for the GIS
|
686 |
+
training algorithm:
|
687 |
+
|
688 |
+
- At least one feature vector index must be nonzero for every
|
689 |
+
token.
|
690 |
+
- The feature vector must sum to a constant non-negative number
|
691 |
+
for every token.
|
692 |
+
"""
|
693 |
+
|
694 |
+
def __init__(
|
695 |
+
self, labels, mapping, unseen_features=False, alwayson_features=False, C=None
|
696 |
+
):
|
697 |
+
"""
|
698 |
+
:param C: The correction constant. The value of the correction
|
699 |
+
feature is based on this value. In particular, its value is
|
700 |
+
``C - sum([v for (f,v) in encoding])``.
|
701 |
+
:seealso: ``BinaryMaxentFeatureEncoding.__init__``
|
702 |
+
"""
|
703 |
+
BinaryMaxentFeatureEncoding.__init__(
|
704 |
+
self, labels, mapping, unseen_features, alwayson_features
|
705 |
+
)
|
706 |
+
if C is None:
|
707 |
+
C = len({fname for (fname, fval, label) in mapping}) + 1
|
708 |
+
self._C = C
|
709 |
+
|
710 |
+
@property
|
711 |
+
def C(self):
|
712 |
+
"""The non-negative constant that all encoded feature vectors
|
713 |
+
will sum to."""
|
714 |
+
return self._C
|
715 |
+
|
716 |
+
def encode(self, featureset, label):
|
717 |
+
# Get the basic encoding.
|
718 |
+
encoding = BinaryMaxentFeatureEncoding.encode(self, featureset, label)
|
719 |
+
base_length = BinaryMaxentFeatureEncoding.length(self)
|
720 |
+
|
721 |
+
# Add a correction feature.
|
722 |
+
total = sum(v for (f, v) in encoding)
|
723 |
+
if total >= self._C:
|
724 |
+
raise ValueError("Correction feature is not high enough!")
|
725 |
+
encoding.append((base_length, self._C - total))
|
726 |
+
|
727 |
+
# Return the result
|
728 |
+
return encoding
|
729 |
+
|
730 |
+
def length(self):
|
731 |
+
return BinaryMaxentFeatureEncoding.length(self) + 1
|
732 |
+
|
733 |
+
def describe(self, f_id):
|
734 |
+
if f_id == BinaryMaxentFeatureEncoding.length(self):
|
735 |
+
return "Correction feature (%s)" % self._C
|
736 |
+
else:
|
737 |
+
return BinaryMaxentFeatureEncoding.describe(self, f_id)
|
738 |
+
|
739 |
+
|
740 |
+
class TadmEventMaxentFeatureEncoding(BinaryMaxentFeatureEncoding):
|
741 |
+
def __init__(self, labels, mapping, unseen_features=False, alwayson_features=False):
|
742 |
+
self._mapping = OrderedDict(mapping)
|
743 |
+
self._label_mapping = OrderedDict()
|
744 |
+
BinaryMaxentFeatureEncoding.__init__(
|
745 |
+
self, labels, self._mapping, unseen_features, alwayson_features
|
746 |
+
)
|
747 |
+
|
748 |
+
def encode(self, featureset, label):
|
749 |
+
encoding = []
|
750 |
+
for feature, value in featureset.items():
|
751 |
+
if (feature, label) not in self._mapping:
|
752 |
+
self._mapping[(feature, label)] = len(self._mapping)
|
753 |
+
if value not in self._label_mapping:
|
754 |
+
if not isinstance(value, int):
|
755 |
+
self._label_mapping[value] = len(self._label_mapping)
|
756 |
+
else:
|
757 |
+
self._label_mapping[value] = value
|
758 |
+
encoding.append(
|
759 |
+
(self._mapping[(feature, label)], self._label_mapping[value])
|
760 |
+
)
|
761 |
+
return encoding
|
762 |
+
|
763 |
+
def labels(self):
|
764 |
+
return self._labels
|
765 |
+
|
766 |
+
def describe(self, fid):
|
767 |
+
for (feature, label) in self._mapping:
|
768 |
+
if self._mapping[(feature, label)] == fid:
|
769 |
+
return (feature, label)
|
770 |
+
|
771 |
+
def length(self):
|
772 |
+
return len(self._mapping)
|
773 |
+
|
774 |
+
@classmethod
|
775 |
+
def train(cls, train_toks, count_cutoff=0, labels=None, **options):
|
776 |
+
mapping = OrderedDict()
|
777 |
+
if not labels:
|
778 |
+
labels = []
|
779 |
+
|
780 |
+
# This gets read twice, so compute the values in case it's lazy.
|
781 |
+
train_toks = list(train_toks)
|
782 |
+
|
783 |
+
for (featureset, label) in train_toks:
|
784 |
+
if label not in labels:
|
785 |
+
labels.append(label)
|
786 |
+
|
787 |
+
for (featureset, label) in train_toks:
|
788 |
+
for label in labels:
|
789 |
+
for feature in featureset:
|
790 |
+
if (feature, label) not in mapping:
|
791 |
+
mapping[(feature, label)] = len(mapping)
|
792 |
+
|
793 |
+
return cls(labels, mapping, **options)
|
794 |
+
|
795 |
+
|
796 |
+
class TypedMaxentFeatureEncoding(MaxentFeatureEncodingI):
|
797 |
+
"""
|
798 |
+
A feature encoding that generates vectors containing integer,
|
799 |
+
float and binary joint-features of the form:
|
800 |
+
|
801 |
+
Binary (for string and boolean features):
|
802 |
+
|
803 |
+
| joint_feat(fs, l) = { 1 if (fs[fname] == fval) and (l == label)
|
804 |
+
| {
|
805 |
+
| { 0 otherwise
|
806 |
+
|
807 |
+
Value (for integer and float features):
|
808 |
+
|
809 |
+
| joint_feat(fs, l) = { fval if (fs[fname] == type(fval))
|
810 |
+
| { and (l == label)
|
811 |
+
| {
|
812 |
+
| { not encoded otherwise
|
813 |
+
|
814 |
+
Where ``fname`` is the name of an input-feature, ``fval`` is a value
|
815 |
+
for that input-feature, and ``label`` is a label.
|
816 |
+
|
817 |
+
Typically, these features are constructed based on a training
|
818 |
+
corpus, using the ``train()`` method.
|
819 |
+
|
820 |
+
For string and boolean features [type(fval) not in (int, float)]
|
821 |
+
this method will create one feature for each combination of
|
822 |
+
``fname``, ``fval``, and ``label`` that occurs at least once in the
|
823 |
+
training corpus.
|
824 |
+
|
825 |
+
For integer and float features [type(fval) in (int, float)] this
|
826 |
+
method will create one feature for each combination of ``fname``
|
827 |
+
and ``label`` that occurs at least once in the training corpus.
|
828 |
+
|
829 |
+
For binary features the ``unseen_features`` parameter can be used
|
830 |
+
to add "unseen-value features", which are used whenever an input
|
831 |
+
feature has a value that was not encountered in the training
|
832 |
+
corpus. These features have the form:
|
833 |
+
|
834 |
+
| joint_feat(fs, l) = { 1 if is_unseen(fname, fs[fname])
|
835 |
+
| { and l == label
|
836 |
+
| {
|
837 |
+
| { 0 otherwise
|
838 |
+
|
839 |
+
Where ``is_unseen(fname, fval)`` is true if the encoding does not
|
840 |
+
contain any joint features that are true when ``fs[fname]==fval``.
|
841 |
+
|
842 |
+
The ``alwayson_features`` parameter can be used to add "always-on
|
843 |
+
features", which have the form:
|
844 |
+
|
845 |
+
| joint_feat(fs, l) = { 1 if (l == label)
|
846 |
+
| {
|
847 |
+
| { 0 otherwise
|
848 |
+
|
849 |
+
These always-on features allow the maxent model to directly model
|
850 |
+
the prior probabilities of each label.
|
851 |
+
"""
|
852 |
+
|
853 |
+
def __init__(self, labels, mapping, unseen_features=False, alwayson_features=False):
|
854 |
+
"""
|
855 |
+
:param labels: A list of the \"known labels\" for this encoding.
|
856 |
+
|
857 |
+
:param mapping: A dictionary mapping from ``(fname,fval,label)``
|
858 |
+
tuples to corresponding joint-feature indexes. These
|
859 |
+
indexes must be the set of integers from 0...len(mapping).
|
860 |
+
If ``mapping[fname,fval,label]=id``, then
|
861 |
+
``self.encode({..., fname:fval, ...``, label)[id]} is 1;
|
862 |
+
otherwise, it is 0.
|
863 |
+
|
864 |
+
:param unseen_features: If true, then include unseen value
|
865 |
+
features in the generated joint-feature vectors.
|
866 |
+
|
867 |
+
:param alwayson_features: If true, then include always-on
|
868 |
+
features in the generated joint-feature vectors.
|
869 |
+
"""
|
870 |
+
if set(mapping.values()) != set(range(len(mapping))):
|
871 |
+
raise ValueError(
|
872 |
+
"Mapping values must be exactly the "
|
873 |
+
"set of integers from 0...len(mapping)"
|
874 |
+
)
|
875 |
+
|
876 |
+
self._labels = list(labels)
|
877 |
+
"""A list of attested labels."""
|
878 |
+
|
879 |
+
self._mapping = mapping
|
880 |
+
"""dict mapping from (fname,fval,label) -> fid"""
|
881 |
+
|
882 |
+
self._length = len(mapping)
|
883 |
+
"""The length of generated joint feature vectors."""
|
884 |
+
|
885 |
+
self._alwayson = None
|
886 |
+
"""dict mapping from label -> fid"""
|
887 |
+
|
888 |
+
self._unseen = None
|
889 |
+
"""dict mapping from fname -> fid"""
|
890 |
+
|
891 |
+
if alwayson_features:
|
892 |
+
self._alwayson = {
|
893 |
+
label: i + self._length for (i, label) in enumerate(labels)
|
894 |
+
}
|
895 |
+
self._length += len(self._alwayson)
|
896 |
+
|
897 |
+
if unseen_features:
|
898 |
+
fnames = {fname for (fname, fval, label) in mapping}
|
899 |
+
self._unseen = {fname: i + self._length for (i, fname) in enumerate(fnames)}
|
900 |
+
self._length += len(fnames)
|
901 |
+
|
902 |
+
def encode(self, featureset, label):
|
903 |
+
# Inherit docs.
|
904 |
+
encoding = []
|
905 |
+
|
906 |
+
# Convert input-features to joint-features:
|
907 |
+
for fname, fval in featureset.items():
|
908 |
+
if isinstance(fval, (int, float)):
|
909 |
+
# Known feature name & value:
|
910 |
+
if (fname, type(fval), label) in self._mapping:
|
911 |
+
encoding.append((self._mapping[fname, type(fval), label], fval))
|
912 |
+
else:
|
913 |
+
# Known feature name & value:
|
914 |
+
if (fname, fval, label) in self._mapping:
|
915 |
+
encoding.append((self._mapping[fname, fval, label], 1))
|
916 |
+
|
917 |
+
# Otherwise, we might want to fire an "unseen-value feature".
|
918 |
+
elif self._unseen:
|
919 |
+
# Have we seen this fname/fval combination with any label?
|
920 |
+
for label2 in self._labels:
|
921 |
+
if (fname, fval, label2) in self._mapping:
|
922 |
+
break # we've seen this fname/fval combo
|
923 |
+
# We haven't -- fire the unseen-value feature
|
924 |
+
else:
|
925 |
+
if fname in self._unseen:
|
926 |
+
encoding.append((self._unseen[fname], 1))
|
927 |
+
|
928 |
+
# Add always-on features:
|
929 |
+
if self._alwayson and label in self._alwayson:
|
930 |
+
encoding.append((self._alwayson[label], 1))
|
931 |
+
|
932 |
+
return encoding
|
933 |
+
|
934 |
+
def describe(self, f_id):
|
935 |
+
# Inherit docs.
|
936 |
+
if not isinstance(f_id, int):
|
937 |
+
raise TypeError("describe() expected an int")
|
938 |
+
try:
|
939 |
+
self._inv_mapping
|
940 |
+
except AttributeError:
|
941 |
+
self._inv_mapping = [-1] * len(self._mapping)
|
942 |
+
for (info, i) in self._mapping.items():
|
943 |
+
self._inv_mapping[i] = info
|
944 |
+
|
945 |
+
if f_id < len(self._mapping):
|
946 |
+
(fname, fval, label) = self._inv_mapping[f_id]
|
947 |
+
return f"{fname}=={fval!r} and label is {label!r}"
|
948 |
+
elif self._alwayson and f_id in self._alwayson.values():
|
949 |
+
for (label, f_id2) in self._alwayson.items():
|
950 |
+
if f_id == f_id2:
|
951 |
+
return "label is %r" % label
|
952 |
+
elif self._unseen and f_id in self._unseen.values():
|
953 |
+
for (fname, f_id2) in self._unseen.items():
|
954 |
+
if f_id == f_id2:
|
955 |
+
return "%s is unseen" % fname
|
956 |
+
else:
|
957 |
+
raise ValueError("Bad feature id")
|
958 |
+
|
959 |
+
def labels(self):
|
960 |
+
# Inherit docs.
|
961 |
+
return self._labels
|
962 |
+
|
963 |
+
def length(self):
|
964 |
+
# Inherit docs.
|
965 |
+
return self._length
|
966 |
+
|
967 |
+
@classmethod
|
968 |
+
def train(cls, train_toks, count_cutoff=0, labels=None, **options):
|
969 |
+
"""
|
970 |
+
Construct and return new feature encoding, based on a given
|
971 |
+
training corpus ``train_toks``. See the class description
|
972 |
+
``TypedMaxentFeatureEncoding`` for a description of the
|
973 |
+
joint-features that will be included in this encoding.
|
974 |
+
|
975 |
+
Note: recognized feature values types are (int, float), over
|
976 |
+
types are interpreted as regular binary features.
|
977 |
+
|
978 |
+
:type train_toks: list(tuple(dict, str))
|
979 |
+
:param train_toks: Training data, represented as a list of
|
980 |
+
pairs, the first member of which is a feature dictionary,
|
981 |
+
and the second of which is a classification label.
|
982 |
+
|
983 |
+
:type count_cutoff: int
|
984 |
+
:param count_cutoff: A cutoff value that is used to discard
|
985 |
+
rare joint-features. If a joint-feature's value is 1
|
986 |
+
fewer than ``count_cutoff`` times in the training corpus,
|
987 |
+
then that joint-feature is not included in the generated
|
988 |
+
encoding.
|
989 |
+
|
990 |
+
:type labels: list
|
991 |
+
:param labels: A list of labels that should be used by the
|
992 |
+
classifier. If not specified, then the set of labels
|
993 |
+
attested in ``train_toks`` will be used.
|
994 |
+
|
995 |
+
:param options: Extra parameters for the constructor, such as
|
996 |
+
``unseen_features`` and ``alwayson_features``.
|
997 |
+
"""
|
998 |
+
mapping = {} # maps (fname, fval, label) -> fid
|
999 |
+
seen_labels = set() # The set of labels we've encountered
|
1000 |
+
count = defaultdict(int) # maps (fname, fval) -> count
|
1001 |
+
|
1002 |
+
for (tok, label) in train_toks:
|
1003 |
+
if labels and label not in labels:
|
1004 |
+
raise ValueError("Unexpected label %s" % label)
|
1005 |
+
seen_labels.add(label)
|
1006 |
+
|
1007 |
+
# Record each of the features.
|
1008 |
+
for (fname, fval) in tok.items():
|
1009 |
+
if type(fval) in (int, float):
|
1010 |
+
fval = type(fval)
|
1011 |
+
# If a count cutoff is given, then only add a joint
|
1012 |
+
# feature once the corresponding (fname, fval, label)
|
1013 |
+
# tuple exceeds that cutoff.
|
1014 |
+
count[fname, fval] += 1
|
1015 |
+
if count[fname, fval] >= count_cutoff:
|
1016 |
+
if (fname, fval, label) not in mapping:
|
1017 |
+
mapping[fname, fval, label] = len(mapping)
|
1018 |
+
|
1019 |
+
if labels is None:
|
1020 |
+
labels = seen_labels
|
1021 |
+
return cls(labels, mapping, **options)
|
1022 |
+
|
1023 |
+
|
1024 |
+
######################################################################
|
1025 |
+
# { Classifier Trainer: Generalized Iterative Scaling
|
1026 |
+
######################################################################
|
1027 |
+
|
1028 |
+
|
1029 |
+
def train_maxent_classifier_with_gis(
|
1030 |
+
train_toks, trace=3, encoding=None, labels=None, **cutoffs
|
1031 |
+
):
|
1032 |
+
"""
|
1033 |
+
Train a new ``ConditionalExponentialClassifier``, using the given
|
1034 |
+
training samples, using the Generalized Iterative Scaling
|
1035 |
+
algorithm. This ``ConditionalExponentialClassifier`` will encode
|
1036 |
+
the model that maximizes entropy from all the models that are
|
1037 |
+
empirically consistent with ``train_toks``.
|
1038 |
+
|
1039 |
+
:see: ``train_maxent_classifier()`` for parameter descriptions.
|
1040 |
+
"""
|
1041 |
+
cutoffs.setdefault("max_iter", 100)
|
1042 |
+
cutoffchecker = CutoffChecker(cutoffs)
|
1043 |
+
|
1044 |
+
# Construct an encoding from the training data.
|
1045 |
+
if encoding is None:
|
1046 |
+
encoding = GISEncoding.train(train_toks, labels=labels)
|
1047 |
+
|
1048 |
+
if not hasattr(encoding, "C"):
|
1049 |
+
raise TypeError(
|
1050 |
+
"The GIS algorithm requires an encoding that "
|
1051 |
+
"defines C (e.g., GISEncoding)."
|
1052 |
+
)
|
1053 |
+
|
1054 |
+
# Cinv is the inverse of the sum of each joint feature vector.
|
1055 |
+
# This controls the learning rate: higher Cinv (or lower C) gives
|
1056 |
+
# faster learning.
|
1057 |
+
Cinv = 1.0 / encoding.C
|
1058 |
+
|
1059 |
+
# Count how many times each feature occurs in the training data.
|
1060 |
+
empirical_fcount = calculate_empirical_fcount(train_toks, encoding)
|
1061 |
+
|
1062 |
+
# Check for any features that are not attested in train_toks.
|
1063 |
+
unattested = set(numpy.nonzero(empirical_fcount == 0)[0])
|
1064 |
+
|
1065 |
+
# Build the classifier. Start with weight=0 for each attested
|
1066 |
+
# feature, and weight=-infinity for each unattested feature.
|
1067 |
+
weights = numpy.zeros(len(empirical_fcount), "d")
|
1068 |
+
for fid in unattested:
|
1069 |
+
weights[fid] = numpy.NINF
|
1070 |
+
classifier = ConditionalExponentialClassifier(encoding, weights)
|
1071 |
+
|
1072 |
+
# Take the log of the empirical fcount.
|
1073 |
+
log_empirical_fcount = numpy.log2(empirical_fcount)
|
1074 |
+
del empirical_fcount
|
1075 |
+
|
1076 |
+
if trace > 0:
|
1077 |
+
print(" ==> Training (%d iterations)" % cutoffs["max_iter"])
|
1078 |
+
if trace > 2:
|
1079 |
+
print()
|
1080 |
+
print(" Iteration Log Likelihood Accuracy")
|
1081 |
+
print(" ---------------------------------------")
|
1082 |
+
|
1083 |
+
# Train the classifier.
|
1084 |
+
try:
|
1085 |
+
while True:
|
1086 |
+
if trace > 2:
|
1087 |
+
ll = cutoffchecker.ll or log_likelihood(classifier, train_toks)
|
1088 |
+
acc = cutoffchecker.acc or accuracy(classifier, train_toks)
|
1089 |
+
iternum = cutoffchecker.iter
|
1090 |
+
print(" %9d %14.5f %9.3f" % (iternum, ll, acc))
|
1091 |
+
|
1092 |
+
# Use the model to estimate the number of times each
|
1093 |
+
# feature should occur in the training data.
|
1094 |
+
estimated_fcount = calculate_estimated_fcount(
|
1095 |
+
classifier, train_toks, encoding
|
1096 |
+
)
|
1097 |
+
|
1098 |
+
# Take the log of estimated fcount (avoid taking log(0).)
|
1099 |
+
for fid in unattested:
|
1100 |
+
estimated_fcount[fid] += 1
|
1101 |
+
log_estimated_fcount = numpy.log2(estimated_fcount)
|
1102 |
+
del estimated_fcount
|
1103 |
+
|
1104 |
+
# Update the classifier weights
|
1105 |
+
weights = classifier.weights()
|
1106 |
+
weights += (log_empirical_fcount - log_estimated_fcount) * Cinv
|
1107 |
+
classifier.set_weights(weights)
|
1108 |
+
|
1109 |
+
# Check the log-likelihood & accuracy cutoffs.
|
1110 |
+
if cutoffchecker.check(classifier, train_toks):
|
1111 |
+
break
|
1112 |
+
|
1113 |
+
except KeyboardInterrupt:
|
1114 |
+
print(" Training stopped: keyboard interrupt")
|
1115 |
+
except:
|
1116 |
+
raise
|
1117 |
+
|
1118 |
+
if trace > 2:
|
1119 |
+
ll = log_likelihood(classifier, train_toks)
|
1120 |
+
acc = accuracy(classifier, train_toks)
|
1121 |
+
print(f" Final {ll:14.5f} {acc:9.3f}")
|
1122 |
+
|
1123 |
+
# Return the classifier.
|
1124 |
+
return classifier
|
1125 |
+
|
1126 |
+
|
1127 |
+
def calculate_empirical_fcount(train_toks, encoding):
|
1128 |
+
fcount = numpy.zeros(encoding.length(), "d")
|
1129 |
+
|
1130 |
+
for tok, label in train_toks:
|
1131 |
+
for (index, val) in encoding.encode(tok, label):
|
1132 |
+
fcount[index] += val
|
1133 |
+
|
1134 |
+
return fcount
|
1135 |
+
|
1136 |
+
|
1137 |
+
def calculate_estimated_fcount(classifier, train_toks, encoding):
|
1138 |
+
fcount = numpy.zeros(encoding.length(), "d")
|
1139 |
+
|
1140 |
+
for tok, label in train_toks:
|
1141 |
+
pdist = classifier.prob_classify(tok)
|
1142 |
+
for label in pdist.samples():
|
1143 |
+
prob = pdist.prob(label)
|
1144 |
+
for (fid, fval) in encoding.encode(tok, label):
|
1145 |
+
fcount[fid] += prob * fval
|
1146 |
+
|
1147 |
+
return fcount
|
1148 |
+
|
1149 |
+
|
1150 |
+
######################################################################
|
1151 |
+
# { Classifier Trainer: Improved Iterative Scaling
|
1152 |
+
######################################################################
|
1153 |
+
|
1154 |
+
|
1155 |
+
def train_maxent_classifier_with_iis(
|
1156 |
+
train_toks, trace=3, encoding=None, labels=None, **cutoffs
|
1157 |
+
):
|
1158 |
+
"""
|
1159 |
+
Train a new ``ConditionalExponentialClassifier``, using the given
|
1160 |
+
training samples, using the Improved Iterative Scaling algorithm.
|
1161 |
+
This ``ConditionalExponentialClassifier`` will encode the model
|
1162 |
+
that maximizes entropy from all the models that are empirically
|
1163 |
+
consistent with ``train_toks``.
|
1164 |
+
|
1165 |
+
:see: ``train_maxent_classifier()`` for parameter descriptions.
|
1166 |
+
"""
|
1167 |
+
cutoffs.setdefault("max_iter", 100)
|
1168 |
+
cutoffchecker = CutoffChecker(cutoffs)
|
1169 |
+
|
1170 |
+
# Construct an encoding from the training data.
|
1171 |
+
if encoding is None:
|
1172 |
+
encoding = BinaryMaxentFeatureEncoding.train(train_toks, labels=labels)
|
1173 |
+
|
1174 |
+
# Count how many times each feature occurs in the training data.
|
1175 |
+
empirical_ffreq = calculate_empirical_fcount(train_toks, encoding) / len(train_toks)
|
1176 |
+
|
1177 |
+
# Find the nf map, and related variables nfarray and nfident.
|
1178 |
+
# nf is the sum of the features for a given labeled text.
|
1179 |
+
# nfmap compresses this sparse set of values to a dense list.
|
1180 |
+
# nfarray performs the reverse operation. nfident is
|
1181 |
+
# nfarray multiplied by an identity matrix.
|
1182 |
+
nfmap = calculate_nfmap(train_toks, encoding)
|
1183 |
+
nfarray = numpy.array(sorted(nfmap, key=nfmap.__getitem__), "d")
|
1184 |
+
nftranspose = numpy.reshape(nfarray, (len(nfarray), 1))
|
1185 |
+
|
1186 |
+
# Check for any features that are not attested in train_toks.
|
1187 |
+
unattested = set(numpy.nonzero(empirical_ffreq == 0)[0])
|
1188 |
+
|
1189 |
+
# Build the classifier. Start with weight=0 for each attested
|
1190 |
+
# feature, and weight=-infinity for each unattested feature.
|
1191 |
+
weights = numpy.zeros(len(empirical_ffreq), "d")
|
1192 |
+
for fid in unattested:
|
1193 |
+
weights[fid] = numpy.NINF
|
1194 |
+
classifier = ConditionalExponentialClassifier(encoding, weights)
|
1195 |
+
|
1196 |
+
if trace > 0:
|
1197 |
+
print(" ==> Training (%d iterations)" % cutoffs["max_iter"])
|
1198 |
+
if trace > 2:
|
1199 |
+
print()
|
1200 |
+
print(" Iteration Log Likelihood Accuracy")
|
1201 |
+
print(" ---------------------------------------")
|
1202 |
+
|
1203 |
+
# Train the classifier.
|
1204 |
+
try:
|
1205 |
+
while True:
|
1206 |
+
if trace > 2:
|
1207 |
+
ll = cutoffchecker.ll or log_likelihood(classifier, train_toks)
|
1208 |
+
acc = cutoffchecker.acc or accuracy(classifier, train_toks)
|
1209 |
+
iternum = cutoffchecker.iter
|
1210 |
+
print(" %9d %14.5f %9.3f" % (iternum, ll, acc))
|
1211 |
+
|
1212 |
+
# Calculate the deltas for this iteration, using Newton's method.
|
1213 |
+
deltas = calculate_deltas(
|
1214 |
+
train_toks,
|
1215 |
+
classifier,
|
1216 |
+
unattested,
|
1217 |
+
empirical_ffreq,
|
1218 |
+
nfmap,
|
1219 |
+
nfarray,
|
1220 |
+
nftranspose,
|
1221 |
+
encoding,
|
1222 |
+
)
|
1223 |
+
|
1224 |
+
# Use the deltas to update our weights.
|
1225 |
+
weights = classifier.weights()
|
1226 |
+
weights += deltas
|
1227 |
+
classifier.set_weights(weights)
|
1228 |
+
|
1229 |
+
# Check the log-likelihood & accuracy cutoffs.
|
1230 |
+
if cutoffchecker.check(classifier, train_toks):
|
1231 |
+
break
|
1232 |
+
|
1233 |
+
except KeyboardInterrupt:
|
1234 |
+
print(" Training stopped: keyboard interrupt")
|
1235 |
+
except:
|
1236 |
+
raise
|
1237 |
+
|
1238 |
+
if trace > 2:
|
1239 |
+
ll = log_likelihood(classifier, train_toks)
|
1240 |
+
acc = accuracy(classifier, train_toks)
|
1241 |
+
print(f" Final {ll:14.5f} {acc:9.3f}")
|
1242 |
+
|
1243 |
+
# Return the classifier.
|
1244 |
+
return classifier
|
1245 |
+
|
1246 |
+
|
1247 |
+
def calculate_nfmap(train_toks, encoding):
|
1248 |
+
"""
|
1249 |
+
Construct a map that can be used to compress ``nf`` (which is
|
1250 |
+
typically sparse).
|
1251 |
+
|
1252 |
+
*nf(feature_vector)* is the sum of the feature values for
|
1253 |
+
*feature_vector*.
|
1254 |
+
|
1255 |
+
This represents the number of features that are active for a
|
1256 |
+
given labeled text. This method finds all values of *nf(t)*
|
1257 |
+
that are attested for at least one token in the given list of
|
1258 |
+
training tokens; and constructs a dictionary mapping these
|
1259 |
+
attested values to a continuous range *0...N*. For example,
|
1260 |
+
if the only values of *nf()* that were attested were 3, 5, and
|
1261 |
+
7, then ``_nfmap`` might return the dictionary ``{3:0, 5:1, 7:2}``.
|
1262 |
+
|
1263 |
+
:return: A map that can be used to compress ``nf`` to a dense
|
1264 |
+
vector.
|
1265 |
+
:rtype: dict(int -> int)
|
1266 |
+
"""
|
1267 |
+
# Map from nf to indices. This allows us to use smaller arrays.
|
1268 |
+
nfset = set()
|
1269 |
+
for tok, _ in train_toks:
|
1270 |
+
for label in encoding.labels():
|
1271 |
+
nfset.add(sum(val for (id, val) in encoding.encode(tok, label)))
|
1272 |
+
return {nf: i for (i, nf) in enumerate(nfset)}
|
1273 |
+
|
1274 |
+
|
1275 |
+
def calculate_deltas(
|
1276 |
+
train_toks,
|
1277 |
+
classifier,
|
1278 |
+
unattested,
|
1279 |
+
ffreq_empirical,
|
1280 |
+
nfmap,
|
1281 |
+
nfarray,
|
1282 |
+
nftranspose,
|
1283 |
+
encoding,
|
1284 |
+
):
|
1285 |
+
r"""
|
1286 |
+
Calculate the update values for the classifier weights for
|
1287 |
+
this iteration of IIS. These update weights are the value of
|
1288 |
+
``delta`` that solves the equation::
|
1289 |
+
|
1290 |
+
ffreq_empirical[i]
|
1291 |
+
=
|
1292 |
+
SUM[fs,l] (classifier.prob_classify(fs).prob(l) *
|
1293 |
+
feature_vector(fs,l)[i] *
|
1294 |
+
exp(delta[i] * nf(feature_vector(fs,l))))
|
1295 |
+
|
1296 |
+
Where:
|
1297 |
+
- *(fs,l)* is a (featureset, label) tuple from ``train_toks``
|
1298 |
+
- *feature_vector(fs,l)* = ``encoding.encode(fs,l)``
|
1299 |
+
- *nf(vector)* = ``sum([val for (id,val) in vector])``
|
1300 |
+
|
1301 |
+
This method uses Newton's method to solve this equation for
|
1302 |
+
*delta[i]*. In particular, it starts with a guess of
|
1303 |
+
``delta[i]`` = 1; and iteratively updates ``delta`` with:
|
1304 |
+
|
1305 |
+
| delta[i] -= (ffreq_empirical[i] - sum1[i])/(-sum2[i])
|
1306 |
+
|
1307 |
+
until convergence, where *sum1* and *sum2* are defined as:
|
1308 |
+
|
1309 |
+
| sum1[i](delta) = SUM[fs,l] f[i](fs,l,delta)
|
1310 |
+
| sum2[i](delta) = SUM[fs,l] (f[i](fs,l,delta).nf(feature_vector(fs,l)))
|
1311 |
+
| f[i](fs,l,delta) = (classifier.prob_classify(fs).prob(l) .
|
1312 |
+
| feature_vector(fs,l)[i] .
|
1313 |
+
| exp(delta[i] . nf(feature_vector(fs,l))))
|
1314 |
+
|
1315 |
+
Note that *sum1* and *sum2* depend on ``delta``; so they need
|
1316 |
+
to be re-computed each iteration.
|
1317 |
+
|
1318 |
+
The variables ``nfmap``, ``nfarray``, and ``nftranspose`` are
|
1319 |
+
used to generate a dense encoding for *nf(ltext)*. This
|
1320 |
+
allows ``_deltas`` to calculate *sum1* and *sum2* using
|
1321 |
+
matrices, which yields a significant performance improvement.
|
1322 |
+
|
1323 |
+
:param train_toks: The set of training tokens.
|
1324 |
+
:type train_toks: list(tuple(dict, str))
|
1325 |
+
:param classifier: The current classifier.
|
1326 |
+
:type classifier: ClassifierI
|
1327 |
+
:param ffreq_empirical: An array containing the empirical
|
1328 |
+
frequency for each feature. The *i*\ th element of this
|
1329 |
+
array is the empirical frequency for feature *i*.
|
1330 |
+
:type ffreq_empirical: sequence of float
|
1331 |
+
:param unattested: An array that is 1 for features that are
|
1332 |
+
not attested in the training data; and 0 for features that
|
1333 |
+
are attested. In other words, ``unattested[i]==0`` iff
|
1334 |
+
``ffreq_empirical[i]==0``.
|
1335 |
+
:type unattested: sequence of int
|
1336 |
+
:param nfmap: A map that can be used to compress ``nf`` to a dense
|
1337 |
+
vector.
|
1338 |
+
:type nfmap: dict(int -> int)
|
1339 |
+
:param nfarray: An array that can be used to uncompress ``nf``
|
1340 |
+
from a dense vector.
|
1341 |
+
:type nfarray: array(float)
|
1342 |
+
:param nftranspose: The transpose of ``nfarray``
|
1343 |
+
:type nftranspose: array(float)
|
1344 |
+
"""
|
1345 |
+
# These parameters control when we decide that we've
|
1346 |
+
# converged. It probably should be possible to set these
|
1347 |
+
# manually, via keyword arguments to train.
|
1348 |
+
NEWTON_CONVERGE = 1e-12
|
1349 |
+
MAX_NEWTON = 300
|
1350 |
+
|
1351 |
+
deltas = numpy.ones(encoding.length(), "d")
|
1352 |
+
|
1353 |
+
# Precompute the A matrix:
|
1354 |
+
# A[nf][id] = sum ( p(fs) * p(label|fs) * f(fs,label) )
|
1355 |
+
# over all label,fs s.t. num_features[label,fs]=nf
|
1356 |
+
A = numpy.zeros((len(nfmap), encoding.length()), "d")
|
1357 |
+
|
1358 |
+
for tok, label in train_toks:
|
1359 |
+
dist = classifier.prob_classify(tok)
|
1360 |
+
|
1361 |
+
for label in encoding.labels():
|
1362 |
+
# Generate the feature vector
|
1363 |
+
feature_vector = encoding.encode(tok, label)
|
1364 |
+
# Find the number of active features
|
1365 |
+
nf = sum(val for (id, val) in feature_vector)
|
1366 |
+
# Update the A matrix
|
1367 |
+
for (id, val) in feature_vector:
|
1368 |
+
A[nfmap[nf], id] += dist.prob(label) * val
|
1369 |
+
A /= len(train_toks)
|
1370 |
+
|
1371 |
+
# Iteratively solve for delta. Use the following variables:
|
1372 |
+
# - nf_delta[x][y] = nfarray[x] * delta[y]
|
1373 |
+
# - exp_nf_delta[x][y] = exp(nf[x] * delta[y])
|
1374 |
+
# - nf_exp_nf_delta[x][y] = nf[x] * exp(nf[x] * delta[y])
|
1375 |
+
# - sum1[i][nf] = sum p(fs)p(label|fs)f[i](label,fs)
|
1376 |
+
# exp(delta[i]nf)
|
1377 |
+
# - sum2[i][nf] = sum p(fs)p(label|fs)f[i](label,fs)
|
1378 |
+
# nf exp(delta[i]nf)
|
1379 |
+
for rangenum in range(MAX_NEWTON):
|
1380 |
+
nf_delta = numpy.outer(nfarray, deltas)
|
1381 |
+
exp_nf_delta = 2**nf_delta
|
1382 |
+
nf_exp_nf_delta = nftranspose * exp_nf_delta
|
1383 |
+
sum1 = numpy.sum(exp_nf_delta * A, axis=0)
|
1384 |
+
sum2 = numpy.sum(nf_exp_nf_delta * A, axis=0)
|
1385 |
+
|
1386 |
+
# Avoid division by zero.
|
1387 |
+
for fid in unattested:
|
1388 |
+
sum2[fid] += 1
|
1389 |
+
|
1390 |
+
# Update the deltas.
|
1391 |
+
deltas -= (ffreq_empirical - sum1) / -sum2
|
1392 |
+
|
1393 |
+
# We can stop once we converge.
|
1394 |
+
n_error = numpy.sum(abs(ffreq_empirical - sum1)) / numpy.sum(abs(deltas))
|
1395 |
+
if n_error < NEWTON_CONVERGE:
|
1396 |
+
return deltas
|
1397 |
+
|
1398 |
+
return deltas
|
1399 |
+
|
1400 |
+
|
1401 |
+
######################################################################
|
1402 |
+
# { Classifier Trainer: megam
|
1403 |
+
######################################################################
|
1404 |
+
|
1405 |
+
# [xx] possible extension: add support for using implicit file format;
|
1406 |
+
# this would need to put requirements on what encoding is used. But
|
1407 |
+
# we may need this for other maxent classifier trainers that require
|
1408 |
+
# implicit formats anyway.
|
1409 |
+
def train_maxent_classifier_with_megam(
|
1410 |
+
train_toks, trace=3, encoding=None, labels=None, gaussian_prior_sigma=0, **kwargs
|
1411 |
+
):
|
1412 |
+
"""
|
1413 |
+
Train a new ``ConditionalExponentialClassifier``, using the given
|
1414 |
+
training samples, using the external ``megam`` library. This
|
1415 |
+
``ConditionalExponentialClassifier`` will encode the model that
|
1416 |
+
maximizes entropy from all the models that are empirically
|
1417 |
+
consistent with ``train_toks``.
|
1418 |
+
|
1419 |
+
:see: ``train_maxent_classifier()`` for parameter descriptions.
|
1420 |
+
:see: ``nltk.classify.megam``
|
1421 |
+
"""
|
1422 |
+
|
1423 |
+
explicit = True
|
1424 |
+
bernoulli = True
|
1425 |
+
if "explicit" in kwargs:
|
1426 |
+
explicit = kwargs["explicit"]
|
1427 |
+
if "bernoulli" in kwargs:
|
1428 |
+
bernoulli = kwargs["bernoulli"]
|
1429 |
+
|
1430 |
+
# Construct an encoding from the training data.
|
1431 |
+
if encoding is None:
|
1432 |
+
# Count cutoff can also be controlled by megam with the -minfc
|
1433 |
+
# option. Not sure where the best place for it is.
|
1434 |
+
count_cutoff = kwargs.get("count_cutoff", 0)
|
1435 |
+
encoding = BinaryMaxentFeatureEncoding.train(
|
1436 |
+
train_toks, count_cutoff, labels=labels, alwayson_features=True
|
1437 |
+
)
|
1438 |
+
elif labels is not None:
|
1439 |
+
raise ValueError("Specify encoding or labels, not both")
|
1440 |
+
|
1441 |
+
# Write a training file for megam.
|
1442 |
+
try:
|
1443 |
+
fd, trainfile_name = tempfile.mkstemp(prefix="nltk-")
|
1444 |
+
with open(trainfile_name, "w") as trainfile:
|
1445 |
+
write_megam_file(
|
1446 |
+
train_toks, encoding, trainfile, explicit=explicit, bernoulli=bernoulli
|
1447 |
+
)
|
1448 |
+
os.close(fd)
|
1449 |
+
except (OSError, ValueError) as e:
|
1450 |
+
raise ValueError("Error while creating megam training file: %s" % e) from e
|
1451 |
+
|
1452 |
+
# Run megam on the training file.
|
1453 |
+
options = []
|
1454 |
+
options += ["-nobias", "-repeat", "10"]
|
1455 |
+
if explicit:
|
1456 |
+
options += ["-explicit"]
|
1457 |
+
if not bernoulli:
|
1458 |
+
options += ["-fvals"]
|
1459 |
+
if gaussian_prior_sigma:
|
1460 |
+
# Lambda is just the precision of the Gaussian prior, i.e. it's the
|
1461 |
+
# inverse variance, so the parameter conversion is 1.0/sigma**2.
|
1462 |
+
# See https://users.umiacs.umd.edu/~hal/docs/daume04cg-bfgs.pdf
|
1463 |
+
inv_variance = 1.0 / gaussian_prior_sigma**2
|
1464 |
+
else:
|
1465 |
+
inv_variance = 0
|
1466 |
+
options += ["-lambda", "%.2f" % inv_variance, "-tune"]
|
1467 |
+
if trace < 3:
|
1468 |
+
options += ["-quiet"]
|
1469 |
+
if "max_iter" in kwargs:
|
1470 |
+
options += ["-maxi", "%s" % kwargs["max_iter"]]
|
1471 |
+
if "ll_delta" in kwargs:
|
1472 |
+
# [xx] this is actually a perplexity delta, not a log
|
1473 |
+
# likelihood delta
|
1474 |
+
options += ["-dpp", "%s" % abs(kwargs["ll_delta"])]
|
1475 |
+
if hasattr(encoding, "cost"):
|
1476 |
+
options += ["-multilabel"] # each possible la
|
1477 |
+
options += ["multiclass", trainfile_name]
|
1478 |
+
stdout = call_megam(options)
|
1479 |
+
# print('./megam_i686.opt ', ' '.join(options))
|
1480 |
+
# Delete the training file
|
1481 |
+
try:
|
1482 |
+
os.remove(trainfile_name)
|
1483 |
+
except OSError as e:
|
1484 |
+
print(f"Warning: unable to delete {trainfile_name}: {e}")
|
1485 |
+
|
1486 |
+
# Parse the generated weight vector.
|
1487 |
+
weights = parse_megam_weights(stdout, encoding.length(), explicit)
|
1488 |
+
|
1489 |
+
# Convert from base-e to base-2 weights.
|
1490 |
+
weights *= numpy.log2(numpy.e)
|
1491 |
+
|
1492 |
+
# Build the classifier
|
1493 |
+
return MaxentClassifier(encoding, weights)
|
1494 |
+
|
1495 |
+
|
1496 |
+
######################################################################
|
1497 |
+
# { Classifier Trainer: tadm
|
1498 |
+
######################################################################
|
1499 |
+
|
1500 |
+
|
1501 |
+
class TadmMaxentClassifier(MaxentClassifier):
|
1502 |
+
@classmethod
|
1503 |
+
def train(cls, train_toks, **kwargs):
|
1504 |
+
algorithm = kwargs.get("algorithm", "tao_lmvm")
|
1505 |
+
trace = kwargs.get("trace", 3)
|
1506 |
+
encoding = kwargs.get("encoding", None)
|
1507 |
+
labels = kwargs.get("labels", None)
|
1508 |
+
sigma = kwargs.get("gaussian_prior_sigma", 0)
|
1509 |
+
count_cutoff = kwargs.get("count_cutoff", 0)
|
1510 |
+
max_iter = kwargs.get("max_iter")
|
1511 |
+
ll_delta = kwargs.get("min_lldelta")
|
1512 |
+
|
1513 |
+
# Construct an encoding from the training data.
|
1514 |
+
if not encoding:
|
1515 |
+
encoding = TadmEventMaxentFeatureEncoding.train(
|
1516 |
+
train_toks, count_cutoff, labels=labels
|
1517 |
+
)
|
1518 |
+
|
1519 |
+
trainfile_fd, trainfile_name = tempfile.mkstemp(
|
1520 |
+
prefix="nltk-tadm-events-", suffix=".gz"
|
1521 |
+
)
|
1522 |
+
weightfile_fd, weightfile_name = tempfile.mkstemp(prefix="nltk-tadm-weights-")
|
1523 |
+
|
1524 |
+
trainfile = gzip_open_unicode(trainfile_name, "w")
|
1525 |
+
write_tadm_file(train_toks, encoding, trainfile)
|
1526 |
+
trainfile.close()
|
1527 |
+
|
1528 |
+
options = []
|
1529 |
+
options.extend(["-monitor"])
|
1530 |
+
options.extend(["-method", algorithm])
|
1531 |
+
if sigma:
|
1532 |
+
options.extend(["-l2", "%.6f" % sigma**2])
|
1533 |
+
if max_iter:
|
1534 |
+
options.extend(["-max_it", "%d" % max_iter])
|
1535 |
+
if ll_delta:
|
1536 |
+
options.extend(["-fatol", "%.6f" % abs(ll_delta)])
|
1537 |
+
options.extend(["-events_in", trainfile_name])
|
1538 |
+
options.extend(["-params_out", weightfile_name])
|
1539 |
+
if trace < 3:
|
1540 |
+
options.extend(["2>&1"])
|
1541 |
+
else:
|
1542 |
+
options.extend(["-summary"])
|
1543 |
+
|
1544 |
+
call_tadm(options)
|
1545 |
+
|
1546 |
+
with open(weightfile_name) as weightfile:
|
1547 |
+
weights = parse_tadm_weights(weightfile)
|
1548 |
+
|
1549 |
+
os.remove(trainfile_name)
|
1550 |
+
os.remove(weightfile_name)
|
1551 |
+
|
1552 |
+
# Convert from base-e to base-2 weights.
|
1553 |
+
weights *= numpy.log2(numpy.e)
|
1554 |
+
|
1555 |
+
# Build the classifier
|
1556 |
+
return cls(encoding, weights)
|
1557 |
+
|
1558 |
+
|
1559 |
+
######################################################################
|
1560 |
+
# { Demo
|
1561 |
+
######################################################################
|
1562 |
+
def demo():
|
1563 |
+
from nltk.classify.util import names_demo
|
1564 |
+
|
1565 |
+
classifier = names_demo(MaxentClassifier.train)
|
1566 |
+
|
1567 |
+
|
1568 |
+
if __name__ == "__main__":
|
1569 |
+
demo()
|
env-llmeval/lib/python3.10/site-packages/nltk/classify/megam.py
ADDED
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Interface to Megam Classifier
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Edward Loper <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
|
8 |
+
"""
|
9 |
+
A set of functions used to interface with the external megam_ maxent
|
10 |
+
optimization package. Before megam can be used, you should tell NLTK where it
|
11 |
+
can find the megam binary, using the ``config_megam()`` function. Typical
|
12 |
+
usage:
|
13 |
+
|
14 |
+
>>> from nltk.classify import megam
|
15 |
+
>>> megam.config_megam() # pass path to megam if not found in PATH # doctest: +SKIP
|
16 |
+
[Found megam: ...]
|
17 |
+
|
18 |
+
Use with MaxentClassifier. Example below, see MaxentClassifier documentation
|
19 |
+
for details.
|
20 |
+
|
21 |
+
nltk.classify.MaxentClassifier.train(corpus, 'megam')
|
22 |
+
|
23 |
+
.. _megam: https://www.umiacs.umd.edu/~hal/megam/index.html
|
24 |
+
"""
|
25 |
+
import subprocess
|
26 |
+
|
27 |
+
from nltk.internals import find_binary
|
28 |
+
|
29 |
+
try:
|
30 |
+
import numpy
|
31 |
+
except ImportError:
|
32 |
+
numpy = None
|
33 |
+
|
34 |
+
######################################################################
|
35 |
+
# { Configuration
|
36 |
+
######################################################################
|
37 |
+
|
38 |
+
_megam_bin = None
|
39 |
+
|
40 |
+
|
41 |
+
def config_megam(bin=None):
|
42 |
+
"""
|
43 |
+
Configure NLTK's interface to the ``megam`` maxent optimization
|
44 |
+
package.
|
45 |
+
|
46 |
+
:param bin: The full path to the ``megam`` binary. If not specified,
|
47 |
+
then nltk will search the system for a ``megam`` binary; and if
|
48 |
+
one is not found, it will raise a ``LookupError`` exception.
|
49 |
+
:type bin: str
|
50 |
+
"""
|
51 |
+
global _megam_bin
|
52 |
+
_megam_bin = find_binary(
|
53 |
+
"megam",
|
54 |
+
bin,
|
55 |
+
env_vars=["MEGAM"],
|
56 |
+
binary_names=["megam.opt", "megam", "megam_686", "megam_i686.opt"],
|
57 |
+
url="https://www.umiacs.umd.edu/~hal/megam/index.html",
|
58 |
+
)
|
59 |
+
|
60 |
+
|
61 |
+
######################################################################
|
62 |
+
# { Megam Interface Functions
|
63 |
+
######################################################################
|
64 |
+
|
65 |
+
|
66 |
+
def write_megam_file(train_toks, encoding, stream, bernoulli=True, explicit=True):
|
67 |
+
"""
|
68 |
+
Generate an input file for ``megam`` based on the given corpus of
|
69 |
+
classified tokens.
|
70 |
+
|
71 |
+
:type train_toks: list(tuple(dict, str))
|
72 |
+
:param train_toks: Training data, represented as a list of
|
73 |
+
pairs, the first member of which is a feature dictionary,
|
74 |
+
and the second of which is a classification label.
|
75 |
+
|
76 |
+
:type encoding: MaxentFeatureEncodingI
|
77 |
+
:param encoding: A feature encoding, used to convert featuresets
|
78 |
+
into feature vectors. May optionally implement a cost() method
|
79 |
+
in order to assign different costs to different class predictions.
|
80 |
+
|
81 |
+
:type stream: stream
|
82 |
+
:param stream: The stream to which the megam input file should be
|
83 |
+
written.
|
84 |
+
|
85 |
+
:param bernoulli: If true, then use the 'bernoulli' format. I.e.,
|
86 |
+
all joint features have binary values, and are listed iff they
|
87 |
+
are true. Otherwise, list feature values explicitly. If
|
88 |
+
``bernoulli=False``, then you must call ``megam`` with the
|
89 |
+
``-fvals`` option.
|
90 |
+
|
91 |
+
:param explicit: If true, then use the 'explicit' format. I.e.,
|
92 |
+
list the features that would fire for any of the possible
|
93 |
+
labels, for each token. If ``explicit=True``, then you must
|
94 |
+
call ``megam`` with the ``-explicit`` option.
|
95 |
+
"""
|
96 |
+
# Look up the set of labels.
|
97 |
+
labels = encoding.labels()
|
98 |
+
labelnum = {label: i for (i, label) in enumerate(labels)}
|
99 |
+
|
100 |
+
# Write the file, which contains one line per instance.
|
101 |
+
for featureset, label in train_toks:
|
102 |
+
# First, the instance number (or, in the weighted multiclass case, the cost of each label).
|
103 |
+
if hasattr(encoding, "cost"):
|
104 |
+
stream.write(
|
105 |
+
":".join(str(encoding.cost(featureset, label, l)) for l in labels)
|
106 |
+
)
|
107 |
+
else:
|
108 |
+
stream.write("%d" % labelnum[label])
|
109 |
+
|
110 |
+
# For implicit file formats, just list the features that fire
|
111 |
+
# for this instance's actual label.
|
112 |
+
if not explicit:
|
113 |
+
_write_megam_features(encoding.encode(featureset, label), stream, bernoulli)
|
114 |
+
|
115 |
+
# For explicit formats, list the features that would fire for
|
116 |
+
# any of the possible labels.
|
117 |
+
else:
|
118 |
+
for l in labels:
|
119 |
+
stream.write(" #")
|
120 |
+
_write_megam_features(encoding.encode(featureset, l), stream, bernoulli)
|
121 |
+
|
122 |
+
# End of the instance.
|
123 |
+
stream.write("\n")
|
124 |
+
|
125 |
+
|
126 |
+
def parse_megam_weights(s, features_count, explicit=True):
|
127 |
+
"""
|
128 |
+
Given the stdout output generated by ``megam`` when training a
|
129 |
+
model, return a ``numpy`` array containing the corresponding weight
|
130 |
+
vector. This function does not currently handle bias features.
|
131 |
+
"""
|
132 |
+
if numpy is None:
|
133 |
+
raise ValueError("This function requires that numpy be installed")
|
134 |
+
assert explicit, "non-explicit not supported yet"
|
135 |
+
lines = s.strip().split("\n")
|
136 |
+
weights = numpy.zeros(features_count, "d")
|
137 |
+
for line in lines:
|
138 |
+
if line.strip():
|
139 |
+
fid, weight = line.split()
|
140 |
+
weights[int(fid)] = float(weight)
|
141 |
+
return weights
|
142 |
+
|
143 |
+
|
144 |
+
def _write_megam_features(vector, stream, bernoulli):
|
145 |
+
if not vector:
|
146 |
+
raise ValueError(
|
147 |
+
"MEGAM classifier requires the use of an " "always-on feature."
|
148 |
+
)
|
149 |
+
for (fid, fval) in vector:
|
150 |
+
if bernoulli:
|
151 |
+
if fval == 1:
|
152 |
+
stream.write(" %s" % fid)
|
153 |
+
elif fval != 0:
|
154 |
+
raise ValueError(
|
155 |
+
"If bernoulli=True, then all" "features must be binary."
|
156 |
+
)
|
157 |
+
else:
|
158 |
+
stream.write(f" {fid} {fval}")
|
159 |
+
|
160 |
+
|
161 |
+
def call_megam(args):
|
162 |
+
"""
|
163 |
+
Call the ``megam`` binary with the given arguments.
|
164 |
+
"""
|
165 |
+
if isinstance(args, str):
|
166 |
+
raise TypeError("args should be a list of strings")
|
167 |
+
if _megam_bin is None:
|
168 |
+
config_megam()
|
169 |
+
|
170 |
+
# Call megam via a subprocess
|
171 |
+
cmd = [_megam_bin] + args
|
172 |
+
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
|
173 |
+
(stdout, stderr) = p.communicate()
|
174 |
+
|
175 |
+
# Check the return code.
|
176 |
+
if p.returncode != 0:
|
177 |
+
print()
|
178 |
+
print(stderr)
|
179 |
+
raise OSError("megam command failed!")
|
180 |
+
|
181 |
+
if isinstance(stdout, str):
|
182 |
+
return stdout
|
183 |
+
else:
|
184 |
+
return stdout.decode("utf-8")
|
env-llmeval/lib/python3.10/site-packages/nltk/classify/naivebayes.py
ADDED
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Naive Bayes Classifiers
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Edward Loper <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
|
8 |
+
"""
|
9 |
+
A classifier based on the Naive Bayes algorithm. In order to find the
|
10 |
+
probability for a label, this algorithm first uses the Bayes rule to
|
11 |
+
express P(label|features) in terms of P(label) and P(features|label):
|
12 |
+
|
13 |
+
| P(label) * P(features|label)
|
14 |
+
| P(label|features) = ------------------------------
|
15 |
+
| P(features)
|
16 |
+
|
17 |
+
The algorithm then makes the 'naive' assumption that all features are
|
18 |
+
independent, given the label:
|
19 |
+
|
20 |
+
| P(label) * P(f1|label) * ... * P(fn|label)
|
21 |
+
| P(label|features) = --------------------------------------------
|
22 |
+
| P(features)
|
23 |
+
|
24 |
+
Rather than computing P(features) explicitly, the algorithm just
|
25 |
+
calculates the numerator for each label, and normalizes them so they
|
26 |
+
sum to one:
|
27 |
+
|
28 |
+
| P(label) * P(f1|label) * ... * P(fn|label)
|
29 |
+
| P(label|features) = --------------------------------------------
|
30 |
+
| SUM[l]( P(l) * P(f1|l) * ... * P(fn|l) )
|
31 |
+
"""
|
32 |
+
|
33 |
+
from collections import defaultdict
|
34 |
+
|
35 |
+
from nltk.classify.api import ClassifierI
|
36 |
+
from nltk.probability import DictionaryProbDist, ELEProbDist, FreqDist, sum_logs
|
37 |
+
|
38 |
+
##//////////////////////////////////////////////////////
|
39 |
+
## Naive Bayes Classifier
|
40 |
+
##//////////////////////////////////////////////////////
|
41 |
+
|
42 |
+
|
43 |
+
class NaiveBayesClassifier(ClassifierI):
|
44 |
+
"""
|
45 |
+
A Naive Bayes classifier. Naive Bayes classifiers are
|
46 |
+
paramaterized by two probability distributions:
|
47 |
+
|
48 |
+
- P(label) gives the probability that an input will receive each
|
49 |
+
label, given no information about the input's features.
|
50 |
+
|
51 |
+
- P(fname=fval|label) gives the probability that a given feature
|
52 |
+
(fname) will receive a given value (fval), given that the
|
53 |
+
label (label).
|
54 |
+
|
55 |
+
If the classifier encounters an input with a feature that has
|
56 |
+
never been seen with any label, then rather than assigning a
|
57 |
+
probability of 0 to all labels, it will ignore that feature.
|
58 |
+
|
59 |
+
The feature value 'None' is reserved for unseen feature values;
|
60 |
+
you generally should not use 'None' as a feature value for one of
|
61 |
+
your own features.
|
62 |
+
"""
|
63 |
+
|
64 |
+
def __init__(self, label_probdist, feature_probdist):
|
65 |
+
"""
|
66 |
+
:param label_probdist: P(label), the probability distribution
|
67 |
+
over labels. It is expressed as a ``ProbDistI`` whose
|
68 |
+
samples are labels. I.e., P(label) =
|
69 |
+
``label_probdist.prob(label)``.
|
70 |
+
|
71 |
+
:param feature_probdist: P(fname=fval|label), the probability
|
72 |
+
distribution for feature values, given labels. It is
|
73 |
+
expressed as a dictionary whose keys are ``(label, fname)``
|
74 |
+
pairs and whose values are ``ProbDistI`` objects over feature
|
75 |
+
values. I.e., P(fname=fval|label) =
|
76 |
+
``feature_probdist[label,fname].prob(fval)``. If a given
|
77 |
+
``(label,fname)`` is not a key in ``feature_probdist``, then
|
78 |
+
it is assumed that the corresponding P(fname=fval|label)
|
79 |
+
is 0 for all values of ``fval``.
|
80 |
+
"""
|
81 |
+
self._label_probdist = label_probdist
|
82 |
+
self._feature_probdist = feature_probdist
|
83 |
+
self._labels = list(label_probdist.samples())
|
84 |
+
|
85 |
+
def labels(self):
|
86 |
+
return self._labels
|
87 |
+
|
88 |
+
def classify(self, featureset):
|
89 |
+
return self.prob_classify(featureset).max()
|
90 |
+
|
91 |
+
def prob_classify(self, featureset):
|
92 |
+
# Discard any feature names that we've never seen before.
|
93 |
+
# Otherwise, we'll just assign a probability of 0 to
|
94 |
+
# everything.
|
95 |
+
featureset = featureset.copy()
|
96 |
+
for fname in list(featureset.keys()):
|
97 |
+
for label in self._labels:
|
98 |
+
if (label, fname) in self._feature_probdist:
|
99 |
+
break
|
100 |
+
else:
|
101 |
+
# print('Ignoring unseen feature %s' % fname)
|
102 |
+
del featureset[fname]
|
103 |
+
|
104 |
+
# Find the log probability of each label, given the features.
|
105 |
+
# Start with the log probability of the label itself.
|
106 |
+
logprob = {}
|
107 |
+
for label in self._labels:
|
108 |
+
logprob[label] = self._label_probdist.logprob(label)
|
109 |
+
|
110 |
+
# Then add in the log probability of features given labels.
|
111 |
+
for label in self._labels:
|
112 |
+
for (fname, fval) in featureset.items():
|
113 |
+
if (label, fname) in self._feature_probdist:
|
114 |
+
feature_probs = self._feature_probdist[label, fname]
|
115 |
+
logprob[label] += feature_probs.logprob(fval)
|
116 |
+
else:
|
117 |
+
# nb: This case will never come up if the
|
118 |
+
# classifier was created by
|
119 |
+
# NaiveBayesClassifier.train().
|
120 |
+
logprob[label] += sum_logs([]) # = -INF.
|
121 |
+
|
122 |
+
return DictionaryProbDist(logprob, normalize=True, log=True)
|
123 |
+
|
124 |
+
def show_most_informative_features(self, n=10):
|
125 |
+
# Determine the most relevant features, and display them.
|
126 |
+
cpdist = self._feature_probdist
|
127 |
+
print("Most Informative Features")
|
128 |
+
|
129 |
+
for (fname, fval) in self.most_informative_features(n):
|
130 |
+
|
131 |
+
def labelprob(l):
|
132 |
+
return cpdist[l, fname].prob(fval)
|
133 |
+
|
134 |
+
labels = sorted(
|
135 |
+
(l for l in self._labels if fval in cpdist[l, fname].samples()),
|
136 |
+
key=lambda element: (-labelprob(element), element),
|
137 |
+
reverse=True,
|
138 |
+
)
|
139 |
+
if len(labels) == 1:
|
140 |
+
continue
|
141 |
+
l0 = labels[0]
|
142 |
+
l1 = labels[-1]
|
143 |
+
if cpdist[l0, fname].prob(fval) == 0:
|
144 |
+
ratio = "INF"
|
145 |
+
else:
|
146 |
+
ratio = "%8.1f" % (
|
147 |
+
cpdist[l1, fname].prob(fval) / cpdist[l0, fname].prob(fval)
|
148 |
+
)
|
149 |
+
print(
|
150 |
+
"%24s = %-14r %6s : %-6s = %s : 1.0"
|
151 |
+
% (fname, fval, ("%s" % l1)[:6], ("%s" % l0)[:6], ratio)
|
152 |
+
)
|
153 |
+
|
154 |
+
def most_informative_features(self, n=100):
|
155 |
+
"""
|
156 |
+
Return a list of the 'most informative' features used by this
|
157 |
+
classifier. For the purpose of this function, the
|
158 |
+
informativeness of a feature ``(fname,fval)`` is equal to the
|
159 |
+
highest value of P(fname=fval|label), for any label, divided by
|
160 |
+
the lowest value of P(fname=fval|label), for any label:
|
161 |
+
|
162 |
+
| max[ P(fname=fval|label1) / P(fname=fval|label2) ]
|
163 |
+
"""
|
164 |
+
if hasattr(self, "_most_informative_features"):
|
165 |
+
return self._most_informative_features[:n]
|
166 |
+
else:
|
167 |
+
# The set of (fname, fval) pairs used by this classifier.
|
168 |
+
features = set()
|
169 |
+
# The max & min probability associated w/ each (fname, fval)
|
170 |
+
# pair. Maps (fname,fval) -> float.
|
171 |
+
maxprob = defaultdict(lambda: 0.0)
|
172 |
+
minprob = defaultdict(lambda: 1.0)
|
173 |
+
|
174 |
+
for (label, fname), probdist in self._feature_probdist.items():
|
175 |
+
for fval in probdist.samples():
|
176 |
+
feature = (fname, fval)
|
177 |
+
features.add(feature)
|
178 |
+
p = probdist.prob(fval)
|
179 |
+
maxprob[feature] = max(p, maxprob[feature])
|
180 |
+
minprob[feature] = min(p, minprob[feature])
|
181 |
+
if minprob[feature] == 0:
|
182 |
+
features.discard(feature)
|
183 |
+
|
184 |
+
# Convert features to a list, & sort it by how informative
|
185 |
+
# features are.
|
186 |
+
self._most_informative_features = sorted(
|
187 |
+
features,
|
188 |
+
key=lambda feature_: (
|
189 |
+
minprob[feature_] / maxprob[feature_],
|
190 |
+
feature_[0],
|
191 |
+
feature_[1] in [None, False, True],
|
192 |
+
str(feature_[1]).lower(),
|
193 |
+
),
|
194 |
+
)
|
195 |
+
return self._most_informative_features[:n]
|
196 |
+
|
197 |
+
@classmethod
|
198 |
+
def train(cls, labeled_featuresets, estimator=ELEProbDist):
|
199 |
+
"""
|
200 |
+
:param labeled_featuresets: A list of classified featuresets,
|
201 |
+
i.e., a list of tuples ``(featureset, label)``.
|
202 |
+
"""
|
203 |
+
label_freqdist = FreqDist()
|
204 |
+
feature_freqdist = defaultdict(FreqDist)
|
205 |
+
feature_values = defaultdict(set)
|
206 |
+
fnames = set()
|
207 |
+
|
208 |
+
# Count up how many times each feature value occurred, given
|
209 |
+
# the label and featurename.
|
210 |
+
for featureset, label in labeled_featuresets:
|
211 |
+
label_freqdist[label] += 1
|
212 |
+
for fname, fval in featureset.items():
|
213 |
+
# Increment freq(fval|label, fname)
|
214 |
+
feature_freqdist[label, fname][fval] += 1
|
215 |
+
# Record that fname can take the value fval.
|
216 |
+
feature_values[fname].add(fval)
|
217 |
+
# Keep a list of all feature names.
|
218 |
+
fnames.add(fname)
|
219 |
+
|
220 |
+
# If a feature didn't have a value given for an instance, then
|
221 |
+
# we assume that it gets the implicit value 'None.' This loop
|
222 |
+
# counts up the number of 'missing' feature values for each
|
223 |
+
# (label,fname) pair, and increments the count of the fval
|
224 |
+
# 'None' by that amount.
|
225 |
+
for label in label_freqdist:
|
226 |
+
num_samples = label_freqdist[label]
|
227 |
+
for fname in fnames:
|
228 |
+
count = feature_freqdist[label, fname].N()
|
229 |
+
# Only add a None key when necessary, i.e. if there are
|
230 |
+
# any samples with feature 'fname' missing.
|
231 |
+
if num_samples - count > 0:
|
232 |
+
feature_freqdist[label, fname][None] += num_samples - count
|
233 |
+
feature_values[fname].add(None)
|
234 |
+
|
235 |
+
# Create the P(label) distribution
|
236 |
+
label_probdist = estimator(label_freqdist)
|
237 |
+
|
238 |
+
# Create the P(fval|label, fname) distribution
|
239 |
+
feature_probdist = {}
|
240 |
+
for ((label, fname), freqdist) in feature_freqdist.items():
|
241 |
+
probdist = estimator(freqdist, bins=len(feature_values[fname]))
|
242 |
+
feature_probdist[label, fname] = probdist
|
243 |
+
|
244 |
+
return cls(label_probdist, feature_probdist)
|
245 |
+
|
246 |
+
|
247 |
+
##//////////////////////////////////////////////////////
|
248 |
+
## Demo
|
249 |
+
##//////////////////////////////////////////////////////
|
250 |
+
|
251 |
+
|
252 |
+
def demo():
|
253 |
+
from nltk.classify.util import names_demo
|
254 |
+
|
255 |
+
classifier = names_demo(NaiveBayesClassifier.train)
|
256 |
+
classifier.show_most_informative_features()
|
257 |
+
|
258 |
+
|
259 |
+
if __name__ == "__main__":
|
260 |
+
demo()
|
env-llmeval/lib/python3.10/site-packages/nltk/classify/positivenaivebayes.py
ADDED
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Positive Naive Bayes Classifier
|
2 |
+
#
|
3 |
+
# Copyright (C) 2012 NLTK Project
|
4 |
+
# Author: Alessandro Presta <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
|
8 |
+
"""
|
9 |
+
A variant of the Naive Bayes Classifier that performs binary classification with
|
10 |
+
partially-labeled training sets. In other words, assume we want to build a classifier
|
11 |
+
that assigns each example to one of two complementary classes (e.g., male names and
|
12 |
+
female names).
|
13 |
+
If we have a training set with labeled examples for both classes, we can use a
|
14 |
+
standard Naive Bayes Classifier. However, consider the case when we only have labeled
|
15 |
+
examples for one of the classes, and other, unlabeled, examples.
|
16 |
+
Then, assuming a prior distribution on the two labels, we can use the unlabeled set
|
17 |
+
to estimate the frequencies of the various features.
|
18 |
+
|
19 |
+
Let the two possible labels be 1 and 0, and let's say we only have examples labeled 1
|
20 |
+
and unlabeled examples. We are also given an estimate of P(1).
|
21 |
+
|
22 |
+
We compute P(feature|1) exactly as in the standard case.
|
23 |
+
|
24 |
+
To compute P(feature|0), we first estimate P(feature) from the unlabeled set (we are
|
25 |
+
assuming that the unlabeled examples are drawn according to the given prior distribution)
|
26 |
+
and then express the conditional probability as:
|
27 |
+
|
28 |
+
| P(feature) - P(feature|1) * P(1)
|
29 |
+
| P(feature|0) = ----------------------------------
|
30 |
+
| P(0)
|
31 |
+
|
32 |
+
Example:
|
33 |
+
|
34 |
+
>>> from nltk.classify import PositiveNaiveBayesClassifier
|
35 |
+
|
36 |
+
Some sentences about sports:
|
37 |
+
|
38 |
+
>>> sports_sentences = [ 'The team dominated the game',
|
39 |
+
... 'They lost the ball',
|
40 |
+
... 'The game was intense',
|
41 |
+
... 'The goalkeeper catched the ball',
|
42 |
+
... 'The other team controlled the ball' ]
|
43 |
+
|
44 |
+
Mixed topics, including sports:
|
45 |
+
|
46 |
+
>>> various_sentences = [ 'The President did not comment',
|
47 |
+
... 'I lost the keys',
|
48 |
+
... 'The team won the game',
|
49 |
+
... 'Sara has two kids',
|
50 |
+
... 'The ball went off the court',
|
51 |
+
... 'They had the ball for the whole game',
|
52 |
+
... 'The show is over' ]
|
53 |
+
|
54 |
+
The features of a sentence are simply the words it contains:
|
55 |
+
|
56 |
+
>>> def features(sentence):
|
57 |
+
... words = sentence.lower().split()
|
58 |
+
... return dict(('contains(%s)' % w, True) for w in words)
|
59 |
+
|
60 |
+
We use the sports sentences as positive examples, the mixed ones ad unlabeled examples:
|
61 |
+
|
62 |
+
>>> positive_featuresets = map(features, sports_sentences)
|
63 |
+
>>> unlabeled_featuresets = map(features, various_sentences)
|
64 |
+
>>> classifier = PositiveNaiveBayesClassifier.train(positive_featuresets,
|
65 |
+
... unlabeled_featuresets)
|
66 |
+
|
67 |
+
Is the following sentence about sports?
|
68 |
+
|
69 |
+
>>> classifier.classify(features('The cat is on the table'))
|
70 |
+
False
|
71 |
+
|
72 |
+
What about this one?
|
73 |
+
|
74 |
+
>>> classifier.classify(features('My team lost the game'))
|
75 |
+
True
|
76 |
+
"""
|
77 |
+
|
78 |
+
from collections import defaultdict
|
79 |
+
|
80 |
+
from nltk.classify.naivebayes import NaiveBayesClassifier
|
81 |
+
from nltk.probability import DictionaryProbDist, ELEProbDist, FreqDist
|
82 |
+
|
83 |
+
##//////////////////////////////////////////////////////
|
84 |
+
## Positive Naive Bayes Classifier
|
85 |
+
##//////////////////////////////////////////////////////
|
86 |
+
|
87 |
+
|
88 |
+
class PositiveNaiveBayesClassifier(NaiveBayesClassifier):
|
89 |
+
@staticmethod
|
90 |
+
def train(
|
91 |
+
positive_featuresets,
|
92 |
+
unlabeled_featuresets,
|
93 |
+
positive_prob_prior=0.5,
|
94 |
+
estimator=ELEProbDist,
|
95 |
+
):
|
96 |
+
"""
|
97 |
+
:param positive_featuresets: An iterable of featuresets that are known as positive
|
98 |
+
examples (i.e., their label is ``True``).
|
99 |
+
|
100 |
+
:param unlabeled_featuresets: An iterable of featuresets whose label is unknown.
|
101 |
+
|
102 |
+
:param positive_prob_prior: A prior estimate of the probability of the label
|
103 |
+
``True`` (default 0.5).
|
104 |
+
"""
|
105 |
+
positive_feature_freqdist = defaultdict(FreqDist)
|
106 |
+
unlabeled_feature_freqdist = defaultdict(FreqDist)
|
107 |
+
feature_values = defaultdict(set)
|
108 |
+
fnames = set()
|
109 |
+
|
110 |
+
# Count up how many times each feature value occurred in positive examples.
|
111 |
+
num_positive_examples = 0
|
112 |
+
for featureset in positive_featuresets:
|
113 |
+
for fname, fval in featureset.items():
|
114 |
+
positive_feature_freqdist[fname][fval] += 1
|
115 |
+
feature_values[fname].add(fval)
|
116 |
+
fnames.add(fname)
|
117 |
+
num_positive_examples += 1
|
118 |
+
|
119 |
+
# Count up how many times each feature value occurred in unlabeled examples.
|
120 |
+
num_unlabeled_examples = 0
|
121 |
+
for featureset in unlabeled_featuresets:
|
122 |
+
for fname, fval in featureset.items():
|
123 |
+
unlabeled_feature_freqdist[fname][fval] += 1
|
124 |
+
feature_values[fname].add(fval)
|
125 |
+
fnames.add(fname)
|
126 |
+
num_unlabeled_examples += 1
|
127 |
+
|
128 |
+
# If a feature didn't have a value given for an instance, then we assume that
|
129 |
+
# it gets the implicit value 'None'.
|
130 |
+
for fname in fnames:
|
131 |
+
count = positive_feature_freqdist[fname].N()
|
132 |
+
positive_feature_freqdist[fname][None] += num_positive_examples - count
|
133 |
+
feature_values[fname].add(None)
|
134 |
+
|
135 |
+
for fname in fnames:
|
136 |
+
count = unlabeled_feature_freqdist[fname].N()
|
137 |
+
unlabeled_feature_freqdist[fname][None] += num_unlabeled_examples - count
|
138 |
+
feature_values[fname].add(None)
|
139 |
+
|
140 |
+
negative_prob_prior = 1.0 - positive_prob_prior
|
141 |
+
|
142 |
+
# Create the P(label) distribution.
|
143 |
+
label_probdist = DictionaryProbDist(
|
144 |
+
{True: positive_prob_prior, False: negative_prob_prior}
|
145 |
+
)
|
146 |
+
|
147 |
+
# Create the P(fval|label, fname) distribution.
|
148 |
+
feature_probdist = {}
|
149 |
+
for fname, freqdist in positive_feature_freqdist.items():
|
150 |
+
probdist = estimator(freqdist, bins=len(feature_values[fname]))
|
151 |
+
feature_probdist[True, fname] = probdist
|
152 |
+
|
153 |
+
for fname, freqdist in unlabeled_feature_freqdist.items():
|
154 |
+
global_probdist = estimator(freqdist, bins=len(feature_values[fname]))
|
155 |
+
negative_feature_probs = {}
|
156 |
+
for fval in feature_values[fname]:
|
157 |
+
prob = (
|
158 |
+
global_probdist.prob(fval)
|
159 |
+
- positive_prob_prior * feature_probdist[True, fname].prob(fval)
|
160 |
+
) / negative_prob_prior
|
161 |
+
# TODO: We need to add some kind of smoothing here, instead of
|
162 |
+
# setting negative probabilities to zero and normalizing.
|
163 |
+
negative_feature_probs[fval] = max(prob, 0.0)
|
164 |
+
feature_probdist[False, fname] = DictionaryProbDist(
|
165 |
+
negative_feature_probs, normalize=True
|
166 |
+
)
|
167 |
+
|
168 |
+
return PositiveNaiveBayesClassifier(label_probdist, feature_probdist)
|
169 |
+
|
170 |
+
|
171 |
+
##//////////////////////////////////////////////////////
|
172 |
+
## Demo
|
173 |
+
##//////////////////////////////////////////////////////
|
174 |
+
|
175 |
+
|
176 |
+
def demo():
|
177 |
+
from nltk.classify.util import partial_names_demo
|
178 |
+
|
179 |
+
classifier = partial_names_demo(PositiveNaiveBayesClassifier.train)
|
180 |
+
classifier.show_most_informative_features()
|
env-llmeval/lib/python3.10/site-packages/nltk/classify/rte_classify.py
ADDED
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: RTE Classifier
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Ewan Klein <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
|
8 |
+
"""
|
9 |
+
Simple classifier for RTE corpus.
|
10 |
+
|
11 |
+
It calculates the overlap in words and named entities between text and
|
12 |
+
hypothesis, and also whether there are words / named entities in the
|
13 |
+
hypothesis which fail to occur in the text, since this is an indicator that
|
14 |
+
the hypothesis is more informative than (i.e not entailed by) the text.
|
15 |
+
|
16 |
+
TO DO: better Named Entity classification
|
17 |
+
TO DO: add lemmatization
|
18 |
+
"""
|
19 |
+
|
20 |
+
from nltk.classify.maxent import MaxentClassifier
|
21 |
+
from nltk.classify.util import accuracy
|
22 |
+
from nltk.tokenize import RegexpTokenizer
|
23 |
+
|
24 |
+
|
25 |
+
class RTEFeatureExtractor:
|
26 |
+
"""
|
27 |
+
This builds a bag of words for both the text and the hypothesis after
|
28 |
+
throwing away some stopwords, then calculates overlap and difference.
|
29 |
+
"""
|
30 |
+
|
31 |
+
def __init__(self, rtepair, stop=True, use_lemmatize=False):
|
32 |
+
"""
|
33 |
+
:param rtepair: a ``RTEPair`` from which features should be extracted
|
34 |
+
:param stop: if ``True``, stopwords are thrown away.
|
35 |
+
:type stop: bool
|
36 |
+
"""
|
37 |
+
self.stop = stop
|
38 |
+
self.stopwords = {
|
39 |
+
"a",
|
40 |
+
"the",
|
41 |
+
"it",
|
42 |
+
"they",
|
43 |
+
"of",
|
44 |
+
"in",
|
45 |
+
"to",
|
46 |
+
"is",
|
47 |
+
"have",
|
48 |
+
"are",
|
49 |
+
"were",
|
50 |
+
"and",
|
51 |
+
"very",
|
52 |
+
".",
|
53 |
+
",",
|
54 |
+
}
|
55 |
+
|
56 |
+
self.negwords = {"no", "not", "never", "failed", "rejected", "denied"}
|
57 |
+
# Try to tokenize so that abbreviations, monetary amounts, email
|
58 |
+
# addresses, URLs are single tokens.
|
59 |
+
tokenizer = RegexpTokenizer(r"[\w.@:/]+|\w+|\$[\d.]+")
|
60 |
+
|
61 |
+
# Get the set of word types for text and hypothesis
|
62 |
+
self.text_tokens = tokenizer.tokenize(rtepair.text)
|
63 |
+
self.hyp_tokens = tokenizer.tokenize(rtepair.hyp)
|
64 |
+
self.text_words = set(self.text_tokens)
|
65 |
+
self.hyp_words = set(self.hyp_tokens)
|
66 |
+
|
67 |
+
if use_lemmatize:
|
68 |
+
self.text_words = {self._lemmatize(token) for token in self.text_tokens}
|
69 |
+
self.hyp_words = {self._lemmatize(token) for token in self.hyp_tokens}
|
70 |
+
|
71 |
+
if self.stop:
|
72 |
+
self.text_words = self.text_words - self.stopwords
|
73 |
+
self.hyp_words = self.hyp_words - self.stopwords
|
74 |
+
|
75 |
+
self._overlap = self.hyp_words & self.text_words
|
76 |
+
self._hyp_extra = self.hyp_words - self.text_words
|
77 |
+
self._txt_extra = self.text_words - self.hyp_words
|
78 |
+
|
79 |
+
def overlap(self, toktype, debug=False):
|
80 |
+
"""
|
81 |
+
Compute the overlap between text and hypothesis.
|
82 |
+
|
83 |
+
:param toktype: distinguish Named Entities from ordinary words
|
84 |
+
:type toktype: 'ne' or 'word'
|
85 |
+
"""
|
86 |
+
ne_overlap = {token for token in self._overlap if self._ne(token)}
|
87 |
+
if toktype == "ne":
|
88 |
+
if debug:
|
89 |
+
print("ne overlap", ne_overlap)
|
90 |
+
return ne_overlap
|
91 |
+
elif toktype == "word":
|
92 |
+
if debug:
|
93 |
+
print("word overlap", self._overlap - ne_overlap)
|
94 |
+
return self._overlap - ne_overlap
|
95 |
+
else:
|
96 |
+
raise ValueError("Type not recognized:'%s'" % toktype)
|
97 |
+
|
98 |
+
def hyp_extra(self, toktype, debug=True):
|
99 |
+
"""
|
100 |
+
Compute the extraneous material in the hypothesis.
|
101 |
+
|
102 |
+
:param toktype: distinguish Named Entities from ordinary words
|
103 |
+
:type toktype: 'ne' or 'word'
|
104 |
+
"""
|
105 |
+
ne_extra = {token for token in self._hyp_extra if self._ne(token)}
|
106 |
+
if toktype == "ne":
|
107 |
+
return ne_extra
|
108 |
+
elif toktype == "word":
|
109 |
+
return self._hyp_extra - ne_extra
|
110 |
+
else:
|
111 |
+
raise ValueError("Type not recognized: '%s'" % toktype)
|
112 |
+
|
113 |
+
@staticmethod
|
114 |
+
def _ne(token):
|
115 |
+
"""
|
116 |
+
This just assumes that words in all caps or titles are
|
117 |
+
named entities.
|
118 |
+
|
119 |
+
:type token: str
|
120 |
+
"""
|
121 |
+
if token.istitle() or token.isupper():
|
122 |
+
return True
|
123 |
+
return False
|
124 |
+
|
125 |
+
@staticmethod
|
126 |
+
def _lemmatize(word):
|
127 |
+
"""
|
128 |
+
Use morphy from WordNet to find the base form of verbs.
|
129 |
+
"""
|
130 |
+
from nltk.corpus import wordnet as wn
|
131 |
+
|
132 |
+
lemma = wn.morphy(word, pos=wn.VERB)
|
133 |
+
if lemma is not None:
|
134 |
+
return lemma
|
135 |
+
return word
|
136 |
+
|
137 |
+
|
138 |
+
def rte_features(rtepair):
|
139 |
+
extractor = RTEFeatureExtractor(rtepair)
|
140 |
+
features = {}
|
141 |
+
features["alwayson"] = True
|
142 |
+
features["word_overlap"] = len(extractor.overlap("word"))
|
143 |
+
features["word_hyp_extra"] = len(extractor.hyp_extra("word"))
|
144 |
+
features["ne_overlap"] = len(extractor.overlap("ne"))
|
145 |
+
features["ne_hyp_extra"] = len(extractor.hyp_extra("ne"))
|
146 |
+
features["neg_txt"] = len(extractor.negwords & extractor.text_words)
|
147 |
+
features["neg_hyp"] = len(extractor.negwords & extractor.hyp_words)
|
148 |
+
return features
|
149 |
+
|
150 |
+
|
151 |
+
def rte_featurize(rte_pairs):
|
152 |
+
return [(rte_features(pair), pair.value) for pair in rte_pairs]
|
153 |
+
|
154 |
+
|
155 |
+
def rte_classifier(algorithm, sample_N=None):
|
156 |
+
from nltk.corpus import rte as rte_corpus
|
157 |
+
|
158 |
+
train_set = rte_corpus.pairs(["rte1_dev.xml", "rte2_dev.xml", "rte3_dev.xml"])
|
159 |
+
test_set = rte_corpus.pairs(["rte1_test.xml", "rte2_test.xml", "rte3_test.xml"])
|
160 |
+
|
161 |
+
if sample_N is not None:
|
162 |
+
train_set = train_set[:sample_N]
|
163 |
+
test_set = test_set[:sample_N]
|
164 |
+
|
165 |
+
featurized_train_set = rte_featurize(train_set)
|
166 |
+
featurized_test_set = rte_featurize(test_set)
|
167 |
+
|
168 |
+
# Train the classifier
|
169 |
+
print("Training classifier...")
|
170 |
+
if algorithm in ["megam"]: # MEGAM based algorithms.
|
171 |
+
clf = MaxentClassifier.train(featurized_train_set, algorithm)
|
172 |
+
elif algorithm in ["GIS", "IIS"]: # Use default GIS/IIS MaxEnt algorithm
|
173 |
+
clf = MaxentClassifier.train(featurized_train_set, algorithm)
|
174 |
+
else:
|
175 |
+
err_msg = str(
|
176 |
+
"RTEClassifier only supports these algorithms:\n "
|
177 |
+
"'megam', 'GIS', 'IIS'.\n"
|
178 |
+
)
|
179 |
+
raise Exception(err_msg)
|
180 |
+
print("Testing classifier...")
|
181 |
+
acc = accuracy(clf, featurized_test_set)
|
182 |
+
print("Accuracy: %6.4f" % acc)
|
183 |
+
return clf
|
env-llmeval/lib/python3.10/site-packages/nltk/classify/scikitlearn.py
ADDED
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Interface to scikit-learn classifiers
|
2 |
+
#
|
3 |
+
# Author: Lars Buitinck <[email protected]>
|
4 |
+
# URL: <https://www.nltk.org/>
|
5 |
+
# For license information, see LICENSE.TXT
|
6 |
+
"""
|
7 |
+
scikit-learn (https://scikit-learn.org) is a machine learning library for
|
8 |
+
Python. It supports many classification algorithms, including SVMs,
|
9 |
+
Naive Bayes, logistic regression (MaxEnt) and decision trees.
|
10 |
+
|
11 |
+
This package implements a wrapper around scikit-learn classifiers. To use this
|
12 |
+
wrapper, construct a scikit-learn estimator object, then use that to construct
|
13 |
+
a SklearnClassifier. E.g., to wrap a linear SVM with default settings:
|
14 |
+
|
15 |
+
>>> from sklearn.svm import LinearSVC
|
16 |
+
>>> from nltk.classify.scikitlearn import SklearnClassifier
|
17 |
+
>>> classif = SklearnClassifier(LinearSVC())
|
18 |
+
|
19 |
+
A scikit-learn classifier may include preprocessing steps when it's wrapped
|
20 |
+
in a Pipeline object. The following constructs and wraps a Naive Bayes text
|
21 |
+
classifier with tf-idf weighting and chi-square feature selection to get the
|
22 |
+
best 1000 features:
|
23 |
+
|
24 |
+
>>> from sklearn.feature_extraction.text import TfidfTransformer
|
25 |
+
>>> from sklearn.feature_selection import SelectKBest, chi2
|
26 |
+
>>> from sklearn.naive_bayes import MultinomialNB
|
27 |
+
>>> from sklearn.pipeline import Pipeline
|
28 |
+
>>> pipeline = Pipeline([('tfidf', TfidfTransformer()),
|
29 |
+
... ('chi2', SelectKBest(chi2, k=1000)),
|
30 |
+
... ('nb', MultinomialNB())])
|
31 |
+
>>> classif = SklearnClassifier(pipeline)
|
32 |
+
"""
|
33 |
+
|
34 |
+
from nltk.classify.api import ClassifierI
|
35 |
+
from nltk.probability import DictionaryProbDist
|
36 |
+
|
37 |
+
try:
|
38 |
+
from sklearn.feature_extraction import DictVectorizer
|
39 |
+
from sklearn.preprocessing import LabelEncoder
|
40 |
+
except ImportError:
|
41 |
+
pass
|
42 |
+
|
43 |
+
__all__ = ["SklearnClassifier"]
|
44 |
+
|
45 |
+
|
46 |
+
class SklearnClassifier(ClassifierI):
|
47 |
+
"""Wrapper for scikit-learn classifiers."""
|
48 |
+
|
49 |
+
def __init__(self, estimator, dtype=float, sparse=True):
|
50 |
+
"""
|
51 |
+
:param estimator: scikit-learn classifier object.
|
52 |
+
|
53 |
+
:param dtype: data type used when building feature array.
|
54 |
+
scikit-learn estimators work exclusively on numeric data. The
|
55 |
+
default value should be fine for almost all situations.
|
56 |
+
|
57 |
+
:param sparse: Whether to use sparse matrices internally.
|
58 |
+
The estimator must support these; not all scikit-learn classifiers
|
59 |
+
do (see their respective documentation and look for "sparse
|
60 |
+
matrix"). The default value is True, since most NLP problems
|
61 |
+
involve sparse feature sets. Setting this to False may take a
|
62 |
+
great amount of memory.
|
63 |
+
:type sparse: boolean.
|
64 |
+
"""
|
65 |
+
self._clf = estimator
|
66 |
+
self._encoder = LabelEncoder()
|
67 |
+
self._vectorizer = DictVectorizer(dtype=dtype, sparse=sparse)
|
68 |
+
|
69 |
+
def __repr__(self):
|
70 |
+
return "<SklearnClassifier(%r)>" % self._clf
|
71 |
+
|
72 |
+
def classify_many(self, featuresets):
|
73 |
+
"""Classify a batch of samples.
|
74 |
+
|
75 |
+
:param featuresets: An iterable over featuresets, each a dict mapping
|
76 |
+
strings to either numbers, booleans or strings.
|
77 |
+
:return: The predicted class label for each input sample.
|
78 |
+
:rtype: list
|
79 |
+
"""
|
80 |
+
X = self._vectorizer.transform(featuresets)
|
81 |
+
classes = self._encoder.classes_
|
82 |
+
return [classes[i] for i in self._clf.predict(X)]
|
83 |
+
|
84 |
+
def prob_classify_many(self, featuresets):
|
85 |
+
"""Compute per-class probabilities for a batch of samples.
|
86 |
+
|
87 |
+
:param featuresets: An iterable over featuresets, each a dict mapping
|
88 |
+
strings to either numbers, booleans or strings.
|
89 |
+
:rtype: list of ``ProbDistI``
|
90 |
+
"""
|
91 |
+
X = self._vectorizer.transform(featuresets)
|
92 |
+
y_proba_list = self._clf.predict_proba(X)
|
93 |
+
return [self._make_probdist(y_proba) for y_proba in y_proba_list]
|
94 |
+
|
95 |
+
def labels(self):
|
96 |
+
"""The class labels used by this classifier.
|
97 |
+
|
98 |
+
:rtype: list
|
99 |
+
"""
|
100 |
+
return list(self._encoder.classes_)
|
101 |
+
|
102 |
+
def train(self, labeled_featuresets):
|
103 |
+
"""
|
104 |
+
Train (fit) the scikit-learn estimator.
|
105 |
+
|
106 |
+
:param labeled_featuresets: A list of ``(featureset, label)``
|
107 |
+
where each ``featureset`` is a dict mapping strings to either
|
108 |
+
numbers, booleans or strings.
|
109 |
+
"""
|
110 |
+
|
111 |
+
X, y = list(zip(*labeled_featuresets))
|
112 |
+
X = self._vectorizer.fit_transform(X)
|
113 |
+
y = self._encoder.fit_transform(y)
|
114 |
+
self._clf.fit(X, y)
|
115 |
+
|
116 |
+
return self
|
117 |
+
|
118 |
+
def _make_probdist(self, y_proba):
|
119 |
+
classes = self._encoder.classes_
|
120 |
+
return DictionaryProbDist({classes[i]: p for i, p in enumerate(y_proba)})
|
121 |
+
|
122 |
+
|
123 |
+
if __name__ == "__main__":
|
124 |
+
from sklearn.linear_model import LogisticRegression
|
125 |
+
from sklearn.naive_bayes import BernoulliNB
|
126 |
+
|
127 |
+
from nltk.classify.util import names_demo, names_demo_features
|
128 |
+
|
129 |
+
# Bernoulli Naive Bayes is designed for binary classification. We set the
|
130 |
+
# binarize option to False since we know we're passing boolean features.
|
131 |
+
print("scikit-learn Naive Bayes:")
|
132 |
+
names_demo(
|
133 |
+
SklearnClassifier(BernoulliNB(binarize=False)).train,
|
134 |
+
features=names_demo_features,
|
135 |
+
)
|
136 |
+
|
137 |
+
# The C parameter on logistic regression (MaxEnt) controls regularization.
|
138 |
+
# The higher it's set, the less regularized the classifier is.
|
139 |
+
print("\n\nscikit-learn logistic regression:")
|
140 |
+
names_demo(
|
141 |
+
SklearnClassifier(LogisticRegression(C=1000)).train,
|
142 |
+
features=names_demo_features,
|
143 |
+
)
|
env-llmeval/lib/python3.10/site-packages/nltk/classify/senna.py
ADDED
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Senna Interface
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Rami Al-Rfou' <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
|
8 |
+
"""
|
9 |
+
A general interface to the SENNA pipeline that supports any of the
|
10 |
+
operations specified in SUPPORTED_OPERATIONS.
|
11 |
+
|
12 |
+
Applying multiple operations at once has the speed advantage. For example,
|
13 |
+
Senna will automatically determine POS tags if you are extracting named
|
14 |
+
entities. Applying both of the operations will cost only the time of
|
15 |
+
extracting the named entities.
|
16 |
+
|
17 |
+
The SENNA pipeline has a fixed maximum size of the sentences that it can read.
|
18 |
+
By default it is 1024 token/sentence. If you have larger sentences, changing
|
19 |
+
the MAX_SENTENCE_SIZE value in SENNA_main.c should be considered and your
|
20 |
+
system specific binary should be rebuilt. Otherwise this could introduce
|
21 |
+
misalignment errors.
|
22 |
+
|
23 |
+
The input is:
|
24 |
+
|
25 |
+
- path to the directory that contains SENNA executables. If the path is incorrect,
|
26 |
+
Senna will automatically search for executable file specified in SENNA environment variable
|
27 |
+
- List of the operations needed to be performed.
|
28 |
+
- (optionally) the encoding of the input data (default:utf-8)
|
29 |
+
|
30 |
+
Note: Unit tests for this module can be found in test/unit/test_senna.py
|
31 |
+
|
32 |
+
>>> from nltk.classify import Senna
|
33 |
+
>>> pipeline = Senna('/usr/share/senna-v3.0', ['pos', 'chk', 'ner']) # doctest: +SKIP
|
34 |
+
>>> sent = 'Dusseldorf is an international business center'.split()
|
35 |
+
>>> [(token['word'], token['chk'], token['ner'], token['pos']) for token in pipeline.tag(sent)] # doctest: +SKIP
|
36 |
+
[('Dusseldorf', 'B-NP', 'B-LOC', 'NNP'), ('is', 'B-VP', 'O', 'VBZ'), ('an', 'B-NP', 'O', 'DT'),
|
37 |
+
('international', 'I-NP', 'O', 'JJ'), ('business', 'I-NP', 'O', 'NN'), ('center', 'I-NP', 'O', 'NN')]
|
38 |
+
"""
|
39 |
+
|
40 |
+
from os import environ, path, sep
|
41 |
+
from platform import architecture, system
|
42 |
+
from subprocess import PIPE, Popen
|
43 |
+
|
44 |
+
from nltk.tag.api import TaggerI
|
45 |
+
|
46 |
+
|
47 |
+
class Senna(TaggerI):
|
48 |
+
|
49 |
+
SUPPORTED_OPERATIONS = ["pos", "chk", "ner"]
|
50 |
+
|
51 |
+
def __init__(self, senna_path, operations, encoding="utf-8"):
|
52 |
+
self._encoding = encoding
|
53 |
+
self._path = path.normpath(senna_path) + sep
|
54 |
+
|
55 |
+
# Verifies the existence of the executable on the self._path first
|
56 |
+
# senna_binary_file_1 = self.executable(self._path)
|
57 |
+
exe_file_1 = self.executable(self._path)
|
58 |
+
if not path.isfile(exe_file_1):
|
59 |
+
# Check for the system environment
|
60 |
+
if "SENNA" in environ:
|
61 |
+
# self._path = path.join(environ['SENNA'],'')
|
62 |
+
self._path = path.normpath(environ["SENNA"]) + sep
|
63 |
+
exe_file_2 = self.executable(self._path)
|
64 |
+
if not path.isfile(exe_file_2):
|
65 |
+
raise LookupError(
|
66 |
+
"Senna executable expected at %s or %s but not found"
|
67 |
+
% (exe_file_1, exe_file_2)
|
68 |
+
)
|
69 |
+
|
70 |
+
self.operations = operations
|
71 |
+
|
72 |
+
def executable(self, base_path):
|
73 |
+
"""
|
74 |
+
The function that determines the system specific binary that should be
|
75 |
+
used in the pipeline. In case, the system is not known the default senna binary will
|
76 |
+
be used.
|
77 |
+
"""
|
78 |
+
os_name = system()
|
79 |
+
if os_name == "Linux":
|
80 |
+
bits = architecture()[0]
|
81 |
+
if bits == "64bit":
|
82 |
+
return path.join(base_path, "senna-linux64")
|
83 |
+
return path.join(base_path, "senna-linux32")
|
84 |
+
if os_name == "Windows":
|
85 |
+
return path.join(base_path, "senna-win32.exe")
|
86 |
+
if os_name == "Darwin":
|
87 |
+
return path.join(base_path, "senna-osx")
|
88 |
+
return path.join(base_path, "senna")
|
89 |
+
|
90 |
+
def _map(self):
|
91 |
+
"""
|
92 |
+
A method that calculates the order of the columns that SENNA pipeline
|
93 |
+
will output the tags into. This depends on the operations being ordered.
|
94 |
+
"""
|
95 |
+
_map = {}
|
96 |
+
i = 1
|
97 |
+
for operation in Senna.SUPPORTED_OPERATIONS:
|
98 |
+
if operation in self.operations:
|
99 |
+
_map[operation] = i
|
100 |
+
i += 1
|
101 |
+
return _map
|
102 |
+
|
103 |
+
def tag(self, tokens):
|
104 |
+
"""
|
105 |
+
Applies the specified operation(s) on a list of tokens.
|
106 |
+
"""
|
107 |
+
return self.tag_sents([tokens])[0]
|
108 |
+
|
109 |
+
def tag_sents(self, sentences):
|
110 |
+
"""
|
111 |
+
Applies the tag method over a list of sentences. This method will return a
|
112 |
+
list of dictionaries. Every dictionary will contain a word with its
|
113 |
+
calculated annotations/tags.
|
114 |
+
"""
|
115 |
+
encoding = self._encoding
|
116 |
+
|
117 |
+
if not path.isfile(self.executable(self._path)):
|
118 |
+
raise LookupError(
|
119 |
+
"Senna executable expected at %s but not found"
|
120 |
+
% self.executable(self._path)
|
121 |
+
)
|
122 |
+
|
123 |
+
# Build the senna command to run the tagger
|
124 |
+
_senna_cmd = [
|
125 |
+
self.executable(self._path),
|
126 |
+
"-path",
|
127 |
+
self._path,
|
128 |
+
"-usrtokens",
|
129 |
+
"-iobtags",
|
130 |
+
]
|
131 |
+
_senna_cmd.extend(["-" + op for op in self.operations])
|
132 |
+
|
133 |
+
# Serialize the actual sentences to a temporary string
|
134 |
+
_input = "\n".join(" ".join(x) for x in sentences) + "\n"
|
135 |
+
if isinstance(_input, str) and encoding:
|
136 |
+
_input = _input.encode(encoding)
|
137 |
+
|
138 |
+
# Run the tagger and get the output
|
139 |
+
p = Popen(_senna_cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
|
140 |
+
(stdout, stderr) = p.communicate(input=_input)
|
141 |
+
senna_output = stdout
|
142 |
+
|
143 |
+
# Check the return code.
|
144 |
+
if p.returncode != 0:
|
145 |
+
raise RuntimeError("Senna command failed! Details: %s" % stderr)
|
146 |
+
|
147 |
+
if encoding:
|
148 |
+
senna_output = stdout.decode(encoding)
|
149 |
+
|
150 |
+
# Output the tagged sentences
|
151 |
+
map_ = self._map()
|
152 |
+
tagged_sentences = [[]]
|
153 |
+
sentence_index = 0
|
154 |
+
token_index = 0
|
155 |
+
for tagged_word in senna_output.strip().split("\n"):
|
156 |
+
if not tagged_word:
|
157 |
+
tagged_sentences.append([])
|
158 |
+
sentence_index += 1
|
159 |
+
token_index = 0
|
160 |
+
continue
|
161 |
+
tags = tagged_word.split("\t")
|
162 |
+
result = {}
|
163 |
+
for tag in map_:
|
164 |
+
result[tag] = tags[map_[tag]].strip()
|
165 |
+
try:
|
166 |
+
result["word"] = sentences[sentence_index][token_index]
|
167 |
+
except IndexError as e:
|
168 |
+
raise IndexError(
|
169 |
+
"Misalignment error occurred at sentence number %d. Possible reason"
|
170 |
+
" is that the sentence size exceeded the maximum size. Check the "
|
171 |
+
"documentation of Senna class for more information."
|
172 |
+
% sentence_index
|
173 |
+
) from e
|
174 |
+
tagged_sentences[-1].append(result)
|
175 |
+
token_index += 1
|
176 |
+
return tagged_sentences
|
env-llmeval/lib/python3.10/site-packages/nltk/classify/svm.py
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: SVM-based classifier
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Leon Derczynski <[email protected]>
|
5 |
+
#
|
6 |
+
# URL: <https://www.nltk.org/>
|
7 |
+
# For license information, see LICENSE.TXT
|
8 |
+
"""
|
9 |
+
nltk.classify.svm was deprecated. For classification based
|
10 |
+
on support vector machines SVMs use nltk.classify.scikitlearn
|
11 |
+
(or `scikit-learn <https://scikit-learn.org>`_ directly).
|
12 |
+
"""
|
13 |
+
|
14 |
+
|
15 |
+
class SvmClassifier:
|
16 |
+
def __init__(self, *args, **kwargs):
|
17 |
+
raise NotImplementedError(__doc__)
|
env-llmeval/lib/python3.10/site-packages/nltk/classify/textcat.py
ADDED
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Language ID module using TextCat algorithm
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Avital Pekker <[email protected]>
|
5 |
+
#
|
6 |
+
# URL: <https://www.nltk.org/>
|
7 |
+
# For license information, see LICENSE.TXT
|
8 |
+
|
9 |
+
"""
|
10 |
+
A module for language identification using the TextCat algorithm.
|
11 |
+
An implementation of the text categorization algorithm
|
12 |
+
presented in Cavnar, W. B. and J. M. Trenkle,
|
13 |
+
"N-Gram-Based Text Categorization".
|
14 |
+
|
15 |
+
The algorithm takes advantage of Zipf's law and uses
|
16 |
+
n-gram frequencies to profile languages and text-yet to
|
17 |
+
be identified-then compares using a distance measure.
|
18 |
+
|
19 |
+
Language n-grams are provided by the "An Crubadan"
|
20 |
+
project. A corpus reader was created separately to read
|
21 |
+
those files.
|
22 |
+
|
23 |
+
For details regarding the algorithm, see:
|
24 |
+
https://www.let.rug.nl/~vannoord/TextCat/textcat.pdf
|
25 |
+
|
26 |
+
For details about An Crubadan, see:
|
27 |
+
https://borel.slu.edu/crubadan/index.html
|
28 |
+
"""
|
29 |
+
|
30 |
+
from sys import maxsize
|
31 |
+
|
32 |
+
from nltk.util import trigrams
|
33 |
+
|
34 |
+
# Note: this is NOT "re" you're likely used to. The regex module
|
35 |
+
# is an alternative to the standard re module that supports
|
36 |
+
# Unicode codepoint properties with the \p{} syntax.
|
37 |
+
# You may have to "pip install regx"
|
38 |
+
try:
|
39 |
+
import regex as re
|
40 |
+
except ImportError:
|
41 |
+
re = None
|
42 |
+
######################################################################
|
43 |
+
## Language identification using TextCat
|
44 |
+
######################################################################
|
45 |
+
|
46 |
+
|
47 |
+
class TextCat:
|
48 |
+
|
49 |
+
_corpus = None
|
50 |
+
fingerprints = {}
|
51 |
+
_START_CHAR = "<"
|
52 |
+
_END_CHAR = ">"
|
53 |
+
|
54 |
+
last_distances = {}
|
55 |
+
|
56 |
+
def __init__(self):
|
57 |
+
if not re:
|
58 |
+
raise OSError(
|
59 |
+
"classify.textcat requires the regex module that "
|
60 |
+
"supports unicode. Try '$ pip install regex' and "
|
61 |
+
"see https://pypi.python.org/pypi/regex for "
|
62 |
+
"further details."
|
63 |
+
)
|
64 |
+
|
65 |
+
from nltk.corpus import crubadan
|
66 |
+
|
67 |
+
self._corpus = crubadan
|
68 |
+
# Load all language ngrams into cache
|
69 |
+
for lang in self._corpus.langs():
|
70 |
+
self._corpus.lang_freq(lang)
|
71 |
+
|
72 |
+
def remove_punctuation(self, text):
|
73 |
+
"""Get rid of punctuation except apostrophes"""
|
74 |
+
return re.sub(r"[^\P{P}\']+", "", text)
|
75 |
+
|
76 |
+
def profile(self, text):
|
77 |
+
"""Create FreqDist of trigrams within text"""
|
78 |
+
from nltk import FreqDist, word_tokenize
|
79 |
+
|
80 |
+
clean_text = self.remove_punctuation(text)
|
81 |
+
tokens = word_tokenize(clean_text)
|
82 |
+
|
83 |
+
fingerprint = FreqDist()
|
84 |
+
for t in tokens:
|
85 |
+
token_trigram_tuples = trigrams(self._START_CHAR + t + self._END_CHAR)
|
86 |
+
token_trigrams = ["".join(tri) for tri in token_trigram_tuples]
|
87 |
+
|
88 |
+
for cur_trigram in token_trigrams:
|
89 |
+
if cur_trigram in fingerprint:
|
90 |
+
fingerprint[cur_trigram] += 1
|
91 |
+
else:
|
92 |
+
fingerprint[cur_trigram] = 1
|
93 |
+
|
94 |
+
return fingerprint
|
95 |
+
|
96 |
+
def calc_dist(self, lang, trigram, text_profile):
|
97 |
+
"""Calculate the "out-of-place" measure between the
|
98 |
+
text and language profile for a single trigram"""
|
99 |
+
|
100 |
+
lang_fd = self._corpus.lang_freq(lang)
|
101 |
+
dist = 0
|
102 |
+
|
103 |
+
if trigram in lang_fd:
|
104 |
+
idx_lang_profile = list(lang_fd.keys()).index(trigram)
|
105 |
+
idx_text = list(text_profile.keys()).index(trigram)
|
106 |
+
|
107 |
+
# print(idx_lang_profile, ", ", idx_text)
|
108 |
+
dist = abs(idx_lang_profile - idx_text)
|
109 |
+
else:
|
110 |
+
# Arbitrary but should be larger than
|
111 |
+
# any possible trigram file length
|
112 |
+
# in terms of total lines
|
113 |
+
dist = maxsize
|
114 |
+
|
115 |
+
return dist
|
116 |
+
|
117 |
+
def lang_dists(self, text):
|
118 |
+
"""Calculate the "out-of-place" measure between
|
119 |
+
the text and all languages"""
|
120 |
+
|
121 |
+
distances = {}
|
122 |
+
profile = self.profile(text)
|
123 |
+
# For all the languages
|
124 |
+
for lang in self._corpus._all_lang_freq.keys():
|
125 |
+
# Calculate distance metric for every trigram in
|
126 |
+
# input text to be identified
|
127 |
+
lang_dist = 0
|
128 |
+
for trigram in profile:
|
129 |
+
lang_dist += self.calc_dist(lang, trigram, profile)
|
130 |
+
|
131 |
+
distances[lang] = lang_dist
|
132 |
+
|
133 |
+
return distances
|
134 |
+
|
135 |
+
def guess_language(self, text):
|
136 |
+
"""Find the language with the min distance
|
137 |
+
to the text and return its ISO 639-3 code"""
|
138 |
+
self.last_distances = self.lang_dists(text)
|
139 |
+
|
140 |
+
return min(self.last_distances, key=self.last_distances.get)
|
141 |
+
#################################################')
|
142 |
+
|
143 |
+
|
144 |
+
def demo():
|
145 |
+
from nltk.corpus import udhr
|
146 |
+
|
147 |
+
langs = [
|
148 |
+
"Kurdish-UTF8",
|
149 |
+
"Abkhaz-UTF8",
|
150 |
+
"Farsi_Persian-UTF8",
|
151 |
+
"Hindi-UTF8",
|
152 |
+
"Hawaiian-UTF8",
|
153 |
+
"Russian-UTF8",
|
154 |
+
"Vietnamese-UTF8",
|
155 |
+
"Serbian_Srpski-UTF8",
|
156 |
+
"Esperanto-UTF8",
|
157 |
+
]
|
158 |
+
|
159 |
+
friendly = {
|
160 |
+
"kmr": "Northern Kurdish",
|
161 |
+
"abk": "Abkhazian",
|
162 |
+
"pes": "Iranian Persian",
|
163 |
+
"hin": "Hindi",
|
164 |
+
"haw": "Hawaiian",
|
165 |
+
"rus": "Russian",
|
166 |
+
"vie": "Vietnamese",
|
167 |
+
"srp": "Serbian",
|
168 |
+
"epo": "Esperanto",
|
169 |
+
}
|
170 |
+
|
171 |
+
tc = TextCat()
|
172 |
+
|
173 |
+
for cur_lang in langs:
|
174 |
+
# Get raw data from UDHR corpus
|
175 |
+
raw_sentences = udhr.sents(cur_lang)
|
176 |
+
rows = len(raw_sentences) - 1
|
177 |
+
cols = list(map(len, raw_sentences))
|
178 |
+
|
179 |
+
sample = ""
|
180 |
+
|
181 |
+
# Generate a sample text of the language
|
182 |
+
for i in range(0, rows):
|
183 |
+
cur_sent = ""
|
184 |
+
for j in range(0, cols[i]):
|
185 |
+
cur_sent += " " + raw_sentences[i][j]
|
186 |
+
|
187 |
+
sample += cur_sent
|
188 |
+
|
189 |
+
# Try to detect what it is
|
190 |
+
print("Language snippet: " + sample[0:140] + "...")
|
191 |
+
guess = tc.guess_language(sample)
|
192 |
+
print(f"Language detection: {guess} ({friendly[guess]})")
|
193 |
+
print("#" * 140)
|
194 |
+
|
195 |
+
|
196 |
+
if __name__ == "__main__":
|
197 |
+
demo()
|
env-llmeval/lib/python3.10/site-packages/nltk/classify/util.py
ADDED
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Classifier Utility Functions
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Edward Loper <[email protected]>
|
5 |
+
# Steven Bird <[email protected]> (minor additions)
|
6 |
+
# URL: <https://www.nltk.org/>
|
7 |
+
# For license information, see LICENSE.TXT
|
8 |
+
|
9 |
+
"""
|
10 |
+
Utility functions and classes for classifiers.
|
11 |
+
"""
|
12 |
+
|
13 |
+
import math
|
14 |
+
|
15 |
+
# from nltk.util import Deprecated
|
16 |
+
import nltk.classify.util # for accuracy & log_likelihood
|
17 |
+
from nltk.util import LazyMap
|
18 |
+
|
19 |
+
######################################################################
|
20 |
+
# { Helper Functions
|
21 |
+
######################################################################
|
22 |
+
|
23 |
+
# alternative name possibility: 'map_featurefunc()'?
|
24 |
+
# alternative name possibility: 'detect_features()'?
|
25 |
+
# alternative name possibility: 'map_featuredetect()'?
|
26 |
+
# or.. just have users use LazyMap directly?
|
27 |
+
def apply_features(feature_func, toks, labeled=None):
|
28 |
+
"""
|
29 |
+
Use the ``LazyMap`` class to construct a lazy list-like
|
30 |
+
object that is analogous to ``map(feature_func, toks)``. In
|
31 |
+
particular, if ``labeled=False``, then the returned list-like
|
32 |
+
object's values are equal to::
|
33 |
+
|
34 |
+
[feature_func(tok) for tok in toks]
|
35 |
+
|
36 |
+
If ``labeled=True``, then the returned list-like object's values
|
37 |
+
are equal to::
|
38 |
+
|
39 |
+
[(feature_func(tok), label) for (tok, label) in toks]
|
40 |
+
|
41 |
+
The primary purpose of this function is to avoid the memory
|
42 |
+
overhead involved in storing all the featuresets for every token
|
43 |
+
in a corpus. Instead, these featuresets are constructed lazily,
|
44 |
+
as-needed. The reduction in memory overhead can be especially
|
45 |
+
significant when the underlying list of tokens is itself lazy (as
|
46 |
+
is the case with many corpus readers).
|
47 |
+
|
48 |
+
:param feature_func: The function that will be applied to each
|
49 |
+
token. It should return a featureset -- i.e., a dict
|
50 |
+
mapping feature names to feature values.
|
51 |
+
:param toks: The list of tokens to which ``feature_func`` should be
|
52 |
+
applied. If ``labeled=True``, then the list elements will be
|
53 |
+
passed directly to ``feature_func()``. If ``labeled=False``,
|
54 |
+
then the list elements should be tuples ``(tok,label)``, and
|
55 |
+
``tok`` will be passed to ``feature_func()``.
|
56 |
+
:param labeled: If true, then ``toks`` contains labeled tokens --
|
57 |
+
i.e., tuples of the form ``(tok, label)``. (Default:
|
58 |
+
auto-detect based on types.)
|
59 |
+
"""
|
60 |
+
if labeled is None:
|
61 |
+
labeled = toks and isinstance(toks[0], (tuple, list))
|
62 |
+
if labeled:
|
63 |
+
|
64 |
+
def lazy_func(labeled_token):
|
65 |
+
return (feature_func(labeled_token[0]), labeled_token[1])
|
66 |
+
|
67 |
+
return LazyMap(lazy_func, toks)
|
68 |
+
else:
|
69 |
+
return LazyMap(feature_func, toks)
|
70 |
+
|
71 |
+
|
72 |
+
def attested_labels(tokens):
|
73 |
+
"""
|
74 |
+
:return: A list of all labels that are attested in the given list
|
75 |
+
of tokens.
|
76 |
+
:rtype: list of (immutable)
|
77 |
+
:param tokens: The list of classified tokens from which to extract
|
78 |
+
labels. A classified token has the form ``(token, label)``.
|
79 |
+
:type tokens: list
|
80 |
+
"""
|
81 |
+
return tuple({label for (tok, label) in tokens})
|
82 |
+
|
83 |
+
|
84 |
+
def log_likelihood(classifier, gold):
|
85 |
+
results = classifier.prob_classify_many([fs for (fs, l) in gold])
|
86 |
+
ll = [pdist.prob(l) for ((fs, l), pdist) in zip(gold, results)]
|
87 |
+
return math.log(sum(ll) / len(ll))
|
88 |
+
|
89 |
+
|
90 |
+
def accuracy(classifier, gold):
|
91 |
+
results = classifier.classify_many([fs for (fs, l) in gold])
|
92 |
+
correct = [l == r for ((fs, l), r) in zip(gold, results)]
|
93 |
+
if correct:
|
94 |
+
return sum(correct) / len(correct)
|
95 |
+
else:
|
96 |
+
return 0
|
97 |
+
|
98 |
+
|
99 |
+
class CutoffChecker:
|
100 |
+
"""
|
101 |
+
A helper class that implements cutoff checks based on number of
|
102 |
+
iterations and log likelihood.
|
103 |
+
|
104 |
+
Accuracy cutoffs are also implemented, but they're almost never
|
105 |
+
a good idea to use.
|
106 |
+
"""
|
107 |
+
|
108 |
+
def __init__(self, cutoffs):
|
109 |
+
self.cutoffs = cutoffs.copy()
|
110 |
+
if "min_ll" in cutoffs:
|
111 |
+
cutoffs["min_ll"] = -abs(cutoffs["min_ll"])
|
112 |
+
if "min_lldelta" in cutoffs:
|
113 |
+
cutoffs["min_lldelta"] = abs(cutoffs["min_lldelta"])
|
114 |
+
self.ll = None
|
115 |
+
self.acc = None
|
116 |
+
self.iter = 1
|
117 |
+
|
118 |
+
def check(self, classifier, train_toks):
|
119 |
+
cutoffs = self.cutoffs
|
120 |
+
self.iter += 1
|
121 |
+
if "max_iter" in cutoffs and self.iter >= cutoffs["max_iter"]:
|
122 |
+
return True # iteration cutoff.
|
123 |
+
|
124 |
+
new_ll = nltk.classify.util.log_likelihood(classifier, train_toks)
|
125 |
+
if math.isnan(new_ll):
|
126 |
+
return True
|
127 |
+
|
128 |
+
if "min_ll" in cutoffs or "min_lldelta" in cutoffs:
|
129 |
+
if "min_ll" in cutoffs and new_ll >= cutoffs["min_ll"]:
|
130 |
+
return True # log likelihood cutoff
|
131 |
+
if (
|
132 |
+
"min_lldelta" in cutoffs
|
133 |
+
and self.ll
|
134 |
+
and ((new_ll - self.ll) <= abs(cutoffs["min_lldelta"]))
|
135 |
+
):
|
136 |
+
return True # log likelihood delta cutoff
|
137 |
+
self.ll = new_ll
|
138 |
+
|
139 |
+
if "max_acc" in cutoffs or "min_accdelta" in cutoffs:
|
140 |
+
new_acc = nltk.classify.util.log_likelihood(classifier, train_toks)
|
141 |
+
if "max_acc" in cutoffs and new_acc >= cutoffs["max_acc"]:
|
142 |
+
return True # log likelihood cutoff
|
143 |
+
if (
|
144 |
+
"min_accdelta" in cutoffs
|
145 |
+
and self.acc
|
146 |
+
and ((new_acc - self.acc) <= abs(cutoffs["min_accdelta"]))
|
147 |
+
):
|
148 |
+
return True # log likelihood delta cutoff
|
149 |
+
self.acc = new_acc
|
150 |
+
|
151 |
+
return False # no cutoff reached.
|
152 |
+
|
153 |
+
|
154 |
+
######################################################################
|
155 |
+
# { Demos
|
156 |
+
######################################################################
|
157 |
+
|
158 |
+
|
159 |
+
def names_demo_features(name):
|
160 |
+
features = {}
|
161 |
+
features["alwayson"] = True
|
162 |
+
features["startswith"] = name[0].lower()
|
163 |
+
features["endswith"] = name[-1].lower()
|
164 |
+
for letter in "abcdefghijklmnopqrstuvwxyz":
|
165 |
+
features["count(%s)" % letter] = name.lower().count(letter)
|
166 |
+
features["has(%s)" % letter] = letter in name.lower()
|
167 |
+
return features
|
168 |
+
|
169 |
+
|
170 |
+
def binary_names_demo_features(name):
|
171 |
+
features = {}
|
172 |
+
features["alwayson"] = True
|
173 |
+
features["startswith(vowel)"] = name[0].lower() in "aeiouy"
|
174 |
+
features["endswith(vowel)"] = name[-1].lower() in "aeiouy"
|
175 |
+
for letter in "abcdefghijklmnopqrstuvwxyz":
|
176 |
+
features["count(%s)" % letter] = name.lower().count(letter)
|
177 |
+
features["has(%s)" % letter] = letter in name.lower()
|
178 |
+
features["startswith(%s)" % letter] = letter == name[0].lower()
|
179 |
+
features["endswith(%s)" % letter] = letter == name[-1].lower()
|
180 |
+
return features
|
181 |
+
|
182 |
+
|
183 |
+
def names_demo(trainer, features=names_demo_features):
|
184 |
+
import random
|
185 |
+
|
186 |
+
from nltk.corpus import names
|
187 |
+
|
188 |
+
# Construct a list of classified names, using the names corpus.
|
189 |
+
namelist = [(name, "male") for name in names.words("male.txt")] + [
|
190 |
+
(name, "female") for name in names.words("female.txt")
|
191 |
+
]
|
192 |
+
|
193 |
+
# Randomly split the names into a test & train set.
|
194 |
+
random.seed(123456)
|
195 |
+
random.shuffle(namelist)
|
196 |
+
train = namelist[:5000]
|
197 |
+
test = namelist[5000:5500]
|
198 |
+
|
199 |
+
# Train up a classifier.
|
200 |
+
print("Training classifier...")
|
201 |
+
classifier = trainer([(features(n), g) for (n, g) in train])
|
202 |
+
|
203 |
+
# Run the classifier on the test data.
|
204 |
+
print("Testing classifier...")
|
205 |
+
acc = accuracy(classifier, [(features(n), g) for (n, g) in test])
|
206 |
+
print("Accuracy: %6.4f" % acc)
|
207 |
+
|
208 |
+
# For classifiers that can find probabilities, show the log
|
209 |
+
# likelihood and some sample probability distributions.
|
210 |
+
try:
|
211 |
+
test_featuresets = [features(n) for (n, g) in test]
|
212 |
+
pdists = classifier.prob_classify_many(test_featuresets)
|
213 |
+
ll = [pdist.logprob(gold) for ((name, gold), pdist) in zip(test, pdists)]
|
214 |
+
print("Avg. log likelihood: %6.4f" % (sum(ll) / len(test)))
|
215 |
+
print()
|
216 |
+
print("Unseen Names P(Male) P(Female)\n" + "-" * 40)
|
217 |
+
for ((name, gender), pdist) in list(zip(test, pdists))[:5]:
|
218 |
+
if gender == "male":
|
219 |
+
fmt = " %-15s *%6.4f %6.4f"
|
220 |
+
else:
|
221 |
+
fmt = " %-15s %6.4f *%6.4f"
|
222 |
+
print(fmt % (name, pdist.prob("male"), pdist.prob("female")))
|
223 |
+
except NotImplementedError:
|
224 |
+
pass
|
225 |
+
|
226 |
+
# Return the classifier
|
227 |
+
return classifier
|
228 |
+
|
229 |
+
|
230 |
+
def partial_names_demo(trainer, features=names_demo_features):
|
231 |
+
import random
|
232 |
+
|
233 |
+
from nltk.corpus import names
|
234 |
+
|
235 |
+
male_names = names.words("male.txt")
|
236 |
+
female_names = names.words("female.txt")
|
237 |
+
|
238 |
+
random.seed(654321)
|
239 |
+
random.shuffle(male_names)
|
240 |
+
random.shuffle(female_names)
|
241 |
+
|
242 |
+
# Create a list of male names to be used as positive-labeled examples for training
|
243 |
+
positive = map(features, male_names[:2000])
|
244 |
+
|
245 |
+
# Create a list of male and female names to be used as unlabeled examples
|
246 |
+
unlabeled = map(features, male_names[2000:2500] + female_names[:500])
|
247 |
+
|
248 |
+
# Create a test set with correctly-labeled male and female names
|
249 |
+
test = [(name, True) for name in male_names[2500:2750]] + [
|
250 |
+
(name, False) for name in female_names[500:750]
|
251 |
+
]
|
252 |
+
|
253 |
+
random.shuffle(test)
|
254 |
+
|
255 |
+
# Train up a classifier.
|
256 |
+
print("Training classifier...")
|
257 |
+
classifier = trainer(positive, unlabeled)
|
258 |
+
|
259 |
+
# Run the classifier on the test data.
|
260 |
+
print("Testing classifier...")
|
261 |
+
acc = accuracy(classifier, [(features(n), m) for (n, m) in test])
|
262 |
+
print("Accuracy: %6.4f" % acc)
|
263 |
+
|
264 |
+
# For classifiers that can find probabilities, show the log
|
265 |
+
# likelihood and some sample probability distributions.
|
266 |
+
try:
|
267 |
+
test_featuresets = [features(n) for (n, m) in test]
|
268 |
+
pdists = classifier.prob_classify_many(test_featuresets)
|
269 |
+
ll = [pdist.logprob(gold) for ((name, gold), pdist) in zip(test, pdists)]
|
270 |
+
print("Avg. log likelihood: %6.4f" % (sum(ll) / len(test)))
|
271 |
+
print()
|
272 |
+
print("Unseen Names P(Male) P(Female)\n" + "-" * 40)
|
273 |
+
for ((name, is_male), pdist) in zip(test, pdists)[:5]:
|
274 |
+
if is_male == True:
|
275 |
+
fmt = " %-15s *%6.4f %6.4f"
|
276 |
+
else:
|
277 |
+
fmt = " %-15s %6.4f *%6.4f"
|
278 |
+
print(fmt % (name, pdist.prob(True), pdist.prob(False)))
|
279 |
+
except NotImplementedError:
|
280 |
+
pass
|
281 |
+
|
282 |
+
# Return the classifier
|
283 |
+
return classifier
|
284 |
+
|
285 |
+
|
286 |
+
_inst_cache = {}
|
287 |
+
|
288 |
+
|
289 |
+
def wsd_demo(trainer, word, features, n=1000):
|
290 |
+
import random
|
291 |
+
|
292 |
+
from nltk.corpus import senseval
|
293 |
+
|
294 |
+
# Get the instances.
|
295 |
+
print("Reading data...")
|
296 |
+
global _inst_cache
|
297 |
+
if word not in _inst_cache:
|
298 |
+
_inst_cache[word] = [(i, i.senses[0]) for i in senseval.instances(word)]
|
299 |
+
instances = _inst_cache[word][:]
|
300 |
+
if n > len(instances):
|
301 |
+
n = len(instances)
|
302 |
+
senses = list({l for (i, l) in instances})
|
303 |
+
print(" Senses: " + " ".join(senses))
|
304 |
+
|
305 |
+
# Randomly split the names into a test & train set.
|
306 |
+
print("Splitting into test & train...")
|
307 |
+
random.seed(123456)
|
308 |
+
random.shuffle(instances)
|
309 |
+
train = instances[: int(0.8 * n)]
|
310 |
+
test = instances[int(0.8 * n) : n]
|
311 |
+
|
312 |
+
# Train up a classifier.
|
313 |
+
print("Training classifier...")
|
314 |
+
classifier = trainer([(features(i), l) for (i, l) in train])
|
315 |
+
|
316 |
+
# Run the classifier on the test data.
|
317 |
+
print("Testing classifier...")
|
318 |
+
acc = accuracy(classifier, [(features(i), l) for (i, l) in test])
|
319 |
+
print("Accuracy: %6.4f" % acc)
|
320 |
+
|
321 |
+
# For classifiers that can find probabilities, show the log
|
322 |
+
# likelihood and some sample probability distributions.
|
323 |
+
try:
|
324 |
+
test_featuresets = [features(i) for (i, n) in test]
|
325 |
+
pdists = classifier.prob_classify_many(test_featuresets)
|
326 |
+
ll = [pdist.logprob(gold) for ((name, gold), pdist) in zip(test, pdists)]
|
327 |
+
print("Avg. log likelihood: %6.4f" % (sum(ll) / len(test)))
|
328 |
+
except NotImplementedError:
|
329 |
+
pass
|
330 |
+
|
331 |
+
# Return the classifier
|
332 |
+
return classifier
|
333 |
+
|
334 |
+
|
335 |
+
def check_megam_config():
|
336 |
+
"""
|
337 |
+
Checks whether the MEGAM binary is configured.
|
338 |
+
"""
|
339 |
+
try:
|
340 |
+
_megam_bin
|
341 |
+
except NameError as e:
|
342 |
+
err_msg = str(
|
343 |
+
"Please configure your megam binary first, e.g.\n"
|
344 |
+
">>> nltk.config_megam('/usr/bin/local/megam')"
|
345 |
+
)
|
346 |
+
raise NameError(err_msg) from e
|
env-llmeval/lib/python3.10/site-packages/nltk/classify/weka.py
ADDED
@@ -0,0 +1,377 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Interface to Weka Classsifiers
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Edward Loper <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
|
8 |
+
"""
|
9 |
+
Classifiers that make use of the external 'Weka' package.
|
10 |
+
"""
|
11 |
+
|
12 |
+
import os
|
13 |
+
import re
|
14 |
+
import subprocess
|
15 |
+
import tempfile
|
16 |
+
import time
|
17 |
+
import zipfile
|
18 |
+
from sys import stdin
|
19 |
+
|
20 |
+
from nltk.classify.api import ClassifierI
|
21 |
+
from nltk.internals import config_java, java
|
22 |
+
from nltk.probability import DictionaryProbDist
|
23 |
+
|
24 |
+
_weka_classpath = None
|
25 |
+
_weka_search = [
|
26 |
+
".",
|
27 |
+
"/usr/share/weka",
|
28 |
+
"/usr/local/share/weka",
|
29 |
+
"/usr/lib/weka",
|
30 |
+
"/usr/local/lib/weka",
|
31 |
+
]
|
32 |
+
|
33 |
+
|
34 |
+
def config_weka(classpath=None):
|
35 |
+
global _weka_classpath
|
36 |
+
|
37 |
+
# Make sure java's configured first.
|
38 |
+
config_java()
|
39 |
+
|
40 |
+
if classpath is not None:
|
41 |
+
_weka_classpath = classpath
|
42 |
+
|
43 |
+
if _weka_classpath is None:
|
44 |
+
searchpath = _weka_search
|
45 |
+
if "WEKAHOME" in os.environ:
|
46 |
+
searchpath.insert(0, os.environ["WEKAHOME"])
|
47 |
+
|
48 |
+
for path in searchpath:
|
49 |
+
if os.path.exists(os.path.join(path, "weka.jar")):
|
50 |
+
_weka_classpath = os.path.join(path, "weka.jar")
|
51 |
+
version = _check_weka_version(_weka_classpath)
|
52 |
+
if version:
|
53 |
+
print(f"[Found Weka: {_weka_classpath} (version {version})]")
|
54 |
+
else:
|
55 |
+
print("[Found Weka: %s]" % _weka_classpath)
|
56 |
+
_check_weka_version(_weka_classpath)
|
57 |
+
|
58 |
+
if _weka_classpath is None:
|
59 |
+
raise LookupError(
|
60 |
+
"Unable to find weka.jar! Use config_weka() "
|
61 |
+
"or set the WEKAHOME environment variable. "
|
62 |
+
"For more information about Weka, please see "
|
63 |
+
"https://www.cs.waikato.ac.nz/ml/weka/"
|
64 |
+
)
|
65 |
+
|
66 |
+
|
67 |
+
def _check_weka_version(jar):
|
68 |
+
try:
|
69 |
+
zf = zipfile.ZipFile(jar)
|
70 |
+
except (SystemExit, KeyboardInterrupt):
|
71 |
+
raise
|
72 |
+
except:
|
73 |
+
return None
|
74 |
+
try:
|
75 |
+
try:
|
76 |
+
return zf.read("weka/core/version.txt")
|
77 |
+
except KeyError:
|
78 |
+
return None
|
79 |
+
finally:
|
80 |
+
zf.close()
|
81 |
+
|
82 |
+
|
83 |
+
class WekaClassifier(ClassifierI):
|
84 |
+
def __init__(self, formatter, model_filename):
|
85 |
+
self._formatter = formatter
|
86 |
+
self._model = model_filename
|
87 |
+
|
88 |
+
def prob_classify_many(self, featuresets):
|
89 |
+
return self._classify_many(featuresets, ["-p", "0", "-distribution"])
|
90 |
+
|
91 |
+
def classify_many(self, featuresets):
|
92 |
+
return self._classify_many(featuresets, ["-p", "0"])
|
93 |
+
|
94 |
+
def _classify_many(self, featuresets, options):
|
95 |
+
# Make sure we can find java & weka.
|
96 |
+
config_weka()
|
97 |
+
|
98 |
+
temp_dir = tempfile.mkdtemp()
|
99 |
+
try:
|
100 |
+
# Write the test data file.
|
101 |
+
test_filename = os.path.join(temp_dir, "test.arff")
|
102 |
+
self._formatter.write(test_filename, featuresets)
|
103 |
+
|
104 |
+
# Call weka to classify the data.
|
105 |
+
cmd = [
|
106 |
+
"weka.classifiers.bayes.NaiveBayes",
|
107 |
+
"-l",
|
108 |
+
self._model,
|
109 |
+
"-T",
|
110 |
+
test_filename,
|
111 |
+
] + options
|
112 |
+
(stdout, stderr) = java(
|
113 |
+
cmd,
|
114 |
+
classpath=_weka_classpath,
|
115 |
+
stdout=subprocess.PIPE,
|
116 |
+
stderr=subprocess.PIPE,
|
117 |
+
)
|
118 |
+
|
119 |
+
# Check if something went wrong:
|
120 |
+
if stderr and not stdout:
|
121 |
+
if "Illegal options: -distribution" in stderr:
|
122 |
+
raise ValueError(
|
123 |
+
"The installed version of weka does "
|
124 |
+
"not support probability distribution "
|
125 |
+
"output."
|
126 |
+
)
|
127 |
+
else:
|
128 |
+
raise ValueError("Weka failed to generate output:\n%s" % stderr)
|
129 |
+
|
130 |
+
# Parse weka's output.
|
131 |
+
return self.parse_weka_output(stdout.decode(stdin.encoding).split("\n"))
|
132 |
+
|
133 |
+
finally:
|
134 |
+
for f in os.listdir(temp_dir):
|
135 |
+
os.remove(os.path.join(temp_dir, f))
|
136 |
+
os.rmdir(temp_dir)
|
137 |
+
|
138 |
+
def parse_weka_distribution(self, s):
|
139 |
+
probs = [float(v) for v in re.split("[*,]+", s) if v.strip()]
|
140 |
+
probs = dict(zip(self._formatter.labels(), probs))
|
141 |
+
return DictionaryProbDist(probs)
|
142 |
+
|
143 |
+
def parse_weka_output(self, lines):
|
144 |
+
# Strip unwanted text from stdout
|
145 |
+
for i, line in enumerate(lines):
|
146 |
+
if line.strip().startswith("inst#"):
|
147 |
+
lines = lines[i:]
|
148 |
+
break
|
149 |
+
|
150 |
+
if lines[0].split() == ["inst#", "actual", "predicted", "error", "prediction"]:
|
151 |
+
return [line.split()[2].split(":")[1] for line in lines[1:] if line.strip()]
|
152 |
+
elif lines[0].split() == [
|
153 |
+
"inst#",
|
154 |
+
"actual",
|
155 |
+
"predicted",
|
156 |
+
"error",
|
157 |
+
"distribution",
|
158 |
+
]:
|
159 |
+
return [
|
160 |
+
self.parse_weka_distribution(line.split()[-1])
|
161 |
+
for line in lines[1:]
|
162 |
+
if line.strip()
|
163 |
+
]
|
164 |
+
|
165 |
+
# is this safe:?
|
166 |
+
elif re.match(r"^0 \w+ [01]\.[0-9]* \?\s*$", lines[0]):
|
167 |
+
return [line.split()[1] for line in lines if line.strip()]
|
168 |
+
|
169 |
+
else:
|
170 |
+
for line in lines[:10]:
|
171 |
+
print(line)
|
172 |
+
raise ValueError(
|
173 |
+
"Unhandled output format -- your version "
|
174 |
+
"of weka may not be supported.\n"
|
175 |
+
" Header: %s" % lines[0]
|
176 |
+
)
|
177 |
+
|
178 |
+
# [xx] full list of classifiers (some may be abstract?):
|
179 |
+
# ADTree, AODE, BayesNet, ComplementNaiveBayes, ConjunctiveRule,
|
180 |
+
# DecisionStump, DecisionTable, HyperPipes, IB1, IBk, Id3, J48,
|
181 |
+
# JRip, KStar, LBR, LeastMedSq, LinearRegression, LMT, Logistic,
|
182 |
+
# LogisticBase, M5Base, MultilayerPerceptron,
|
183 |
+
# MultipleClassifiersCombiner, NaiveBayes, NaiveBayesMultinomial,
|
184 |
+
# NaiveBayesSimple, NBTree, NNge, OneR, PaceRegression, PART,
|
185 |
+
# PreConstructedLinearModel, Prism, RandomForest,
|
186 |
+
# RandomizableClassifier, RandomTree, RBFNetwork, REPTree, Ridor,
|
187 |
+
# RuleNode, SimpleLinearRegression, SimpleLogistic,
|
188 |
+
# SingleClassifierEnhancer, SMO, SMOreg, UserClassifier, VFI,
|
189 |
+
# VotedPerceptron, Winnow, ZeroR
|
190 |
+
|
191 |
+
_CLASSIFIER_CLASS = {
|
192 |
+
"naivebayes": "weka.classifiers.bayes.NaiveBayes",
|
193 |
+
"C4.5": "weka.classifiers.trees.J48",
|
194 |
+
"log_regression": "weka.classifiers.functions.Logistic",
|
195 |
+
"svm": "weka.classifiers.functions.SMO",
|
196 |
+
"kstar": "weka.classifiers.lazy.KStar",
|
197 |
+
"ripper": "weka.classifiers.rules.JRip",
|
198 |
+
}
|
199 |
+
|
200 |
+
@classmethod
|
201 |
+
def train(
|
202 |
+
cls,
|
203 |
+
model_filename,
|
204 |
+
featuresets,
|
205 |
+
classifier="naivebayes",
|
206 |
+
options=[],
|
207 |
+
quiet=True,
|
208 |
+
):
|
209 |
+
# Make sure we can find java & weka.
|
210 |
+
config_weka()
|
211 |
+
|
212 |
+
# Build an ARFF formatter.
|
213 |
+
formatter = ARFF_Formatter.from_train(featuresets)
|
214 |
+
|
215 |
+
temp_dir = tempfile.mkdtemp()
|
216 |
+
try:
|
217 |
+
# Write the training data file.
|
218 |
+
train_filename = os.path.join(temp_dir, "train.arff")
|
219 |
+
formatter.write(train_filename, featuresets)
|
220 |
+
|
221 |
+
if classifier in cls._CLASSIFIER_CLASS:
|
222 |
+
javaclass = cls._CLASSIFIER_CLASS[classifier]
|
223 |
+
elif classifier in cls._CLASSIFIER_CLASS.values():
|
224 |
+
javaclass = classifier
|
225 |
+
else:
|
226 |
+
raise ValueError("Unknown classifier %s" % classifier)
|
227 |
+
|
228 |
+
# Train the weka model.
|
229 |
+
cmd = [javaclass, "-d", model_filename, "-t", train_filename]
|
230 |
+
cmd += list(options)
|
231 |
+
if quiet:
|
232 |
+
stdout = subprocess.PIPE
|
233 |
+
else:
|
234 |
+
stdout = None
|
235 |
+
java(cmd, classpath=_weka_classpath, stdout=stdout)
|
236 |
+
|
237 |
+
# Return the new classifier.
|
238 |
+
return WekaClassifier(formatter, model_filename)
|
239 |
+
|
240 |
+
finally:
|
241 |
+
for f in os.listdir(temp_dir):
|
242 |
+
os.remove(os.path.join(temp_dir, f))
|
243 |
+
os.rmdir(temp_dir)
|
244 |
+
|
245 |
+
|
246 |
+
class ARFF_Formatter:
|
247 |
+
"""
|
248 |
+
Converts featuresets and labeled featuresets to ARFF-formatted
|
249 |
+
strings, appropriate for input into Weka.
|
250 |
+
|
251 |
+
Features and classes can be specified manually in the constructor, or may
|
252 |
+
be determined from data using ``from_train``.
|
253 |
+
"""
|
254 |
+
|
255 |
+
def __init__(self, labels, features):
|
256 |
+
"""
|
257 |
+
:param labels: A list of all class labels that can be generated.
|
258 |
+
:param features: A list of feature specifications, where
|
259 |
+
each feature specification is a tuple (fname, ftype);
|
260 |
+
and ftype is an ARFF type string such as NUMERIC or
|
261 |
+
STRING.
|
262 |
+
"""
|
263 |
+
self._labels = labels
|
264 |
+
self._features = features
|
265 |
+
|
266 |
+
def format(self, tokens):
|
267 |
+
"""Returns a string representation of ARFF output for the given data."""
|
268 |
+
return self.header_section() + self.data_section(tokens)
|
269 |
+
|
270 |
+
def labels(self):
|
271 |
+
"""Returns the list of classes."""
|
272 |
+
return list(self._labels)
|
273 |
+
|
274 |
+
def write(self, outfile, tokens):
|
275 |
+
"""Writes ARFF data to a file for the given data."""
|
276 |
+
if not hasattr(outfile, "write"):
|
277 |
+
outfile = open(outfile, "w")
|
278 |
+
outfile.write(self.format(tokens))
|
279 |
+
outfile.close()
|
280 |
+
|
281 |
+
@staticmethod
|
282 |
+
def from_train(tokens):
|
283 |
+
"""
|
284 |
+
Constructs an ARFF_Formatter instance with class labels and feature
|
285 |
+
types determined from the given data. Handles boolean, numeric and
|
286 |
+
string (note: not nominal) types.
|
287 |
+
"""
|
288 |
+
# Find the set of all attested labels.
|
289 |
+
labels = {label for (tok, label) in tokens}
|
290 |
+
|
291 |
+
# Determine the types of all features.
|
292 |
+
features = {}
|
293 |
+
for tok, label in tokens:
|
294 |
+
for (fname, fval) in tok.items():
|
295 |
+
if issubclass(type(fval), bool):
|
296 |
+
ftype = "{True, False}"
|
297 |
+
elif issubclass(type(fval), (int, float, bool)):
|
298 |
+
ftype = "NUMERIC"
|
299 |
+
elif issubclass(type(fval), str):
|
300 |
+
ftype = "STRING"
|
301 |
+
elif fval is None:
|
302 |
+
continue # can't tell the type.
|
303 |
+
else:
|
304 |
+
raise ValueError("Unsupported value type %r" % ftype)
|
305 |
+
|
306 |
+
if features.get(fname, ftype) != ftype:
|
307 |
+
raise ValueError("Inconsistent type for %s" % fname)
|
308 |
+
features[fname] = ftype
|
309 |
+
features = sorted(features.items())
|
310 |
+
|
311 |
+
return ARFF_Formatter(labels, features)
|
312 |
+
|
313 |
+
def header_section(self):
|
314 |
+
"""Returns an ARFF header as a string."""
|
315 |
+
# Header comment.
|
316 |
+
s = (
|
317 |
+
"% Weka ARFF file\n"
|
318 |
+
+ "% Generated automatically by NLTK\n"
|
319 |
+
+ "%% %s\n\n" % time.ctime()
|
320 |
+
)
|
321 |
+
|
322 |
+
# Relation name
|
323 |
+
s += "@RELATION rel\n\n"
|
324 |
+
|
325 |
+
# Input attribute specifications
|
326 |
+
for fname, ftype in self._features:
|
327 |
+
s += "@ATTRIBUTE %-30r %s\n" % (fname, ftype)
|
328 |
+
|
329 |
+
# Label attribute specification
|
330 |
+
s += "@ATTRIBUTE %-30r {%s}\n" % ("-label-", ",".join(self._labels))
|
331 |
+
|
332 |
+
return s
|
333 |
+
|
334 |
+
def data_section(self, tokens, labeled=None):
|
335 |
+
"""
|
336 |
+
Returns the ARFF data section for the given data.
|
337 |
+
|
338 |
+
:param tokens: a list of featuresets (dicts) or labelled featuresets
|
339 |
+
which are tuples (featureset, label).
|
340 |
+
:param labeled: Indicates whether the given tokens are labeled
|
341 |
+
or not. If None, then the tokens will be assumed to be
|
342 |
+
labeled if the first token's value is a tuple or list.
|
343 |
+
"""
|
344 |
+
# Check if the tokens are labeled or unlabeled. If unlabeled,
|
345 |
+
# then use 'None'
|
346 |
+
if labeled is None:
|
347 |
+
labeled = tokens and isinstance(tokens[0], (tuple, list))
|
348 |
+
if not labeled:
|
349 |
+
tokens = [(tok, None) for tok in tokens]
|
350 |
+
|
351 |
+
# Data section
|
352 |
+
s = "\n@DATA\n"
|
353 |
+
for (tok, label) in tokens:
|
354 |
+
for fname, ftype in self._features:
|
355 |
+
s += "%s," % self._fmt_arff_val(tok.get(fname))
|
356 |
+
s += "%s\n" % self._fmt_arff_val(label)
|
357 |
+
|
358 |
+
return s
|
359 |
+
|
360 |
+
def _fmt_arff_val(self, fval):
|
361 |
+
if fval is None:
|
362 |
+
return "?"
|
363 |
+
elif isinstance(fval, (bool, int)):
|
364 |
+
return "%s" % fval
|
365 |
+
elif isinstance(fval, float):
|
366 |
+
return "%r" % fval
|
367 |
+
else:
|
368 |
+
return "%r" % fval
|
369 |
+
|
370 |
+
|
371 |
+
if __name__ == "__main__":
|
372 |
+
from nltk.classify.util import binary_names_demo_features, names_demo
|
373 |
+
|
374 |
+
def make_classifier(featuresets):
|
375 |
+
return WekaClassifier.train("/tmp/name.model", featuresets, "C4.5")
|
376 |
+
|
377 |
+
classifier = names_demo(make_classifier, binary_names_demo_features)
|
env-llmeval/lib/python3.10/site-packages/nltk/draw/__init__.py
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: graphical representations package
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Edward Loper <[email protected]>
|
5 |
+
# Steven Bird <[email protected]>
|
6 |
+
# URL: <https://www.nltk.org/>
|
7 |
+
# For license information, see LICENSE.TXT
|
8 |
+
|
9 |
+
# Import Tkinter-based modules if Tkinter is installed
|
10 |
+
try:
|
11 |
+
import tkinter
|
12 |
+
except ImportError:
|
13 |
+
import warnings
|
14 |
+
|
15 |
+
warnings.warn("nltk.draw package not loaded (please install Tkinter library).")
|
16 |
+
else:
|
17 |
+
from nltk.draw.cfg import ProductionList, CFGEditor, CFGDemo
|
18 |
+
from nltk.draw.tree import (
|
19 |
+
TreeSegmentWidget,
|
20 |
+
tree_to_treesegment,
|
21 |
+
TreeWidget,
|
22 |
+
TreeView,
|
23 |
+
draw_trees,
|
24 |
+
)
|
25 |
+
from nltk.draw.table import Table
|
26 |
+
|
27 |
+
from nltk.draw.dispersion import dispersion_plot
|
env-llmeval/lib/python3.10/site-packages/nltk/draw/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (680 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/nltk/draw/__pycache__/cfg.cpython-310.pyc
ADDED
Binary file (20.6 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/nltk/draw/__pycache__/dispersion.cpython-310.pyc
ADDED
Binary file (1.83 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/nltk/draw/__pycache__/table.cpython-310.pyc
ADDED
Binary file (38.3 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/nltk/draw/__pycache__/tree.cpython-310.pyc
ADDED
Binary file (28 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/nltk/draw/__pycache__/util.cpython-310.pyc
ADDED
Binary file (77.6 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/nltk/draw/cfg.py
ADDED
@@ -0,0 +1,859 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Edward Loper <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
|
8 |
+
"""
|
9 |
+
Visualization tools for CFGs.
|
10 |
+
"""
|
11 |
+
|
12 |
+
# Idea for a nice demo:
|
13 |
+
# - 3 panes: grammar, treelet, working area
|
14 |
+
# - grammar is a list of productions
|
15 |
+
# - when you select a production, the treelet that it licenses appears
|
16 |
+
# in the treelet area
|
17 |
+
# - the working area has the text on the bottom, and S at top. When
|
18 |
+
# you select a production, it shows (ghosted) the locations where
|
19 |
+
# that production's treelet could be attached to either the text
|
20 |
+
# or the tree rooted at S.
|
21 |
+
# - the user can drag the treelet onto one of those (or click on them?)
|
22 |
+
# - the user can delete pieces of the tree from the working area
|
23 |
+
# (right click?)
|
24 |
+
# - connecting top to bottom? drag one NP onto another?
|
25 |
+
#
|
26 |
+
# +-------------------------------------------------------------+
|
27 |
+
# | S -> NP VP | S |
|
28 |
+
# |[NP -> Det N ]| / \ |
|
29 |
+
# | ... | NP VP |
|
30 |
+
# | N -> 'dog' | |
|
31 |
+
# | N -> 'cat' | |
|
32 |
+
# | ... | |
|
33 |
+
# +--------------+ |
|
34 |
+
# | NP | Det N |
|
35 |
+
# | / \ | | | |
|
36 |
+
# | Det N | the cat saw the dog |
|
37 |
+
# | | |
|
38 |
+
# +--------------+----------------------------------------------+
|
39 |
+
#
|
40 |
+
# Operations:
|
41 |
+
# - connect a new treelet -- drag or click shadow
|
42 |
+
# - delete a treelet -- right click
|
43 |
+
# - if only connected to top, delete everything below
|
44 |
+
# - if only connected to bottom, delete everything above
|
45 |
+
# - connect top & bottom -- drag a leaf to a root or a root to a leaf
|
46 |
+
# - disconnect top & bottom -- right click
|
47 |
+
# - if connected to top & bottom, then disconnect
|
48 |
+
|
49 |
+
import re
|
50 |
+
from tkinter import (
|
51 |
+
Button,
|
52 |
+
Canvas,
|
53 |
+
Entry,
|
54 |
+
Frame,
|
55 |
+
IntVar,
|
56 |
+
Label,
|
57 |
+
Scrollbar,
|
58 |
+
Text,
|
59 |
+
Tk,
|
60 |
+
Toplevel,
|
61 |
+
)
|
62 |
+
|
63 |
+
from nltk.draw.tree import TreeSegmentWidget, tree_to_treesegment
|
64 |
+
from nltk.draw.util import (
|
65 |
+
CanvasFrame,
|
66 |
+
ColorizedList,
|
67 |
+
ShowText,
|
68 |
+
SymbolWidget,
|
69 |
+
TextWidget,
|
70 |
+
)
|
71 |
+
from nltk.grammar import CFG, Nonterminal, _read_cfg_production, nonterminals
|
72 |
+
from nltk.tree import Tree
|
73 |
+
|
74 |
+
######################################################################
|
75 |
+
# Production List
|
76 |
+
######################################################################
|
77 |
+
|
78 |
+
|
79 |
+
class ProductionList(ColorizedList):
|
80 |
+
ARROW = SymbolWidget.SYMBOLS["rightarrow"]
|
81 |
+
|
82 |
+
def _init_colortags(self, textwidget, options):
|
83 |
+
textwidget.tag_config("terminal", foreground="#006000")
|
84 |
+
textwidget.tag_config("arrow", font="symbol", underline="0")
|
85 |
+
textwidget.tag_config(
|
86 |
+
"nonterminal", foreground="blue", font=("helvetica", -12, "bold")
|
87 |
+
)
|
88 |
+
|
89 |
+
def _item_repr(self, item):
|
90 |
+
contents = []
|
91 |
+
contents.append(("%s\t" % item.lhs(), "nonterminal"))
|
92 |
+
contents.append((self.ARROW, "arrow"))
|
93 |
+
for elt in item.rhs():
|
94 |
+
if isinstance(elt, Nonterminal):
|
95 |
+
contents.append((" %s" % elt.symbol(), "nonterminal"))
|
96 |
+
else:
|
97 |
+
contents.append((" %r" % elt, "terminal"))
|
98 |
+
return contents
|
99 |
+
|
100 |
+
|
101 |
+
######################################################################
|
102 |
+
# CFG Editor
|
103 |
+
######################################################################
|
104 |
+
|
105 |
+
_CFGEditor_HELP = """
|
106 |
+
|
107 |
+
The CFG Editor can be used to create or modify context free grammars.
|
108 |
+
A context free grammar consists of a start symbol and a list of
|
109 |
+
productions. The start symbol is specified by the text entry field in
|
110 |
+
the upper right hand corner of the editor; and the list of productions
|
111 |
+
are specified in the main text editing box.
|
112 |
+
|
113 |
+
Every non-blank line specifies a single production. Each production
|
114 |
+
has the form "LHS -> RHS," where LHS is a single nonterminal, and RHS
|
115 |
+
is a list of nonterminals and terminals.
|
116 |
+
|
117 |
+
Nonterminals must be a single word, such as S or NP or NP_subj.
|
118 |
+
Currently, nonterminals must consists of alphanumeric characters and
|
119 |
+
underscores (_). Nonterminals are colored blue. If you place the
|
120 |
+
mouse over any nonterminal, then all occurrences of that nonterminal
|
121 |
+
will be highlighted.
|
122 |
+
|
123 |
+
Terminals must be surrounded by single quotes (') or double
|
124 |
+
quotes(\"). For example, "dog" and "New York" are terminals.
|
125 |
+
Currently, the string within the quotes must consist of alphanumeric
|
126 |
+
characters, underscores, and spaces.
|
127 |
+
|
128 |
+
To enter a new production, go to a blank line, and type a nonterminal,
|
129 |
+
followed by an arrow (->), followed by a sequence of terminals and
|
130 |
+
nonterminals. Note that "->" (dash + greater-than) is automatically
|
131 |
+
converted to an arrow symbol. When you move your cursor to a
|
132 |
+
different line, your production will automatically be colorized. If
|
133 |
+
there are any errors, they will be highlighted in red.
|
134 |
+
|
135 |
+
Note that the order of the productions is significant for some
|
136 |
+
algorithms. To re-order the productions, use cut and paste to move
|
137 |
+
them.
|
138 |
+
|
139 |
+
Use the buttons at the bottom of the window when you are done editing
|
140 |
+
the CFG:
|
141 |
+
- Ok: apply the new CFG, and exit the editor.
|
142 |
+
- Apply: apply the new CFG, and do not exit the editor.
|
143 |
+
- Reset: revert to the original CFG, and do not exit the editor.
|
144 |
+
- Cancel: revert to the original CFG, and exit the editor.
|
145 |
+
|
146 |
+
"""
|
147 |
+
|
148 |
+
|
149 |
+
class CFGEditor:
|
150 |
+
"""
|
151 |
+
A dialog window for creating and editing context free grammars.
|
152 |
+
``CFGEditor`` imposes the following restrictions:
|
153 |
+
|
154 |
+
- All nonterminals must be strings consisting of word
|
155 |
+
characters.
|
156 |
+
- All terminals must be strings consisting of word characters
|
157 |
+
and space characters.
|
158 |
+
"""
|
159 |
+
|
160 |
+
# Regular expressions used by _analyze_line. Precompile them, so
|
161 |
+
# we can process the text faster.
|
162 |
+
ARROW = SymbolWidget.SYMBOLS["rightarrow"]
|
163 |
+
_LHS_RE = re.compile(r"(^\s*\w+\s*)(->|(" + ARROW + "))")
|
164 |
+
_ARROW_RE = re.compile(r"\s*(->|(" + ARROW + r"))\s*")
|
165 |
+
_PRODUCTION_RE = re.compile(
|
166 |
+
r"(^\s*\w+\s*)"
|
167 |
+
+ "(->|(" # LHS
|
168 |
+
+ ARROW
|
169 |
+
+ r"))\s*"
|
170 |
+
+ r"((\w+|'[\w ]*'|\"[\w ]*\"|\|)\s*)*$" # arrow
|
171 |
+
) # RHS
|
172 |
+
_TOKEN_RE = re.compile("\\w+|->|'[\\w ]+'|\"[\\w ]+\"|(" + ARROW + ")")
|
173 |
+
_BOLD = ("helvetica", -12, "bold")
|
174 |
+
|
175 |
+
def __init__(self, parent, cfg=None, set_cfg_callback=None):
|
176 |
+
self._parent = parent
|
177 |
+
if cfg is not None:
|
178 |
+
self._cfg = cfg
|
179 |
+
else:
|
180 |
+
self._cfg = CFG(Nonterminal("S"), [])
|
181 |
+
self._set_cfg_callback = set_cfg_callback
|
182 |
+
|
183 |
+
self._highlight_matching_nonterminals = 1
|
184 |
+
|
185 |
+
# Create the top-level window.
|
186 |
+
self._top = Toplevel(parent)
|
187 |
+
self._init_bindings()
|
188 |
+
|
189 |
+
self._init_startframe()
|
190 |
+
self._startframe.pack(side="top", fill="x", expand=0)
|
191 |
+
self._init_prodframe()
|
192 |
+
self._prodframe.pack(side="top", fill="both", expand=1)
|
193 |
+
self._init_buttons()
|
194 |
+
self._buttonframe.pack(side="bottom", fill="x", expand=0)
|
195 |
+
|
196 |
+
self._textwidget.focus()
|
197 |
+
|
198 |
+
def _init_startframe(self):
|
199 |
+
frame = self._startframe = Frame(self._top)
|
200 |
+
self._start = Entry(frame)
|
201 |
+
self._start.pack(side="right")
|
202 |
+
Label(frame, text="Start Symbol:").pack(side="right")
|
203 |
+
Label(frame, text="Productions:").pack(side="left")
|
204 |
+
self._start.insert(0, self._cfg.start().symbol())
|
205 |
+
|
206 |
+
def _init_buttons(self):
|
207 |
+
frame = self._buttonframe = Frame(self._top)
|
208 |
+
Button(frame, text="Ok", command=self._ok, underline=0, takefocus=0).pack(
|
209 |
+
side="left"
|
210 |
+
)
|
211 |
+
Button(frame, text="Apply", command=self._apply, underline=0, takefocus=0).pack(
|
212 |
+
side="left"
|
213 |
+
)
|
214 |
+
Button(frame, text="Reset", command=self._reset, underline=0, takefocus=0).pack(
|
215 |
+
side="left"
|
216 |
+
)
|
217 |
+
Button(
|
218 |
+
frame, text="Cancel", command=self._cancel, underline=0, takefocus=0
|
219 |
+
).pack(side="left")
|
220 |
+
Button(frame, text="Help", command=self._help, underline=0, takefocus=0).pack(
|
221 |
+
side="right"
|
222 |
+
)
|
223 |
+
|
224 |
+
def _init_bindings(self):
|
225 |
+
self._top.title("CFG Editor")
|
226 |
+
self._top.bind("<Control-q>", self._cancel)
|
227 |
+
self._top.bind("<Alt-q>", self._cancel)
|
228 |
+
self._top.bind("<Control-d>", self._cancel)
|
229 |
+
# self._top.bind('<Control-x>', self._cancel)
|
230 |
+
self._top.bind("<Alt-x>", self._cancel)
|
231 |
+
self._top.bind("<Escape>", self._cancel)
|
232 |
+
# self._top.bind('<Control-c>', self._cancel)
|
233 |
+
self._top.bind("<Alt-c>", self._cancel)
|
234 |
+
|
235 |
+
self._top.bind("<Control-o>", self._ok)
|
236 |
+
self._top.bind("<Alt-o>", self._ok)
|
237 |
+
self._top.bind("<Control-a>", self._apply)
|
238 |
+
self._top.bind("<Alt-a>", self._apply)
|
239 |
+
self._top.bind("<Control-r>", self._reset)
|
240 |
+
self._top.bind("<Alt-r>", self._reset)
|
241 |
+
self._top.bind("<Control-h>", self._help)
|
242 |
+
self._top.bind("<Alt-h>", self._help)
|
243 |
+
self._top.bind("<F1>", self._help)
|
244 |
+
|
245 |
+
def _init_prodframe(self):
|
246 |
+
self._prodframe = Frame(self._top)
|
247 |
+
|
248 |
+
# Create the basic Text widget & scrollbar.
|
249 |
+
self._textwidget = Text(
|
250 |
+
self._prodframe, background="#e0e0e0", exportselection=1
|
251 |
+
)
|
252 |
+
self._textscroll = Scrollbar(self._prodframe, takefocus=0, orient="vertical")
|
253 |
+
self._textwidget.config(yscrollcommand=self._textscroll.set)
|
254 |
+
self._textscroll.config(command=self._textwidget.yview)
|
255 |
+
self._textscroll.pack(side="right", fill="y")
|
256 |
+
self._textwidget.pack(expand=1, fill="both", side="left")
|
257 |
+
|
258 |
+
# Initialize the colorization tags. Each nonterminal gets its
|
259 |
+
# own tag, so they aren't listed here.
|
260 |
+
self._textwidget.tag_config("terminal", foreground="#006000")
|
261 |
+
self._textwidget.tag_config("arrow", font="symbol")
|
262 |
+
self._textwidget.tag_config("error", background="red")
|
263 |
+
|
264 |
+
# Keep track of what line they're on. We use that to remember
|
265 |
+
# to re-analyze a line whenever they leave it.
|
266 |
+
self._linenum = 0
|
267 |
+
|
268 |
+
# Expand "->" to an arrow.
|
269 |
+
self._top.bind(">", self._replace_arrows)
|
270 |
+
|
271 |
+
# Re-colorize lines when appropriate.
|
272 |
+
self._top.bind("<<Paste>>", self._analyze)
|
273 |
+
self._top.bind("<KeyPress>", self._check_analyze)
|
274 |
+
self._top.bind("<ButtonPress>", self._check_analyze)
|
275 |
+
|
276 |
+
# Tab cycles focus. (why doesn't this work??)
|
277 |
+
def cycle(e, textwidget=self._textwidget):
|
278 |
+
textwidget.tk_focusNext().focus()
|
279 |
+
|
280 |
+
self._textwidget.bind("<Tab>", cycle)
|
281 |
+
|
282 |
+
prod_tuples = [(p.lhs(), [p.rhs()]) for p in self._cfg.productions()]
|
283 |
+
for i in range(len(prod_tuples) - 1, 0, -1):
|
284 |
+
if prod_tuples[i][0] == prod_tuples[i - 1][0]:
|
285 |
+
if () in prod_tuples[i][1]:
|
286 |
+
continue
|
287 |
+
if () in prod_tuples[i - 1][1]:
|
288 |
+
continue
|
289 |
+
print(prod_tuples[i - 1][1])
|
290 |
+
print(prod_tuples[i][1])
|
291 |
+
prod_tuples[i - 1][1].extend(prod_tuples[i][1])
|
292 |
+
del prod_tuples[i]
|
293 |
+
|
294 |
+
for lhs, rhss in prod_tuples:
|
295 |
+
print(lhs, rhss)
|
296 |
+
s = "%s ->" % lhs
|
297 |
+
for rhs in rhss:
|
298 |
+
for elt in rhs:
|
299 |
+
if isinstance(elt, Nonterminal):
|
300 |
+
s += " %s" % elt
|
301 |
+
else:
|
302 |
+
s += " %r" % elt
|
303 |
+
s += " |"
|
304 |
+
s = s[:-2] + "\n"
|
305 |
+
self._textwidget.insert("end", s)
|
306 |
+
|
307 |
+
self._analyze()
|
308 |
+
|
309 |
+
# # Add the producitons to the text widget, and colorize them.
|
310 |
+
# prod_by_lhs = {}
|
311 |
+
# for prod in self._cfg.productions():
|
312 |
+
# if len(prod.rhs()) > 0:
|
313 |
+
# prod_by_lhs.setdefault(prod.lhs(),[]).append(prod)
|
314 |
+
# for (lhs, prods) in prod_by_lhs.items():
|
315 |
+
# self._textwidget.insert('end', '%s ->' % lhs)
|
316 |
+
# self._textwidget.insert('end', self._rhs(prods[0]))
|
317 |
+
# for prod in prods[1:]:
|
318 |
+
# print '\t|'+self._rhs(prod),
|
319 |
+
# self._textwidget.insert('end', '\t|'+self._rhs(prod))
|
320 |
+
# print
|
321 |
+
# self._textwidget.insert('end', '\n')
|
322 |
+
# for prod in self._cfg.productions():
|
323 |
+
# if len(prod.rhs()) == 0:
|
324 |
+
# self._textwidget.insert('end', '%s' % prod)
|
325 |
+
# self._analyze()
|
326 |
+
|
327 |
+
# def _rhs(self, prod):
|
328 |
+
# s = ''
|
329 |
+
# for elt in prod.rhs():
|
330 |
+
# if isinstance(elt, Nonterminal): s += ' %s' % elt.symbol()
|
331 |
+
# else: s += ' %r' % elt
|
332 |
+
# return s
|
333 |
+
|
334 |
+
def _clear_tags(self, linenum):
|
335 |
+
"""
|
336 |
+
Remove all tags (except ``arrow`` and ``sel``) from the given
|
337 |
+
line of the text widget used for editing the productions.
|
338 |
+
"""
|
339 |
+
start = "%d.0" % linenum
|
340 |
+
end = "%d.end" % linenum
|
341 |
+
for tag in self._textwidget.tag_names():
|
342 |
+
if tag not in ("arrow", "sel"):
|
343 |
+
self._textwidget.tag_remove(tag, start, end)
|
344 |
+
|
345 |
+
def _check_analyze(self, *e):
|
346 |
+
"""
|
347 |
+
Check if we've moved to a new line. If we have, then remove
|
348 |
+
all colorization from the line we moved to, and re-colorize
|
349 |
+
the line that we moved from.
|
350 |
+
"""
|
351 |
+
linenum = int(self._textwidget.index("insert").split(".")[0])
|
352 |
+
if linenum != self._linenum:
|
353 |
+
self._clear_tags(linenum)
|
354 |
+
self._analyze_line(self._linenum)
|
355 |
+
self._linenum = linenum
|
356 |
+
|
357 |
+
def _replace_arrows(self, *e):
|
358 |
+
"""
|
359 |
+
Replace any ``'->'`` text strings with arrows (char \\256, in
|
360 |
+
symbol font). This searches the whole buffer, but is fast
|
361 |
+
enough to be done anytime they press '>'.
|
362 |
+
"""
|
363 |
+
arrow = "1.0"
|
364 |
+
while True:
|
365 |
+
arrow = self._textwidget.search("->", arrow, "end+1char")
|
366 |
+
if arrow == "":
|
367 |
+
break
|
368 |
+
self._textwidget.delete(arrow, arrow + "+2char")
|
369 |
+
self._textwidget.insert(arrow, self.ARROW, "arrow")
|
370 |
+
self._textwidget.insert(arrow, "\t")
|
371 |
+
|
372 |
+
arrow = "1.0"
|
373 |
+
while True:
|
374 |
+
arrow = self._textwidget.search(self.ARROW, arrow + "+1char", "end+1char")
|
375 |
+
if arrow == "":
|
376 |
+
break
|
377 |
+
self._textwidget.tag_add("arrow", arrow, arrow + "+1char")
|
378 |
+
|
379 |
+
def _analyze_token(self, match, linenum):
|
380 |
+
"""
|
381 |
+
Given a line number and a regexp match for a token on that
|
382 |
+
line, colorize the token. Note that the regexp match gives us
|
383 |
+
the token's text, start index (on the line), and end index (on
|
384 |
+
the line).
|
385 |
+
"""
|
386 |
+
# What type of token is it?
|
387 |
+
if match.group()[0] in "'\"":
|
388 |
+
tag = "terminal"
|
389 |
+
elif match.group() in ("->", self.ARROW):
|
390 |
+
tag = "arrow"
|
391 |
+
else:
|
392 |
+
# If it's a nonterminal, then set up new bindings, so we
|
393 |
+
# can highlight all instances of that nonterminal when we
|
394 |
+
# put the mouse over it.
|
395 |
+
tag = "nonterminal_" + match.group()
|
396 |
+
if tag not in self._textwidget.tag_names():
|
397 |
+
self._init_nonterminal_tag(tag)
|
398 |
+
|
399 |
+
start = "%d.%d" % (linenum, match.start())
|
400 |
+
end = "%d.%d" % (linenum, match.end())
|
401 |
+
self._textwidget.tag_add(tag, start, end)
|
402 |
+
|
403 |
+
def _init_nonterminal_tag(self, tag, foreground="blue"):
|
404 |
+
self._textwidget.tag_config(tag, foreground=foreground, font=CFGEditor._BOLD)
|
405 |
+
if not self._highlight_matching_nonterminals:
|
406 |
+
return
|
407 |
+
|
408 |
+
def enter(e, textwidget=self._textwidget, tag=tag):
|
409 |
+
textwidget.tag_config(tag, background="#80ff80")
|
410 |
+
|
411 |
+
def leave(e, textwidget=self._textwidget, tag=tag):
|
412 |
+
textwidget.tag_config(tag, background="")
|
413 |
+
|
414 |
+
self._textwidget.tag_bind(tag, "<Enter>", enter)
|
415 |
+
self._textwidget.tag_bind(tag, "<Leave>", leave)
|
416 |
+
|
417 |
+
def _analyze_line(self, linenum):
|
418 |
+
"""
|
419 |
+
Colorize a given line.
|
420 |
+
"""
|
421 |
+
# Get rid of any tags that were previously on the line.
|
422 |
+
self._clear_tags(linenum)
|
423 |
+
|
424 |
+
# Get the line line's text string.
|
425 |
+
line = self._textwidget.get(repr(linenum) + ".0", repr(linenum) + ".end")
|
426 |
+
|
427 |
+
# If it's a valid production, then colorize each token.
|
428 |
+
if CFGEditor._PRODUCTION_RE.match(line):
|
429 |
+
# It's valid; Use _TOKEN_RE to tokenize the production,
|
430 |
+
# and call analyze_token on each token.
|
431 |
+
def analyze_token(match, self=self, linenum=linenum):
|
432 |
+
self._analyze_token(match, linenum)
|
433 |
+
return ""
|
434 |
+
|
435 |
+
CFGEditor._TOKEN_RE.sub(analyze_token, line)
|
436 |
+
elif line.strip() != "":
|
437 |
+
# It's invalid; show the user where the error is.
|
438 |
+
self._mark_error(linenum, line)
|
439 |
+
|
440 |
+
def _mark_error(self, linenum, line):
|
441 |
+
"""
|
442 |
+
Mark the location of an error in a line.
|
443 |
+
"""
|
444 |
+
arrowmatch = CFGEditor._ARROW_RE.search(line)
|
445 |
+
if not arrowmatch:
|
446 |
+
# If there's no arrow at all, highlight the whole line.
|
447 |
+
start = "%d.0" % linenum
|
448 |
+
end = "%d.end" % linenum
|
449 |
+
elif not CFGEditor._LHS_RE.match(line):
|
450 |
+
# Otherwise, if the LHS is bad, highlight it.
|
451 |
+
start = "%d.0" % linenum
|
452 |
+
end = "%d.%d" % (linenum, arrowmatch.start())
|
453 |
+
else:
|
454 |
+
# Otherwise, highlight the RHS.
|
455 |
+
start = "%d.%d" % (linenum, arrowmatch.end())
|
456 |
+
end = "%d.end" % linenum
|
457 |
+
|
458 |
+
# If we're highlighting 0 chars, highlight the whole line.
|
459 |
+
if self._textwidget.compare(start, "==", end):
|
460 |
+
start = "%d.0" % linenum
|
461 |
+
end = "%d.end" % linenum
|
462 |
+
self._textwidget.tag_add("error", start, end)
|
463 |
+
|
464 |
+
def _analyze(self, *e):
|
465 |
+
"""
|
466 |
+
Replace ``->`` with arrows, and colorize the entire buffer.
|
467 |
+
"""
|
468 |
+
self._replace_arrows()
|
469 |
+
numlines = int(self._textwidget.index("end").split(".")[0])
|
470 |
+
for linenum in range(1, numlines + 1): # line numbers start at 1.
|
471 |
+
self._analyze_line(linenum)
|
472 |
+
|
473 |
+
def _parse_productions(self):
|
474 |
+
"""
|
475 |
+
Parse the current contents of the textwidget buffer, to create
|
476 |
+
a list of productions.
|
477 |
+
"""
|
478 |
+
productions = []
|
479 |
+
|
480 |
+
# Get the text, normalize it, and split it into lines.
|
481 |
+
text = self._textwidget.get("1.0", "end")
|
482 |
+
text = re.sub(self.ARROW, "->", text)
|
483 |
+
text = re.sub("\t", " ", text)
|
484 |
+
lines = text.split("\n")
|
485 |
+
|
486 |
+
# Convert each line to a CFG production
|
487 |
+
for line in lines:
|
488 |
+
line = line.strip()
|
489 |
+
if line == "":
|
490 |
+
continue
|
491 |
+
productions += _read_cfg_production(line)
|
492 |
+
# if line.strip() == '': continue
|
493 |
+
# if not CFGEditor._PRODUCTION_RE.match(line):
|
494 |
+
# raise ValueError('Bad production string %r' % line)
|
495 |
+
#
|
496 |
+
# (lhs_str, rhs_str) = line.split('->')
|
497 |
+
# lhs = Nonterminal(lhs_str.strip())
|
498 |
+
# rhs = []
|
499 |
+
# def parse_token(match, rhs=rhs):
|
500 |
+
# token = match.group()
|
501 |
+
# if token[0] in "'\"": rhs.append(token[1:-1])
|
502 |
+
# else: rhs.append(Nonterminal(token))
|
503 |
+
# return ''
|
504 |
+
# CFGEditor._TOKEN_RE.sub(parse_token, rhs_str)
|
505 |
+
#
|
506 |
+
# productions.append(Production(lhs, *rhs))
|
507 |
+
|
508 |
+
return productions
|
509 |
+
|
510 |
+
def _destroy(self, *e):
|
511 |
+
if self._top is None:
|
512 |
+
return
|
513 |
+
self._top.destroy()
|
514 |
+
self._top = None
|
515 |
+
|
516 |
+
def _ok(self, *e):
|
517 |
+
self._apply()
|
518 |
+
self._destroy()
|
519 |
+
|
520 |
+
def _apply(self, *e):
|
521 |
+
productions = self._parse_productions()
|
522 |
+
start = Nonterminal(self._start.get())
|
523 |
+
cfg = CFG(start, productions)
|
524 |
+
if self._set_cfg_callback is not None:
|
525 |
+
self._set_cfg_callback(cfg)
|
526 |
+
|
527 |
+
def _reset(self, *e):
|
528 |
+
self._textwidget.delete("1.0", "end")
|
529 |
+
for production in self._cfg.productions():
|
530 |
+
self._textwidget.insert("end", "%s\n" % production)
|
531 |
+
self._analyze()
|
532 |
+
if self._set_cfg_callback is not None:
|
533 |
+
self._set_cfg_callback(self._cfg)
|
534 |
+
|
535 |
+
def _cancel(self, *e):
|
536 |
+
try:
|
537 |
+
self._reset()
|
538 |
+
except:
|
539 |
+
pass
|
540 |
+
self._destroy()
|
541 |
+
|
542 |
+
def _help(self, *e):
|
543 |
+
# The default font's not very legible; try using 'fixed' instead.
|
544 |
+
try:
|
545 |
+
ShowText(
|
546 |
+
self._parent,
|
547 |
+
"Help: Chart Parser Demo",
|
548 |
+
(_CFGEditor_HELP).strip(),
|
549 |
+
width=75,
|
550 |
+
font="fixed",
|
551 |
+
)
|
552 |
+
except:
|
553 |
+
ShowText(
|
554 |
+
self._parent,
|
555 |
+
"Help: Chart Parser Demo",
|
556 |
+
(_CFGEditor_HELP).strip(),
|
557 |
+
width=75,
|
558 |
+
)
|
559 |
+
|
560 |
+
|
561 |
+
######################################################################
|
562 |
+
# New Demo (built tree based on cfg)
|
563 |
+
######################################################################
|
564 |
+
|
565 |
+
|
566 |
+
class CFGDemo:
|
567 |
+
def __init__(self, grammar, text):
|
568 |
+
self._grammar = grammar
|
569 |
+
self._text = text
|
570 |
+
|
571 |
+
# Set up the main window.
|
572 |
+
self._top = Tk()
|
573 |
+
self._top.title("Context Free Grammar Demo")
|
574 |
+
|
575 |
+
# Base font size
|
576 |
+
self._size = IntVar(self._top)
|
577 |
+
self._size.set(12) # = medium
|
578 |
+
|
579 |
+
# Set up the key bindings
|
580 |
+
self._init_bindings(self._top)
|
581 |
+
|
582 |
+
# Create the basic frames
|
583 |
+
frame1 = Frame(self._top)
|
584 |
+
frame1.pack(side="left", fill="y", expand=0)
|
585 |
+
self._init_menubar(self._top)
|
586 |
+
self._init_buttons(self._top)
|
587 |
+
self._init_grammar(frame1)
|
588 |
+
self._init_treelet(frame1)
|
589 |
+
self._init_workspace(self._top)
|
590 |
+
|
591 |
+
# //////////////////////////////////////////////////
|
592 |
+
# Initialization
|
593 |
+
# //////////////////////////////////////////////////
|
594 |
+
|
595 |
+
def _init_bindings(self, top):
|
596 |
+
top.bind("<Control-q>", self.destroy)
|
597 |
+
|
598 |
+
def _init_menubar(self, parent):
|
599 |
+
pass
|
600 |
+
|
601 |
+
def _init_buttons(self, parent):
|
602 |
+
pass
|
603 |
+
|
604 |
+
def _init_grammar(self, parent):
|
605 |
+
self._prodlist = ProductionList(parent, self._grammar, width=20)
|
606 |
+
self._prodlist.pack(side="top", fill="both", expand=1)
|
607 |
+
self._prodlist.focus()
|
608 |
+
self._prodlist.add_callback("select", self._selectprod_cb)
|
609 |
+
self._prodlist.add_callback("move", self._selectprod_cb)
|
610 |
+
|
611 |
+
def _init_treelet(self, parent):
|
612 |
+
self._treelet_canvas = Canvas(parent, background="white")
|
613 |
+
self._treelet_canvas.pack(side="bottom", fill="x")
|
614 |
+
self._treelet = None
|
615 |
+
|
616 |
+
def _init_workspace(self, parent):
|
617 |
+
self._workspace = CanvasFrame(parent, background="white")
|
618 |
+
self._workspace.pack(side="right", fill="both", expand=1)
|
619 |
+
self._tree = None
|
620 |
+
self.reset_workspace()
|
621 |
+
|
622 |
+
# //////////////////////////////////////////////////
|
623 |
+
# Workspace
|
624 |
+
# //////////////////////////////////////////////////
|
625 |
+
|
626 |
+
def reset_workspace(self):
|
627 |
+
c = self._workspace.canvas()
|
628 |
+
fontsize = int(self._size.get())
|
629 |
+
node_font = ("helvetica", -(fontsize + 4), "bold")
|
630 |
+
leaf_font = ("helvetica", -(fontsize + 2))
|
631 |
+
|
632 |
+
# Remove the old tree
|
633 |
+
if self._tree is not None:
|
634 |
+
self._workspace.remove_widget(self._tree)
|
635 |
+
|
636 |
+
# The root of the tree.
|
637 |
+
start = self._grammar.start().symbol()
|
638 |
+
rootnode = TextWidget(c, start, font=node_font, draggable=1)
|
639 |
+
|
640 |
+
# The leaves of the tree.
|
641 |
+
leaves = []
|
642 |
+
for word in self._text:
|
643 |
+
leaves.append(TextWidget(c, word, font=leaf_font, draggable=1))
|
644 |
+
|
645 |
+
# Put it all together into one tree
|
646 |
+
self._tree = TreeSegmentWidget(c, rootnode, leaves, color="white")
|
647 |
+
|
648 |
+
# Add it to the workspace.
|
649 |
+
self._workspace.add_widget(self._tree)
|
650 |
+
|
651 |
+
# Move the leaves to the bottom of the workspace.
|
652 |
+
for leaf in leaves:
|
653 |
+
leaf.move(0, 100)
|
654 |
+
|
655 |
+
# self._nodes = {start:1}
|
656 |
+
# self._leaves = dict([(l,1) for l in leaves])
|
657 |
+
|
658 |
+
def workspace_markprod(self, production):
|
659 |
+
pass
|
660 |
+
|
661 |
+
def _markproduction(self, prod, tree=None):
|
662 |
+
if tree is None:
|
663 |
+
tree = self._tree
|
664 |
+
for i in range(len(tree.subtrees()) - len(prod.rhs())):
|
665 |
+
if tree["color", i] == "white":
|
666 |
+
self._markproduction # FIXME: Is this necessary at all?
|
667 |
+
|
668 |
+
for j, node in enumerate(prod.rhs()):
|
669 |
+
widget = tree.subtrees()[i + j]
|
670 |
+
if (
|
671 |
+
isinstance(node, Nonterminal)
|
672 |
+
and isinstance(widget, TreeSegmentWidget)
|
673 |
+
and node.symbol == widget.label().text()
|
674 |
+
):
|
675 |
+
pass # matching nonterminal
|
676 |
+
elif (
|
677 |
+
isinstance(node, str)
|
678 |
+
and isinstance(widget, TextWidget)
|
679 |
+
and node == widget.text()
|
680 |
+
):
|
681 |
+
pass # matching nonterminal
|
682 |
+
else:
|
683 |
+
break
|
684 |
+
else:
|
685 |
+
# Everything matched!
|
686 |
+
print("MATCH AT", i)
|
687 |
+
|
688 |
+
# //////////////////////////////////////////////////
|
689 |
+
# Grammar
|
690 |
+
# //////////////////////////////////////////////////
|
691 |
+
|
692 |
+
def _selectprod_cb(self, production):
|
693 |
+
canvas = self._treelet_canvas
|
694 |
+
|
695 |
+
self._prodlist.highlight(production)
|
696 |
+
if self._treelet is not None:
|
697 |
+
self._treelet.destroy()
|
698 |
+
|
699 |
+
# Convert the production to a tree.
|
700 |
+
rhs = production.rhs()
|
701 |
+
for (i, elt) in enumerate(rhs):
|
702 |
+
if isinstance(elt, Nonterminal):
|
703 |
+
elt = Tree(elt)
|
704 |
+
tree = Tree(production.lhs().symbol(), *rhs)
|
705 |
+
|
706 |
+
# Draw the tree in the treelet area.
|
707 |
+
fontsize = int(self._size.get())
|
708 |
+
node_font = ("helvetica", -(fontsize + 4), "bold")
|
709 |
+
leaf_font = ("helvetica", -(fontsize + 2))
|
710 |
+
self._treelet = tree_to_treesegment(
|
711 |
+
canvas, tree, node_font=node_font, leaf_font=leaf_font
|
712 |
+
)
|
713 |
+
self._treelet["draggable"] = 1
|
714 |
+
|
715 |
+
# Center the treelet.
|
716 |
+
(x1, y1, x2, y2) = self._treelet.bbox()
|
717 |
+
w, h = int(canvas["width"]), int(canvas["height"])
|
718 |
+
self._treelet.move((w - x1 - x2) / 2, (h - y1 - y2) / 2)
|
719 |
+
|
720 |
+
# Mark the places where we can add it to the workspace.
|
721 |
+
self._markproduction(production)
|
722 |
+
|
723 |
+
def destroy(self, *args):
|
724 |
+
self._top.destroy()
|
725 |
+
|
726 |
+
def mainloop(self, *args, **kwargs):
|
727 |
+
self._top.mainloop(*args, **kwargs)
|
728 |
+
|
729 |
+
|
730 |
+
def demo2():
|
731 |
+
from nltk import CFG, Nonterminal, Production
|
732 |
+
|
733 |
+
nonterminals = "S VP NP PP P N Name V Det"
|
734 |
+
(S, VP, NP, PP, P, N, Name, V, Det) = (Nonterminal(s) for s in nonterminals.split())
|
735 |
+
productions = (
|
736 |
+
# Syntactic Productions
|
737 |
+
Production(S, [NP, VP]),
|
738 |
+
Production(NP, [Det, N]),
|
739 |
+
Production(NP, [NP, PP]),
|
740 |
+
Production(VP, [VP, PP]),
|
741 |
+
Production(VP, [V, NP, PP]),
|
742 |
+
Production(VP, [V, NP]),
|
743 |
+
Production(PP, [P, NP]),
|
744 |
+
Production(PP, []),
|
745 |
+
Production(PP, ["up", "over", NP]),
|
746 |
+
# Lexical Productions
|
747 |
+
Production(NP, ["I"]),
|
748 |
+
Production(Det, ["the"]),
|
749 |
+
Production(Det, ["a"]),
|
750 |
+
Production(N, ["man"]),
|
751 |
+
Production(V, ["saw"]),
|
752 |
+
Production(P, ["in"]),
|
753 |
+
Production(P, ["with"]),
|
754 |
+
Production(N, ["park"]),
|
755 |
+
Production(N, ["dog"]),
|
756 |
+
Production(N, ["statue"]),
|
757 |
+
Production(Det, ["my"]),
|
758 |
+
)
|
759 |
+
grammar = CFG(S, productions)
|
760 |
+
|
761 |
+
text = "I saw a man in the park".split()
|
762 |
+
d = CFGDemo(grammar, text)
|
763 |
+
d.mainloop()
|
764 |
+
|
765 |
+
|
766 |
+
######################################################################
|
767 |
+
# Old Demo
|
768 |
+
######################################################################
|
769 |
+
|
770 |
+
|
771 |
+
def demo():
|
772 |
+
from nltk import CFG, Nonterminal
|
773 |
+
|
774 |
+
nonterminals = "S VP NP PP P N Name V Det"
|
775 |
+
(S, VP, NP, PP, P, N, Name, V, Det) = (Nonterminal(s) for s in nonterminals.split())
|
776 |
+
|
777 |
+
grammar = CFG.fromstring(
|
778 |
+
"""
|
779 |
+
S -> NP VP
|
780 |
+
PP -> P NP
|
781 |
+
NP -> Det N
|
782 |
+
NP -> NP PP
|
783 |
+
VP -> V NP
|
784 |
+
VP -> VP PP
|
785 |
+
Det -> 'a'
|
786 |
+
Det -> 'the'
|
787 |
+
Det -> 'my'
|
788 |
+
NP -> 'I'
|
789 |
+
N -> 'dog'
|
790 |
+
N -> 'man'
|
791 |
+
N -> 'park'
|
792 |
+
N -> 'statue'
|
793 |
+
V -> 'saw'
|
794 |
+
P -> 'in'
|
795 |
+
P -> 'up'
|
796 |
+
P -> 'over'
|
797 |
+
P -> 'with'
|
798 |
+
"""
|
799 |
+
)
|
800 |
+
|
801 |
+
def cb(grammar):
|
802 |
+
print(grammar)
|
803 |
+
|
804 |
+
top = Tk()
|
805 |
+
editor = CFGEditor(top, grammar, cb)
|
806 |
+
Label(top, text="\nTesting CFG Editor\n").pack()
|
807 |
+
Button(top, text="Quit", command=top.destroy).pack()
|
808 |
+
top.mainloop()
|
809 |
+
|
810 |
+
|
811 |
+
def demo3():
|
812 |
+
from nltk import Production
|
813 |
+
|
814 |
+
(S, VP, NP, PP, P, N, Name, V, Det) = nonterminals(
|
815 |
+
"S, VP, NP, PP, P, N, Name, V, Det"
|
816 |
+
)
|
817 |
+
|
818 |
+
productions = (
|
819 |
+
# Syntactic Productions
|
820 |
+
Production(S, [NP, VP]),
|
821 |
+
Production(NP, [Det, N]),
|
822 |
+
Production(NP, [NP, PP]),
|
823 |
+
Production(VP, [VP, PP]),
|
824 |
+
Production(VP, [V, NP, PP]),
|
825 |
+
Production(VP, [V, NP]),
|
826 |
+
Production(PP, [P, NP]),
|
827 |
+
Production(PP, []),
|
828 |
+
Production(PP, ["up", "over", NP]),
|
829 |
+
# Lexical Productions
|
830 |
+
Production(NP, ["I"]),
|
831 |
+
Production(Det, ["the"]),
|
832 |
+
Production(Det, ["a"]),
|
833 |
+
Production(N, ["man"]),
|
834 |
+
Production(V, ["saw"]),
|
835 |
+
Production(P, ["in"]),
|
836 |
+
Production(P, ["with"]),
|
837 |
+
Production(N, ["park"]),
|
838 |
+
Production(N, ["dog"]),
|
839 |
+
Production(N, ["statue"]),
|
840 |
+
Production(Det, ["my"]),
|
841 |
+
)
|
842 |
+
|
843 |
+
t = Tk()
|
844 |
+
|
845 |
+
def destroy(e, t=t):
|
846 |
+
t.destroy()
|
847 |
+
|
848 |
+
t.bind("q", destroy)
|
849 |
+
p = ProductionList(t, productions)
|
850 |
+
p.pack(expand=1, fill="both")
|
851 |
+
p.add_callback("select", p.markonly)
|
852 |
+
p.add_callback("move", p.markonly)
|
853 |
+
p.focus()
|
854 |
+
p.mark(productions[2])
|
855 |
+
p.mark(productions[8])
|
856 |
+
|
857 |
+
|
858 |
+
if __name__ == "__main__":
|
859 |
+
demo()
|
env-llmeval/lib/python3.10/site-packages/nltk/draw/dispersion.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Dispersion Plots
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Steven Bird <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
|
8 |
+
"""
|
9 |
+
A utility for displaying lexical dispersion.
|
10 |
+
"""
|
11 |
+
|
12 |
+
|
13 |
+
def dispersion_plot(text, words, ignore_case=False, title="Lexical Dispersion Plot"):
|
14 |
+
"""
|
15 |
+
Generate a lexical dispersion plot.
|
16 |
+
|
17 |
+
:param text: The source text
|
18 |
+
:type text: list(str) or iter(str)
|
19 |
+
:param words: The target words
|
20 |
+
:type words: list of str
|
21 |
+
:param ignore_case: flag to set if case should be ignored when searching text
|
22 |
+
:type ignore_case: bool
|
23 |
+
:return: a matplotlib Axes object that may still be modified before plotting
|
24 |
+
:rtype: Axes
|
25 |
+
"""
|
26 |
+
|
27 |
+
try:
|
28 |
+
import matplotlib.pyplot as plt
|
29 |
+
except ImportError as e:
|
30 |
+
raise ImportError(
|
31 |
+
"The plot function requires matplotlib to be installed. "
|
32 |
+
"See https://matplotlib.org/"
|
33 |
+
) from e
|
34 |
+
|
35 |
+
word2y = {
|
36 |
+
word.casefold() if ignore_case else word: y
|
37 |
+
for y, word in enumerate(reversed(words))
|
38 |
+
}
|
39 |
+
xs, ys = [], []
|
40 |
+
for x, token in enumerate(text):
|
41 |
+
token = token.casefold() if ignore_case else token
|
42 |
+
y = word2y.get(token)
|
43 |
+
if y is not None:
|
44 |
+
xs.append(x)
|
45 |
+
ys.append(y)
|
46 |
+
|
47 |
+
_, ax = plt.subplots()
|
48 |
+
ax.plot(xs, ys, "|")
|
49 |
+
ax.set_yticks(list(range(len(words))), words, color="C0")
|
50 |
+
ax.set_ylim(-1, len(words))
|
51 |
+
ax.set_title(title)
|
52 |
+
ax.set_xlabel("Word Offset")
|
53 |
+
return ax
|
54 |
+
|
55 |
+
|
56 |
+
if __name__ == "__main__":
|
57 |
+
import matplotlib.pyplot as plt
|
58 |
+
|
59 |
+
from nltk.corpus import gutenberg
|
60 |
+
|
61 |
+
words = ["Elinor", "Marianne", "Edward", "Willoughby"]
|
62 |
+
dispersion_plot(gutenberg.words("austen-sense.txt"), words)
|
63 |
+
plt.show()
|
env-llmeval/lib/python3.10/site-packages/nltk/draw/table.py
ADDED
@@ -0,0 +1,1177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Table widget
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Edward Loper <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
|
8 |
+
"""
|
9 |
+
Tkinter widgets for displaying multi-column listboxes and tables.
|
10 |
+
"""
|
11 |
+
|
12 |
+
import operator
|
13 |
+
from tkinter import Frame, Label, Listbox, Scrollbar, Tk
|
14 |
+
|
15 |
+
######################################################################
|
16 |
+
# Multi-Column Listbox
|
17 |
+
######################################################################
|
18 |
+
|
19 |
+
|
20 |
+
class MultiListbox(Frame):
|
21 |
+
"""
|
22 |
+
A multi-column listbox, where the current selection applies to an
|
23 |
+
entire row. Based on the MultiListbox Tkinter widget
|
24 |
+
recipe from the Python Cookbook (https://code.activestate.com/recipes/52266/)
|
25 |
+
|
26 |
+
For the most part, ``MultiListbox`` methods delegate to its
|
27 |
+
contained listboxes. For any methods that do not have docstrings,
|
28 |
+
see ``Tkinter.Listbox`` for a description of what that method does.
|
29 |
+
"""
|
30 |
+
|
31 |
+
# /////////////////////////////////////////////////////////////////
|
32 |
+
# Configuration
|
33 |
+
# /////////////////////////////////////////////////////////////////
|
34 |
+
|
35 |
+
#: Default configuration values for the frame.
|
36 |
+
FRAME_CONFIG = dict(background="#888", takefocus=True, highlightthickness=1)
|
37 |
+
|
38 |
+
#: Default configurations for the column labels.
|
39 |
+
LABEL_CONFIG = dict(
|
40 |
+
borderwidth=1,
|
41 |
+
relief="raised",
|
42 |
+
font="helvetica -16 bold",
|
43 |
+
background="#444",
|
44 |
+
foreground="white",
|
45 |
+
)
|
46 |
+
|
47 |
+
#: Default configuration for the column listboxes.
|
48 |
+
LISTBOX_CONFIG = dict(
|
49 |
+
borderwidth=1,
|
50 |
+
selectborderwidth=0,
|
51 |
+
highlightthickness=0,
|
52 |
+
exportselection=False,
|
53 |
+
selectbackground="#888",
|
54 |
+
activestyle="none",
|
55 |
+
takefocus=False,
|
56 |
+
)
|
57 |
+
|
58 |
+
# /////////////////////////////////////////////////////////////////
|
59 |
+
# Constructor
|
60 |
+
# /////////////////////////////////////////////////////////////////
|
61 |
+
|
62 |
+
def __init__(self, master, columns, column_weights=None, cnf={}, **kw):
|
63 |
+
"""
|
64 |
+
Construct a new multi-column listbox widget.
|
65 |
+
|
66 |
+
:param master: The widget that should contain the new
|
67 |
+
multi-column listbox.
|
68 |
+
|
69 |
+
:param columns: Specifies what columns should be included in
|
70 |
+
the new multi-column listbox. If ``columns`` is an integer,
|
71 |
+
then it is the number of columns to include. If it is
|
72 |
+
a list, then its length indicates the number of columns
|
73 |
+
to include; and each element of the list will be used as
|
74 |
+
a label for the corresponding column.
|
75 |
+
|
76 |
+
:param cnf, kw: Configuration parameters for this widget.
|
77 |
+
Use ``label_*`` to configure all labels; and ``listbox_*``
|
78 |
+
to configure all listboxes. E.g.:
|
79 |
+
>>> root = Tk() # doctest: +SKIP
|
80 |
+
>>> MultiListbox(root, ["Subject", "Sender", "Date"], label_foreground='red').pack() # doctest: +SKIP
|
81 |
+
"""
|
82 |
+
# If columns was specified as an int, convert it to a list.
|
83 |
+
if isinstance(columns, int):
|
84 |
+
columns = list(range(columns))
|
85 |
+
include_labels = False
|
86 |
+
else:
|
87 |
+
include_labels = True
|
88 |
+
|
89 |
+
if len(columns) == 0:
|
90 |
+
raise ValueError("Expected at least one column")
|
91 |
+
|
92 |
+
# Instance variables
|
93 |
+
self._column_names = tuple(columns)
|
94 |
+
self._listboxes = []
|
95 |
+
self._labels = []
|
96 |
+
|
97 |
+
# Pick a default value for column_weights, if none was specified.
|
98 |
+
if column_weights is None:
|
99 |
+
column_weights = [1] * len(columns)
|
100 |
+
elif len(column_weights) != len(columns):
|
101 |
+
raise ValueError("Expected one column_weight for each column")
|
102 |
+
self._column_weights = column_weights
|
103 |
+
|
104 |
+
# Configure our widgets.
|
105 |
+
Frame.__init__(self, master, **self.FRAME_CONFIG)
|
106 |
+
self.grid_rowconfigure(1, weight=1)
|
107 |
+
for i, label in enumerate(self._column_names):
|
108 |
+
self.grid_columnconfigure(i, weight=column_weights[i])
|
109 |
+
|
110 |
+
# Create a label for the column
|
111 |
+
if include_labels:
|
112 |
+
l = Label(self, text=label, **self.LABEL_CONFIG)
|
113 |
+
self._labels.append(l)
|
114 |
+
l.grid(column=i, row=0, sticky="news", padx=0, pady=0)
|
115 |
+
l.column_index = i
|
116 |
+
|
117 |
+
# Create a listbox for the column
|
118 |
+
lb = Listbox(self, **self.LISTBOX_CONFIG)
|
119 |
+
self._listboxes.append(lb)
|
120 |
+
lb.grid(column=i, row=1, sticky="news", padx=0, pady=0)
|
121 |
+
lb.column_index = i
|
122 |
+
|
123 |
+
# Clicking or dragging selects:
|
124 |
+
lb.bind("<Button-1>", self._select)
|
125 |
+
lb.bind("<B1-Motion>", self._select)
|
126 |
+
# Scroll wheel scrolls:
|
127 |
+
lb.bind("<Button-4>", lambda e: self._scroll(-1))
|
128 |
+
lb.bind("<Button-5>", lambda e: self._scroll(+1))
|
129 |
+
lb.bind("<MouseWheel>", lambda e: self._scroll(e.delta))
|
130 |
+
# Button 2 can be used to scan:
|
131 |
+
lb.bind("<Button-2>", lambda e: self.scan_mark(e.x, e.y))
|
132 |
+
lb.bind("<B2-Motion>", lambda e: self.scan_dragto(e.x, e.y))
|
133 |
+
# Dragging outside the window has no effect (disable
|
134 |
+
# the default listbox behavior, which scrolls):
|
135 |
+
lb.bind("<B1-Leave>", lambda e: "break")
|
136 |
+
# Columns can be resized by dragging them:
|
137 |
+
lb.bind("<Button-1>", self._resize_column)
|
138 |
+
|
139 |
+
# Columns can be resized by dragging them. (This binding is
|
140 |
+
# used if they click on the grid between columns:)
|
141 |
+
self.bind("<Button-1>", self._resize_column)
|
142 |
+
|
143 |
+
# Set up key bindings for the widget:
|
144 |
+
self.bind("<Up>", lambda e: self.select(delta=-1))
|
145 |
+
self.bind("<Down>", lambda e: self.select(delta=1))
|
146 |
+
self.bind("<Prior>", lambda e: self.select(delta=-self._pagesize()))
|
147 |
+
self.bind("<Next>", lambda e: self.select(delta=self._pagesize()))
|
148 |
+
|
149 |
+
# Configuration customizations
|
150 |
+
self.configure(cnf, **kw)
|
151 |
+
|
152 |
+
# /////////////////////////////////////////////////////////////////
|
153 |
+
# Column Resizing
|
154 |
+
# /////////////////////////////////////////////////////////////////
|
155 |
+
|
156 |
+
def _resize_column(self, event):
|
157 |
+
"""
|
158 |
+
Callback used to resize a column of the table. Return ``True``
|
159 |
+
if the column is actually getting resized (if the user clicked
|
160 |
+
on the far left or far right 5 pixels of a label); and
|
161 |
+
``False`` otherwies.
|
162 |
+
"""
|
163 |
+
# If we're already waiting for a button release, then ignore
|
164 |
+
# the new button press.
|
165 |
+
if event.widget.bind("<ButtonRelease>"):
|
166 |
+
return False
|
167 |
+
|
168 |
+
# Decide which column (if any) to resize.
|
169 |
+
self._resize_column_index = None
|
170 |
+
if event.widget is self:
|
171 |
+
for i, lb in enumerate(self._listboxes):
|
172 |
+
if abs(event.x - (lb.winfo_x() + lb.winfo_width())) < 10:
|
173 |
+
self._resize_column_index = i
|
174 |
+
elif event.x > (event.widget.winfo_width() - 5):
|
175 |
+
self._resize_column_index = event.widget.column_index
|
176 |
+
elif event.x < 5 and event.widget.column_index != 0:
|
177 |
+
self._resize_column_index = event.widget.column_index - 1
|
178 |
+
|
179 |
+
# Bind callbacks that are used to resize it.
|
180 |
+
if self._resize_column_index is not None:
|
181 |
+
event.widget.bind("<Motion>", self._resize_column_motion_cb)
|
182 |
+
event.widget.bind(
|
183 |
+
"<ButtonRelease-%d>" % event.num, self._resize_column_buttonrelease_cb
|
184 |
+
)
|
185 |
+
return True
|
186 |
+
else:
|
187 |
+
return False
|
188 |
+
|
189 |
+
def _resize_column_motion_cb(self, event):
|
190 |
+
lb = self._listboxes[self._resize_column_index]
|
191 |
+
charwidth = lb.winfo_width() / lb["width"]
|
192 |
+
|
193 |
+
x1 = event.x + event.widget.winfo_x()
|
194 |
+
x2 = lb.winfo_x() + lb.winfo_width()
|
195 |
+
|
196 |
+
lb["width"] = max(3, lb["width"] + (x1 - x2) // charwidth)
|
197 |
+
|
198 |
+
def _resize_column_buttonrelease_cb(self, event):
|
199 |
+
event.widget.unbind("<ButtonRelease-%d>" % event.num)
|
200 |
+
event.widget.unbind("<Motion>")
|
201 |
+
|
202 |
+
# /////////////////////////////////////////////////////////////////
|
203 |
+
# Properties
|
204 |
+
# /////////////////////////////////////////////////////////////////
|
205 |
+
|
206 |
+
@property
|
207 |
+
def column_names(self):
|
208 |
+
"""
|
209 |
+
A tuple containing the names of the columns used by this
|
210 |
+
multi-column listbox.
|
211 |
+
"""
|
212 |
+
return self._column_names
|
213 |
+
|
214 |
+
@property
|
215 |
+
def column_labels(self):
|
216 |
+
"""
|
217 |
+
A tuple containing the ``Tkinter.Label`` widgets used to
|
218 |
+
display the label of each column. If this multi-column
|
219 |
+
listbox was created without labels, then this will be an empty
|
220 |
+
tuple. These widgets will all be augmented with a
|
221 |
+
``column_index`` attribute, which can be used to determine
|
222 |
+
which column they correspond to. This can be convenient,
|
223 |
+
e.g., when defining callbacks for bound events.
|
224 |
+
"""
|
225 |
+
return tuple(self._labels)
|
226 |
+
|
227 |
+
@property
|
228 |
+
def listboxes(self):
|
229 |
+
"""
|
230 |
+
A tuple containing the ``Tkinter.Listbox`` widgets used to
|
231 |
+
display individual columns. These widgets will all be
|
232 |
+
augmented with a ``column_index`` attribute, which can be used
|
233 |
+
to determine which column they correspond to. This can be
|
234 |
+
convenient, e.g., when defining callbacks for bound events.
|
235 |
+
"""
|
236 |
+
return tuple(self._listboxes)
|
237 |
+
|
238 |
+
# /////////////////////////////////////////////////////////////////
|
239 |
+
# Mouse & Keyboard Callback Functions
|
240 |
+
# /////////////////////////////////////////////////////////////////
|
241 |
+
|
242 |
+
def _select(self, e):
|
243 |
+
i = e.widget.nearest(e.y)
|
244 |
+
self.selection_clear(0, "end")
|
245 |
+
self.selection_set(i)
|
246 |
+
self.activate(i)
|
247 |
+
self.focus()
|
248 |
+
|
249 |
+
def _scroll(self, delta):
|
250 |
+
for lb in self._listboxes:
|
251 |
+
lb.yview_scroll(delta, "unit")
|
252 |
+
return "break"
|
253 |
+
|
254 |
+
def _pagesize(self):
|
255 |
+
""":return: The number of rows that makes up one page"""
|
256 |
+
return int(self.index("@0,1000000")) - int(self.index("@0,0"))
|
257 |
+
|
258 |
+
# /////////////////////////////////////////////////////////////////
|
259 |
+
# Row selection
|
260 |
+
# /////////////////////////////////////////////////////////////////
|
261 |
+
|
262 |
+
def select(self, index=None, delta=None, see=True):
|
263 |
+
"""
|
264 |
+
Set the selected row. If ``index`` is specified, then select
|
265 |
+
row ``index``. Otherwise, if ``delta`` is specified, then move
|
266 |
+
the current selection by ``delta`` (negative numbers for up,
|
267 |
+
positive numbers for down). This will not move the selection
|
268 |
+
past the top or the bottom of the list.
|
269 |
+
|
270 |
+
:param see: If true, then call ``self.see()`` with the newly
|
271 |
+
selected index, to ensure that it is visible.
|
272 |
+
"""
|
273 |
+
if (index is not None) and (delta is not None):
|
274 |
+
raise ValueError("specify index or delta, but not both")
|
275 |
+
|
276 |
+
# If delta was given, then calculate index.
|
277 |
+
if delta is not None:
|
278 |
+
if len(self.curselection()) == 0:
|
279 |
+
index = -1 + delta
|
280 |
+
else:
|
281 |
+
index = int(self.curselection()[0]) + delta
|
282 |
+
|
283 |
+
# Clear all selected rows.
|
284 |
+
self.selection_clear(0, "end")
|
285 |
+
|
286 |
+
# Select the specified index
|
287 |
+
if index is not None:
|
288 |
+
index = min(max(index, 0), self.size() - 1)
|
289 |
+
# self.activate(index)
|
290 |
+
self.selection_set(index)
|
291 |
+
if see:
|
292 |
+
self.see(index)
|
293 |
+
|
294 |
+
# /////////////////////////////////////////////////////////////////
|
295 |
+
# Configuration
|
296 |
+
# /////////////////////////////////////////////////////////////////
|
297 |
+
|
298 |
+
def configure(self, cnf={}, **kw):
|
299 |
+
"""
|
300 |
+
Configure this widget. Use ``label_*`` to configure all
|
301 |
+
labels; and ``listbox_*`` to configure all listboxes. E.g.:
|
302 |
+
|
303 |
+
>>> master = Tk() # doctest: +SKIP
|
304 |
+
>>> mlb = MultiListbox(master, 5) # doctest: +SKIP
|
305 |
+
>>> mlb.configure(label_foreground='red') # doctest: +SKIP
|
306 |
+
>>> mlb.configure(listbox_foreground='red') # doctest: +SKIP
|
307 |
+
"""
|
308 |
+
cnf = dict(list(cnf.items()) + list(kw.items()))
|
309 |
+
for (key, val) in list(cnf.items()):
|
310 |
+
if key.startswith("label_") or key.startswith("label-"):
|
311 |
+
for label in self._labels:
|
312 |
+
label.configure({key[6:]: val})
|
313 |
+
elif key.startswith("listbox_") or key.startswith("listbox-"):
|
314 |
+
for listbox in self._listboxes:
|
315 |
+
listbox.configure({key[8:]: val})
|
316 |
+
else:
|
317 |
+
Frame.configure(self, {key: val})
|
318 |
+
|
319 |
+
def __setitem__(self, key, val):
|
320 |
+
"""
|
321 |
+
Configure this widget. This is equivalent to
|
322 |
+
``self.configure({key,val``)}. See ``configure()``.
|
323 |
+
"""
|
324 |
+
self.configure({key: val})
|
325 |
+
|
326 |
+
def rowconfigure(self, row_index, cnf={}, **kw):
|
327 |
+
"""
|
328 |
+
Configure all table cells in the given row. Valid keyword
|
329 |
+
arguments are: ``background``, ``bg``, ``foreground``, ``fg``,
|
330 |
+
``selectbackground``, ``selectforeground``.
|
331 |
+
"""
|
332 |
+
for lb in self._listboxes:
|
333 |
+
lb.itemconfigure(row_index, cnf, **kw)
|
334 |
+
|
335 |
+
def columnconfigure(self, col_index, cnf={}, **kw):
|
336 |
+
"""
|
337 |
+
Configure all table cells in the given column. Valid keyword
|
338 |
+
arguments are: ``background``, ``bg``, ``foreground``, ``fg``,
|
339 |
+
``selectbackground``, ``selectforeground``.
|
340 |
+
"""
|
341 |
+
lb = self._listboxes[col_index]
|
342 |
+
|
343 |
+
cnf = dict(list(cnf.items()) + list(kw.items()))
|
344 |
+
for (key, val) in list(cnf.items()):
|
345 |
+
if key in (
|
346 |
+
"background",
|
347 |
+
"bg",
|
348 |
+
"foreground",
|
349 |
+
"fg",
|
350 |
+
"selectbackground",
|
351 |
+
"selectforeground",
|
352 |
+
):
|
353 |
+
for i in range(lb.size()):
|
354 |
+
lb.itemconfigure(i, {key: val})
|
355 |
+
else:
|
356 |
+
lb.configure({key: val})
|
357 |
+
|
358 |
+
def itemconfigure(self, row_index, col_index, cnf=None, **kw):
|
359 |
+
"""
|
360 |
+
Configure the table cell at the given row and column. Valid
|
361 |
+
keyword arguments are: ``background``, ``bg``, ``foreground``,
|
362 |
+
``fg``, ``selectbackground``, ``selectforeground``.
|
363 |
+
"""
|
364 |
+
lb = self._listboxes[col_index]
|
365 |
+
return lb.itemconfigure(row_index, cnf, **kw)
|
366 |
+
|
367 |
+
# /////////////////////////////////////////////////////////////////
|
368 |
+
# Value Access
|
369 |
+
# /////////////////////////////////////////////////////////////////
|
370 |
+
|
371 |
+
def insert(self, index, *rows):
|
372 |
+
"""
|
373 |
+
Insert the given row or rows into the table, at the given
|
374 |
+
index. Each row value should be a tuple of cell values, one
|
375 |
+
for each column in the row. Index may be an integer or any of
|
376 |
+
the special strings (such as ``'end'``) accepted by
|
377 |
+
``Tkinter.Listbox``.
|
378 |
+
"""
|
379 |
+
for elt in rows:
|
380 |
+
if len(elt) != len(self._column_names):
|
381 |
+
raise ValueError(
|
382 |
+
"rows should be tuples whose length "
|
383 |
+
"is equal to the number of columns"
|
384 |
+
)
|
385 |
+
for (lb, elts) in zip(self._listboxes, list(zip(*rows))):
|
386 |
+
lb.insert(index, *elts)
|
387 |
+
|
388 |
+
def get(self, first, last=None):
|
389 |
+
"""
|
390 |
+
Return the value(s) of the specified row(s). If ``last`` is
|
391 |
+
not specified, then return a single row value; otherwise,
|
392 |
+
return a list of row values. Each row value is a tuple of
|
393 |
+
cell values, one for each column in the row.
|
394 |
+
"""
|
395 |
+
values = [lb.get(first, last) for lb in self._listboxes]
|
396 |
+
if last:
|
397 |
+
return [tuple(row) for row in zip(*values)]
|
398 |
+
else:
|
399 |
+
return tuple(values)
|
400 |
+
|
401 |
+
def bbox(self, row, col):
|
402 |
+
"""
|
403 |
+
Return the bounding box for the given table cell, relative to
|
404 |
+
this widget's top-left corner. The bounding box is a tuple
|
405 |
+
of integers ``(left, top, width, height)``.
|
406 |
+
"""
|
407 |
+
dx, dy, _, _ = self.grid_bbox(row=0, column=col)
|
408 |
+
x, y, w, h = self._listboxes[col].bbox(row)
|
409 |
+
return int(x) + int(dx), int(y) + int(dy), int(w), int(h)
|
410 |
+
|
411 |
+
# /////////////////////////////////////////////////////////////////
|
412 |
+
# Hide/Show Columns
|
413 |
+
# /////////////////////////////////////////////////////////////////
|
414 |
+
|
415 |
+
def hide_column(self, col_index):
|
416 |
+
"""
|
417 |
+
Hide the given column. The column's state is still
|
418 |
+
maintained: its values will still be returned by ``get()``, and
|
419 |
+
you must supply its values when calling ``insert()``. It is
|
420 |
+
safe to call this on a column that is already hidden.
|
421 |
+
|
422 |
+
:see: ``show_column()``
|
423 |
+
"""
|
424 |
+
if self._labels:
|
425 |
+
self._labels[col_index].grid_forget()
|
426 |
+
self.listboxes[col_index].grid_forget()
|
427 |
+
self.grid_columnconfigure(col_index, weight=0)
|
428 |
+
|
429 |
+
def show_column(self, col_index):
|
430 |
+
"""
|
431 |
+
Display a column that has been hidden using ``hide_column()``.
|
432 |
+
It is safe to call this on a column that is not hidden.
|
433 |
+
"""
|
434 |
+
weight = self._column_weights[col_index]
|
435 |
+
if self._labels:
|
436 |
+
self._labels[col_index].grid(
|
437 |
+
column=col_index, row=0, sticky="news", padx=0, pady=0
|
438 |
+
)
|
439 |
+
self._listboxes[col_index].grid(
|
440 |
+
column=col_index, row=1, sticky="news", padx=0, pady=0
|
441 |
+
)
|
442 |
+
self.grid_columnconfigure(col_index, weight=weight)
|
443 |
+
|
444 |
+
# /////////////////////////////////////////////////////////////////
|
445 |
+
# Binding Methods
|
446 |
+
# /////////////////////////////////////////////////////////////////
|
447 |
+
|
448 |
+
def bind_to_labels(self, sequence=None, func=None, add=None):
|
449 |
+
"""
|
450 |
+
Add a binding to each ``Tkinter.Label`` widget in this
|
451 |
+
mult-column listbox that will call ``func`` in response to the
|
452 |
+
event sequence.
|
453 |
+
|
454 |
+
:return: A list of the identifiers of replaced binding
|
455 |
+
functions (if any), allowing for their deletion (to
|
456 |
+
prevent a memory leak).
|
457 |
+
"""
|
458 |
+
return [label.bind(sequence, func, add) for label in self.column_labels]
|
459 |
+
|
460 |
+
def bind_to_listboxes(self, sequence=None, func=None, add=None):
|
461 |
+
"""
|
462 |
+
Add a binding to each ``Tkinter.Listbox`` widget in this
|
463 |
+
mult-column listbox that will call ``func`` in response to the
|
464 |
+
event sequence.
|
465 |
+
|
466 |
+
:return: A list of the identifiers of replaced binding
|
467 |
+
functions (if any), allowing for their deletion (to
|
468 |
+
prevent a memory leak).
|
469 |
+
"""
|
470 |
+
for listbox in self.listboxes:
|
471 |
+
listbox.bind(sequence, func, add)
|
472 |
+
|
473 |
+
def bind_to_columns(self, sequence=None, func=None, add=None):
|
474 |
+
"""
|
475 |
+
Add a binding to each ``Tkinter.Label`` and ``Tkinter.Listbox``
|
476 |
+
widget in this mult-column listbox that will call ``func`` in
|
477 |
+
response to the event sequence.
|
478 |
+
|
479 |
+
:return: A list of the identifiers of replaced binding
|
480 |
+
functions (if any), allowing for their deletion (to
|
481 |
+
prevent a memory leak).
|
482 |
+
"""
|
483 |
+
return self.bind_to_labels(sequence, func, add) + self.bind_to_listboxes(
|
484 |
+
sequence, func, add
|
485 |
+
)
|
486 |
+
|
487 |
+
# /////////////////////////////////////////////////////////////////
|
488 |
+
# Simple Delegation
|
489 |
+
# /////////////////////////////////////////////////////////////////
|
490 |
+
|
491 |
+
# These methods delegate to the first listbox:
|
492 |
+
def curselection(self, *args, **kwargs):
|
493 |
+
return self._listboxes[0].curselection(*args, **kwargs)
|
494 |
+
|
495 |
+
def selection_includes(self, *args, **kwargs):
|
496 |
+
return self._listboxes[0].selection_includes(*args, **kwargs)
|
497 |
+
|
498 |
+
def itemcget(self, *args, **kwargs):
|
499 |
+
return self._listboxes[0].itemcget(*args, **kwargs)
|
500 |
+
|
501 |
+
def size(self, *args, **kwargs):
|
502 |
+
return self._listboxes[0].size(*args, **kwargs)
|
503 |
+
|
504 |
+
def index(self, *args, **kwargs):
|
505 |
+
return self._listboxes[0].index(*args, **kwargs)
|
506 |
+
|
507 |
+
def nearest(self, *args, **kwargs):
|
508 |
+
return self._listboxes[0].nearest(*args, **kwargs)
|
509 |
+
|
510 |
+
# These methods delegate to each listbox (and return None):
|
511 |
+
def activate(self, *args, **kwargs):
|
512 |
+
for lb in self._listboxes:
|
513 |
+
lb.activate(*args, **kwargs)
|
514 |
+
|
515 |
+
def delete(self, *args, **kwargs):
|
516 |
+
for lb in self._listboxes:
|
517 |
+
lb.delete(*args, **kwargs)
|
518 |
+
|
519 |
+
def scan_mark(self, *args, **kwargs):
|
520 |
+
for lb in self._listboxes:
|
521 |
+
lb.scan_mark(*args, **kwargs)
|
522 |
+
|
523 |
+
def scan_dragto(self, *args, **kwargs):
|
524 |
+
for lb in self._listboxes:
|
525 |
+
lb.scan_dragto(*args, **kwargs)
|
526 |
+
|
527 |
+
def see(self, *args, **kwargs):
|
528 |
+
for lb in self._listboxes:
|
529 |
+
lb.see(*args, **kwargs)
|
530 |
+
|
531 |
+
def selection_anchor(self, *args, **kwargs):
|
532 |
+
for lb in self._listboxes:
|
533 |
+
lb.selection_anchor(*args, **kwargs)
|
534 |
+
|
535 |
+
def selection_clear(self, *args, **kwargs):
|
536 |
+
for lb in self._listboxes:
|
537 |
+
lb.selection_clear(*args, **kwargs)
|
538 |
+
|
539 |
+
def selection_set(self, *args, **kwargs):
|
540 |
+
for lb in self._listboxes:
|
541 |
+
lb.selection_set(*args, **kwargs)
|
542 |
+
|
543 |
+
def yview(self, *args, **kwargs):
|
544 |
+
for lb in self._listboxes:
|
545 |
+
v = lb.yview(*args, **kwargs)
|
546 |
+
return v # if called with no arguments
|
547 |
+
|
548 |
+
def yview_moveto(self, *args, **kwargs):
|
549 |
+
for lb in self._listboxes:
|
550 |
+
lb.yview_moveto(*args, **kwargs)
|
551 |
+
|
552 |
+
def yview_scroll(self, *args, **kwargs):
|
553 |
+
for lb in self._listboxes:
|
554 |
+
lb.yview_scroll(*args, **kwargs)
|
555 |
+
|
556 |
+
# /////////////////////////////////////////////////////////////////
|
557 |
+
# Aliases
|
558 |
+
# /////////////////////////////////////////////////////////////////
|
559 |
+
|
560 |
+
itemconfig = itemconfigure
|
561 |
+
rowconfig = rowconfigure
|
562 |
+
columnconfig = columnconfigure
|
563 |
+
select_anchor = selection_anchor
|
564 |
+
select_clear = selection_clear
|
565 |
+
select_includes = selection_includes
|
566 |
+
select_set = selection_set
|
567 |
+
|
568 |
+
# /////////////////////////////////////////////////////////////////
|
569 |
+
# These listbox methods are not defined for multi-listbox
|
570 |
+
# /////////////////////////////////////////////////////////////////
|
571 |
+
# def xview(self, *what): pass
|
572 |
+
# def xview_moveto(self, fraction): pass
|
573 |
+
# def xview_scroll(self, number, what): pass
|
574 |
+
|
575 |
+
|
576 |
+
######################################################################
|
577 |
+
# Table
|
578 |
+
######################################################################
|
579 |
+
|
580 |
+
|
581 |
+
class Table:
|
582 |
+
"""
|
583 |
+
A display widget for a table of values, based on a ``MultiListbox``
|
584 |
+
widget. For many purposes, ``Table`` can be treated as a
|
585 |
+
list-of-lists. E.g., table[i] is a list of the values for row i;
|
586 |
+
and table.append(row) adds a new row with the given list of
|
587 |
+
values. Individual cells can be accessed using table[i,j], which
|
588 |
+
refers to the j-th column of the i-th row. This can be used to
|
589 |
+
both read and write values from the table. E.g.:
|
590 |
+
|
591 |
+
>>> table[i,j] = 'hello' # doctest: +SKIP
|
592 |
+
|
593 |
+
The column (j) can be given either as an index number, or as a
|
594 |
+
column name. E.g., the following prints the value in the 3rd row
|
595 |
+
for the 'First Name' column:
|
596 |
+
|
597 |
+
>>> print(table[3, 'First Name']) # doctest: +SKIP
|
598 |
+
John
|
599 |
+
|
600 |
+
You can configure the colors for individual rows, columns, or
|
601 |
+
cells using ``rowconfig()``, ``columnconfig()``, and ``itemconfig()``.
|
602 |
+
The color configuration for each row will be preserved if the
|
603 |
+
table is modified; however, when new rows are added, any color
|
604 |
+
configurations that have been made for *columns* will not be
|
605 |
+
applied to the new row.
|
606 |
+
|
607 |
+
Note: Although ``Table`` acts like a widget in some ways (e.g., it
|
608 |
+
defines ``grid()``, ``pack()``, and ``bind()``), it is not itself a
|
609 |
+
widget; it just contains one. This is because widgets need to
|
610 |
+
define ``__getitem__()``, ``__setitem__()``, and ``__nonzero__()`` in
|
611 |
+
a way that's incompatible with the fact that ``Table`` behaves as a
|
612 |
+
list-of-lists.
|
613 |
+
|
614 |
+
:ivar _mlb: The multi-column listbox used to display this table's data.
|
615 |
+
:ivar _rows: A list-of-lists used to hold the cell values of this
|
616 |
+
table. Each element of _rows is a row value, i.e., a list of
|
617 |
+
cell values, one for each column in the row.
|
618 |
+
"""
|
619 |
+
|
620 |
+
def __init__(
|
621 |
+
self,
|
622 |
+
master,
|
623 |
+
column_names,
|
624 |
+
rows=None,
|
625 |
+
column_weights=None,
|
626 |
+
scrollbar=True,
|
627 |
+
click_to_sort=True,
|
628 |
+
reprfunc=None,
|
629 |
+
cnf={},
|
630 |
+
**kw
|
631 |
+
):
|
632 |
+
"""
|
633 |
+
Construct a new Table widget.
|
634 |
+
|
635 |
+
:type master: Tkinter.Widget
|
636 |
+
:param master: The widget that should contain the new table.
|
637 |
+
:type column_names: list(str)
|
638 |
+
:param column_names: A list of names for the columns; these
|
639 |
+
names will be used to create labels for each column;
|
640 |
+
and can be used as an index when reading or writing
|
641 |
+
cell values from the table.
|
642 |
+
:type rows: list(list)
|
643 |
+
:param rows: A list of row values used to initialize the table.
|
644 |
+
Each row value should be a tuple of cell values, one for
|
645 |
+
each column in the row.
|
646 |
+
:type scrollbar: bool
|
647 |
+
:param scrollbar: If true, then create a scrollbar for the
|
648 |
+
new table widget.
|
649 |
+
:type click_to_sort: bool
|
650 |
+
:param click_to_sort: If true, then create bindings that will
|
651 |
+
sort the table's rows by a given column's values if the
|
652 |
+
user clicks on that colum's label.
|
653 |
+
:type reprfunc: function
|
654 |
+
:param reprfunc: If specified, then use this function to
|
655 |
+
convert each table cell value to a string suitable for
|
656 |
+
display. ``reprfunc`` has the following signature:
|
657 |
+
reprfunc(row_index, col_index, cell_value) -> str
|
658 |
+
(Note that the column is specified by index, not by name.)
|
659 |
+
:param cnf, kw: Configuration parameters for this widget's
|
660 |
+
contained ``MultiListbox``. See ``MultiListbox.__init__()``
|
661 |
+
for details.
|
662 |
+
"""
|
663 |
+
self._num_columns = len(column_names)
|
664 |
+
self._reprfunc = reprfunc
|
665 |
+
self._frame = Frame(master)
|
666 |
+
|
667 |
+
self._column_name_to_index = {c: i for (i, c) in enumerate(column_names)}
|
668 |
+
|
669 |
+
# Make a copy of the rows & check that it's valid.
|
670 |
+
if rows is None:
|
671 |
+
self._rows = []
|
672 |
+
else:
|
673 |
+
self._rows = [[v for v in row] for row in rows]
|
674 |
+
for row in self._rows:
|
675 |
+
self._checkrow(row)
|
676 |
+
|
677 |
+
# Create our multi-list box.
|
678 |
+
self._mlb = MultiListbox(self._frame, column_names, column_weights, cnf, **kw)
|
679 |
+
self._mlb.pack(side="left", expand=True, fill="both")
|
680 |
+
|
681 |
+
# Optional scrollbar
|
682 |
+
if scrollbar:
|
683 |
+
sb = Scrollbar(self._frame, orient="vertical", command=self._mlb.yview)
|
684 |
+
self._mlb.listboxes[0]["yscrollcommand"] = sb.set
|
685 |
+
# for listbox in self._mlb.listboxes:
|
686 |
+
# listbox['yscrollcommand'] = sb.set
|
687 |
+
sb.pack(side="right", fill="y")
|
688 |
+
self._scrollbar = sb
|
689 |
+
|
690 |
+
# Set up sorting
|
691 |
+
self._sortkey = None
|
692 |
+
if click_to_sort:
|
693 |
+
for i, l in enumerate(self._mlb.column_labels):
|
694 |
+
l.bind("<Button-1>", self._sort)
|
695 |
+
|
696 |
+
# Fill in our multi-list box.
|
697 |
+
self._fill_table()
|
698 |
+
|
699 |
+
# /////////////////////////////////////////////////////////////////
|
700 |
+
# { Widget-like Methods
|
701 |
+
# /////////////////////////////////////////////////////////////////
|
702 |
+
# These all just delegate to either our frame or our MLB.
|
703 |
+
|
704 |
+
def pack(self, *args, **kwargs):
|
705 |
+
"""Position this table's main frame widget in its parent
|
706 |
+
widget. See ``Tkinter.Frame.pack()`` for more info."""
|
707 |
+
self._frame.pack(*args, **kwargs)
|
708 |
+
|
709 |
+
def grid(self, *args, **kwargs):
|
710 |
+
"""Position this table's main frame widget in its parent
|
711 |
+
widget. See ``Tkinter.Frame.grid()`` for more info."""
|
712 |
+
self._frame.grid(*args, **kwargs)
|
713 |
+
|
714 |
+
def focus(self):
|
715 |
+
"""Direct (keyboard) input foxus to this widget."""
|
716 |
+
self._mlb.focus()
|
717 |
+
|
718 |
+
def bind(self, sequence=None, func=None, add=None):
|
719 |
+
"""Add a binding to this table's main frame that will call
|
720 |
+
``func`` in response to the event sequence."""
|
721 |
+
self._mlb.bind(sequence, func, add)
|
722 |
+
|
723 |
+
def rowconfigure(self, row_index, cnf={}, **kw):
|
724 |
+
""":see: ``MultiListbox.rowconfigure()``"""
|
725 |
+
self._mlb.rowconfigure(row_index, cnf, **kw)
|
726 |
+
|
727 |
+
def columnconfigure(self, col_index, cnf={}, **kw):
|
728 |
+
""":see: ``MultiListbox.columnconfigure()``"""
|
729 |
+
col_index = self.column_index(col_index)
|
730 |
+
self._mlb.columnconfigure(col_index, cnf, **kw)
|
731 |
+
|
732 |
+
def itemconfigure(self, row_index, col_index, cnf=None, **kw):
|
733 |
+
""":see: ``MultiListbox.itemconfigure()``"""
|
734 |
+
col_index = self.column_index(col_index)
|
735 |
+
return self._mlb.itemconfigure(row_index, col_index, cnf, **kw)
|
736 |
+
|
737 |
+
def bind_to_labels(self, sequence=None, func=None, add=None):
|
738 |
+
""":see: ``MultiListbox.bind_to_labels()``"""
|
739 |
+
return self._mlb.bind_to_labels(sequence, func, add)
|
740 |
+
|
741 |
+
def bind_to_listboxes(self, sequence=None, func=None, add=None):
|
742 |
+
""":see: ``MultiListbox.bind_to_listboxes()``"""
|
743 |
+
return self._mlb.bind_to_listboxes(sequence, func, add)
|
744 |
+
|
745 |
+
def bind_to_columns(self, sequence=None, func=None, add=None):
|
746 |
+
""":see: ``MultiListbox.bind_to_columns()``"""
|
747 |
+
return self._mlb.bind_to_columns(sequence, func, add)
|
748 |
+
|
749 |
+
rowconfig = rowconfigure
|
750 |
+
columnconfig = columnconfigure
|
751 |
+
itemconfig = itemconfigure
|
752 |
+
|
753 |
+
# /////////////////////////////////////////////////////////////////
|
754 |
+
# { Table as list-of-lists
|
755 |
+
# /////////////////////////////////////////////////////////////////
|
756 |
+
|
757 |
+
def insert(self, row_index, rowvalue):
|
758 |
+
"""
|
759 |
+
Insert a new row into the table, so that its row index will be
|
760 |
+
``row_index``. If the table contains any rows whose row index
|
761 |
+
is greater than or equal to ``row_index``, then they will be
|
762 |
+
shifted down.
|
763 |
+
|
764 |
+
:param rowvalue: A tuple of cell values, one for each column
|
765 |
+
in the new row.
|
766 |
+
"""
|
767 |
+
self._checkrow(rowvalue)
|
768 |
+
self._rows.insert(row_index, rowvalue)
|
769 |
+
if self._reprfunc is not None:
|
770 |
+
rowvalue = [
|
771 |
+
self._reprfunc(row_index, j, v) for (j, v) in enumerate(rowvalue)
|
772 |
+
]
|
773 |
+
self._mlb.insert(row_index, rowvalue)
|
774 |
+
if self._DEBUG:
|
775 |
+
self._check_table_vs_mlb()
|
776 |
+
|
777 |
+
def extend(self, rowvalues):
|
778 |
+
"""
|
779 |
+
Add new rows at the end of the table.
|
780 |
+
|
781 |
+
:param rowvalues: A list of row values used to initialize the
|
782 |
+
table. Each row value should be a tuple of cell values,
|
783 |
+
one for each column in the row.
|
784 |
+
"""
|
785 |
+
for rowvalue in rowvalues:
|
786 |
+
self.append(rowvalue)
|
787 |
+
if self._DEBUG:
|
788 |
+
self._check_table_vs_mlb()
|
789 |
+
|
790 |
+
def append(self, rowvalue):
|
791 |
+
"""
|
792 |
+
Add a new row to the end of the table.
|
793 |
+
|
794 |
+
:param rowvalue: A tuple of cell values, one for each column
|
795 |
+
in the new row.
|
796 |
+
"""
|
797 |
+
self.insert(len(self._rows), rowvalue)
|
798 |
+
if self._DEBUG:
|
799 |
+
self._check_table_vs_mlb()
|
800 |
+
|
801 |
+
def clear(self):
|
802 |
+
"""
|
803 |
+
Delete all rows in this table.
|
804 |
+
"""
|
805 |
+
self._rows = []
|
806 |
+
self._mlb.delete(0, "end")
|
807 |
+
if self._DEBUG:
|
808 |
+
self._check_table_vs_mlb()
|
809 |
+
|
810 |
+
def __getitem__(self, index):
|
811 |
+
"""
|
812 |
+
Return the value of a row or a cell in this table. If
|
813 |
+
``index`` is an integer, then the row value for the ``index``th
|
814 |
+
row. This row value consists of a tuple of cell values, one
|
815 |
+
for each column in the row. If ``index`` is a tuple of two
|
816 |
+
integers, ``(i,j)``, then return the value of the cell in the
|
817 |
+
``i``th row and the ``j``th column.
|
818 |
+
"""
|
819 |
+
if isinstance(index, slice):
|
820 |
+
raise ValueError("Slicing not supported")
|
821 |
+
elif isinstance(index, tuple) and len(index) == 2:
|
822 |
+
return self._rows[index[0]][self.column_index(index[1])]
|
823 |
+
else:
|
824 |
+
return tuple(self._rows[index])
|
825 |
+
|
826 |
+
def __setitem__(self, index, val):
|
827 |
+
"""
|
828 |
+
Replace the value of a row or a cell in this table with
|
829 |
+
``val``.
|
830 |
+
|
831 |
+
If ``index`` is an integer, then ``val`` should be a row value
|
832 |
+
(i.e., a tuple of cell values, one for each column). In this
|
833 |
+
case, the values of the ``index``th row of the table will be
|
834 |
+
replaced with the values in ``val``.
|
835 |
+
|
836 |
+
If ``index`` is a tuple of integers, ``(i,j)``, then replace the
|
837 |
+
value of the cell in the ``i``th row and ``j``th column with
|
838 |
+
``val``.
|
839 |
+
"""
|
840 |
+
if isinstance(index, slice):
|
841 |
+
raise ValueError("Slicing not supported")
|
842 |
+
|
843 |
+
# table[i,j] = val
|
844 |
+
elif isinstance(index, tuple) and len(index) == 2:
|
845 |
+
i, j = index[0], self.column_index(index[1])
|
846 |
+
config_cookie = self._save_config_info([i])
|
847 |
+
self._rows[i][j] = val
|
848 |
+
if self._reprfunc is not None:
|
849 |
+
val = self._reprfunc(i, j, val)
|
850 |
+
self._mlb.listboxes[j].insert(i, val)
|
851 |
+
self._mlb.listboxes[j].delete(i + 1)
|
852 |
+
self._restore_config_info(config_cookie)
|
853 |
+
|
854 |
+
# table[i] = val
|
855 |
+
else:
|
856 |
+
config_cookie = self._save_config_info([index])
|
857 |
+
self._checkrow(val)
|
858 |
+
self._rows[index] = list(val)
|
859 |
+
if self._reprfunc is not None:
|
860 |
+
val = [self._reprfunc(index, j, v) for (j, v) in enumerate(val)]
|
861 |
+
self._mlb.insert(index, val)
|
862 |
+
self._mlb.delete(index + 1)
|
863 |
+
self._restore_config_info(config_cookie)
|
864 |
+
|
865 |
+
def __delitem__(self, row_index):
|
866 |
+
"""
|
867 |
+
Delete the ``row_index``th row from this table.
|
868 |
+
"""
|
869 |
+
if isinstance(row_index, slice):
|
870 |
+
raise ValueError("Slicing not supported")
|
871 |
+
if isinstance(row_index, tuple) and len(row_index) == 2:
|
872 |
+
raise ValueError("Cannot delete a single cell!")
|
873 |
+
del self._rows[row_index]
|
874 |
+
self._mlb.delete(row_index)
|
875 |
+
if self._DEBUG:
|
876 |
+
self._check_table_vs_mlb()
|
877 |
+
|
878 |
+
def __len__(self):
|
879 |
+
"""
|
880 |
+
:return: the number of rows in this table.
|
881 |
+
"""
|
882 |
+
return len(self._rows)
|
883 |
+
|
884 |
+
def _checkrow(self, rowvalue):
|
885 |
+
"""
|
886 |
+
Helper function: check that a given row value has the correct
|
887 |
+
number of elements; and if not, raise an exception.
|
888 |
+
"""
|
889 |
+
if len(rowvalue) != self._num_columns:
|
890 |
+
raise ValueError(
|
891 |
+
"Row %r has %d columns; expected %d"
|
892 |
+
% (rowvalue, len(rowvalue), self._num_columns)
|
893 |
+
)
|
894 |
+
|
895 |
+
# /////////////////////////////////////////////////////////////////
|
896 |
+
# Columns
|
897 |
+
# /////////////////////////////////////////////////////////////////
|
898 |
+
|
899 |
+
@property
|
900 |
+
def column_names(self):
|
901 |
+
"""A list of the names of the columns in this table."""
|
902 |
+
return self._mlb.column_names
|
903 |
+
|
904 |
+
def column_index(self, i):
|
905 |
+
"""
|
906 |
+
If ``i`` is a valid column index integer, then return it as is.
|
907 |
+
Otherwise, check if ``i`` is used as the name for any column;
|
908 |
+
if so, return that column's index. Otherwise, raise a
|
909 |
+
``KeyError`` exception.
|
910 |
+
"""
|
911 |
+
if isinstance(i, int) and 0 <= i < self._num_columns:
|
912 |
+
return i
|
913 |
+
else:
|
914 |
+
# This raises a key error if the column is not found.
|
915 |
+
return self._column_name_to_index[i]
|
916 |
+
|
917 |
+
def hide_column(self, column_index):
|
918 |
+
""":see: ``MultiListbox.hide_column()``"""
|
919 |
+
self._mlb.hide_column(self.column_index(column_index))
|
920 |
+
|
921 |
+
def show_column(self, column_index):
|
922 |
+
""":see: ``MultiListbox.show_column()``"""
|
923 |
+
self._mlb.show_column(self.column_index(column_index))
|
924 |
+
|
925 |
+
# /////////////////////////////////////////////////////////////////
|
926 |
+
# Selection
|
927 |
+
# /////////////////////////////////////////////////////////////////
|
928 |
+
|
929 |
+
def selected_row(self):
|
930 |
+
"""
|
931 |
+
Return the index of the currently selected row, or None if
|
932 |
+
no row is selected. To get the row value itself, use
|
933 |
+
``table[table.selected_row()]``.
|
934 |
+
"""
|
935 |
+
sel = self._mlb.curselection()
|
936 |
+
if sel:
|
937 |
+
return int(sel[0])
|
938 |
+
else:
|
939 |
+
return None
|
940 |
+
|
941 |
+
def select(self, index=None, delta=None, see=True):
|
942 |
+
""":see: ``MultiListbox.select()``"""
|
943 |
+
self._mlb.select(index, delta, see)
|
944 |
+
|
945 |
+
# /////////////////////////////////////////////////////////////////
|
946 |
+
# Sorting
|
947 |
+
# /////////////////////////////////////////////////////////////////
|
948 |
+
|
949 |
+
def sort_by(self, column_index, order="toggle"):
|
950 |
+
"""
|
951 |
+
Sort the rows in this table, using the specified column's
|
952 |
+
values as a sort key.
|
953 |
+
|
954 |
+
:param column_index: Specifies which column to sort, using
|
955 |
+
either a column index (int) or a column's label name
|
956 |
+
(str).
|
957 |
+
|
958 |
+
:param order: Specifies whether to sort the values in
|
959 |
+
ascending or descending order:
|
960 |
+
|
961 |
+
- ``'ascending'``: Sort from least to greatest.
|
962 |
+
- ``'descending'``: Sort from greatest to least.
|
963 |
+
- ``'toggle'``: If the most recent call to ``sort_by()``
|
964 |
+
sorted the table by the same column (``column_index``),
|
965 |
+
then reverse the rows; otherwise sort in ascending
|
966 |
+
order.
|
967 |
+
"""
|
968 |
+
if order not in ("ascending", "descending", "toggle"):
|
969 |
+
raise ValueError(
|
970 |
+
'sort_by(): order should be "ascending", ' '"descending", or "toggle".'
|
971 |
+
)
|
972 |
+
column_index = self.column_index(column_index)
|
973 |
+
config_cookie = self._save_config_info(index_by_id=True)
|
974 |
+
|
975 |
+
# Sort the rows.
|
976 |
+
if order == "toggle" and column_index == self._sortkey:
|
977 |
+
self._rows.reverse()
|
978 |
+
else:
|
979 |
+
self._rows.sort(
|
980 |
+
key=operator.itemgetter(column_index), reverse=(order == "descending")
|
981 |
+
)
|
982 |
+
self._sortkey = column_index
|
983 |
+
|
984 |
+
# Redraw the table.
|
985 |
+
self._fill_table()
|
986 |
+
self._restore_config_info(config_cookie, index_by_id=True, see=True)
|
987 |
+
if self._DEBUG:
|
988 |
+
self._check_table_vs_mlb()
|
989 |
+
|
990 |
+
def _sort(self, event):
|
991 |
+
"""Event handler for clicking on a column label -- sort by
|
992 |
+
that column."""
|
993 |
+
column_index = event.widget.column_index
|
994 |
+
|
995 |
+
# If they click on the far-left of far-right of a column's
|
996 |
+
# label, then resize rather than sorting.
|
997 |
+
if self._mlb._resize_column(event):
|
998 |
+
return "continue"
|
999 |
+
|
1000 |
+
# Otherwise, sort.
|
1001 |
+
else:
|
1002 |
+
self.sort_by(column_index)
|
1003 |
+
return "continue"
|
1004 |
+
|
1005 |
+
# /////////////////////////////////////////////////////////////////
|
1006 |
+
# { Table Drawing Helpers
|
1007 |
+
# /////////////////////////////////////////////////////////////////
|
1008 |
+
|
1009 |
+
def _fill_table(self, save_config=True):
|
1010 |
+
"""
|
1011 |
+
Re-draw the table from scratch, by clearing out the table's
|
1012 |
+
multi-column listbox; and then filling it in with values from
|
1013 |
+
``self._rows``. Note that any cell-, row-, or column-specific
|
1014 |
+
color configuration that has been done will be lost. The
|
1015 |
+
selection will also be lost -- i.e., no row will be selected
|
1016 |
+
after this call completes.
|
1017 |
+
"""
|
1018 |
+
self._mlb.delete(0, "end")
|
1019 |
+
for i, row in enumerate(self._rows):
|
1020 |
+
if self._reprfunc is not None:
|
1021 |
+
row = [self._reprfunc(i, j, v) for (j, v) in enumerate(row)]
|
1022 |
+
self._mlb.insert("end", row)
|
1023 |
+
|
1024 |
+
def _get_itemconfig(self, r, c):
|
1025 |
+
return {
|
1026 |
+
k: self._mlb.itemconfig(r, c, k)[-1]
|
1027 |
+
for k in (
|
1028 |
+
"foreground",
|
1029 |
+
"selectforeground",
|
1030 |
+
"background",
|
1031 |
+
"selectbackground",
|
1032 |
+
)
|
1033 |
+
}
|
1034 |
+
|
1035 |
+
def _save_config_info(self, row_indices=None, index_by_id=False):
|
1036 |
+
"""
|
1037 |
+
Return a 'cookie' containing information about which row is
|
1038 |
+
selected, and what color configurations have been applied.
|
1039 |
+
this information can the be re-applied to the table (after
|
1040 |
+
making modifications) using ``_restore_config_info()``. Color
|
1041 |
+
configuration information will be saved for any rows in
|
1042 |
+
``row_indices``, or in the entire table, if
|
1043 |
+
``row_indices=None``. If ``index_by_id=True``, the the cookie
|
1044 |
+
will associate rows with their configuration information based
|
1045 |
+
on the rows' python id. This is useful when performing
|
1046 |
+
operations that re-arrange the rows (e.g. ``sort``). If
|
1047 |
+
``index_by_id=False``, then it is assumed that all rows will be
|
1048 |
+
in the same order when ``_restore_config_info()`` is called.
|
1049 |
+
"""
|
1050 |
+
# Default value for row_indices is all rows.
|
1051 |
+
if row_indices is None:
|
1052 |
+
row_indices = list(range(len(self._rows)))
|
1053 |
+
|
1054 |
+
# Look up our current selection.
|
1055 |
+
selection = self.selected_row()
|
1056 |
+
if index_by_id and selection is not None:
|
1057 |
+
selection = id(self._rows[selection])
|
1058 |
+
|
1059 |
+
# Look up the color configuration info for each row.
|
1060 |
+
if index_by_id:
|
1061 |
+
config = {
|
1062 |
+
id(self._rows[r]): [
|
1063 |
+
self._get_itemconfig(r, c) for c in range(self._num_columns)
|
1064 |
+
]
|
1065 |
+
for r in row_indices
|
1066 |
+
}
|
1067 |
+
else:
|
1068 |
+
config = {
|
1069 |
+
r: [self._get_itemconfig(r, c) for c in range(self._num_columns)]
|
1070 |
+
for r in row_indices
|
1071 |
+
}
|
1072 |
+
|
1073 |
+
return selection, config
|
1074 |
+
|
1075 |
+
def _restore_config_info(self, cookie, index_by_id=False, see=False):
|
1076 |
+
"""
|
1077 |
+
Restore selection & color configuration information that was
|
1078 |
+
saved using ``_save_config_info``.
|
1079 |
+
"""
|
1080 |
+
selection, config = cookie
|
1081 |
+
|
1082 |
+
# Clear the selection.
|
1083 |
+
if selection is None:
|
1084 |
+
self._mlb.selection_clear(0, "end")
|
1085 |
+
|
1086 |
+
# Restore selection & color config
|
1087 |
+
if index_by_id:
|
1088 |
+
for r, row in enumerate(self._rows):
|
1089 |
+
if id(row) in config:
|
1090 |
+
for c in range(self._num_columns):
|
1091 |
+
self._mlb.itemconfigure(r, c, config[id(row)][c])
|
1092 |
+
if id(row) == selection:
|
1093 |
+
self._mlb.select(r, see=see)
|
1094 |
+
else:
|
1095 |
+
if selection is not None:
|
1096 |
+
self._mlb.select(selection, see=see)
|
1097 |
+
for r in config:
|
1098 |
+
for c in range(self._num_columns):
|
1099 |
+
self._mlb.itemconfigure(r, c, config[r][c])
|
1100 |
+
|
1101 |
+
# /////////////////////////////////////////////////////////////////
|
1102 |
+
# Debugging (Invariant Checker)
|
1103 |
+
# /////////////////////////////////////////////////////////////////
|
1104 |
+
|
1105 |
+
_DEBUG = False
|
1106 |
+
"""If true, then run ``_check_table_vs_mlb()`` after any operation
|
1107 |
+
that modifies the table."""
|
1108 |
+
|
1109 |
+
def _check_table_vs_mlb(self):
|
1110 |
+
"""
|
1111 |
+
Verify that the contents of the table's ``_rows`` variable match
|
1112 |
+
the contents of its multi-listbox (``_mlb``). This is just
|
1113 |
+
included for debugging purposes, to make sure that the
|
1114 |
+
list-modifying operations are working correctly.
|
1115 |
+
"""
|
1116 |
+
for col in self._mlb.listboxes:
|
1117 |
+
assert len(self) == col.size()
|
1118 |
+
for row in self:
|
1119 |
+
assert len(row) == self._num_columns
|
1120 |
+
assert self._num_columns == len(self._mlb.column_names)
|
1121 |
+
# assert self._column_names == self._mlb.column_names
|
1122 |
+
for i, row in enumerate(self):
|
1123 |
+
for j, cell in enumerate(row):
|
1124 |
+
if self._reprfunc is not None:
|
1125 |
+
cell = self._reprfunc(i, j, cell)
|
1126 |
+
assert self._mlb.get(i)[j] == cell
|
1127 |
+
|
1128 |
+
|
1129 |
+
######################################################################
|
1130 |
+
# Demo/Test Function
|
1131 |
+
######################################################################
|
1132 |
+
|
1133 |
+
# update this to use new WordNet API
|
1134 |
+
def demo():
|
1135 |
+
root = Tk()
|
1136 |
+
root.bind("<Control-q>", lambda e: root.destroy())
|
1137 |
+
|
1138 |
+
table = Table(
|
1139 |
+
root,
|
1140 |
+
"Word Synset Hypernym Hyponym".split(),
|
1141 |
+
column_weights=[0, 1, 1, 1],
|
1142 |
+
reprfunc=(lambda i, j, s: " %s" % s),
|
1143 |
+
)
|
1144 |
+
table.pack(expand=True, fill="both")
|
1145 |
+
|
1146 |
+
from nltk.corpus import brown, wordnet
|
1147 |
+
|
1148 |
+
for word, pos in sorted(set(brown.tagged_words()[:500])):
|
1149 |
+
if pos[0] != "N":
|
1150 |
+
continue
|
1151 |
+
word = word.lower()
|
1152 |
+
for synset in wordnet.synsets(word):
|
1153 |
+
try:
|
1154 |
+
hyper_def = synset.hypernyms()[0].definition()
|
1155 |
+
except:
|
1156 |
+
hyper_def = "*none*"
|
1157 |
+
try:
|
1158 |
+
hypo_def = synset.hypernyms()[0].definition()
|
1159 |
+
except:
|
1160 |
+
hypo_def = "*none*"
|
1161 |
+
table.append([word, synset.definition(), hyper_def, hypo_def])
|
1162 |
+
|
1163 |
+
table.columnconfig("Word", background="#afa")
|
1164 |
+
table.columnconfig("Synset", background="#efe")
|
1165 |
+
table.columnconfig("Hypernym", background="#fee")
|
1166 |
+
table.columnconfig("Hyponym", background="#ffe")
|
1167 |
+
for row in range(len(table)):
|
1168 |
+
for column in ("Hypernym", "Hyponym"):
|
1169 |
+
if table[row, column] == "*none*":
|
1170 |
+
table.itemconfig(
|
1171 |
+
row, column, foreground="#666", selectforeground="#666"
|
1172 |
+
)
|
1173 |
+
root.mainloop()
|
1174 |
+
|
1175 |
+
|
1176 |
+
if __name__ == "__main__":
|
1177 |
+
demo()
|
env-llmeval/lib/python3.10/site-packages/nltk/draw/tree.py
ADDED
@@ -0,0 +1,1129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Graphical Representations for Trees
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Edward Loper <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
|
8 |
+
"""
|
9 |
+
Graphically display a Tree.
|
10 |
+
"""
|
11 |
+
|
12 |
+
from tkinter import IntVar, Menu, Tk
|
13 |
+
|
14 |
+
from nltk.draw.util import (
|
15 |
+
BoxWidget,
|
16 |
+
CanvasFrame,
|
17 |
+
CanvasWidget,
|
18 |
+
OvalWidget,
|
19 |
+
ParenWidget,
|
20 |
+
TextWidget,
|
21 |
+
)
|
22 |
+
from nltk.tree import Tree
|
23 |
+
from nltk.util import in_idle
|
24 |
+
|
25 |
+
##//////////////////////////////////////////////////////
|
26 |
+
## Tree Segment
|
27 |
+
##//////////////////////////////////////////////////////
|
28 |
+
|
29 |
+
|
30 |
+
class TreeSegmentWidget(CanvasWidget):
|
31 |
+
"""
|
32 |
+
A canvas widget that displays a single segment of a hierarchical
|
33 |
+
tree. Each ``TreeSegmentWidget`` connects a single "node widget"
|
34 |
+
to a sequence of zero or more "subtree widgets". By default, the
|
35 |
+
bottom of the node is connected to the top of each subtree by a
|
36 |
+
single line. However, if the ``roof`` attribute is set, then a
|
37 |
+
single triangular "roof" will connect the node to all of its
|
38 |
+
children.
|
39 |
+
|
40 |
+
Attributes:
|
41 |
+
- ``roof``: What sort of connection to draw between the node and
|
42 |
+
its subtrees. If ``roof`` is true, draw a single triangular
|
43 |
+
"roof" over the subtrees. If ``roof`` is false, draw a line
|
44 |
+
between each subtree and the node. Default value is false.
|
45 |
+
- ``xspace``: The amount of horizontal space to leave between
|
46 |
+
subtrees when managing this widget. Default value is 10.
|
47 |
+
- ``yspace``: The amount of space to place between the node and
|
48 |
+
its children when managing this widget. Default value is 15.
|
49 |
+
- ``color``: The color of the lines connecting the node to its
|
50 |
+
subtrees; and of the outline of the triangular roof. Default
|
51 |
+
value is ``'#006060'``.
|
52 |
+
- ``fill``: The fill color for the triangular roof. Default
|
53 |
+
value is ``''`` (no fill).
|
54 |
+
- ``width``: The width of the lines connecting the node to its
|
55 |
+
subtrees; and of the outline of the triangular roof. Default
|
56 |
+
value is 1.
|
57 |
+
- ``orientation``: Determines whether the tree branches downwards
|
58 |
+
or rightwards. Possible values are ``'horizontal'`` and
|
59 |
+
``'vertical'``. The default value is ``'vertical'`` (i.e.,
|
60 |
+
branch downwards).
|
61 |
+
- ``draggable``: whether the widget can be dragged by the user.
|
62 |
+
"""
|
63 |
+
|
64 |
+
def __init__(self, canvas, label, subtrees, **attribs):
|
65 |
+
"""
|
66 |
+
:type node:
|
67 |
+
:type subtrees: list(CanvasWidgetI)
|
68 |
+
"""
|
69 |
+
self._label = label
|
70 |
+
self._subtrees = subtrees
|
71 |
+
|
72 |
+
# Attributes
|
73 |
+
self._horizontal = 0
|
74 |
+
self._roof = 0
|
75 |
+
self._xspace = 10
|
76 |
+
self._yspace = 15
|
77 |
+
self._ordered = False
|
78 |
+
|
79 |
+
# Create canvas objects.
|
80 |
+
self._lines = [canvas.create_line(0, 0, 0, 0, fill="#006060") for c in subtrees]
|
81 |
+
self._polygon = canvas.create_polygon(
|
82 |
+
0, 0, fill="", state="hidden", outline="#006060"
|
83 |
+
)
|
84 |
+
|
85 |
+
# Register child widgets (label + subtrees)
|
86 |
+
self._add_child_widget(label)
|
87 |
+
for subtree in subtrees:
|
88 |
+
self._add_child_widget(subtree)
|
89 |
+
|
90 |
+
# Are we currently managing?
|
91 |
+
self._managing = False
|
92 |
+
|
93 |
+
CanvasWidget.__init__(self, canvas, **attribs)
|
94 |
+
|
95 |
+
def __setitem__(self, attr, value):
|
96 |
+
canvas = self.canvas()
|
97 |
+
if attr == "roof":
|
98 |
+
self._roof = value
|
99 |
+
if self._roof:
|
100 |
+
for l in self._lines:
|
101 |
+
canvas.itemconfig(l, state="hidden")
|
102 |
+
canvas.itemconfig(self._polygon, state="normal")
|
103 |
+
else:
|
104 |
+
for l in self._lines:
|
105 |
+
canvas.itemconfig(l, state="normal")
|
106 |
+
canvas.itemconfig(self._polygon, state="hidden")
|
107 |
+
elif attr == "orientation":
|
108 |
+
if value == "horizontal":
|
109 |
+
self._horizontal = 1
|
110 |
+
elif value == "vertical":
|
111 |
+
self._horizontal = 0
|
112 |
+
else:
|
113 |
+
raise ValueError("orientation must be horizontal or vertical")
|
114 |
+
elif attr == "color":
|
115 |
+
for l in self._lines:
|
116 |
+
canvas.itemconfig(l, fill=value)
|
117 |
+
canvas.itemconfig(self._polygon, outline=value)
|
118 |
+
elif isinstance(attr, tuple) and attr[0] == "color":
|
119 |
+
# Set the color of an individual line.
|
120 |
+
l = self._lines[int(attr[1])]
|
121 |
+
canvas.itemconfig(l, fill=value)
|
122 |
+
elif attr == "fill":
|
123 |
+
canvas.itemconfig(self._polygon, fill=value)
|
124 |
+
elif attr == "width":
|
125 |
+
canvas.itemconfig(self._polygon, {attr: value})
|
126 |
+
for l in self._lines:
|
127 |
+
canvas.itemconfig(l, {attr: value})
|
128 |
+
elif attr in ("xspace", "yspace"):
|
129 |
+
if attr == "xspace":
|
130 |
+
self._xspace = value
|
131 |
+
elif attr == "yspace":
|
132 |
+
self._yspace = value
|
133 |
+
self.update(self._label)
|
134 |
+
elif attr == "ordered":
|
135 |
+
self._ordered = value
|
136 |
+
else:
|
137 |
+
CanvasWidget.__setitem__(self, attr, value)
|
138 |
+
|
139 |
+
def __getitem__(self, attr):
|
140 |
+
if attr == "roof":
|
141 |
+
return self._roof
|
142 |
+
elif attr == "width":
|
143 |
+
return self.canvas().itemcget(self._polygon, attr)
|
144 |
+
elif attr == "color":
|
145 |
+
return self.canvas().itemcget(self._polygon, "outline")
|
146 |
+
elif isinstance(attr, tuple) and attr[0] == "color":
|
147 |
+
l = self._lines[int(attr[1])]
|
148 |
+
return self.canvas().itemcget(l, "fill")
|
149 |
+
elif attr == "xspace":
|
150 |
+
return self._xspace
|
151 |
+
elif attr == "yspace":
|
152 |
+
return self._yspace
|
153 |
+
elif attr == "orientation":
|
154 |
+
if self._horizontal:
|
155 |
+
return "horizontal"
|
156 |
+
else:
|
157 |
+
return "vertical"
|
158 |
+
elif attr == "ordered":
|
159 |
+
return self._ordered
|
160 |
+
else:
|
161 |
+
return CanvasWidget.__getitem__(self, attr)
|
162 |
+
|
163 |
+
def label(self):
|
164 |
+
return self._label
|
165 |
+
|
166 |
+
def subtrees(self):
|
167 |
+
return self._subtrees[:]
|
168 |
+
|
169 |
+
def set_label(self, label):
|
170 |
+
"""
|
171 |
+
Set the node label to ``label``.
|
172 |
+
"""
|
173 |
+
self._remove_child_widget(self._label)
|
174 |
+
self._add_child_widget(label)
|
175 |
+
self._label = label
|
176 |
+
self.update(self._label)
|
177 |
+
|
178 |
+
def replace_child(self, oldchild, newchild):
|
179 |
+
"""
|
180 |
+
Replace the child ``oldchild`` with ``newchild``.
|
181 |
+
"""
|
182 |
+
index = self._subtrees.index(oldchild)
|
183 |
+
self._subtrees[index] = newchild
|
184 |
+
self._remove_child_widget(oldchild)
|
185 |
+
self._add_child_widget(newchild)
|
186 |
+
self.update(newchild)
|
187 |
+
|
188 |
+
def remove_child(self, child):
|
189 |
+
index = self._subtrees.index(child)
|
190 |
+
del self._subtrees[index]
|
191 |
+
self._remove_child_widget(child)
|
192 |
+
self.canvas().delete(self._lines.pop())
|
193 |
+
self.update(self._label)
|
194 |
+
|
195 |
+
def insert_child(self, index, child):
|
196 |
+
canvas = self.canvas()
|
197 |
+
self._subtrees.insert(index, child)
|
198 |
+
self._add_child_widget(child)
|
199 |
+
self._lines.append(canvas.create_line(0, 0, 0, 0, fill="#006060"))
|
200 |
+
self.update(self._label)
|
201 |
+
|
202 |
+
# but.. lines???
|
203 |
+
|
204 |
+
def _tags(self):
|
205 |
+
if self._roof:
|
206 |
+
return [self._polygon]
|
207 |
+
else:
|
208 |
+
return self._lines
|
209 |
+
|
210 |
+
def _subtree_top(self, child):
|
211 |
+
if isinstance(child, TreeSegmentWidget):
|
212 |
+
bbox = child.label().bbox()
|
213 |
+
else:
|
214 |
+
bbox = child.bbox()
|
215 |
+
if self._horizontal:
|
216 |
+
return (bbox[0], (bbox[1] + bbox[3]) / 2.0)
|
217 |
+
else:
|
218 |
+
return ((bbox[0] + bbox[2]) / 2.0, bbox[1])
|
219 |
+
|
220 |
+
def _node_bottom(self):
|
221 |
+
bbox = self._label.bbox()
|
222 |
+
if self._horizontal:
|
223 |
+
return (bbox[2], (bbox[1] + bbox[3]) / 2.0)
|
224 |
+
else:
|
225 |
+
return ((bbox[0] + bbox[2]) / 2.0, bbox[3])
|
226 |
+
|
227 |
+
def _update(self, child):
|
228 |
+
if len(self._subtrees) == 0:
|
229 |
+
return
|
230 |
+
if self._label.bbox() is None:
|
231 |
+
return # [XX] ???
|
232 |
+
|
233 |
+
# Which lines need to be redrawn?
|
234 |
+
if child is self._label:
|
235 |
+
need_update = self._subtrees
|
236 |
+
else:
|
237 |
+
need_update = [child]
|
238 |
+
|
239 |
+
if self._ordered and not self._managing:
|
240 |
+
need_update = self._maintain_order(child)
|
241 |
+
|
242 |
+
# Update the polygon.
|
243 |
+
(nodex, nodey) = self._node_bottom()
|
244 |
+
(xmin, ymin, xmax, ymax) = self._subtrees[0].bbox()
|
245 |
+
for subtree in self._subtrees[1:]:
|
246 |
+
bbox = subtree.bbox()
|
247 |
+
xmin = min(xmin, bbox[0])
|
248 |
+
ymin = min(ymin, bbox[1])
|
249 |
+
xmax = max(xmax, bbox[2])
|
250 |
+
ymax = max(ymax, bbox[3])
|
251 |
+
|
252 |
+
if self._horizontal:
|
253 |
+
self.canvas().coords(
|
254 |
+
self._polygon, nodex, nodey, xmin, ymin, xmin, ymax, nodex, nodey
|
255 |
+
)
|
256 |
+
else:
|
257 |
+
self.canvas().coords(
|
258 |
+
self._polygon, nodex, nodey, xmin, ymin, xmax, ymin, nodex, nodey
|
259 |
+
)
|
260 |
+
|
261 |
+
# Redraw all lines that need it.
|
262 |
+
for subtree in need_update:
|
263 |
+
(nodex, nodey) = self._node_bottom()
|
264 |
+
line = self._lines[self._subtrees.index(subtree)]
|
265 |
+
(subtreex, subtreey) = self._subtree_top(subtree)
|
266 |
+
self.canvas().coords(line, nodex, nodey, subtreex, subtreey)
|
267 |
+
|
268 |
+
def _maintain_order(self, child):
|
269 |
+
if self._horizontal:
|
270 |
+
return self._maintain_order_horizontal(child)
|
271 |
+
else:
|
272 |
+
return self._maintain_order_vertical(child)
|
273 |
+
|
274 |
+
def _maintain_order_vertical(self, child):
|
275 |
+
(left, top, right, bot) = child.bbox()
|
276 |
+
|
277 |
+
if child is self._label:
|
278 |
+
# Check all the leaves
|
279 |
+
for subtree in self._subtrees:
|
280 |
+
(x1, y1, x2, y2) = subtree.bbox()
|
281 |
+
if bot + self._yspace > y1:
|
282 |
+
subtree.move(0, bot + self._yspace - y1)
|
283 |
+
|
284 |
+
return self._subtrees
|
285 |
+
else:
|
286 |
+
moved = [child]
|
287 |
+
index = self._subtrees.index(child)
|
288 |
+
|
289 |
+
# Check leaves to our right.
|
290 |
+
x = right + self._xspace
|
291 |
+
for i in range(index + 1, len(self._subtrees)):
|
292 |
+
(x1, y1, x2, y2) = self._subtrees[i].bbox()
|
293 |
+
if x > x1:
|
294 |
+
self._subtrees[i].move(x - x1, 0)
|
295 |
+
x += x2 - x1 + self._xspace
|
296 |
+
moved.append(self._subtrees[i])
|
297 |
+
|
298 |
+
# Check leaves to our left.
|
299 |
+
x = left - self._xspace
|
300 |
+
for i in range(index - 1, -1, -1):
|
301 |
+
(x1, y1, x2, y2) = self._subtrees[i].bbox()
|
302 |
+
if x < x2:
|
303 |
+
self._subtrees[i].move(x - x2, 0)
|
304 |
+
x -= x2 - x1 + self._xspace
|
305 |
+
moved.append(self._subtrees[i])
|
306 |
+
|
307 |
+
# Check the node
|
308 |
+
(x1, y1, x2, y2) = self._label.bbox()
|
309 |
+
if y2 > top - self._yspace:
|
310 |
+
self._label.move(0, top - self._yspace - y2)
|
311 |
+
moved = self._subtrees
|
312 |
+
|
313 |
+
# Return a list of the nodes we moved
|
314 |
+
return moved
|
315 |
+
|
316 |
+
def _maintain_order_horizontal(self, child):
|
317 |
+
(left, top, right, bot) = child.bbox()
|
318 |
+
|
319 |
+
if child is self._label:
|
320 |
+
# Check all the leaves
|
321 |
+
for subtree in self._subtrees:
|
322 |
+
(x1, y1, x2, y2) = subtree.bbox()
|
323 |
+
if right + self._xspace > x1:
|
324 |
+
subtree.move(right + self._xspace - x1)
|
325 |
+
|
326 |
+
return self._subtrees
|
327 |
+
else:
|
328 |
+
moved = [child]
|
329 |
+
index = self._subtrees.index(child)
|
330 |
+
|
331 |
+
# Check leaves below us.
|
332 |
+
y = bot + self._yspace
|
333 |
+
for i in range(index + 1, len(self._subtrees)):
|
334 |
+
(x1, y1, x2, y2) = self._subtrees[i].bbox()
|
335 |
+
if y > y1:
|
336 |
+
self._subtrees[i].move(0, y - y1)
|
337 |
+
y += y2 - y1 + self._yspace
|
338 |
+
moved.append(self._subtrees[i])
|
339 |
+
|
340 |
+
# Check leaves above us
|
341 |
+
y = top - self._yspace
|
342 |
+
for i in range(index - 1, -1, -1):
|
343 |
+
(x1, y1, x2, y2) = self._subtrees[i].bbox()
|
344 |
+
if y < y2:
|
345 |
+
self._subtrees[i].move(0, y - y2)
|
346 |
+
y -= y2 - y1 + self._yspace
|
347 |
+
moved.append(self._subtrees[i])
|
348 |
+
|
349 |
+
# Check the node
|
350 |
+
(x1, y1, x2, y2) = self._label.bbox()
|
351 |
+
if x2 > left - self._xspace:
|
352 |
+
self._label.move(left - self._xspace - x2, 0)
|
353 |
+
moved = self._subtrees
|
354 |
+
|
355 |
+
# Return a list of the nodes we moved
|
356 |
+
return moved
|
357 |
+
|
358 |
+
def _manage_horizontal(self):
|
359 |
+
(nodex, nodey) = self._node_bottom()
|
360 |
+
|
361 |
+
# Put the subtrees in a line.
|
362 |
+
y = 20
|
363 |
+
for subtree in self._subtrees:
|
364 |
+
subtree_bbox = subtree.bbox()
|
365 |
+
dx = nodex - subtree_bbox[0] + self._xspace
|
366 |
+
dy = y - subtree_bbox[1]
|
367 |
+
subtree.move(dx, dy)
|
368 |
+
y += subtree_bbox[3] - subtree_bbox[1] + self._yspace
|
369 |
+
|
370 |
+
# Find the center of their tops.
|
371 |
+
center = 0.0
|
372 |
+
for subtree in self._subtrees:
|
373 |
+
center += self._subtree_top(subtree)[1]
|
374 |
+
center /= len(self._subtrees)
|
375 |
+
|
376 |
+
# Center the subtrees with the node.
|
377 |
+
for subtree in self._subtrees:
|
378 |
+
subtree.move(0, nodey - center)
|
379 |
+
|
380 |
+
def _manage_vertical(self):
|
381 |
+
(nodex, nodey) = self._node_bottom()
|
382 |
+
|
383 |
+
# Put the subtrees in a line.
|
384 |
+
x = 0
|
385 |
+
for subtree in self._subtrees:
|
386 |
+
subtree_bbox = subtree.bbox()
|
387 |
+
dy = nodey - subtree_bbox[1] + self._yspace
|
388 |
+
dx = x - subtree_bbox[0]
|
389 |
+
subtree.move(dx, dy)
|
390 |
+
x += subtree_bbox[2] - subtree_bbox[0] + self._xspace
|
391 |
+
|
392 |
+
# Find the center of their tops.
|
393 |
+
center = 0.0
|
394 |
+
for subtree in self._subtrees:
|
395 |
+
center += self._subtree_top(subtree)[0] / len(self._subtrees)
|
396 |
+
|
397 |
+
# Center the subtrees with the node.
|
398 |
+
for subtree in self._subtrees:
|
399 |
+
subtree.move(nodex - center, 0)
|
400 |
+
|
401 |
+
def _manage(self):
|
402 |
+
self._managing = True
|
403 |
+
(nodex, nodey) = self._node_bottom()
|
404 |
+
if len(self._subtrees) == 0:
|
405 |
+
return
|
406 |
+
|
407 |
+
if self._horizontal:
|
408 |
+
self._manage_horizontal()
|
409 |
+
else:
|
410 |
+
self._manage_vertical()
|
411 |
+
|
412 |
+
# Update lines to subtrees.
|
413 |
+
for subtree in self._subtrees:
|
414 |
+
self._update(subtree)
|
415 |
+
|
416 |
+
self._managing = False
|
417 |
+
|
418 |
+
def __repr__(self):
|
419 |
+
return f"[TreeSeg {self._label}: {self._subtrees}]"
|
420 |
+
|
421 |
+
|
422 |
+
def _tree_to_treeseg(
|
423 |
+
canvas,
|
424 |
+
t,
|
425 |
+
make_node,
|
426 |
+
make_leaf,
|
427 |
+
tree_attribs,
|
428 |
+
node_attribs,
|
429 |
+
leaf_attribs,
|
430 |
+
loc_attribs,
|
431 |
+
):
|
432 |
+
if isinstance(t, Tree):
|
433 |
+
label = make_node(canvas, t.label(), **node_attribs)
|
434 |
+
subtrees = [
|
435 |
+
_tree_to_treeseg(
|
436 |
+
canvas,
|
437 |
+
child,
|
438 |
+
make_node,
|
439 |
+
make_leaf,
|
440 |
+
tree_attribs,
|
441 |
+
node_attribs,
|
442 |
+
leaf_attribs,
|
443 |
+
loc_attribs,
|
444 |
+
)
|
445 |
+
for child in t
|
446 |
+
]
|
447 |
+
return TreeSegmentWidget(canvas, label, subtrees, **tree_attribs)
|
448 |
+
else:
|
449 |
+
return make_leaf(canvas, t, **leaf_attribs)
|
450 |
+
|
451 |
+
|
452 |
+
def tree_to_treesegment(
|
453 |
+
canvas, t, make_node=TextWidget, make_leaf=TextWidget, **attribs
|
454 |
+
):
|
455 |
+
"""
|
456 |
+
Convert a Tree into a ``TreeSegmentWidget``.
|
457 |
+
|
458 |
+
:param make_node: A ``CanvasWidget`` constructor or a function that
|
459 |
+
creates ``CanvasWidgets``. ``make_node`` is used to convert
|
460 |
+
the Tree's nodes into ``CanvasWidgets``. If no constructor
|
461 |
+
is specified, then ``TextWidget`` will be used.
|
462 |
+
:param make_leaf: A ``CanvasWidget`` constructor or a function that
|
463 |
+
creates ``CanvasWidgets``. ``make_leaf`` is used to convert
|
464 |
+
the Tree's leafs into ``CanvasWidgets``. If no constructor
|
465 |
+
is specified, then ``TextWidget`` will be used.
|
466 |
+
:param attribs: Attributes for the canvas widgets that make up the
|
467 |
+
returned ``TreeSegmentWidget``. Any attribute beginning with
|
468 |
+
``'tree_'`` will be passed to all ``TreeSegmentWidgets`` (with
|
469 |
+
the ``'tree_'`` prefix removed. Any attribute beginning with
|
470 |
+
``'node_'`` will be passed to all nodes. Any attribute
|
471 |
+
beginning with ``'leaf_'`` will be passed to all leaves. And
|
472 |
+
any attribute beginning with ``'loc_'`` will be passed to all
|
473 |
+
text locations (for Trees).
|
474 |
+
"""
|
475 |
+
# Process attribs.
|
476 |
+
tree_attribs = {}
|
477 |
+
node_attribs = {}
|
478 |
+
leaf_attribs = {}
|
479 |
+
loc_attribs = {}
|
480 |
+
|
481 |
+
for (key, value) in list(attribs.items()):
|
482 |
+
if key[:5] == "tree_":
|
483 |
+
tree_attribs[key[5:]] = value
|
484 |
+
elif key[:5] == "node_":
|
485 |
+
node_attribs[key[5:]] = value
|
486 |
+
elif key[:5] == "leaf_":
|
487 |
+
leaf_attribs[key[5:]] = value
|
488 |
+
elif key[:4] == "loc_":
|
489 |
+
loc_attribs[key[4:]] = value
|
490 |
+
else:
|
491 |
+
raise ValueError("Bad attribute: %s" % key)
|
492 |
+
return _tree_to_treeseg(
|
493 |
+
canvas,
|
494 |
+
t,
|
495 |
+
make_node,
|
496 |
+
make_leaf,
|
497 |
+
tree_attribs,
|
498 |
+
node_attribs,
|
499 |
+
leaf_attribs,
|
500 |
+
loc_attribs,
|
501 |
+
)
|
502 |
+
|
503 |
+
|
504 |
+
##//////////////////////////////////////////////////////
|
505 |
+
## Tree Widget
|
506 |
+
##//////////////////////////////////////////////////////
|
507 |
+
|
508 |
+
|
509 |
+
class TreeWidget(CanvasWidget):
|
510 |
+
"""
|
511 |
+
A canvas widget that displays a single Tree.
|
512 |
+
``TreeWidget`` manages a group of ``TreeSegmentWidgets`` that are
|
513 |
+
used to display a Tree.
|
514 |
+
|
515 |
+
Attributes:
|
516 |
+
|
517 |
+
- ``node_attr``: Sets the attribute ``attr`` on all of the
|
518 |
+
node widgets for this ``TreeWidget``.
|
519 |
+
- ``node_attr``: Sets the attribute ``attr`` on all of the
|
520 |
+
leaf widgets for this ``TreeWidget``.
|
521 |
+
- ``loc_attr``: Sets the attribute ``attr`` on all of the
|
522 |
+
location widgets for this ``TreeWidget`` (if it was built from
|
523 |
+
a Tree). Note that a location widget is a ``TextWidget``.
|
524 |
+
|
525 |
+
- ``xspace``: The amount of horizontal space to leave between
|
526 |
+
subtrees when managing this widget. Default value is 10.
|
527 |
+
- ``yspace``: The amount of space to place between the node and
|
528 |
+
its children when managing this widget. Default value is 15.
|
529 |
+
|
530 |
+
- ``line_color``: The color of the lines connecting each expanded
|
531 |
+
node to its subtrees.
|
532 |
+
- ``roof_color``: The color of the outline of the triangular roof
|
533 |
+
for collapsed trees.
|
534 |
+
- ``roof_fill``: The fill color for the triangular roof for
|
535 |
+
collapsed trees.
|
536 |
+
- ``width``
|
537 |
+
|
538 |
+
- ``orientation``: Determines whether the tree branches downwards
|
539 |
+
or rightwards. Possible values are ``'horizontal'`` and
|
540 |
+
``'vertical'``. The default value is ``'vertical'`` (i.e.,
|
541 |
+
branch downwards).
|
542 |
+
|
543 |
+
- ``shapeable``: whether the subtrees can be independently
|
544 |
+
dragged by the user. THIS property simply sets the
|
545 |
+
``DRAGGABLE`` property on all of the ``TreeWidget``'s tree
|
546 |
+
segments.
|
547 |
+
- ``draggable``: whether the widget can be dragged by the user.
|
548 |
+
"""
|
549 |
+
|
550 |
+
def __init__(
|
551 |
+
self, canvas, t, make_node=TextWidget, make_leaf=TextWidget, **attribs
|
552 |
+
):
|
553 |
+
# Node & leaf canvas widget constructors
|
554 |
+
self._make_node = make_node
|
555 |
+
self._make_leaf = make_leaf
|
556 |
+
self._tree = t
|
557 |
+
|
558 |
+
# Attributes.
|
559 |
+
self._nodeattribs = {}
|
560 |
+
self._leafattribs = {}
|
561 |
+
self._locattribs = {"color": "#008000"}
|
562 |
+
self._line_color = "#008080"
|
563 |
+
self._line_width = 1
|
564 |
+
self._roof_color = "#008080"
|
565 |
+
self._roof_fill = "#c0c0c0"
|
566 |
+
self._shapeable = False
|
567 |
+
self._xspace = 10
|
568 |
+
self._yspace = 10
|
569 |
+
self._orientation = "vertical"
|
570 |
+
self._ordered = False
|
571 |
+
|
572 |
+
# Build trees.
|
573 |
+
self._keys = {} # treeseg -> key
|
574 |
+
self._expanded_trees = {}
|
575 |
+
self._collapsed_trees = {}
|
576 |
+
self._nodes = []
|
577 |
+
self._leaves = []
|
578 |
+
# self._locs = []
|
579 |
+
self._make_collapsed_trees(canvas, t, ())
|
580 |
+
self._treeseg = self._make_expanded_tree(canvas, t, ())
|
581 |
+
self._add_child_widget(self._treeseg)
|
582 |
+
|
583 |
+
CanvasWidget.__init__(self, canvas, **attribs)
|
584 |
+
|
585 |
+
def expanded_tree(self, *path_to_tree):
|
586 |
+
"""
|
587 |
+
Return the ``TreeSegmentWidget`` for the specified subtree.
|
588 |
+
|
589 |
+
:param path_to_tree: A list of indices i1, i2, ..., in, where
|
590 |
+
the desired widget is the widget corresponding to
|
591 |
+
``tree.children()[i1].children()[i2]....children()[in]``.
|
592 |
+
For the root, the path is ``()``.
|
593 |
+
"""
|
594 |
+
return self._expanded_trees[path_to_tree]
|
595 |
+
|
596 |
+
def collapsed_tree(self, *path_to_tree):
|
597 |
+
"""
|
598 |
+
Return the ``TreeSegmentWidget`` for the specified subtree.
|
599 |
+
|
600 |
+
:param path_to_tree: A list of indices i1, i2, ..., in, where
|
601 |
+
the desired widget is the widget corresponding to
|
602 |
+
``tree.children()[i1].children()[i2]....children()[in]``.
|
603 |
+
For the root, the path is ``()``.
|
604 |
+
"""
|
605 |
+
return self._collapsed_trees[path_to_tree]
|
606 |
+
|
607 |
+
def bind_click_trees(self, callback, button=1):
|
608 |
+
"""
|
609 |
+
Add a binding to all tree segments.
|
610 |
+
"""
|
611 |
+
for tseg in list(self._expanded_trees.values()):
|
612 |
+
tseg.bind_click(callback, button)
|
613 |
+
for tseg in list(self._collapsed_trees.values()):
|
614 |
+
tseg.bind_click(callback, button)
|
615 |
+
|
616 |
+
def bind_drag_trees(self, callback, button=1):
|
617 |
+
"""
|
618 |
+
Add a binding to all tree segments.
|
619 |
+
"""
|
620 |
+
for tseg in list(self._expanded_trees.values()):
|
621 |
+
tseg.bind_drag(callback, button)
|
622 |
+
for tseg in list(self._collapsed_trees.values()):
|
623 |
+
tseg.bind_drag(callback, button)
|
624 |
+
|
625 |
+
def bind_click_leaves(self, callback, button=1):
|
626 |
+
"""
|
627 |
+
Add a binding to all leaves.
|
628 |
+
"""
|
629 |
+
for leaf in self._leaves:
|
630 |
+
leaf.bind_click(callback, button)
|
631 |
+
for leaf in self._leaves:
|
632 |
+
leaf.bind_click(callback, button)
|
633 |
+
|
634 |
+
def bind_drag_leaves(self, callback, button=1):
|
635 |
+
"""
|
636 |
+
Add a binding to all leaves.
|
637 |
+
"""
|
638 |
+
for leaf in self._leaves:
|
639 |
+
leaf.bind_drag(callback, button)
|
640 |
+
for leaf in self._leaves:
|
641 |
+
leaf.bind_drag(callback, button)
|
642 |
+
|
643 |
+
def bind_click_nodes(self, callback, button=1):
|
644 |
+
"""
|
645 |
+
Add a binding to all nodes.
|
646 |
+
"""
|
647 |
+
for node in self._nodes:
|
648 |
+
node.bind_click(callback, button)
|
649 |
+
for node in self._nodes:
|
650 |
+
node.bind_click(callback, button)
|
651 |
+
|
652 |
+
def bind_drag_nodes(self, callback, button=1):
|
653 |
+
"""
|
654 |
+
Add a binding to all nodes.
|
655 |
+
"""
|
656 |
+
for node in self._nodes:
|
657 |
+
node.bind_drag(callback, button)
|
658 |
+
for node in self._nodes:
|
659 |
+
node.bind_drag(callback, button)
|
660 |
+
|
661 |
+
def _make_collapsed_trees(self, canvas, t, key):
|
662 |
+
if not isinstance(t, Tree):
|
663 |
+
return
|
664 |
+
make_node = self._make_node
|
665 |
+
make_leaf = self._make_leaf
|
666 |
+
|
667 |
+
node = make_node(canvas, t.label(), **self._nodeattribs)
|
668 |
+
self._nodes.append(node)
|
669 |
+
leaves = [make_leaf(canvas, l, **self._leafattribs) for l in t.leaves()]
|
670 |
+
self._leaves += leaves
|
671 |
+
treeseg = TreeSegmentWidget(
|
672 |
+
canvas,
|
673 |
+
node,
|
674 |
+
leaves,
|
675 |
+
roof=1,
|
676 |
+
color=self._roof_color,
|
677 |
+
fill=self._roof_fill,
|
678 |
+
width=self._line_width,
|
679 |
+
)
|
680 |
+
|
681 |
+
self._collapsed_trees[key] = treeseg
|
682 |
+
self._keys[treeseg] = key
|
683 |
+
# self._add_child_widget(treeseg)
|
684 |
+
treeseg.hide()
|
685 |
+
|
686 |
+
# Build trees for children.
|
687 |
+
for i in range(len(t)):
|
688 |
+
child = t[i]
|
689 |
+
self._make_collapsed_trees(canvas, child, key + (i,))
|
690 |
+
|
691 |
+
def _make_expanded_tree(self, canvas, t, key):
|
692 |
+
make_node = self._make_node
|
693 |
+
make_leaf = self._make_leaf
|
694 |
+
|
695 |
+
if isinstance(t, Tree):
|
696 |
+
node = make_node(canvas, t.label(), **self._nodeattribs)
|
697 |
+
self._nodes.append(node)
|
698 |
+
children = t
|
699 |
+
subtrees = [
|
700 |
+
self._make_expanded_tree(canvas, children[i], key + (i,))
|
701 |
+
for i in range(len(children))
|
702 |
+
]
|
703 |
+
treeseg = TreeSegmentWidget(
|
704 |
+
canvas, node, subtrees, color=self._line_color, width=self._line_width
|
705 |
+
)
|
706 |
+
self._expanded_trees[key] = treeseg
|
707 |
+
self._keys[treeseg] = key
|
708 |
+
return treeseg
|
709 |
+
else:
|
710 |
+
leaf = make_leaf(canvas, t, **self._leafattribs)
|
711 |
+
self._leaves.append(leaf)
|
712 |
+
return leaf
|
713 |
+
|
714 |
+
def __setitem__(self, attr, value):
|
715 |
+
if attr[:5] == "node_":
|
716 |
+
for node in self._nodes:
|
717 |
+
node[attr[5:]] = value
|
718 |
+
elif attr[:5] == "leaf_":
|
719 |
+
for leaf in self._leaves:
|
720 |
+
leaf[attr[5:]] = value
|
721 |
+
elif attr == "line_color":
|
722 |
+
self._line_color = value
|
723 |
+
for tseg in list(self._expanded_trees.values()):
|
724 |
+
tseg["color"] = value
|
725 |
+
elif attr == "line_width":
|
726 |
+
self._line_width = value
|
727 |
+
for tseg in list(self._expanded_trees.values()):
|
728 |
+
tseg["width"] = value
|
729 |
+
for tseg in list(self._collapsed_trees.values()):
|
730 |
+
tseg["width"] = value
|
731 |
+
elif attr == "roof_color":
|
732 |
+
self._roof_color = value
|
733 |
+
for tseg in list(self._collapsed_trees.values()):
|
734 |
+
tseg["color"] = value
|
735 |
+
elif attr == "roof_fill":
|
736 |
+
self._roof_fill = value
|
737 |
+
for tseg in list(self._collapsed_trees.values()):
|
738 |
+
tseg["fill"] = value
|
739 |
+
elif attr == "shapeable":
|
740 |
+
self._shapeable = value
|
741 |
+
for tseg in list(self._expanded_trees.values()):
|
742 |
+
tseg["draggable"] = value
|
743 |
+
for tseg in list(self._collapsed_trees.values()):
|
744 |
+
tseg["draggable"] = value
|
745 |
+
for leaf in self._leaves:
|
746 |
+
leaf["draggable"] = value
|
747 |
+
elif attr == "xspace":
|
748 |
+
self._xspace = value
|
749 |
+
for tseg in list(self._expanded_trees.values()):
|
750 |
+
tseg["xspace"] = value
|
751 |
+
for tseg in list(self._collapsed_trees.values()):
|
752 |
+
tseg["xspace"] = value
|
753 |
+
self.manage()
|
754 |
+
elif attr == "yspace":
|
755 |
+
self._yspace = value
|
756 |
+
for tseg in list(self._expanded_trees.values()):
|
757 |
+
tseg["yspace"] = value
|
758 |
+
for tseg in list(self._collapsed_trees.values()):
|
759 |
+
tseg["yspace"] = value
|
760 |
+
self.manage()
|
761 |
+
elif attr == "orientation":
|
762 |
+
self._orientation = value
|
763 |
+
for tseg in list(self._expanded_trees.values()):
|
764 |
+
tseg["orientation"] = value
|
765 |
+
for tseg in list(self._collapsed_trees.values()):
|
766 |
+
tseg["orientation"] = value
|
767 |
+
self.manage()
|
768 |
+
elif attr == "ordered":
|
769 |
+
self._ordered = value
|
770 |
+
for tseg in list(self._expanded_trees.values()):
|
771 |
+
tseg["ordered"] = value
|
772 |
+
for tseg in list(self._collapsed_trees.values()):
|
773 |
+
tseg["ordered"] = value
|
774 |
+
else:
|
775 |
+
CanvasWidget.__setitem__(self, attr, value)
|
776 |
+
|
777 |
+
def __getitem__(self, attr):
|
778 |
+
if attr[:5] == "node_":
|
779 |
+
return self._nodeattribs.get(attr[5:], None)
|
780 |
+
elif attr[:5] == "leaf_":
|
781 |
+
return self._leafattribs.get(attr[5:], None)
|
782 |
+
elif attr[:4] == "loc_":
|
783 |
+
return self._locattribs.get(attr[4:], None)
|
784 |
+
elif attr == "line_color":
|
785 |
+
return self._line_color
|
786 |
+
elif attr == "line_width":
|
787 |
+
return self._line_width
|
788 |
+
elif attr == "roof_color":
|
789 |
+
return self._roof_color
|
790 |
+
elif attr == "roof_fill":
|
791 |
+
return self._roof_fill
|
792 |
+
elif attr == "shapeable":
|
793 |
+
return self._shapeable
|
794 |
+
elif attr == "xspace":
|
795 |
+
return self._xspace
|
796 |
+
elif attr == "yspace":
|
797 |
+
return self._yspace
|
798 |
+
elif attr == "orientation":
|
799 |
+
return self._orientation
|
800 |
+
else:
|
801 |
+
return CanvasWidget.__getitem__(self, attr)
|
802 |
+
|
803 |
+
def _tags(self):
|
804 |
+
return []
|
805 |
+
|
806 |
+
def _manage(self):
|
807 |
+
segs = list(self._expanded_trees.values()) + list(
|
808 |
+
self._collapsed_trees.values()
|
809 |
+
)
|
810 |
+
for tseg in segs:
|
811 |
+
if tseg.hidden():
|
812 |
+
tseg.show()
|
813 |
+
tseg.manage()
|
814 |
+
tseg.hide()
|
815 |
+
|
816 |
+
def toggle_collapsed(self, treeseg):
|
817 |
+
"""
|
818 |
+
Collapse/expand a tree.
|
819 |
+
"""
|
820 |
+
old_treeseg = treeseg
|
821 |
+
if old_treeseg["roof"]:
|
822 |
+
new_treeseg = self._expanded_trees[self._keys[old_treeseg]]
|
823 |
+
else:
|
824 |
+
new_treeseg = self._collapsed_trees[self._keys[old_treeseg]]
|
825 |
+
|
826 |
+
# Replace the old tree with the new tree.
|
827 |
+
if old_treeseg.parent() is self:
|
828 |
+
self._remove_child_widget(old_treeseg)
|
829 |
+
self._add_child_widget(new_treeseg)
|
830 |
+
self._treeseg = new_treeseg
|
831 |
+
else:
|
832 |
+
old_treeseg.parent().replace_child(old_treeseg, new_treeseg)
|
833 |
+
|
834 |
+
# Move the new tree to where the old tree was. Show it first,
|
835 |
+
# so we can find its bounding box.
|
836 |
+
new_treeseg.show()
|
837 |
+
(newx, newy) = new_treeseg.label().bbox()[:2]
|
838 |
+
(oldx, oldy) = old_treeseg.label().bbox()[:2]
|
839 |
+
new_treeseg.move(oldx - newx, oldy - newy)
|
840 |
+
|
841 |
+
# Hide the old tree
|
842 |
+
old_treeseg.hide()
|
843 |
+
|
844 |
+
# We could do parent.manage() here instead, if we wanted.
|
845 |
+
new_treeseg.parent().update(new_treeseg)
|
846 |
+
|
847 |
+
|
848 |
+
##//////////////////////////////////////////////////////
|
849 |
+
## draw_trees
|
850 |
+
##//////////////////////////////////////////////////////
|
851 |
+
|
852 |
+
|
853 |
+
class TreeView:
|
854 |
+
def __init__(self, *trees):
|
855 |
+
from math import ceil, sqrt
|
856 |
+
|
857 |
+
self._trees = trees
|
858 |
+
|
859 |
+
self._top = Tk()
|
860 |
+
self._top.title("NLTK")
|
861 |
+
self._top.bind("<Control-x>", self.destroy)
|
862 |
+
self._top.bind("<Control-q>", self.destroy)
|
863 |
+
|
864 |
+
cf = self._cframe = CanvasFrame(self._top)
|
865 |
+
self._top.bind("<Control-p>", self._cframe.print_to_file)
|
866 |
+
|
867 |
+
# Size is variable.
|
868 |
+
self._size = IntVar(self._top)
|
869 |
+
self._size.set(12)
|
870 |
+
bold = ("helvetica", -self._size.get(), "bold")
|
871 |
+
helv = ("helvetica", -self._size.get())
|
872 |
+
|
873 |
+
# Lay the trees out in a square.
|
874 |
+
self._width = int(ceil(sqrt(len(trees))))
|
875 |
+
self._widgets = []
|
876 |
+
for i in range(len(trees)):
|
877 |
+
widget = TreeWidget(
|
878 |
+
cf.canvas(),
|
879 |
+
trees[i],
|
880 |
+
node_font=bold,
|
881 |
+
leaf_color="#008040",
|
882 |
+
node_color="#004080",
|
883 |
+
roof_color="#004040",
|
884 |
+
roof_fill="white",
|
885 |
+
line_color="#004040",
|
886 |
+
draggable=1,
|
887 |
+
leaf_font=helv,
|
888 |
+
)
|
889 |
+
widget.bind_click_trees(widget.toggle_collapsed)
|
890 |
+
self._widgets.append(widget)
|
891 |
+
cf.add_widget(widget, 0, 0)
|
892 |
+
|
893 |
+
self._layout()
|
894 |
+
self._cframe.pack(expand=1, fill="both")
|
895 |
+
self._init_menubar()
|
896 |
+
|
897 |
+
def _layout(self):
|
898 |
+
i = x = y = ymax = 0
|
899 |
+
width = self._width
|
900 |
+
for i in range(len(self._widgets)):
|
901 |
+
widget = self._widgets[i]
|
902 |
+
(oldx, oldy) = widget.bbox()[:2]
|
903 |
+
if i % width == 0:
|
904 |
+
y = ymax
|
905 |
+
x = 0
|
906 |
+
widget.move(x - oldx, y - oldy)
|
907 |
+
x = widget.bbox()[2] + 10
|
908 |
+
ymax = max(ymax, widget.bbox()[3] + 10)
|
909 |
+
|
910 |
+
def _init_menubar(self):
|
911 |
+
menubar = Menu(self._top)
|
912 |
+
|
913 |
+
filemenu = Menu(menubar, tearoff=0)
|
914 |
+
filemenu.add_command(
|
915 |
+
label="Print to Postscript",
|
916 |
+
underline=0,
|
917 |
+
command=self._cframe.print_to_file,
|
918 |
+
accelerator="Ctrl-p",
|
919 |
+
)
|
920 |
+
filemenu.add_command(
|
921 |
+
label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-x"
|
922 |
+
)
|
923 |
+
menubar.add_cascade(label="File", underline=0, menu=filemenu)
|
924 |
+
|
925 |
+
zoommenu = Menu(menubar, tearoff=0)
|
926 |
+
zoommenu.add_radiobutton(
|
927 |
+
label="Tiny",
|
928 |
+
variable=self._size,
|
929 |
+
underline=0,
|
930 |
+
value=10,
|
931 |
+
command=self.resize,
|
932 |
+
)
|
933 |
+
zoommenu.add_radiobutton(
|
934 |
+
label="Small",
|
935 |
+
variable=self._size,
|
936 |
+
underline=0,
|
937 |
+
value=12,
|
938 |
+
command=self.resize,
|
939 |
+
)
|
940 |
+
zoommenu.add_radiobutton(
|
941 |
+
label="Medium",
|
942 |
+
variable=self._size,
|
943 |
+
underline=0,
|
944 |
+
value=14,
|
945 |
+
command=self.resize,
|
946 |
+
)
|
947 |
+
zoommenu.add_radiobutton(
|
948 |
+
label="Large",
|
949 |
+
variable=self._size,
|
950 |
+
underline=0,
|
951 |
+
value=28,
|
952 |
+
command=self.resize,
|
953 |
+
)
|
954 |
+
zoommenu.add_radiobutton(
|
955 |
+
label="Huge",
|
956 |
+
variable=self._size,
|
957 |
+
underline=0,
|
958 |
+
value=50,
|
959 |
+
command=self.resize,
|
960 |
+
)
|
961 |
+
menubar.add_cascade(label="Zoom", underline=0, menu=zoommenu)
|
962 |
+
|
963 |
+
self._top.config(menu=menubar)
|
964 |
+
|
965 |
+
def resize(self, *e):
|
966 |
+
bold = ("helvetica", -self._size.get(), "bold")
|
967 |
+
helv = ("helvetica", -self._size.get())
|
968 |
+
xspace = self._size.get()
|
969 |
+
yspace = self._size.get()
|
970 |
+
for widget in self._widgets:
|
971 |
+
widget["node_font"] = bold
|
972 |
+
widget["leaf_font"] = helv
|
973 |
+
widget["xspace"] = xspace
|
974 |
+
widget["yspace"] = yspace
|
975 |
+
if self._size.get() < 20:
|
976 |
+
widget["line_width"] = 1
|
977 |
+
elif self._size.get() < 30:
|
978 |
+
widget["line_width"] = 2
|
979 |
+
else:
|
980 |
+
widget["line_width"] = 3
|
981 |
+
self._layout()
|
982 |
+
|
983 |
+
def destroy(self, *e):
|
984 |
+
if self._top is None:
|
985 |
+
return
|
986 |
+
self._top.destroy()
|
987 |
+
self._top = None
|
988 |
+
|
989 |
+
def mainloop(self, *args, **kwargs):
|
990 |
+
"""
|
991 |
+
Enter the Tkinter mainloop. This function must be called if
|
992 |
+
this demo is created from a non-interactive program (e.g.
|
993 |
+
from a secript); otherwise, the demo will close as soon as
|
994 |
+
the script completes.
|
995 |
+
"""
|
996 |
+
if in_idle():
|
997 |
+
return
|
998 |
+
self._top.mainloop(*args, **kwargs)
|
999 |
+
|
1000 |
+
|
1001 |
+
def draw_trees(*trees):
|
1002 |
+
"""
|
1003 |
+
Open a new window containing a graphical diagram of the given
|
1004 |
+
trees.
|
1005 |
+
|
1006 |
+
:rtype: None
|
1007 |
+
"""
|
1008 |
+
TreeView(*trees).mainloop()
|
1009 |
+
return
|
1010 |
+
|
1011 |
+
|
1012 |
+
##//////////////////////////////////////////////////////
|
1013 |
+
## Demo Code
|
1014 |
+
##//////////////////////////////////////////////////////
|
1015 |
+
|
1016 |
+
|
1017 |
+
def demo():
|
1018 |
+
import random
|
1019 |
+
|
1020 |
+
def fill(cw):
|
1021 |
+
cw["fill"] = "#%06d" % random.randint(0, 999999)
|
1022 |
+
|
1023 |
+
cf = CanvasFrame(width=550, height=450, closeenough=2)
|
1024 |
+
|
1025 |
+
t = Tree.fromstring(
|
1026 |
+
"""
|
1027 |
+
(S (NP the very big cat)
|
1028 |
+
(VP (Adv sorta) (V saw) (NP (Det the) (N dog))))"""
|
1029 |
+
)
|
1030 |
+
|
1031 |
+
tc = TreeWidget(
|
1032 |
+
cf.canvas(),
|
1033 |
+
t,
|
1034 |
+
draggable=1,
|
1035 |
+
node_font=("helvetica", -14, "bold"),
|
1036 |
+
leaf_font=("helvetica", -12, "italic"),
|
1037 |
+
roof_fill="white",
|
1038 |
+
roof_color="black",
|
1039 |
+
leaf_color="green4",
|
1040 |
+
node_color="blue2",
|
1041 |
+
)
|
1042 |
+
cf.add_widget(tc, 10, 10)
|
1043 |
+
|
1044 |
+
def boxit(canvas, text):
|
1045 |
+
big = ("helvetica", -16, "bold")
|
1046 |
+
return BoxWidget(canvas, TextWidget(canvas, text, font=big), fill="green")
|
1047 |
+
|
1048 |
+
def ovalit(canvas, text):
|
1049 |
+
return OvalWidget(canvas, TextWidget(canvas, text), fill="cyan")
|
1050 |
+
|
1051 |
+
treetok = Tree.fromstring("(S (NP this tree) (VP (V is) (AdjP shapeable)))")
|
1052 |
+
tc2 = TreeWidget(cf.canvas(), treetok, boxit, ovalit, shapeable=1)
|
1053 |
+
|
1054 |
+
def color(node):
|
1055 |
+
node["color"] = "#%04d00" % random.randint(0, 9999)
|
1056 |
+
|
1057 |
+
def color2(treeseg):
|
1058 |
+
treeseg.label()["fill"] = "#%06d" % random.randint(0, 9999)
|
1059 |
+
treeseg.label().child()["color"] = "white"
|
1060 |
+
|
1061 |
+
tc.bind_click_trees(tc.toggle_collapsed)
|
1062 |
+
tc2.bind_click_trees(tc2.toggle_collapsed)
|
1063 |
+
tc.bind_click_nodes(color, 3)
|
1064 |
+
tc2.expanded_tree(1).bind_click(color2, 3)
|
1065 |
+
tc2.expanded_tree().bind_click(color2, 3)
|
1066 |
+
|
1067 |
+
paren = ParenWidget(cf.canvas(), tc2)
|
1068 |
+
cf.add_widget(paren, tc.bbox()[2] + 10, 10)
|
1069 |
+
|
1070 |
+
tree3 = Tree.fromstring(
|
1071 |
+
"""
|
1072 |
+
(S (NP this tree) (AUX was)
|
1073 |
+
(VP (V built) (PP (P with) (NP (N tree_to_treesegment)))))"""
|
1074 |
+
)
|
1075 |
+
tc3 = tree_to_treesegment(
|
1076 |
+
cf.canvas(), tree3, tree_color="green4", tree_xspace=2, tree_width=2
|
1077 |
+
)
|
1078 |
+
tc3["draggable"] = 1
|
1079 |
+
cf.add_widget(tc3, 10, tc.bbox()[3] + 10)
|
1080 |
+
|
1081 |
+
def orientswitch(treewidget):
|
1082 |
+
if treewidget["orientation"] == "horizontal":
|
1083 |
+
treewidget.expanded_tree(1, 1).subtrees()[0].set_text("vertical")
|
1084 |
+
treewidget.collapsed_tree(1, 1).subtrees()[0].set_text("vertical")
|
1085 |
+
treewidget.collapsed_tree(1).subtrees()[1].set_text("vertical")
|
1086 |
+
treewidget.collapsed_tree().subtrees()[3].set_text("vertical")
|
1087 |
+
treewidget["orientation"] = "vertical"
|
1088 |
+
else:
|
1089 |
+
treewidget.expanded_tree(1, 1).subtrees()[0].set_text("horizontal")
|
1090 |
+
treewidget.collapsed_tree(1, 1).subtrees()[0].set_text("horizontal")
|
1091 |
+
treewidget.collapsed_tree(1).subtrees()[1].set_text("horizontal")
|
1092 |
+
treewidget.collapsed_tree().subtrees()[3].set_text("horizontal")
|
1093 |
+
treewidget["orientation"] = "horizontal"
|
1094 |
+
|
1095 |
+
text = """
|
1096 |
+
Try clicking, right clicking, and dragging
|
1097 |
+
different elements of each of the trees.
|
1098 |
+
The top-left tree is a TreeWidget built from
|
1099 |
+
a Tree. The top-right is a TreeWidget built
|
1100 |
+
from a Tree, using non-default widget
|
1101 |
+
constructors for the nodes & leaves (BoxWidget
|
1102 |
+
and OvalWidget). The bottom-left tree is
|
1103 |
+
built from tree_to_treesegment."""
|
1104 |
+
twidget = TextWidget(cf.canvas(), text.strip())
|
1105 |
+
textbox = BoxWidget(cf.canvas(), twidget, fill="white", draggable=1)
|
1106 |
+
cf.add_widget(textbox, tc3.bbox()[2] + 10, tc2.bbox()[3] + 10)
|
1107 |
+
|
1108 |
+
tree4 = Tree.fromstring("(S (NP this tree) (VP (V is) (Adj horizontal)))")
|
1109 |
+
tc4 = TreeWidget(
|
1110 |
+
cf.canvas(),
|
1111 |
+
tree4,
|
1112 |
+
draggable=1,
|
1113 |
+
line_color="brown2",
|
1114 |
+
roof_color="brown2",
|
1115 |
+
node_font=("helvetica", -12, "bold"),
|
1116 |
+
node_color="brown4",
|
1117 |
+
orientation="horizontal",
|
1118 |
+
)
|
1119 |
+
tc4.manage()
|
1120 |
+
cf.add_widget(tc4, tc3.bbox()[2] + 10, textbox.bbox()[3] + 10)
|
1121 |
+
tc4.bind_click(orientswitch)
|
1122 |
+
tc4.bind_click_trees(tc4.toggle_collapsed, 3)
|
1123 |
+
|
1124 |
+
# Run mainloop
|
1125 |
+
cf.mainloop()
|
1126 |
+
|
1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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Drawing utilities
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Edward Loper <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
|
8 |
+
"""
|
9 |
+
Tools for graphically displaying and interacting with the objects and
|
10 |
+
processing classes defined by the Toolkit. These tools are primarily
|
11 |
+
intended to help students visualize the objects that they create.
|
12 |
+
|
13 |
+
The graphical tools are typically built using "canvas widgets", each
|
14 |
+
of which encapsulates the graphical elements and bindings used to
|
15 |
+
display a complex object on a Tkinter ``Canvas``. For example, NLTK
|
16 |
+
defines canvas widgets for displaying trees and directed graphs, as
|
17 |
+
well as a number of simpler widgets. These canvas widgets make it
|
18 |
+
easier to build new graphical tools and demos. See the class
|
19 |
+
documentation for ``CanvasWidget`` for more information.
|
20 |
+
|
21 |
+
The ``nltk.draw`` module defines the abstract ``CanvasWidget`` base
|
22 |
+
class, and a number of simple canvas widgets. The remaining canvas
|
23 |
+
widgets are defined by submodules, such as ``nltk.draw.tree``.
|
24 |
+
|
25 |
+
The ``nltk.draw`` module also defines ``CanvasFrame``, which
|
26 |
+
encapsulates a ``Canvas`` and its scrollbars. It uses a
|
27 |
+
``ScrollWatcherWidget`` to ensure that all canvas widgets contained on
|
28 |
+
its canvas are within the scroll region.
|
29 |
+
|
30 |
+
Acknowledgements: Many of the ideas behind the canvas widget system
|
31 |
+
are derived from ``CLIG``, a Tk-based grapher for linguistic data
|
32 |
+
structures. For more information, see the CLIG
|
33 |
+
homepage (http://www.ags.uni-sb.de/~konrad/clig.html).
|
34 |
+
|
35 |
+
"""
|
36 |
+
from abc import ABCMeta, abstractmethod
|
37 |
+
from tkinter import (
|
38 |
+
RAISED,
|
39 |
+
Button,
|
40 |
+
Canvas,
|
41 |
+
Entry,
|
42 |
+
Frame,
|
43 |
+
Label,
|
44 |
+
Menu,
|
45 |
+
Menubutton,
|
46 |
+
Scrollbar,
|
47 |
+
StringVar,
|
48 |
+
Text,
|
49 |
+
Tk,
|
50 |
+
Toplevel,
|
51 |
+
Widget,
|
52 |
+
)
|
53 |
+
from tkinter.filedialog import asksaveasfilename
|
54 |
+
|
55 |
+
from nltk.util import in_idle
|
56 |
+
|
57 |
+
##//////////////////////////////////////////////////////
|
58 |
+
## CanvasWidget
|
59 |
+
##//////////////////////////////////////////////////////
|
60 |
+
|
61 |
+
|
62 |
+
class CanvasWidget(metaclass=ABCMeta):
|
63 |
+
"""
|
64 |
+
A collection of graphical elements and bindings used to display a
|
65 |
+
complex object on a Tkinter ``Canvas``. A canvas widget is
|
66 |
+
responsible for managing the ``Canvas`` tags and callback bindings
|
67 |
+
necessary to display and interact with the object. Canvas widgets
|
68 |
+
are often organized into hierarchies, where parent canvas widgets
|
69 |
+
control aspects of their child widgets.
|
70 |
+
|
71 |
+
Each canvas widget is bound to a single ``Canvas``. This ``Canvas``
|
72 |
+
is specified as the first argument to the ``CanvasWidget``'s
|
73 |
+
constructor.
|
74 |
+
|
75 |
+
Attributes. Each canvas widget can support a variety of
|
76 |
+
"attributes", which control how the canvas widget is displayed.
|
77 |
+
Some typical examples attributes are ``color``, ``font``, and
|
78 |
+
``radius``. Each attribute has a default value. This default
|
79 |
+
value can be overridden in the constructor, using keyword
|
80 |
+
arguments of the form ``attribute=value``:
|
81 |
+
|
82 |
+
>>> from nltk.draw.util import TextWidget
|
83 |
+
>>> cn = TextWidget(Canvas(), 'test', color='red') # doctest: +SKIP
|
84 |
+
|
85 |
+
Attribute values can also be changed after a canvas widget has
|
86 |
+
been constructed, using the ``__setitem__`` operator:
|
87 |
+
|
88 |
+
>>> cn['font'] = 'times' # doctest: +SKIP
|
89 |
+
|
90 |
+
The current value of an attribute value can be queried using the
|
91 |
+
``__getitem__`` operator:
|
92 |
+
|
93 |
+
>>> cn['color'] # doctest: +SKIP
|
94 |
+
'red'
|
95 |
+
|
96 |
+
For a list of the attributes supported by a type of canvas widget,
|
97 |
+
see its class documentation.
|
98 |
+
|
99 |
+
Interaction. The attribute ``'draggable'`` controls whether the
|
100 |
+
user can drag a canvas widget around the canvas. By default,
|
101 |
+
canvas widgets are not draggable.
|
102 |
+
|
103 |
+
``CanvasWidget`` provides callback support for two types of user
|
104 |
+
interaction: clicking and dragging. The method ``bind_click``
|
105 |
+
registers a callback function that is called whenever the canvas
|
106 |
+
widget is clicked. The method ``bind_drag`` registers a callback
|
107 |
+
function that is called after the canvas widget is dragged. If
|
108 |
+
the user clicks or drags a canvas widget with no registered
|
109 |
+
callback function, then the interaction event will propagate to
|
110 |
+
its parent. For each canvas widget, only one callback function
|
111 |
+
may be registered for an interaction event. Callback functions
|
112 |
+
can be deregistered with the ``unbind_click`` and ``unbind_drag``
|
113 |
+
methods.
|
114 |
+
|
115 |
+
Subclassing. ``CanvasWidget`` is an abstract class. Subclasses
|
116 |
+
are required to implement the following methods:
|
117 |
+
|
118 |
+
- ``__init__``: Builds a new canvas widget. It must perform the
|
119 |
+
following three tasks (in order):
|
120 |
+
|
121 |
+
- Create any new graphical elements.
|
122 |
+
- Call ``_add_child_widget`` on each child widget.
|
123 |
+
- Call the ``CanvasWidget`` constructor.
|
124 |
+
- ``_tags``: Returns a list of the canvas tags for all graphical
|
125 |
+
elements managed by this canvas widget, not including
|
126 |
+
graphical elements managed by its child widgets.
|
127 |
+
- ``_manage``: Arranges the child widgets of this canvas widget.
|
128 |
+
This is typically only called when the canvas widget is
|
129 |
+
created.
|
130 |
+
- ``_update``: Update this canvas widget in response to a
|
131 |
+
change in a single child.
|
132 |
+
|
133 |
+
For a ``CanvasWidget`` with no child widgets, the default
|
134 |
+
definitions for ``_manage`` and ``_update`` may be used.
|
135 |
+
|
136 |
+
If a subclass defines any attributes, then it should implement
|
137 |
+
``__getitem__`` and ``__setitem__``. If either of these methods is
|
138 |
+
called with an unknown attribute, then they should propagate the
|
139 |
+
request to ``CanvasWidget``.
|
140 |
+
|
141 |
+
Most subclasses implement a number of additional methods that
|
142 |
+
modify the ``CanvasWidget`` in some way. These methods must call
|
143 |
+
``parent.update(self)`` after making any changes to the canvas
|
144 |
+
widget's graphical elements. The canvas widget must also call
|
145 |
+
``parent.update(self)`` after changing any attribute value that
|
146 |
+
affects the shape or position of the canvas widget's graphical
|
147 |
+
elements.
|
148 |
+
|
149 |
+
:type __canvas: Tkinter.Canvas
|
150 |
+
:ivar __canvas: This ``CanvasWidget``'s canvas.
|
151 |
+
|
152 |
+
:type __parent: CanvasWidget or None
|
153 |
+
:ivar __parent: This ``CanvasWidget``'s hierarchical parent widget.
|
154 |
+
:type __children: list(CanvasWidget)
|
155 |
+
:ivar __children: This ``CanvasWidget``'s hierarchical child widgets.
|
156 |
+
|
157 |
+
:type __updating: bool
|
158 |
+
:ivar __updating: Is this canvas widget currently performing an
|
159 |
+
update? If it is, then it will ignore any new update requests
|
160 |
+
from child widgets.
|
161 |
+
|
162 |
+
:type __draggable: bool
|
163 |
+
:ivar __draggable: Is this canvas widget draggable?
|
164 |
+
:type __press: event
|
165 |
+
:ivar __press: The ButtonPress event that we're currently handling.
|
166 |
+
:type __drag_x: int
|
167 |
+
:ivar __drag_x: Where it's been moved to (to find dx)
|
168 |
+
:type __drag_y: int
|
169 |
+
:ivar __drag_y: Where it's been moved to (to find dy)
|
170 |
+
:type __callbacks: dictionary
|
171 |
+
:ivar __callbacks: Registered callbacks. Currently, four keys are
|
172 |
+
used: ``1``, ``2``, ``3``, and ``'drag'``. The values are
|
173 |
+
callback functions. Each callback function takes a single
|
174 |
+
argument, which is the ``CanvasWidget`` that triggered the
|
175 |
+
callback.
|
176 |
+
"""
|
177 |
+
|
178 |
+
def __init__(self, canvas, parent=None, **attribs):
|
179 |
+
"""
|
180 |
+
Create a new canvas widget. This constructor should only be
|
181 |
+
called by subclass constructors; and it should be called only
|
182 |
+
"after" the subclass has constructed all graphical canvas
|
183 |
+
objects and registered all child widgets.
|
184 |
+
|
185 |
+
:param canvas: This canvas widget's canvas.
|
186 |
+
:type canvas: Tkinter.Canvas
|
187 |
+
:param parent: This canvas widget's hierarchical parent.
|
188 |
+
:type parent: CanvasWidget
|
189 |
+
:param attribs: The new canvas widget's attributes.
|
190 |
+
"""
|
191 |
+
if self.__class__ == CanvasWidget:
|
192 |
+
raise TypeError("CanvasWidget is an abstract base class")
|
193 |
+
|
194 |
+
if not isinstance(canvas, Canvas):
|
195 |
+
raise TypeError("Expected a canvas!")
|
196 |
+
|
197 |
+
self.__canvas = canvas
|
198 |
+
self.__parent = parent
|
199 |
+
|
200 |
+
# If the subclass constructor called _add_child_widget, then
|
201 |
+
# self.__children will already exist.
|
202 |
+
if not hasattr(self, "_CanvasWidget__children"):
|
203 |
+
self.__children = []
|
204 |
+
|
205 |
+
# Is this widget hidden?
|
206 |
+
self.__hidden = 0
|
207 |
+
|
208 |
+
# Update control (prevents infinite loops)
|
209 |
+
self.__updating = 0
|
210 |
+
|
211 |
+
# Button-press and drag callback handling.
|
212 |
+
self.__press = None
|
213 |
+
self.__drag_x = self.__drag_y = 0
|
214 |
+
self.__callbacks = {}
|
215 |
+
self.__draggable = 0
|
216 |
+
|
217 |
+
# Set up attributes.
|
218 |
+
for (attr, value) in list(attribs.items()):
|
219 |
+
self[attr] = value
|
220 |
+
|
221 |
+
# Manage this canvas widget
|
222 |
+
self._manage()
|
223 |
+
|
224 |
+
# Register any new bindings
|
225 |
+
for tag in self._tags():
|
226 |
+
self.__canvas.tag_bind(tag, "<ButtonPress-1>", self.__press_cb)
|
227 |
+
self.__canvas.tag_bind(tag, "<ButtonPress-2>", self.__press_cb)
|
228 |
+
self.__canvas.tag_bind(tag, "<ButtonPress-3>", self.__press_cb)
|
229 |
+
|
230 |
+
##//////////////////////////////////////////////////////
|
231 |
+
## Inherited methods.
|
232 |
+
##//////////////////////////////////////////////////////
|
233 |
+
|
234 |
+
def bbox(self):
|
235 |
+
"""
|
236 |
+
:return: A bounding box for this ``CanvasWidget``. The bounding
|
237 |
+
box is a tuple of four coordinates, *(xmin, ymin, xmax, ymax)*,
|
238 |
+
for a rectangle which encloses all of the canvas
|
239 |
+
widget's graphical elements. Bounding box coordinates are
|
240 |
+
specified with respect to the coordinate space of the ``Canvas``.
|
241 |
+
:rtype: tuple(int, int, int, int)
|
242 |
+
"""
|
243 |
+
if self.__hidden:
|
244 |
+
return (0, 0, 0, 0)
|
245 |
+
if len(self.tags()) == 0:
|
246 |
+
raise ValueError("No tags")
|
247 |
+
return self.__canvas.bbox(*self.tags())
|
248 |
+
|
249 |
+
def width(self):
|
250 |
+
"""
|
251 |
+
:return: The width of this canvas widget's bounding box, in
|
252 |
+
its ``Canvas``'s coordinate space.
|
253 |
+
:rtype: int
|
254 |
+
"""
|
255 |
+
if len(self.tags()) == 0:
|
256 |
+
raise ValueError("No tags")
|
257 |
+
bbox = self.__canvas.bbox(*self.tags())
|
258 |
+
return bbox[2] - bbox[0]
|
259 |
+
|
260 |
+
def height(self):
|
261 |
+
"""
|
262 |
+
:return: The height of this canvas widget's bounding box, in
|
263 |
+
its ``Canvas``'s coordinate space.
|
264 |
+
:rtype: int
|
265 |
+
"""
|
266 |
+
if len(self.tags()) == 0:
|
267 |
+
raise ValueError("No tags")
|
268 |
+
bbox = self.__canvas.bbox(*self.tags())
|
269 |
+
return bbox[3] - bbox[1]
|
270 |
+
|
271 |
+
def parent(self):
|
272 |
+
"""
|
273 |
+
:return: The hierarchical parent of this canvas widget.
|
274 |
+
``self`` is considered a subpart of its parent for
|
275 |
+
purposes of user interaction.
|
276 |
+
:rtype: CanvasWidget or None
|
277 |
+
"""
|
278 |
+
return self.__parent
|
279 |
+
|
280 |
+
def child_widgets(self):
|
281 |
+
"""
|
282 |
+
:return: A list of the hierarchical children of this canvas
|
283 |
+
widget. These children are considered part of ``self``
|
284 |
+
for purposes of user interaction.
|
285 |
+
:rtype: list of CanvasWidget
|
286 |
+
"""
|
287 |
+
return self.__children
|
288 |
+
|
289 |
+
def canvas(self):
|
290 |
+
"""
|
291 |
+
:return: The canvas that this canvas widget is bound to.
|
292 |
+
:rtype: Tkinter.Canvas
|
293 |
+
"""
|
294 |
+
return self.__canvas
|
295 |
+
|
296 |
+
def move(self, dx, dy):
|
297 |
+
"""
|
298 |
+
Move this canvas widget by a given distance. In particular,
|
299 |
+
shift the canvas widget right by ``dx`` pixels, and down by
|
300 |
+
``dy`` pixels. Both ``dx`` and ``dy`` may be negative, resulting
|
301 |
+
in leftward or upward movement.
|
302 |
+
|
303 |
+
:type dx: int
|
304 |
+
:param dx: The number of pixels to move this canvas widget
|
305 |
+
rightwards.
|
306 |
+
:type dy: int
|
307 |
+
:param dy: The number of pixels to move this canvas widget
|
308 |
+
downwards.
|
309 |
+
:rtype: None
|
310 |
+
"""
|
311 |
+
if dx == dy == 0:
|
312 |
+
return
|
313 |
+
for tag in self.tags():
|
314 |
+
self.__canvas.move(tag, dx, dy)
|
315 |
+
if self.__parent:
|
316 |
+
self.__parent.update(self)
|
317 |
+
|
318 |
+
def moveto(self, x, y, anchor="NW"):
|
319 |
+
"""
|
320 |
+
Move this canvas widget to the given location. In particular,
|
321 |
+
shift the canvas widget such that the corner or side of the
|
322 |
+
bounding box specified by ``anchor`` is at location (``x``,
|
323 |
+
``y``).
|
324 |
+
|
325 |
+
:param x,y: The location that the canvas widget should be moved
|
326 |
+
to.
|
327 |
+
:param anchor: The corner or side of the canvas widget that
|
328 |
+
should be moved to the specified location. ``'N'``
|
329 |
+
specifies the top center; ``'NE'`` specifies the top right
|
330 |
+
corner; etc.
|
331 |
+
"""
|
332 |
+
x1, y1, x2, y2 = self.bbox()
|
333 |
+
if anchor == "NW":
|
334 |
+
self.move(x - x1, y - y1)
|
335 |
+
if anchor == "N":
|
336 |
+
self.move(x - x1 / 2 - x2 / 2, y - y1)
|
337 |
+
if anchor == "NE":
|
338 |
+
self.move(x - x2, y - y1)
|
339 |
+
if anchor == "E":
|
340 |
+
self.move(x - x2, y - y1 / 2 - y2 / 2)
|
341 |
+
if anchor == "SE":
|
342 |
+
self.move(x - x2, y - y2)
|
343 |
+
if anchor == "S":
|
344 |
+
self.move(x - x1 / 2 - x2 / 2, y - y2)
|
345 |
+
if anchor == "SW":
|
346 |
+
self.move(x - x1, y - y2)
|
347 |
+
if anchor == "W":
|
348 |
+
self.move(x - x1, y - y1 / 2 - y2 / 2)
|
349 |
+
|
350 |
+
def destroy(self):
|
351 |
+
"""
|
352 |
+
Remove this ``CanvasWidget`` from its ``Canvas``. After a
|
353 |
+
``CanvasWidget`` has been destroyed, it should not be accessed.
|
354 |
+
|
355 |
+
Note that you only need to destroy a top-level
|
356 |
+
``CanvasWidget``; its child widgets will be destroyed
|
357 |
+
automatically. If you destroy a non-top-level
|
358 |
+
``CanvasWidget``, then the entire top-level widget will be
|
359 |
+
destroyed.
|
360 |
+
|
361 |
+
:raise ValueError: if this ``CanvasWidget`` has a parent.
|
362 |
+
:rtype: None
|
363 |
+
"""
|
364 |
+
if self.__parent is not None:
|
365 |
+
self.__parent.destroy()
|
366 |
+
return
|
367 |
+
|
368 |
+
for tag in self.tags():
|
369 |
+
self.__canvas.tag_unbind(tag, "<ButtonPress-1>")
|
370 |
+
self.__canvas.tag_unbind(tag, "<ButtonPress-2>")
|
371 |
+
self.__canvas.tag_unbind(tag, "<ButtonPress-3>")
|
372 |
+
self.__canvas.delete(*self.tags())
|
373 |
+
self.__canvas = None
|
374 |
+
|
375 |
+
def update(self, child):
|
376 |
+
"""
|
377 |
+
Update the graphical display of this canvas widget, and all of
|
378 |
+
its ancestors, in response to a change in one of this canvas
|
379 |
+
widget's children.
|
380 |
+
|
381 |
+
:param child: The child widget that changed.
|
382 |
+
:type child: CanvasWidget
|
383 |
+
"""
|
384 |
+
if self.__hidden or child.__hidden:
|
385 |
+
return
|
386 |
+
# If we're already updating, then do nothing. This prevents
|
387 |
+
# infinite loops when _update modifies its children.
|
388 |
+
if self.__updating:
|
389 |
+
return
|
390 |
+
self.__updating = 1
|
391 |
+
|
392 |
+
# Update this CanvasWidget.
|
393 |
+
self._update(child)
|
394 |
+
|
395 |
+
# Propagate update request to the parent.
|
396 |
+
if self.__parent:
|
397 |
+
self.__parent.update(self)
|
398 |
+
|
399 |
+
# We're done updating.
|
400 |
+
self.__updating = 0
|
401 |
+
|
402 |
+
def manage(self):
|
403 |
+
"""
|
404 |
+
Arrange this canvas widget and all of its descendants.
|
405 |
+
|
406 |
+
:rtype: None
|
407 |
+
"""
|
408 |
+
if self.__hidden:
|
409 |
+
return
|
410 |
+
for child in self.__children:
|
411 |
+
child.manage()
|
412 |
+
self._manage()
|
413 |
+
|
414 |
+
def tags(self):
|
415 |
+
"""
|
416 |
+
:return: a list of the canvas tags for all graphical
|
417 |
+
elements managed by this canvas widget, including
|
418 |
+
graphical elements managed by its child widgets.
|
419 |
+
:rtype: list of int
|
420 |
+
"""
|
421 |
+
if self.__canvas is None:
|
422 |
+
raise ValueError("Attempt to access a destroyed canvas widget")
|
423 |
+
tags = []
|
424 |
+
tags += self._tags()
|
425 |
+
for child in self.__children:
|
426 |
+
tags += child.tags()
|
427 |
+
return tags
|
428 |
+
|
429 |
+
def __setitem__(self, attr, value):
|
430 |
+
"""
|
431 |
+
Set the value of the attribute ``attr`` to ``value``. See the
|
432 |
+
class documentation for a list of attributes supported by this
|
433 |
+
canvas widget.
|
434 |
+
|
435 |
+
:rtype: None
|
436 |
+
"""
|
437 |
+
if attr == "draggable":
|
438 |
+
self.__draggable = value
|
439 |
+
else:
|
440 |
+
raise ValueError("Unknown attribute %r" % attr)
|
441 |
+
|
442 |
+
def __getitem__(self, attr):
|
443 |
+
"""
|
444 |
+
:return: the value of the attribute ``attr``. See the class
|
445 |
+
documentation for a list of attributes supported by this
|
446 |
+
canvas widget.
|
447 |
+
:rtype: (any)
|
448 |
+
"""
|
449 |
+
if attr == "draggable":
|
450 |
+
return self.__draggable
|
451 |
+
else:
|
452 |
+
raise ValueError("Unknown attribute %r" % attr)
|
453 |
+
|
454 |
+
def __repr__(self):
|
455 |
+
"""
|
456 |
+
:return: a string representation of this canvas widget.
|
457 |
+
:rtype: str
|
458 |
+
"""
|
459 |
+
return "<%s>" % self.__class__.__name__
|
460 |
+
|
461 |
+
def hide(self):
|
462 |
+
"""
|
463 |
+
Temporarily hide this canvas widget.
|
464 |
+
|
465 |
+
:rtype: None
|
466 |
+
"""
|
467 |
+
self.__hidden = 1
|
468 |
+
for tag in self.tags():
|
469 |
+
self.__canvas.itemconfig(tag, state="hidden")
|
470 |
+
|
471 |
+
def show(self):
|
472 |
+
"""
|
473 |
+
Show a hidden canvas widget.
|
474 |
+
|
475 |
+
:rtype: None
|
476 |
+
"""
|
477 |
+
self.__hidden = 0
|
478 |
+
for tag in self.tags():
|
479 |
+
self.__canvas.itemconfig(tag, state="normal")
|
480 |
+
|
481 |
+
def hidden(self):
|
482 |
+
"""
|
483 |
+
:return: True if this canvas widget is hidden.
|
484 |
+
:rtype: bool
|
485 |
+
"""
|
486 |
+
return self.__hidden
|
487 |
+
|
488 |
+
##//////////////////////////////////////////////////////
|
489 |
+
## Callback interface
|
490 |
+
##//////////////////////////////////////////////////////
|
491 |
+
|
492 |
+
def bind_click(self, callback, button=1):
|
493 |
+
"""
|
494 |
+
Register a new callback that will be called whenever this
|
495 |
+
``CanvasWidget`` is clicked on.
|
496 |
+
|
497 |
+
:type callback: function
|
498 |
+
:param callback: The callback function that will be called
|
499 |
+
whenever this ``CanvasWidget`` is clicked. This function
|
500 |
+
will be called with this ``CanvasWidget`` as its argument.
|
501 |
+
:type button: int
|
502 |
+
:param button: Which button the user should use to click on
|
503 |
+
this ``CanvasWidget``. Typically, this should be 1 (left
|
504 |
+
button), 3 (right button), or 2 (middle button).
|
505 |
+
"""
|
506 |
+
self.__callbacks[button] = callback
|
507 |
+
|
508 |
+
def bind_drag(self, callback):
|
509 |
+
"""
|
510 |
+
Register a new callback that will be called after this
|
511 |
+
``CanvasWidget`` is dragged. This implicitly makes this
|
512 |
+
``CanvasWidget`` draggable.
|
513 |
+
|
514 |
+
:type callback: function
|
515 |
+
:param callback: The callback function that will be called
|
516 |
+
whenever this ``CanvasWidget`` is clicked. This function
|
517 |
+
will be called with this ``CanvasWidget`` as its argument.
|
518 |
+
"""
|
519 |
+
self.__draggable = 1
|
520 |
+
self.__callbacks["drag"] = callback
|
521 |
+
|
522 |
+
def unbind_click(self, button=1):
|
523 |
+
"""
|
524 |
+
Remove a callback that was registered with ``bind_click``.
|
525 |
+
|
526 |
+
:type button: int
|
527 |
+
:param button: Which button the user should use to click on
|
528 |
+
this ``CanvasWidget``. Typically, this should be 1 (left
|
529 |
+
button), 3 (right button), or 2 (middle button).
|
530 |
+
"""
|
531 |
+
try:
|
532 |
+
del self.__callbacks[button]
|
533 |
+
except:
|
534 |
+
pass
|
535 |
+
|
536 |
+
def unbind_drag(self):
|
537 |
+
"""
|
538 |
+
Remove a callback that was registered with ``bind_drag``.
|
539 |
+
"""
|
540 |
+
try:
|
541 |
+
del self.__callbacks["drag"]
|
542 |
+
except:
|
543 |
+
pass
|
544 |
+
|
545 |
+
##//////////////////////////////////////////////////////
|
546 |
+
## Callback internals
|
547 |
+
##//////////////////////////////////////////////////////
|
548 |
+
|
549 |
+
def __press_cb(self, event):
|
550 |
+
"""
|
551 |
+
Handle a button-press event:
|
552 |
+
- record the button press event in ``self.__press``
|
553 |
+
- register a button-release callback.
|
554 |
+
- if this CanvasWidget or any of its ancestors are
|
555 |
+
draggable, then register the appropriate motion callback.
|
556 |
+
"""
|
557 |
+
# If we're already waiting for a button release, then ignore
|
558 |
+
# this new button press.
|
559 |
+
if (
|
560 |
+
self.__canvas.bind("<ButtonRelease-1>")
|
561 |
+
or self.__canvas.bind("<ButtonRelease-2>")
|
562 |
+
or self.__canvas.bind("<ButtonRelease-3>")
|
563 |
+
):
|
564 |
+
return
|
565 |
+
|
566 |
+
# Unbind motion (just in case; this shouldn't be necessary)
|
567 |
+
self.__canvas.unbind("<Motion>")
|
568 |
+
|
569 |
+
# Record the button press event.
|
570 |
+
self.__press = event
|
571 |
+
|
572 |
+
# If any ancestor is draggable, set up a motion callback.
|
573 |
+
# (Only if they pressed button number 1)
|
574 |
+
if event.num == 1:
|
575 |
+
widget = self
|
576 |
+
while widget is not None:
|
577 |
+
if widget["draggable"]:
|
578 |
+
widget.__start_drag(event)
|
579 |
+
break
|
580 |
+
widget = widget.parent()
|
581 |
+
|
582 |
+
# Set up the button release callback.
|
583 |
+
self.__canvas.bind("<ButtonRelease-%d>" % event.num, self.__release_cb)
|
584 |
+
|
585 |
+
def __start_drag(self, event):
|
586 |
+
"""
|
587 |
+
Begin dragging this object:
|
588 |
+
- register a motion callback
|
589 |
+
- record the drag coordinates
|
590 |
+
"""
|
591 |
+
self.__canvas.bind("<Motion>", self.__motion_cb)
|
592 |
+
self.__drag_x = event.x
|
593 |
+
self.__drag_y = event.y
|
594 |
+
|
595 |
+
def __motion_cb(self, event):
|
596 |
+
"""
|
597 |
+
Handle a motion event:
|
598 |
+
- move this object to the new location
|
599 |
+
- record the new drag coordinates
|
600 |
+
"""
|
601 |
+
self.move(event.x - self.__drag_x, event.y - self.__drag_y)
|
602 |
+
self.__drag_x = event.x
|
603 |
+
self.__drag_y = event.y
|
604 |
+
|
605 |
+
def __release_cb(self, event):
|
606 |
+
"""
|
607 |
+
Handle a release callback:
|
608 |
+
- unregister motion & button release callbacks.
|
609 |
+
- decide whether they clicked, dragged, or cancelled
|
610 |
+
- call the appropriate handler.
|
611 |
+
"""
|
612 |
+
# Unbind the button release & motion callbacks.
|
613 |
+
self.__canvas.unbind("<ButtonRelease-%d>" % event.num)
|
614 |
+
self.__canvas.unbind("<Motion>")
|
615 |
+
|
616 |
+
# Is it a click or a drag?
|
617 |
+
if (
|
618 |
+
event.time - self.__press.time < 100
|
619 |
+
and abs(event.x - self.__press.x) + abs(event.y - self.__press.y) < 5
|
620 |
+
):
|
621 |
+
# Move it back, if we were dragging.
|
622 |
+
if self.__draggable and event.num == 1:
|
623 |
+
self.move(
|
624 |
+
self.__press.x - self.__drag_x, self.__press.y - self.__drag_y
|
625 |
+
)
|
626 |
+
self.__click(event.num)
|
627 |
+
elif event.num == 1:
|
628 |
+
self.__drag()
|
629 |
+
|
630 |
+
self.__press = None
|
631 |
+
|
632 |
+
def __drag(self):
|
633 |
+
"""
|
634 |
+
If this ``CanvasWidget`` has a drag callback, then call it;
|
635 |
+
otherwise, find the closest ancestor with a drag callback, and
|
636 |
+
call it. If no ancestors have a drag callback, do nothing.
|
637 |
+
"""
|
638 |
+
if self.__draggable:
|
639 |
+
if "drag" in self.__callbacks:
|
640 |
+
cb = self.__callbacks["drag"]
|
641 |
+
try:
|
642 |
+
cb(self)
|
643 |
+
except:
|
644 |
+
print("Error in drag callback for %r" % self)
|
645 |
+
elif self.__parent is not None:
|
646 |
+
self.__parent.__drag()
|
647 |
+
|
648 |
+
def __click(self, button):
|
649 |
+
"""
|
650 |
+
If this ``CanvasWidget`` has a drag callback, then call it;
|
651 |
+
otherwise, find the closest ancestor with a click callback, and
|
652 |
+
call it. If no ancestors have a click callback, do nothing.
|
653 |
+
"""
|
654 |
+
if button in self.__callbacks:
|
655 |
+
cb = self.__callbacks[button]
|
656 |
+
# try:
|
657 |
+
cb(self)
|
658 |
+
# except:
|
659 |
+
# print('Error in click callback for %r' % self)
|
660 |
+
# raise
|
661 |
+
elif self.__parent is not None:
|
662 |
+
self.__parent.__click(button)
|
663 |
+
|
664 |
+
##//////////////////////////////////////////////////////
|
665 |
+
## Child/parent Handling
|
666 |
+
##//////////////////////////////////////////////////////
|
667 |
+
|
668 |
+
def _add_child_widget(self, child):
|
669 |
+
"""
|
670 |
+
Register a hierarchical child widget. The child will be
|
671 |
+
considered part of this canvas widget for purposes of user
|
672 |
+
interaction. ``_add_child_widget`` has two direct effects:
|
673 |
+
- It sets ``child``'s parent to this canvas widget.
|
674 |
+
- It adds ``child`` to the list of canvas widgets returned by
|
675 |
+
the ``child_widgets`` member function.
|
676 |
+
|
677 |
+
:param child: The new child widget. ``child`` must not already
|
678 |
+
have a parent.
|
679 |
+
:type child: CanvasWidget
|
680 |
+
"""
|
681 |
+
if not hasattr(self, "_CanvasWidget__children"):
|
682 |
+
self.__children = []
|
683 |
+
if child.__parent is not None:
|
684 |
+
raise ValueError(f"{child} already has a parent")
|
685 |
+
child.__parent = self
|
686 |
+
self.__children.append(child)
|
687 |
+
|
688 |
+
def _remove_child_widget(self, child):
|
689 |
+
"""
|
690 |
+
Remove a hierarchical child widget. This child will no longer
|
691 |
+
be considered part of this canvas widget for purposes of user
|
692 |
+
interaction. ``_add_child_widget`` has two direct effects:
|
693 |
+
- It sets ``child``'s parent to None.
|
694 |
+
- It removes ``child`` from the list of canvas widgets
|
695 |
+
returned by the ``child_widgets`` member function.
|
696 |
+
|
697 |
+
:param child: The child widget to remove. ``child`` must be a
|
698 |
+
child of this canvas widget.
|
699 |
+
:type child: CanvasWidget
|
700 |
+
"""
|
701 |
+
self.__children.remove(child)
|
702 |
+
child.__parent = None
|
703 |
+
|
704 |
+
##//////////////////////////////////////////////////////
|
705 |
+
## Defined by subclass
|
706 |
+
##//////////////////////////////////////////////////////
|
707 |
+
|
708 |
+
@abstractmethod
|
709 |
+
def _tags(self):
|
710 |
+
"""
|
711 |
+
:return: a list of canvas tags for all graphical elements
|
712 |
+
managed by this canvas widget, not including graphical
|
713 |
+
elements managed by its child widgets.
|
714 |
+
:rtype: list of int
|
715 |
+
"""
|
716 |
+
|
717 |
+
def _manage(self):
|
718 |
+
"""
|
719 |
+
Arrange the child widgets of this canvas widget. This method
|
720 |
+
is called when the canvas widget is initially created. It is
|
721 |
+
also called if the user calls the ``manage`` method on this
|
722 |
+
canvas widget or any of its ancestors.
|
723 |
+
|
724 |
+
:rtype: None
|
725 |
+
"""
|
726 |
+
|
727 |
+
def _update(self, child):
|
728 |
+
"""
|
729 |
+
Update this canvas widget in response to a change in one of
|
730 |
+
its children.
|
731 |
+
|
732 |
+
:param child: The child that changed.
|
733 |
+
:type child: CanvasWidget
|
734 |
+
:rtype: None
|
735 |
+
"""
|
736 |
+
|
737 |
+
|
738 |
+
##//////////////////////////////////////////////////////
|
739 |
+
## Basic widgets.
|
740 |
+
##//////////////////////////////////////////////////////
|
741 |
+
|
742 |
+
|
743 |
+
class TextWidget(CanvasWidget):
|
744 |
+
"""
|
745 |
+
A canvas widget that displays a single string of text.
|
746 |
+
|
747 |
+
Attributes:
|
748 |
+
- ``color``: the color of the text.
|
749 |
+
- ``font``: the font used to display the text.
|
750 |
+
- ``justify``: justification for multi-line texts. Valid values
|
751 |
+
are ``left``, ``center``, and ``right``.
|
752 |
+
- ``width``: the width of the text. If the text is wider than
|
753 |
+
this width, it will be line-wrapped at whitespace.
|
754 |
+
- ``draggable``: whether the text can be dragged by the user.
|
755 |
+
"""
|
756 |
+
|
757 |
+
def __init__(self, canvas, text, **attribs):
|
758 |
+
"""
|
759 |
+
Create a new text widget.
|
760 |
+
|
761 |
+
:type canvas: Tkinter.Canvas
|
762 |
+
:param canvas: This canvas widget's canvas.
|
763 |
+
:type text: str
|
764 |
+
:param text: The string of text to display.
|
765 |
+
:param attribs: The new canvas widget's attributes.
|
766 |
+
"""
|
767 |
+
self._text = text
|
768 |
+
self._tag = canvas.create_text(1, 1, text=text)
|
769 |
+
CanvasWidget.__init__(self, canvas, **attribs)
|
770 |
+
|
771 |
+
def __setitem__(self, attr, value):
|
772 |
+
if attr in ("color", "font", "justify", "width"):
|
773 |
+
if attr == "color":
|
774 |
+
attr = "fill"
|
775 |
+
self.canvas().itemconfig(self._tag, {attr: value})
|
776 |
+
else:
|
777 |
+
CanvasWidget.__setitem__(self, attr, value)
|
778 |
+
|
779 |
+
def __getitem__(self, attr):
|
780 |
+
if attr == "width":
|
781 |
+
return int(self.canvas().itemcget(self._tag, attr))
|
782 |
+
elif attr in ("color", "font", "justify"):
|
783 |
+
if attr == "color":
|
784 |
+
attr = "fill"
|
785 |
+
return self.canvas().itemcget(self._tag, attr)
|
786 |
+
else:
|
787 |
+
return CanvasWidget.__getitem__(self, attr)
|
788 |
+
|
789 |
+
def _tags(self):
|
790 |
+
return [self._tag]
|
791 |
+
|
792 |
+
def text(self):
|
793 |
+
"""
|
794 |
+
:return: The text displayed by this text widget.
|
795 |
+
:rtype: str
|
796 |
+
"""
|
797 |
+
return self.canvas().itemcget(self._tag, "TEXT")
|
798 |
+
|
799 |
+
def set_text(self, text):
|
800 |
+
"""
|
801 |
+
Change the text that is displayed by this text widget.
|
802 |
+
|
803 |
+
:type text: str
|
804 |
+
:param text: The string of text to display.
|
805 |
+
:rtype: None
|
806 |
+
"""
|
807 |
+
self.canvas().itemconfig(self._tag, text=text)
|
808 |
+
if self.parent() is not None:
|
809 |
+
self.parent().update(self)
|
810 |
+
|
811 |
+
def __repr__(self):
|
812 |
+
return "[Text: %r]" % self._text
|
813 |
+
|
814 |
+
|
815 |
+
class SymbolWidget(TextWidget):
|
816 |
+
"""
|
817 |
+
A canvas widget that displays special symbols, such as the
|
818 |
+
negation sign and the exists operator. Symbols are specified by
|
819 |
+
name. Currently, the following symbol names are defined: ``neg``,
|
820 |
+
``disj``, ``conj``, ``lambda``, ``merge``, ``forall``, ``exists``,
|
821 |
+
``subseteq``, ``subset``, ``notsubset``, ``emptyset``, ``imp``,
|
822 |
+
``rightarrow``, ``equal``, ``notequal``, ``epsilon``.
|
823 |
+
|
824 |
+
Attributes:
|
825 |
+
|
826 |
+
- ``color``: the color of the text.
|
827 |
+
- ``draggable``: whether the text can be dragged by the user.
|
828 |
+
|
829 |
+
:cvar SYMBOLS: A dictionary mapping from symbols to the character
|
830 |
+
in the ``symbol`` font used to render them.
|
831 |
+
"""
|
832 |
+
|
833 |
+
SYMBOLS = {
|
834 |
+
"neg": "\330",
|
835 |
+
"disj": "\332",
|
836 |
+
"conj": "\331",
|
837 |
+
"lambda": "\154",
|
838 |
+
"merge": "\304",
|
839 |
+
"forall": "\042",
|
840 |
+
"exists": "\044",
|
841 |
+
"subseteq": "\315",
|
842 |
+
"subset": "\314",
|
843 |
+
"notsubset": "\313",
|
844 |
+
"emptyset": "\306",
|
845 |
+
"imp": "\336",
|
846 |
+
"rightarrow": chr(222), #'\256',
|
847 |
+
"equal": "\75",
|
848 |
+
"notequal": "\271",
|
849 |
+
"intersection": "\307",
|
850 |
+
"union": "\310",
|
851 |
+
"epsilon": "e",
|
852 |
+
}
|
853 |
+
|
854 |
+
def __init__(self, canvas, symbol, **attribs):
|
855 |
+
"""
|
856 |
+
Create a new symbol widget.
|
857 |
+
|
858 |
+
:type canvas: Tkinter.Canvas
|
859 |
+
:param canvas: This canvas widget's canvas.
|
860 |
+
:type symbol: str
|
861 |
+
:param symbol: The name of the symbol to display.
|
862 |
+
:param attribs: The new canvas widget's attributes.
|
863 |
+
"""
|
864 |
+
attribs["font"] = "symbol"
|
865 |
+
TextWidget.__init__(self, canvas, "", **attribs)
|
866 |
+
self.set_symbol(symbol)
|
867 |
+
|
868 |
+
def symbol(self):
|
869 |
+
"""
|
870 |
+
:return: the name of the symbol that is displayed by this
|
871 |
+
symbol widget.
|
872 |
+
:rtype: str
|
873 |
+
"""
|
874 |
+
return self._symbol
|
875 |
+
|
876 |
+
def set_symbol(self, symbol):
|
877 |
+
"""
|
878 |
+
Change the symbol that is displayed by this symbol widget.
|
879 |
+
|
880 |
+
:type symbol: str
|
881 |
+
:param symbol: The name of the symbol to display.
|
882 |
+
"""
|
883 |
+
if symbol not in SymbolWidget.SYMBOLS:
|
884 |
+
raise ValueError("Unknown symbol: %s" % symbol)
|
885 |
+
self._symbol = symbol
|
886 |
+
self.set_text(SymbolWidget.SYMBOLS[symbol])
|
887 |
+
|
888 |
+
def __repr__(self):
|
889 |
+
return "[Symbol: %r]" % self._symbol
|
890 |
+
|
891 |
+
@staticmethod
|
892 |
+
def symbolsheet(size=20):
|
893 |
+
"""
|
894 |
+
Open a new Tkinter window that displays the entire alphabet
|
895 |
+
for the symbol font. This is useful for constructing the
|
896 |
+
``SymbolWidget.SYMBOLS`` dictionary.
|
897 |
+
"""
|
898 |
+
top = Tk()
|
899 |
+
|
900 |
+
def destroy(e, top=top):
|
901 |
+
top.destroy()
|
902 |
+
|
903 |
+
top.bind("q", destroy)
|
904 |
+
Button(top, text="Quit", command=top.destroy).pack(side="bottom")
|
905 |
+
text = Text(top, font=("helvetica", -size), width=20, height=30)
|
906 |
+
text.pack(side="left")
|
907 |
+
sb = Scrollbar(top, command=text.yview)
|
908 |
+
text["yscrollcommand"] = sb.set
|
909 |
+
sb.pack(side="right", fill="y")
|
910 |
+
text.tag_config("symbol", font=("symbol", -size))
|
911 |
+
for i in range(256):
|
912 |
+
if i in (0, 10):
|
913 |
+
continue # null and newline
|
914 |
+
for k, v in list(SymbolWidget.SYMBOLS.items()):
|
915 |
+
if v == chr(i):
|
916 |
+
text.insert("end", "%-10s\t" % k)
|
917 |
+
break
|
918 |
+
else:
|
919 |
+
text.insert("end", "%-10d \t" % i)
|
920 |
+
text.insert("end", "[%s]\n" % chr(i), "symbol")
|
921 |
+
top.mainloop()
|
922 |
+
|
923 |
+
|
924 |
+
class AbstractContainerWidget(CanvasWidget):
|
925 |
+
"""
|
926 |
+
An abstract class for canvas widgets that contain a single child,
|
927 |
+
such as ``BoxWidget`` and ``OvalWidget``. Subclasses must define
|
928 |
+
a constructor, which should create any new graphical elements and
|
929 |
+
then call the ``AbstractCanvasContainer`` constructor. Subclasses
|
930 |
+
must also define the ``_update`` method and the ``_tags`` method;
|
931 |
+
and any subclasses that define attributes should define
|
932 |
+
``__setitem__`` and ``__getitem__``.
|
933 |
+
"""
|
934 |
+
|
935 |
+
def __init__(self, canvas, child, **attribs):
|
936 |
+
"""
|
937 |
+
Create a new container widget. This constructor should only
|
938 |
+
be called by subclass constructors.
|
939 |
+
|
940 |
+
:type canvas: Tkinter.Canvas
|
941 |
+
:param canvas: This canvas widget's canvas.
|
942 |
+
:param child: The container's child widget. ``child`` must not
|
943 |
+
have a parent.
|
944 |
+
:type child: CanvasWidget
|
945 |
+
:param attribs: The new canvas widget's attributes.
|
946 |
+
"""
|
947 |
+
self._child = child
|
948 |
+
self._add_child_widget(child)
|
949 |
+
CanvasWidget.__init__(self, canvas, **attribs)
|
950 |
+
|
951 |
+
def _manage(self):
|
952 |
+
self._update(self._child)
|
953 |
+
|
954 |
+
def child(self):
|
955 |
+
"""
|
956 |
+
:return: The child widget contained by this container widget.
|
957 |
+
:rtype: CanvasWidget
|
958 |
+
"""
|
959 |
+
return self._child
|
960 |
+
|
961 |
+
def set_child(self, child):
|
962 |
+
"""
|
963 |
+
Change the child widget contained by this container widget.
|
964 |
+
|
965 |
+
:param child: The new child widget. ``child`` must not have a
|
966 |
+
parent.
|
967 |
+
:type child: CanvasWidget
|
968 |
+
:rtype: None
|
969 |
+
"""
|
970 |
+
self._remove_child_widget(self._child)
|
971 |
+
self._add_child_widget(child)
|
972 |
+
self._child = child
|
973 |
+
self.update(child)
|
974 |
+
|
975 |
+
def __repr__(self):
|
976 |
+
name = self.__class__.__name__
|
977 |
+
if name[-6:] == "Widget":
|
978 |
+
name = name[:-6]
|
979 |
+
return f"[{name}: {self._child!r}]"
|
980 |
+
|
981 |
+
|
982 |
+
class BoxWidget(AbstractContainerWidget):
|
983 |
+
"""
|
984 |
+
A canvas widget that places a box around a child widget.
|
985 |
+
|
986 |
+
Attributes:
|
987 |
+
- ``fill``: The color used to fill the interior of the box.
|
988 |
+
- ``outline``: The color used to draw the outline of the box.
|
989 |
+
- ``width``: The width of the outline of the box.
|
990 |
+
- ``margin``: The number of pixels space left between the child
|
991 |
+
and the box.
|
992 |
+
- ``draggable``: whether the text can be dragged by the user.
|
993 |
+
"""
|
994 |
+
|
995 |
+
def __init__(self, canvas, child, **attribs):
|
996 |
+
"""
|
997 |
+
Create a new box widget.
|
998 |
+
|
999 |
+
:type canvas: Tkinter.Canvas
|
1000 |
+
:param canvas: This canvas widget's canvas.
|
1001 |
+
:param child: The child widget. ``child`` must not have a
|
1002 |
+
parent.
|
1003 |
+
:type child: CanvasWidget
|
1004 |
+
:param attribs: The new canvas widget's attributes.
|
1005 |
+
"""
|
1006 |
+
self._child = child
|
1007 |
+
self._margin = 1
|
1008 |
+
self._box = canvas.create_rectangle(1, 1, 1, 1)
|
1009 |
+
canvas.tag_lower(self._box)
|
1010 |
+
AbstractContainerWidget.__init__(self, canvas, child, **attribs)
|
1011 |
+
|
1012 |
+
def __setitem__(self, attr, value):
|
1013 |
+
if attr == "margin":
|
1014 |
+
self._margin = value
|
1015 |
+
elif attr in ("outline", "fill", "width"):
|
1016 |
+
self.canvas().itemconfig(self._box, {attr: value})
|
1017 |
+
else:
|
1018 |
+
CanvasWidget.__setitem__(self, attr, value)
|
1019 |
+
|
1020 |
+
def __getitem__(self, attr):
|
1021 |
+
if attr == "margin":
|
1022 |
+
return self._margin
|
1023 |
+
elif attr == "width":
|
1024 |
+
return float(self.canvas().itemcget(self._box, attr))
|
1025 |
+
elif attr in ("outline", "fill", "width"):
|
1026 |
+
return self.canvas().itemcget(self._box, attr)
|
1027 |
+
else:
|
1028 |
+
return CanvasWidget.__getitem__(self, attr)
|
1029 |
+
|
1030 |
+
def _update(self, child):
|
1031 |
+
(x1, y1, x2, y2) = child.bbox()
|
1032 |
+
margin = self._margin + self["width"] / 2
|
1033 |
+
self.canvas().coords(
|
1034 |
+
self._box, x1 - margin, y1 - margin, x2 + margin, y2 + margin
|
1035 |
+
)
|
1036 |
+
|
1037 |
+
def _tags(self):
|
1038 |
+
return [self._box]
|
1039 |
+
|
1040 |
+
|
1041 |
+
class OvalWidget(AbstractContainerWidget):
|
1042 |
+
"""
|
1043 |
+
A canvas widget that places a oval around a child widget.
|
1044 |
+
|
1045 |
+
Attributes:
|
1046 |
+
- ``fill``: The color used to fill the interior of the oval.
|
1047 |
+
- ``outline``: The color used to draw the outline of the oval.
|
1048 |
+
- ``width``: The width of the outline of the oval.
|
1049 |
+
- ``margin``: The number of pixels space left between the child
|
1050 |
+
and the oval.
|
1051 |
+
- ``draggable``: whether the text can be dragged by the user.
|
1052 |
+
- ``double``: If true, then a double-oval is drawn.
|
1053 |
+
"""
|
1054 |
+
|
1055 |
+
def __init__(self, canvas, child, **attribs):
|
1056 |
+
"""
|
1057 |
+
Create a new oval widget.
|
1058 |
+
|
1059 |
+
:type canvas: Tkinter.Canvas
|
1060 |
+
:param canvas: This canvas widget's canvas.
|
1061 |
+
:param child: The child widget. ``child`` must not have a
|
1062 |
+
parent.
|
1063 |
+
:type child: CanvasWidget
|
1064 |
+
:param attribs: The new canvas widget's attributes.
|
1065 |
+
"""
|
1066 |
+
self._child = child
|
1067 |
+
self._margin = 1
|
1068 |
+
self._oval = canvas.create_oval(1, 1, 1, 1)
|
1069 |
+
self._circle = attribs.pop("circle", False)
|
1070 |
+
self._double = attribs.pop("double", False)
|
1071 |
+
if self._double:
|
1072 |
+
self._oval2 = canvas.create_oval(1, 1, 1, 1)
|
1073 |
+
else:
|
1074 |
+
self._oval2 = None
|
1075 |
+
canvas.tag_lower(self._oval)
|
1076 |
+
AbstractContainerWidget.__init__(self, canvas, child, **attribs)
|
1077 |
+
|
1078 |
+
def __setitem__(self, attr, value):
|
1079 |
+
c = self.canvas()
|
1080 |
+
if attr == "margin":
|
1081 |
+
self._margin = value
|
1082 |
+
elif attr == "double":
|
1083 |
+
if value == True and self._oval2 is None:
|
1084 |
+
# Copy attributes & position from self._oval.
|
1085 |
+
x1, y1, x2, y2 = c.bbox(self._oval)
|
1086 |
+
w = self["width"] * 2
|
1087 |
+
self._oval2 = c.create_oval(
|
1088 |
+
x1 - w,
|
1089 |
+
y1 - w,
|
1090 |
+
x2 + w,
|
1091 |
+
y2 + w,
|
1092 |
+
outline=c.itemcget(self._oval, "outline"),
|
1093 |
+
width=c.itemcget(self._oval, "width"),
|
1094 |
+
)
|
1095 |
+
c.tag_lower(self._oval2)
|
1096 |
+
if value == False and self._oval2 is not None:
|
1097 |
+
c.delete(self._oval2)
|
1098 |
+
self._oval2 = None
|
1099 |
+
elif attr in ("outline", "fill", "width"):
|
1100 |
+
c.itemconfig(self._oval, {attr: value})
|
1101 |
+
if self._oval2 is not None and attr != "fill":
|
1102 |
+
c.itemconfig(self._oval2, {attr: value})
|
1103 |
+
if self._oval2 is not None and attr != "fill":
|
1104 |
+
self.canvas().itemconfig(self._oval2, {attr: value})
|
1105 |
+
else:
|
1106 |
+
CanvasWidget.__setitem__(self, attr, value)
|
1107 |
+
|
1108 |
+
def __getitem__(self, attr):
|
1109 |
+
if attr == "margin":
|
1110 |
+
return self._margin
|
1111 |
+
elif attr == "double":
|
1112 |
+
return self._double is not None
|
1113 |
+
elif attr == "width":
|
1114 |
+
return float(self.canvas().itemcget(self._oval, attr))
|
1115 |
+
elif attr in ("outline", "fill", "width"):
|
1116 |
+
return self.canvas().itemcget(self._oval, attr)
|
1117 |
+
else:
|
1118 |
+
return CanvasWidget.__getitem__(self, attr)
|
1119 |
+
|
1120 |
+
# The ratio between inscribed & circumscribed ovals
|
1121 |
+
RATIO = 1.4142135623730949
|
1122 |
+
|
1123 |
+
def _update(self, child):
|
1124 |
+
R = OvalWidget.RATIO
|
1125 |
+
(x1, y1, x2, y2) = child.bbox()
|
1126 |
+
margin = self._margin
|
1127 |
+
|
1128 |
+
# If we're a circle, pretend our contents are square.
|
1129 |
+
if self._circle:
|
1130 |
+
dx, dy = abs(x1 - x2), abs(y1 - y2)
|
1131 |
+
if dx > dy:
|
1132 |
+
y = (y1 + y2) / 2
|
1133 |
+
y1, y2 = y - dx / 2, y + dx / 2
|
1134 |
+
elif dy > dx:
|
1135 |
+
x = (x1 + x2) / 2
|
1136 |
+
x1, x2 = x - dy / 2, x + dy / 2
|
1137 |
+
|
1138 |
+
# Find the four corners.
|
1139 |
+
left = int((x1 * (1 + R) + x2 * (1 - R)) / 2)
|
1140 |
+
right = left + int((x2 - x1) * R)
|
1141 |
+
top = int((y1 * (1 + R) + y2 * (1 - R)) / 2)
|
1142 |
+
bot = top + int((y2 - y1) * R)
|
1143 |
+
self.canvas().coords(
|
1144 |
+
self._oval, left - margin, top - margin, right + margin, bot + margin
|
1145 |
+
)
|
1146 |
+
if self._oval2 is not None:
|
1147 |
+
self.canvas().coords(
|
1148 |
+
self._oval2,
|
1149 |
+
left - margin + 2,
|
1150 |
+
top - margin + 2,
|
1151 |
+
right + margin - 2,
|
1152 |
+
bot + margin - 2,
|
1153 |
+
)
|
1154 |
+
|
1155 |
+
def _tags(self):
|
1156 |
+
if self._oval2 is None:
|
1157 |
+
return [self._oval]
|
1158 |
+
else:
|
1159 |
+
return [self._oval, self._oval2]
|
1160 |
+
|
1161 |
+
|
1162 |
+
class ParenWidget(AbstractContainerWidget):
|
1163 |
+
"""
|
1164 |
+
A canvas widget that places a pair of parenthases around a child
|
1165 |
+
widget.
|
1166 |
+
|
1167 |
+
Attributes:
|
1168 |
+
- ``color``: The color used to draw the parenthases.
|
1169 |
+
- ``width``: The width of the parenthases.
|
1170 |
+
- ``draggable``: whether the text can be dragged by the user.
|
1171 |
+
"""
|
1172 |
+
|
1173 |
+
def __init__(self, canvas, child, **attribs):
|
1174 |
+
"""
|
1175 |
+
Create a new parenthasis widget.
|
1176 |
+
|
1177 |
+
:type canvas: Tkinter.Canvas
|
1178 |
+
:param canvas: This canvas widget's canvas.
|
1179 |
+
:param child: The child widget. ``child`` must not have a
|
1180 |
+
parent.
|
1181 |
+
:type child: CanvasWidget
|
1182 |
+
:param attribs: The new canvas widget's attributes.
|
1183 |
+
"""
|
1184 |
+
self._child = child
|
1185 |
+
self._oparen = canvas.create_arc(1, 1, 1, 1, style="arc", start=90, extent=180)
|
1186 |
+
self._cparen = canvas.create_arc(1, 1, 1, 1, style="arc", start=-90, extent=180)
|
1187 |
+
AbstractContainerWidget.__init__(self, canvas, child, **attribs)
|
1188 |
+
|
1189 |
+
def __setitem__(self, attr, value):
|
1190 |
+
if attr == "color":
|
1191 |
+
self.canvas().itemconfig(self._oparen, outline=value)
|
1192 |
+
self.canvas().itemconfig(self._cparen, outline=value)
|
1193 |
+
elif attr == "width":
|
1194 |
+
self.canvas().itemconfig(self._oparen, width=value)
|
1195 |
+
self.canvas().itemconfig(self._cparen, width=value)
|
1196 |
+
else:
|
1197 |
+
CanvasWidget.__setitem__(self, attr, value)
|
1198 |
+
|
1199 |
+
def __getitem__(self, attr):
|
1200 |
+
if attr == "color":
|
1201 |
+
return self.canvas().itemcget(self._oparen, "outline")
|
1202 |
+
elif attr == "width":
|
1203 |
+
return self.canvas().itemcget(self._oparen, "width")
|
1204 |
+
else:
|
1205 |
+
return CanvasWidget.__getitem__(self, attr)
|
1206 |
+
|
1207 |
+
def _update(self, child):
|
1208 |
+
(x1, y1, x2, y2) = child.bbox()
|
1209 |
+
width = max((y2 - y1) / 6, 4)
|
1210 |
+
self.canvas().coords(self._oparen, x1 - width, y1, x1 + width, y2)
|
1211 |
+
self.canvas().coords(self._cparen, x2 - width, y1, x2 + width, y2)
|
1212 |
+
|
1213 |
+
def _tags(self):
|
1214 |
+
return [self._oparen, self._cparen]
|
1215 |
+
|
1216 |
+
|
1217 |
+
class BracketWidget(AbstractContainerWidget):
|
1218 |
+
"""
|
1219 |
+
A canvas widget that places a pair of brackets around a child
|
1220 |
+
widget.
|
1221 |
+
|
1222 |
+
Attributes:
|
1223 |
+
- ``color``: The color used to draw the brackets.
|
1224 |
+
- ``width``: The width of the brackets.
|
1225 |
+
- ``draggable``: whether the text can be dragged by the user.
|
1226 |
+
"""
|
1227 |
+
|
1228 |
+
def __init__(self, canvas, child, **attribs):
|
1229 |
+
"""
|
1230 |
+
Create a new bracket widget.
|
1231 |
+
|
1232 |
+
:type canvas: Tkinter.Canvas
|
1233 |
+
:param canvas: This canvas widget's canvas.
|
1234 |
+
:param child: The child widget. ``child`` must not have a
|
1235 |
+
parent.
|
1236 |
+
:type child: CanvasWidget
|
1237 |
+
:param attribs: The new canvas widget's attributes.
|
1238 |
+
"""
|
1239 |
+
self._child = child
|
1240 |
+
self._obrack = canvas.create_line(1, 1, 1, 1, 1, 1, 1, 1)
|
1241 |
+
self._cbrack = canvas.create_line(1, 1, 1, 1, 1, 1, 1, 1)
|
1242 |
+
AbstractContainerWidget.__init__(self, canvas, child, **attribs)
|
1243 |
+
|
1244 |
+
def __setitem__(self, attr, value):
|
1245 |
+
if attr == "color":
|
1246 |
+
self.canvas().itemconfig(self._obrack, fill=value)
|
1247 |
+
self.canvas().itemconfig(self._cbrack, fill=value)
|
1248 |
+
elif attr == "width":
|
1249 |
+
self.canvas().itemconfig(self._obrack, width=value)
|
1250 |
+
self.canvas().itemconfig(self._cbrack, width=value)
|
1251 |
+
else:
|
1252 |
+
CanvasWidget.__setitem__(self, attr, value)
|
1253 |
+
|
1254 |
+
def __getitem__(self, attr):
|
1255 |
+
if attr == "color":
|
1256 |
+
return self.canvas().itemcget(self._obrack, "outline")
|
1257 |
+
elif attr == "width":
|
1258 |
+
return self.canvas().itemcget(self._obrack, "width")
|
1259 |
+
else:
|
1260 |
+
return CanvasWidget.__getitem__(self, attr)
|
1261 |
+
|
1262 |
+
def _update(self, child):
|
1263 |
+
(x1, y1, x2, y2) = child.bbox()
|
1264 |
+
width = max((y2 - y1) / 8, 2)
|
1265 |
+
self.canvas().coords(
|
1266 |
+
self._obrack, x1, y1, x1 - width, y1, x1 - width, y2, x1, y2
|
1267 |
+
)
|
1268 |
+
self.canvas().coords(
|
1269 |
+
self._cbrack, x2, y1, x2 + width, y1, x2 + width, y2, x2, y2
|
1270 |
+
)
|
1271 |
+
|
1272 |
+
def _tags(self):
|
1273 |
+
return [self._obrack, self._cbrack]
|
1274 |
+
|
1275 |
+
|
1276 |
+
class SequenceWidget(CanvasWidget):
|
1277 |
+
"""
|
1278 |
+
A canvas widget that keeps a list of canvas widgets in a
|
1279 |
+
horizontal line.
|
1280 |
+
|
1281 |
+
Attributes:
|
1282 |
+
- ``align``: The vertical alignment of the children. Possible
|
1283 |
+
values are ``'top'``, ``'center'``, and ``'bottom'``. By
|
1284 |
+
default, children are center-aligned.
|
1285 |
+
- ``space``: The amount of horizontal space to place between
|
1286 |
+
children. By default, one pixel of space is used.
|
1287 |
+
- ``ordered``: If true, then keep the children in their
|
1288 |
+
original order.
|
1289 |
+
"""
|
1290 |
+
|
1291 |
+
def __init__(self, canvas, *children, **attribs):
|
1292 |
+
"""
|
1293 |
+
Create a new sequence widget.
|
1294 |
+
|
1295 |
+
:type canvas: Tkinter.Canvas
|
1296 |
+
:param canvas: This canvas widget's canvas.
|
1297 |
+
:param children: The widgets that should be aligned
|
1298 |
+
horizontally. Each child must not have a parent.
|
1299 |
+
:type children: list(CanvasWidget)
|
1300 |
+
:param attribs: The new canvas widget's attributes.
|
1301 |
+
"""
|
1302 |
+
self._align = "center"
|
1303 |
+
self._space = 1
|
1304 |
+
self._ordered = False
|
1305 |
+
self._children = list(children)
|
1306 |
+
for child in children:
|
1307 |
+
self._add_child_widget(child)
|
1308 |
+
CanvasWidget.__init__(self, canvas, **attribs)
|
1309 |
+
|
1310 |
+
def __setitem__(self, attr, value):
|
1311 |
+
if attr == "align":
|
1312 |
+
if value not in ("top", "bottom", "center"):
|
1313 |
+
raise ValueError("Bad alignment: %r" % value)
|
1314 |
+
self._align = value
|
1315 |
+
elif attr == "space":
|
1316 |
+
self._space = value
|
1317 |
+
elif attr == "ordered":
|
1318 |
+
self._ordered = value
|
1319 |
+
else:
|
1320 |
+
CanvasWidget.__setitem__(self, attr, value)
|
1321 |
+
|
1322 |
+
def __getitem__(self, attr):
|
1323 |
+
if attr == "align":
|
1324 |
+
return self._align
|
1325 |
+
elif attr == "space":
|
1326 |
+
return self._space
|
1327 |
+
elif attr == "ordered":
|
1328 |
+
return self._ordered
|
1329 |
+
else:
|
1330 |
+
return CanvasWidget.__getitem__(self, attr)
|
1331 |
+
|
1332 |
+
def _tags(self):
|
1333 |
+
return []
|
1334 |
+
|
1335 |
+
def _yalign(self, top, bot):
|
1336 |
+
if self._align == "top":
|
1337 |
+
return top
|
1338 |
+
if self._align == "bottom":
|
1339 |
+
return bot
|
1340 |
+
if self._align == "center":
|
1341 |
+
return (top + bot) / 2
|
1342 |
+
|
1343 |
+
def _update(self, child):
|
1344 |
+
# Align all children with child.
|
1345 |
+
(left, top, right, bot) = child.bbox()
|
1346 |
+
y = self._yalign(top, bot)
|
1347 |
+
for c in self._children:
|
1348 |
+
(x1, y1, x2, y2) = c.bbox()
|
1349 |
+
c.move(0, y - self._yalign(y1, y2))
|
1350 |
+
|
1351 |
+
if self._ordered and len(self._children) > 1:
|
1352 |
+
index = self._children.index(child)
|
1353 |
+
|
1354 |
+
x = right + self._space
|
1355 |
+
for i in range(index + 1, len(self._children)):
|
1356 |
+
(x1, y1, x2, y2) = self._children[i].bbox()
|
1357 |
+
if x > x1:
|
1358 |
+
self._children[i].move(x - x1, 0)
|
1359 |
+
x += x2 - x1 + self._space
|
1360 |
+
|
1361 |
+
x = left - self._space
|
1362 |
+
for i in range(index - 1, -1, -1):
|
1363 |
+
(x1, y1, x2, y2) = self._children[i].bbox()
|
1364 |
+
if x < x2:
|
1365 |
+
self._children[i].move(x - x2, 0)
|
1366 |
+
x -= x2 - x1 + self._space
|
1367 |
+
|
1368 |
+
def _manage(self):
|
1369 |
+
if len(self._children) == 0:
|
1370 |
+
return
|
1371 |
+
child = self._children[0]
|
1372 |
+
|
1373 |
+
# Align all children with child.
|
1374 |
+
(left, top, right, bot) = child.bbox()
|
1375 |
+
y = self._yalign(top, bot)
|
1376 |
+
|
1377 |
+
index = self._children.index(child)
|
1378 |
+
|
1379 |
+
# Line up children to the right of child.
|
1380 |
+
x = right + self._space
|
1381 |
+
for i in range(index + 1, len(self._children)):
|
1382 |
+
(x1, y1, x2, y2) = self._children[i].bbox()
|
1383 |
+
self._children[i].move(x - x1, y - self._yalign(y1, y2))
|
1384 |
+
x += x2 - x1 + self._space
|
1385 |
+
|
1386 |
+
# Line up children to the left of child.
|
1387 |
+
x = left - self._space
|
1388 |
+
for i in range(index - 1, -1, -1):
|
1389 |
+
(x1, y1, x2, y2) = self._children[i].bbox()
|
1390 |
+
self._children[i].move(x - x2, y - self._yalign(y1, y2))
|
1391 |
+
x -= x2 - x1 + self._space
|
1392 |
+
|
1393 |
+
def __repr__(self):
|
1394 |
+
return "[Sequence: " + repr(self._children)[1:-1] + "]"
|
1395 |
+
|
1396 |
+
# Provide an alias for the child_widgets() member.
|
1397 |
+
children = CanvasWidget.child_widgets
|
1398 |
+
|
1399 |
+
def replace_child(self, oldchild, newchild):
|
1400 |
+
"""
|
1401 |
+
Replace the child canvas widget ``oldchild`` with ``newchild``.
|
1402 |
+
``newchild`` must not have a parent. ``oldchild``'s parent will
|
1403 |
+
be set to None.
|
1404 |
+
|
1405 |
+
:type oldchild: CanvasWidget
|
1406 |
+
:param oldchild: The child canvas widget to remove.
|
1407 |
+
:type newchild: CanvasWidget
|
1408 |
+
:param newchild: The canvas widget that should replace
|
1409 |
+
``oldchild``.
|
1410 |
+
"""
|
1411 |
+
index = self._children.index(oldchild)
|
1412 |
+
self._children[index] = newchild
|
1413 |
+
self._remove_child_widget(oldchild)
|
1414 |
+
self._add_child_widget(newchild)
|
1415 |
+
self.update(newchild)
|
1416 |
+
|
1417 |
+
def remove_child(self, child):
|
1418 |
+
"""
|
1419 |
+
Remove the given child canvas widget. ``child``'s parent will
|
1420 |
+
be set to None.
|
1421 |
+
|
1422 |
+
:type child: CanvasWidget
|
1423 |
+
:param child: The child canvas widget to remove.
|
1424 |
+
"""
|
1425 |
+
index = self._children.index(child)
|
1426 |
+
del self._children[index]
|
1427 |
+
self._remove_child_widget(child)
|
1428 |
+
if len(self._children) > 0:
|
1429 |
+
self.update(self._children[0])
|
1430 |
+
|
1431 |
+
def insert_child(self, index, child):
|
1432 |
+
"""
|
1433 |
+
Insert a child canvas widget before a given index.
|
1434 |
+
|
1435 |
+
:type child: CanvasWidget
|
1436 |
+
:param child: The canvas widget that should be inserted.
|
1437 |
+
:type index: int
|
1438 |
+
:param index: The index where the child widget should be
|
1439 |
+
inserted. In particular, the index of ``child`` will be
|
1440 |
+
``index``; and the index of any children whose indices were
|
1441 |
+
greater than equal to ``index`` before ``child`` was
|
1442 |
+
inserted will be incremented by one.
|
1443 |
+
"""
|
1444 |
+
self._children.insert(index, child)
|
1445 |
+
self._add_child_widget(child)
|
1446 |
+
|
1447 |
+
|
1448 |
+
class StackWidget(CanvasWidget):
|
1449 |
+
"""
|
1450 |
+
A canvas widget that keeps a list of canvas widgets in a vertical
|
1451 |
+
line.
|
1452 |
+
|
1453 |
+
Attributes:
|
1454 |
+
- ``align``: The horizontal alignment of the children. Possible
|
1455 |
+
values are ``'left'``, ``'center'``, and ``'right'``. By
|
1456 |
+
default, children are center-aligned.
|
1457 |
+
- ``space``: The amount of vertical space to place between
|
1458 |
+
children. By default, one pixel of space is used.
|
1459 |
+
- ``ordered``: If true, then keep the children in their
|
1460 |
+
original order.
|
1461 |
+
"""
|
1462 |
+
|
1463 |
+
def __init__(self, canvas, *children, **attribs):
|
1464 |
+
"""
|
1465 |
+
Create a new stack widget.
|
1466 |
+
|
1467 |
+
:type canvas: Tkinter.Canvas
|
1468 |
+
:param canvas: This canvas widget's canvas.
|
1469 |
+
:param children: The widgets that should be aligned
|
1470 |
+
vertically. Each child must not have a parent.
|
1471 |
+
:type children: list(CanvasWidget)
|
1472 |
+
:param attribs: The new canvas widget's attributes.
|
1473 |
+
"""
|
1474 |
+
self._align = "center"
|
1475 |
+
self._space = 1
|
1476 |
+
self._ordered = False
|
1477 |
+
self._children = list(children)
|
1478 |
+
for child in children:
|
1479 |
+
self._add_child_widget(child)
|
1480 |
+
CanvasWidget.__init__(self, canvas, **attribs)
|
1481 |
+
|
1482 |
+
def __setitem__(self, attr, value):
|
1483 |
+
if attr == "align":
|
1484 |
+
if value not in ("left", "right", "center"):
|
1485 |
+
raise ValueError("Bad alignment: %r" % value)
|
1486 |
+
self._align = value
|
1487 |
+
elif attr == "space":
|
1488 |
+
self._space = value
|
1489 |
+
elif attr == "ordered":
|
1490 |
+
self._ordered = value
|
1491 |
+
else:
|
1492 |
+
CanvasWidget.__setitem__(self, attr, value)
|
1493 |
+
|
1494 |
+
def __getitem__(self, attr):
|
1495 |
+
if attr == "align":
|
1496 |
+
return self._align
|
1497 |
+
elif attr == "space":
|
1498 |
+
return self._space
|
1499 |
+
elif attr == "ordered":
|
1500 |
+
return self._ordered
|
1501 |
+
else:
|
1502 |
+
return CanvasWidget.__getitem__(self, attr)
|
1503 |
+
|
1504 |
+
def _tags(self):
|
1505 |
+
return []
|
1506 |
+
|
1507 |
+
def _xalign(self, left, right):
|
1508 |
+
if self._align == "left":
|
1509 |
+
return left
|
1510 |
+
if self._align == "right":
|
1511 |
+
return right
|
1512 |
+
if self._align == "center":
|
1513 |
+
return (left + right) / 2
|
1514 |
+
|
1515 |
+
def _update(self, child):
|
1516 |
+
# Align all children with child.
|
1517 |
+
(left, top, right, bot) = child.bbox()
|
1518 |
+
x = self._xalign(left, right)
|
1519 |
+
for c in self._children:
|
1520 |
+
(x1, y1, x2, y2) = c.bbox()
|
1521 |
+
c.move(x - self._xalign(x1, x2), 0)
|
1522 |
+
|
1523 |
+
if self._ordered and len(self._children) > 1:
|
1524 |
+
index = self._children.index(child)
|
1525 |
+
|
1526 |
+
y = bot + self._space
|
1527 |
+
for i in range(index + 1, len(self._children)):
|
1528 |
+
(x1, y1, x2, y2) = self._children[i].bbox()
|
1529 |
+
if y > y1:
|
1530 |
+
self._children[i].move(0, y - y1)
|
1531 |
+
y += y2 - y1 + self._space
|
1532 |
+
|
1533 |
+
y = top - self._space
|
1534 |
+
for i in range(index - 1, -1, -1):
|
1535 |
+
(x1, y1, x2, y2) = self._children[i].bbox()
|
1536 |
+
if y < y2:
|
1537 |
+
self._children[i].move(0, y - y2)
|
1538 |
+
y -= y2 - y1 + self._space
|
1539 |
+
|
1540 |
+
def _manage(self):
|
1541 |
+
if len(self._children) == 0:
|
1542 |
+
return
|
1543 |
+
child = self._children[0]
|
1544 |
+
|
1545 |
+
# Align all children with child.
|
1546 |
+
(left, top, right, bot) = child.bbox()
|
1547 |
+
x = self._xalign(left, right)
|
1548 |
+
|
1549 |
+
index = self._children.index(child)
|
1550 |
+
|
1551 |
+
# Line up children below the child.
|
1552 |
+
y = bot + self._space
|
1553 |
+
for i in range(index + 1, len(self._children)):
|
1554 |
+
(x1, y1, x2, y2) = self._children[i].bbox()
|
1555 |
+
self._children[i].move(x - self._xalign(x1, x2), y - y1)
|
1556 |
+
y += y2 - y1 + self._space
|
1557 |
+
|
1558 |
+
# Line up children above the child.
|
1559 |
+
y = top - self._space
|
1560 |
+
for i in range(index - 1, -1, -1):
|
1561 |
+
(x1, y1, x2, y2) = self._children[i].bbox()
|
1562 |
+
self._children[i].move(x - self._xalign(x1, x2), y - y2)
|
1563 |
+
y -= y2 - y1 + self._space
|
1564 |
+
|
1565 |
+
def __repr__(self):
|
1566 |
+
return "[Stack: " + repr(self._children)[1:-1] + "]"
|
1567 |
+
|
1568 |
+
# Provide an alias for the child_widgets() member.
|
1569 |
+
children = CanvasWidget.child_widgets
|
1570 |
+
|
1571 |
+
def replace_child(self, oldchild, newchild):
|
1572 |
+
"""
|
1573 |
+
Replace the child canvas widget ``oldchild`` with ``newchild``.
|
1574 |
+
``newchild`` must not have a parent. ``oldchild``'s parent will
|
1575 |
+
be set to None.
|
1576 |
+
|
1577 |
+
:type oldchild: CanvasWidget
|
1578 |
+
:param oldchild: The child canvas widget to remove.
|
1579 |
+
:type newchild: CanvasWidget
|
1580 |
+
:param newchild: The canvas widget that should replace
|
1581 |
+
``oldchild``.
|
1582 |
+
"""
|
1583 |
+
index = self._children.index(oldchild)
|
1584 |
+
self._children[index] = newchild
|
1585 |
+
self._remove_child_widget(oldchild)
|
1586 |
+
self._add_child_widget(newchild)
|
1587 |
+
self.update(newchild)
|
1588 |
+
|
1589 |
+
def remove_child(self, child):
|
1590 |
+
"""
|
1591 |
+
Remove the given child canvas widget. ``child``'s parent will
|
1592 |
+
be set to None.
|
1593 |
+
|
1594 |
+
:type child: CanvasWidget
|
1595 |
+
:param child: The child canvas widget to remove.
|
1596 |
+
"""
|
1597 |
+
index = self._children.index(child)
|
1598 |
+
del self._children[index]
|
1599 |
+
self._remove_child_widget(child)
|
1600 |
+
if len(self._children) > 0:
|
1601 |
+
self.update(self._children[0])
|
1602 |
+
|
1603 |
+
def insert_child(self, index, child):
|
1604 |
+
"""
|
1605 |
+
Insert a child canvas widget before a given index.
|
1606 |
+
|
1607 |
+
:type child: CanvasWidget
|
1608 |
+
:param child: The canvas widget that should be inserted.
|
1609 |
+
:type index: int
|
1610 |
+
:param index: The index where the child widget should be
|
1611 |
+
inserted. In particular, the index of ``child`` will be
|
1612 |
+
``index``; and the index of any children whose indices were
|
1613 |
+
greater than equal to ``index`` before ``child`` was
|
1614 |
+
inserted will be incremented by one.
|
1615 |
+
"""
|
1616 |
+
self._children.insert(index, child)
|
1617 |
+
self._add_child_widget(child)
|
1618 |
+
|
1619 |
+
|
1620 |
+
class SpaceWidget(CanvasWidget):
|
1621 |
+
"""
|
1622 |
+
A canvas widget that takes up space but does not display
|
1623 |
+
anything. A ``SpaceWidget`` can be used to add space between
|
1624 |
+
elements. Each space widget is characterized by a width and a
|
1625 |
+
height. If you wish to only create horizontal space, then use a
|
1626 |
+
height of zero; and if you wish to only create vertical space, use
|
1627 |
+
a width of zero.
|
1628 |
+
"""
|
1629 |
+
|
1630 |
+
def __init__(self, canvas, width, height, **attribs):
|
1631 |
+
"""
|
1632 |
+
Create a new space widget.
|
1633 |
+
|
1634 |
+
:type canvas: Tkinter.Canvas
|
1635 |
+
:param canvas: This canvas widget's canvas.
|
1636 |
+
:type width: int
|
1637 |
+
:param width: The width of the new space widget.
|
1638 |
+
:type height: int
|
1639 |
+
:param height: The height of the new space widget.
|
1640 |
+
:param attribs: The new canvas widget's attributes.
|
1641 |
+
"""
|
1642 |
+
# For some reason,
|
1643 |
+
if width > 4:
|
1644 |
+
width -= 4
|
1645 |
+
if height > 4:
|
1646 |
+
height -= 4
|
1647 |
+
self._tag = canvas.create_line(1, 1, width, height, fill="")
|
1648 |
+
CanvasWidget.__init__(self, canvas, **attribs)
|
1649 |
+
|
1650 |
+
# note: width() and height() are already defined by CanvasWidget.
|
1651 |
+
def set_width(self, width):
|
1652 |
+
"""
|
1653 |
+
Change the width of this space widget.
|
1654 |
+
|
1655 |
+
:param width: The new width.
|
1656 |
+
:type width: int
|
1657 |
+
:rtype: None
|
1658 |
+
"""
|
1659 |
+
[x1, y1, x2, y2] = self.bbox()
|
1660 |
+
self.canvas().coords(self._tag, x1, y1, x1 + width, y2)
|
1661 |
+
|
1662 |
+
def set_height(self, height):
|
1663 |
+
"""
|
1664 |
+
Change the height of this space widget.
|
1665 |
+
|
1666 |
+
:param height: The new height.
|
1667 |
+
:type height: int
|
1668 |
+
:rtype: None
|
1669 |
+
"""
|
1670 |
+
[x1, y1, x2, y2] = self.bbox()
|
1671 |
+
self.canvas().coords(self._tag, x1, y1, x2, y1 + height)
|
1672 |
+
|
1673 |
+
def _tags(self):
|
1674 |
+
return [self._tag]
|
1675 |
+
|
1676 |
+
def __repr__(self):
|
1677 |
+
return "[Space]"
|
1678 |
+
|
1679 |
+
|
1680 |
+
class ScrollWatcherWidget(CanvasWidget):
|
1681 |
+
"""
|
1682 |
+
A special canvas widget that adjusts its ``Canvas``'s scrollregion
|
1683 |
+
to always include the bounding boxes of all of its children. The
|
1684 |
+
scroll-watcher widget will only increase the size of the
|
1685 |
+
``Canvas``'s scrollregion; it will never decrease it.
|
1686 |
+
"""
|
1687 |
+
|
1688 |
+
def __init__(self, canvas, *children, **attribs):
|
1689 |
+
"""
|
1690 |
+
Create a new scroll-watcher widget.
|
1691 |
+
|
1692 |
+
:type canvas: Tkinter.Canvas
|
1693 |
+
:param canvas: This canvas widget's canvas.
|
1694 |
+
:type children: list(CanvasWidget)
|
1695 |
+
:param children: The canvas widgets watched by the
|
1696 |
+
scroll-watcher. The scroll-watcher will ensure that these
|
1697 |
+
canvas widgets are always contained in their canvas's
|
1698 |
+
scrollregion.
|
1699 |
+
:param attribs: The new canvas widget's attributes.
|
1700 |
+
"""
|
1701 |
+
for child in children:
|
1702 |
+
self._add_child_widget(child)
|
1703 |
+
CanvasWidget.__init__(self, canvas, **attribs)
|
1704 |
+
|
1705 |
+
def add_child(self, canvaswidget):
|
1706 |
+
"""
|
1707 |
+
Add a new canvas widget to the scroll-watcher. The
|
1708 |
+
scroll-watcher will ensure that the new canvas widget is
|
1709 |
+
always contained in its canvas's scrollregion.
|
1710 |
+
|
1711 |
+
:param canvaswidget: The new canvas widget.
|
1712 |
+
:type canvaswidget: CanvasWidget
|
1713 |
+
:rtype: None
|
1714 |
+
"""
|
1715 |
+
self._add_child_widget(canvaswidget)
|
1716 |
+
self.update(canvaswidget)
|
1717 |
+
|
1718 |
+
def remove_child(self, canvaswidget):
|
1719 |
+
"""
|
1720 |
+
Remove a canvas widget from the scroll-watcher. The
|
1721 |
+
scroll-watcher will no longer ensure that the new canvas
|
1722 |
+
widget is always contained in its canvas's scrollregion.
|
1723 |
+
|
1724 |
+
:param canvaswidget: The canvas widget to remove.
|
1725 |
+
:type canvaswidget: CanvasWidget
|
1726 |
+
:rtype: None
|
1727 |
+
"""
|
1728 |
+
self._remove_child_widget(canvaswidget)
|
1729 |
+
|
1730 |
+
def _tags(self):
|
1731 |
+
return []
|
1732 |
+
|
1733 |
+
def _update(self, child):
|
1734 |
+
self._adjust_scrollregion()
|
1735 |
+
|
1736 |
+
def _adjust_scrollregion(self):
|
1737 |
+
"""
|
1738 |
+
Adjust the scrollregion of this scroll-watcher's ``Canvas`` to
|
1739 |
+
include the bounding boxes of all of its children.
|
1740 |
+
"""
|
1741 |
+
bbox = self.bbox()
|
1742 |
+
canvas = self.canvas()
|
1743 |
+
scrollregion = [int(n) for n in canvas["scrollregion"].split()]
|
1744 |
+
if len(scrollregion) != 4:
|
1745 |
+
return
|
1746 |
+
if (
|
1747 |
+
bbox[0] < scrollregion[0]
|
1748 |
+
or bbox[1] < scrollregion[1]
|
1749 |
+
or bbox[2] > scrollregion[2]
|
1750 |
+
or bbox[3] > scrollregion[3]
|
1751 |
+
):
|
1752 |
+
scrollregion = "%d %d %d %d" % (
|
1753 |
+
min(bbox[0], scrollregion[0]),
|
1754 |
+
min(bbox[1], scrollregion[1]),
|
1755 |
+
max(bbox[2], scrollregion[2]),
|
1756 |
+
max(bbox[3], scrollregion[3]),
|
1757 |
+
)
|
1758 |
+
canvas["scrollregion"] = scrollregion
|
1759 |
+
|
1760 |
+
|
1761 |
+
##//////////////////////////////////////////////////////
|
1762 |
+
## Canvas Frame
|
1763 |
+
##//////////////////////////////////////////////////////
|
1764 |
+
|
1765 |
+
|
1766 |
+
class CanvasFrame:
|
1767 |
+
"""
|
1768 |
+
A ``Tkinter`` frame containing a canvas and scrollbars.
|
1769 |
+
``CanvasFrame`` uses a ``ScrollWatcherWidget`` to ensure that all of
|
1770 |
+
the canvas widgets contained on its canvas are within its
|
1771 |
+
scrollregion. In order for ``CanvasFrame`` to make these checks,
|
1772 |
+
all canvas widgets must be registered with ``add_widget`` when they
|
1773 |
+
are added to the canvas; and destroyed with ``destroy_widget`` when
|
1774 |
+
they are no longer needed.
|
1775 |
+
|
1776 |
+
If a ``CanvasFrame`` is created with no parent, then it will create
|
1777 |
+
its own main window, including a "Done" button and a "Print"
|
1778 |
+
button.
|
1779 |
+
"""
|
1780 |
+
|
1781 |
+
def __init__(self, parent=None, **kw):
|
1782 |
+
"""
|
1783 |
+
Create a new ``CanvasFrame``.
|
1784 |
+
|
1785 |
+
:type parent: Tkinter.BaseWidget or Tkinter.Tk
|
1786 |
+
:param parent: The parent ``Tkinter`` widget. If no parent is
|
1787 |
+
specified, then ``CanvasFrame`` will create a new main
|
1788 |
+
window.
|
1789 |
+
:param kw: Keyword arguments for the new ``Canvas``. See the
|
1790 |
+
documentation for ``Tkinter.Canvas`` for more information.
|
1791 |
+
"""
|
1792 |
+
# If no parent was given, set up a top-level window.
|
1793 |
+
if parent is None:
|
1794 |
+
self._parent = Tk()
|
1795 |
+
self._parent.title("NLTK")
|
1796 |
+
self._parent.bind("<Control-p>", lambda e: self.print_to_file())
|
1797 |
+
self._parent.bind("<Control-x>", self.destroy)
|
1798 |
+
self._parent.bind("<Control-q>", self.destroy)
|
1799 |
+
else:
|
1800 |
+
self._parent = parent
|
1801 |
+
|
1802 |
+
# Create a frame for the canvas & scrollbars
|
1803 |
+
self._frame = frame = Frame(self._parent)
|
1804 |
+
self._canvas = canvas = Canvas(frame, **kw)
|
1805 |
+
xscrollbar = Scrollbar(self._frame, orient="horizontal")
|
1806 |
+
yscrollbar = Scrollbar(self._frame, orient="vertical")
|
1807 |
+
xscrollbar["command"] = canvas.xview
|
1808 |
+
yscrollbar["command"] = canvas.yview
|
1809 |
+
canvas["xscrollcommand"] = xscrollbar.set
|
1810 |
+
canvas["yscrollcommand"] = yscrollbar.set
|
1811 |
+
yscrollbar.pack(fill="y", side="right")
|
1812 |
+
xscrollbar.pack(fill="x", side="bottom")
|
1813 |
+
canvas.pack(expand=1, fill="both", side="left")
|
1814 |
+
|
1815 |
+
# Set initial scroll region.
|
1816 |
+
scrollregion = "0 0 {} {}".format(canvas["width"], canvas["height"])
|
1817 |
+
canvas["scrollregion"] = scrollregion
|
1818 |
+
|
1819 |
+
self._scrollwatcher = ScrollWatcherWidget(canvas)
|
1820 |
+
|
1821 |
+
# If no parent was given, pack the frame, and add a menu.
|
1822 |
+
if parent is None:
|
1823 |
+
self.pack(expand=1, fill="both")
|
1824 |
+
self._init_menubar()
|
1825 |
+
|
1826 |
+
def _init_menubar(self):
|
1827 |
+
menubar = Menu(self._parent)
|
1828 |
+
|
1829 |
+
filemenu = Menu(menubar, tearoff=0)
|
1830 |
+
filemenu.add_command(
|
1831 |
+
label="Print to Postscript",
|
1832 |
+
underline=0,
|
1833 |
+
command=self.print_to_file,
|
1834 |
+
accelerator="Ctrl-p",
|
1835 |
+
)
|
1836 |
+
filemenu.add_command(
|
1837 |
+
label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-x"
|
1838 |
+
)
|
1839 |
+
menubar.add_cascade(label="File", underline=0, menu=filemenu)
|
1840 |
+
|
1841 |
+
self._parent.config(menu=menubar)
|
1842 |
+
|
1843 |
+
def print_to_file(self, filename=None):
|
1844 |
+
"""
|
1845 |
+
Print the contents of this ``CanvasFrame`` to a postscript
|
1846 |
+
file. If no filename is given, then prompt the user for one.
|
1847 |
+
|
1848 |
+
:param filename: The name of the file to print the tree to.
|
1849 |
+
:type filename: str
|
1850 |
+
:rtype: None
|
1851 |
+
"""
|
1852 |
+
if filename is None:
|
1853 |
+
ftypes = [("Postscript files", ".ps"), ("All files", "*")]
|
1854 |
+
filename = asksaveasfilename(filetypes=ftypes, defaultextension=".ps")
|
1855 |
+
if not filename:
|
1856 |
+
return
|
1857 |
+
(x0, y0, w, h) = self.scrollregion()
|
1858 |
+
postscript = self._canvas.postscript(
|
1859 |
+
x=x0,
|
1860 |
+
y=y0,
|
1861 |
+
width=w + 2,
|
1862 |
+
height=h + 2,
|
1863 |
+
pagewidth=w + 2, # points = 1/72 inch
|
1864 |
+
pageheight=h + 2, # points = 1/72 inch
|
1865 |
+
pagex=0,
|
1866 |
+
pagey=0,
|
1867 |
+
)
|
1868 |
+
# workaround for bug in Tk font handling
|
1869 |
+
postscript = postscript.replace(" 0 scalefont ", " 9 scalefont ")
|
1870 |
+
with open(filename, "wb") as f:
|
1871 |
+
f.write(postscript.encode("utf8"))
|
1872 |
+
|
1873 |
+
def scrollregion(self):
|
1874 |
+
"""
|
1875 |
+
:return: The current scroll region for the canvas managed by
|
1876 |
+
this ``CanvasFrame``.
|
1877 |
+
:rtype: 4-tuple of int
|
1878 |
+
"""
|
1879 |
+
(x1, y1, x2, y2) = self._canvas["scrollregion"].split()
|
1880 |
+
return (int(x1), int(y1), int(x2), int(y2))
|
1881 |
+
|
1882 |
+
def canvas(self):
|
1883 |
+
"""
|
1884 |
+
:return: The canvas managed by this ``CanvasFrame``.
|
1885 |
+
:rtype: Tkinter.Canvas
|
1886 |
+
"""
|
1887 |
+
return self._canvas
|
1888 |
+
|
1889 |
+
def add_widget(self, canvaswidget, x=None, y=None):
|
1890 |
+
"""
|
1891 |
+
Register a canvas widget with this ``CanvasFrame``. The
|
1892 |
+
``CanvasFrame`` will ensure that this canvas widget is always
|
1893 |
+
within the ``Canvas``'s scrollregion. If no coordinates are
|
1894 |
+
given for the canvas widget, then the ``CanvasFrame`` will
|
1895 |
+
attempt to find a clear area of the canvas for it.
|
1896 |
+
|
1897 |
+
:type canvaswidget: CanvasWidget
|
1898 |
+
:param canvaswidget: The new canvas widget. ``canvaswidget``
|
1899 |
+
must have been created on this ``CanvasFrame``'s canvas.
|
1900 |
+
:type x: int
|
1901 |
+
:param x: The initial x coordinate for the upper left hand
|
1902 |
+
corner of ``canvaswidget``, in the canvas's coordinate
|
1903 |
+
space.
|
1904 |
+
:type y: int
|
1905 |
+
:param y: The initial y coordinate for the upper left hand
|
1906 |
+
corner of ``canvaswidget``, in the canvas's coordinate
|
1907 |
+
space.
|
1908 |
+
"""
|
1909 |
+
if x is None or y is None:
|
1910 |
+
(x, y) = self._find_room(canvaswidget, x, y)
|
1911 |
+
|
1912 |
+
# Move to (x,y)
|
1913 |
+
(x1, y1, x2, y2) = canvaswidget.bbox()
|
1914 |
+
canvaswidget.move(x - x1, y - y1)
|
1915 |
+
|
1916 |
+
# Register with scrollwatcher.
|
1917 |
+
self._scrollwatcher.add_child(canvaswidget)
|
1918 |
+
|
1919 |
+
def _find_room(self, widget, desired_x, desired_y):
|
1920 |
+
"""
|
1921 |
+
Try to find a space for a given widget.
|
1922 |
+
"""
|
1923 |
+
(left, top, right, bot) = self.scrollregion()
|
1924 |
+
w = widget.width()
|
1925 |
+
h = widget.height()
|
1926 |
+
|
1927 |
+
if w >= (right - left):
|
1928 |
+
return (0, 0)
|
1929 |
+
if h >= (bot - top):
|
1930 |
+
return (0, 0)
|
1931 |
+
|
1932 |
+
# Move the widget out of the way, for now.
|
1933 |
+
(x1, y1, x2, y2) = widget.bbox()
|
1934 |
+
widget.move(left - x2 - 50, top - y2 - 50)
|
1935 |
+
|
1936 |
+
if desired_x is not None:
|
1937 |
+
x = desired_x
|
1938 |
+
for y in range(top, bot - h, int((bot - top - h) / 10)):
|
1939 |
+
if not self._canvas.find_overlapping(
|
1940 |
+
x - 5, y - 5, x + w + 5, y + h + 5
|
1941 |
+
):
|
1942 |
+
return (x, y)
|
1943 |
+
|
1944 |
+
if desired_y is not None:
|
1945 |
+
y = desired_y
|
1946 |
+
for x in range(left, right - w, int((right - left - w) / 10)):
|
1947 |
+
if not self._canvas.find_overlapping(
|
1948 |
+
x - 5, y - 5, x + w + 5, y + h + 5
|
1949 |
+
):
|
1950 |
+
return (x, y)
|
1951 |
+
|
1952 |
+
for y in range(top, bot - h, int((bot - top - h) / 10)):
|
1953 |
+
for x in range(left, right - w, int((right - left - w) / 10)):
|
1954 |
+
if not self._canvas.find_overlapping(
|
1955 |
+
x - 5, y - 5, x + w + 5, y + h + 5
|
1956 |
+
):
|
1957 |
+
return (x, y)
|
1958 |
+
return (0, 0)
|
1959 |
+
|
1960 |
+
def destroy_widget(self, canvaswidget):
|
1961 |
+
"""
|
1962 |
+
Remove a canvas widget from this ``CanvasFrame``. This
|
1963 |
+
deregisters the canvas widget, and destroys it.
|
1964 |
+
"""
|
1965 |
+
self.remove_widget(canvaswidget)
|
1966 |
+
canvaswidget.destroy()
|
1967 |
+
|
1968 |
+
def remove_widget(self, canvaswidget):
|
1969 |
+
# Deregister with scrollwatcher.
|
1970 |
+
self._scrollwatcher.remove_child(canvaswidget)
|
1971 |
+
|
1972 |
+
def pack(self, cnf={}, **kw):
|
1973 |
+
"""
|
1974 |
+
Pack this ``CanvasFrame``. See the documentation for
|
1975 |
+
``Tkinter.Pack`` for more information.
|
1976 |
+
"""
|
1977 |
+
self._frame.pack(cnf, **kw)
|
1978 |
+
# Adjust to be big enough for kids?
|
1979 |
+
|
1980 |
+
def destroy(self, *e):
|
1981 |
+
"""
|
1982 |
+
Destroy this ``CanvasFrame``. If this ``CanvasFrame`` created a
|
1983 |
+
top-level window, then this will close that window.
|
1984 |
+
"""
|
1985 |
+
if self._parent is None:
|
1986 |
+
return
|
1987 |
+
self._parent.destroy()
|
1988 |
+
self._parent = None
|
1989 |
+
|
1990 |
+
def mainloop(self, *args, **kwargs):
|
1991 |
+
"""
|
1992 |
+
Enter the Tkinter mainloop. This function must be called if
|
1993 |
+
this frame is created from a non-interactive program (e.g.
|
1994 |
+
from a secript); otherwise, the frame will close as soon as
|
1995 |
+
the script completes.
|
1996 |
+
"""
|
1997 |
+
if in_idle():
|
1998 |
+
return
|
1999 |
+
self._parent.mainloop(*args, **kwargs)
|
2000 |
+
|
2001 |
+
|
2002 |
+
##//////////////////////////////////////////////////////
|
2003 |
+
## Text display
|
2004 |
+
##//////////////////////////////////////////////////////
|
2005 |
+
|
2006 |
+
|
2007 |
+
class ShowText:
|
2008 |
+
"""
|
2009 |
+
A ``Tkinter`` window used to display a text. ``ShowText`` is
|
2010 |
+
typically used by graphical tools to display help text, or similar
|
2011 |
+
information.
|
2012 |
+
"""
|
2013 |
+
|
2014 |
+
def __init__(self, root, title, text, width=None, height=None, **textbox_options):
|
2015 |
+
if width is None or height is None:
|
2016 |
+
(width, height) = self.find_dimentions(text, width, height)
|
2017 |
+
|
2018 |
+
# Create the main window.
|
2019 |
+
if root is None:
|
2020 |
+
self._top = top = Tk()
|
2021 |
+
else:
|
2022 |
+
self._top = top = Toplevel(root)
|
2023 |
+
top.title(title)
|
2024 |
+
|
2025 |
+
b = Button(top, text="Ok", command=self.destroy)
|
2026 |
+
b.pack(side="bottom")
|
2027 |
+
|
2028 |
+
tbf = Frame(top)
|
2029 |
+
tbf.pack(expand=1, fill="both")
|
2030 |
+
scrollbar = Scrollbar(tbf, orient="vertical")
|
2031 |
+
scrollbar.pack(side="right", fill="y")
|
2032 |
+
textbox = Text(tbf, wrap="word", width=width, height=height, **textbox_options)
|
2033 |
+
textbox.insert("end", text)
|
2034 |
+
textbox["state"] = "disabled"
|
2035 |
+
textbox.pack(side="left", expand=1, fill="both")
|
2036 |
+
scrollbar["command"] = textbox.yview
|
2037 |
+
textbox["yscrollcommand"] = scrollbar.set
|
2038 |
+
|
2039 |
+
# Make it easy to close the window.
|
2040 |
+
top.bind("q", self.destroy)
|
2041 |
+
top.bind("x", self.destroy)
|
2042 |
+
top.bind("c", self.destroy)
|
2043 |
+
top.bind("<Return>", self.destroy)
|
2044 |
+
top.bind("<Escape>", self.destroy)
|
2045 |
+
|
2046 |
+
# Focus the scrollbar, so they can use up/down, etc.
|
2047 |
+
scrollbar.focus()
|
2048 |
+
|
2049 |
+
def find_dimentions(self, text, width, height):
|
2050 |
+
lines = text.split("\n")
|
2051 |
+
if width is None:
|
2052 |
+
maxwidth = max(len(line) for line in lines)
|
2053 |
+
width = min(maxwidth, 80)
|
2054 |
+
|
2055 |
+
# Now, find height.
|
2056 |
+
height = 0
|
2057 |
+
for line in lines:
|
2058 |
+
while len(line) > width:
|
2059 |
+
brk = line[:width].rfind(" ")
|
2060 |
+
line = line[brk:]
|
2061 |
+
height += 1
|
2062 |
+
height += 1
|
2063 |
+
height = min(height, 25)
|
2064 |
+
|
2065 |
+
return (width, height)
|
2066 |
+
|
2067 |
+
def destroy(self, *e):
|
2068 |
+
if self._top is None:
|
2069 |
+
return
|
2070 |
+
self._top.destroy()
|
2071 |
+
self._top = None
|
2072 |
+
|
2073 |
+
def mainloop(self, *args, **kwargs):
|
2074 |
+
"""
|
2075 |
+
Enter the Tkinter mainloop. This function must be called if
|
2076 |
+
this window is created from a non-interactive program (e.g.
|
2077 |
+
from a secript); otherwise, the window will close as soon as
|
2078 |
+
the script completes.
|
2079 |
+
"""
|
2080 |
+
if in_idle():
|
2081 |
+
return
|
2082 |
+
self._top.mainloop(*args, **kwargs)
|
2083 |
+
|
2084 |
+
|
2085 |
+
##//////////////////////////////////////////////////////
|
2086 |
+
## Entry dialog
|
2087 |
+
##//////////////////////////////////////////////////////
|
2088 |
+
|
2089 |
+
|
2090 |
+
class EntryDialog:
|
2091 |
+
"""
|
2092 |
+
A dialog box for entering
|
2093 |
+
"""
|
2094 |
+
|
2095 |
+
def __init__(
|
2096 |
+
self, parent, original_text="", instructions="", set_callback=None, title=None
|
2097 |
+
):
|
2098 |
+
self._parent = parent
|
2099 |
+
self._original_text = original_text
|
2100 |
+
self._set_callback = set_callback
|
2101 |
+
|
2102 |
+
width = int(max(30, len(original_text) * 3 / 2))
|
2103 |
+
self._top = Toplevel(parent)
|
2104 |
+
|
2105 |
+
if title:
|
2106 |
+
self._top.title(title)
|
2107 |
+
|
2108 |
+
# The text entry box.
|
2109 |
+
entryframe = Frame(self._top)
|
2110 |
+
entryframe.pack(expand=1, fill="both", padx=5, pady=5, ipady=10)
|
2111 |
+
if instructions:
|
2112 |
+
l = Label(entryframe, text=instructions)
|
2113 |
+
l.pack(side="top", anchor="w", padx=30)
|
2114 |
+
self._entry = Entry(entryframe, width=width)
|
2115 |
+
self._entry.pack(expand=1, fill="x", padx=30)
|
2116 |
+
self._entry.insert(0, original_text)
|
2117 |
+
|
2118 |
+
# A divider
|
2119 |
+
divider = Frame(self._top, borderwidth=1, relief="sunken")
|
2120 |
+
divider.pack(fill="x", ipady=1, padx=10)
|
2121 |
+
|
2122 |
+
# The buttons.
|
2123 |
+
buttons = Frame(self._top)
|
2124 |
+
buttons.pack(expand=0, fill="x", padx=5, pady=5)
|
2125 |
+
b = Button(buttons, text="Cancel", command=self._cancel, width=8)
|
2126 |
+
b.pack(side="right", padx=5)
|
2127 |
+
b = Button(buttons, text="Ok", command=self._ok, width=8, default="active")
|
2128 |
+
b.pack(side="left", padx=5)
|
2129 |
+
b = Button(buttons, text="Apply", command=self._apply, width=8)
|
2130 |
+
b.pack(side="left")
|
2131 |
+
|
2132 |
+
self._top.bind("<Return>", self._ok)
|
2133 |
+
self._top.bind("<Control-q>", self._cancel)
|
2134 |
+
self._top.bind("<Escape>", self._cancel)
|
2135 |
+
|
2136 |
+
self._entry.focus()
|
2137 |
+
|
2138 |
+
def _reset(self, *e):
|
2139 |
+
self._entry.delete(0, "end")
|
2140 |
+
self._entry.insert(0, self._original_text)
|
2141 |
+
if self._set_callback:
|
2142 |
+
self._set_callback(self._original_text)
|
2143 |
+
|
2144 |
+
def _cancel(self, *e):
|
2145 |
+
try:
|
2146 |
+
self._reset()
|
2147 |
+
except:
|
2148 |
+
pass
|
2149 |
+
self._destroy()
|
2150 |
+
|
2151 |
+
def _ok(self, *e):
|
2152 |
+
self._apply()
|
2153 |
+
self._destroy()
|
2154 |
+
|
2155 |
+
def _apply(self, *e):
|
2156 |
+
if self._set_callback:
|
2157 |
+
self._set_callback(self._entry.get())
|
2158 |
+
|
2159 |
+
def _destroy(self, *e):
|
2160 |
+
if self._top is None:
|
2161 |
+
return
|
2162 |
+
self._top.destroy()
|
2163 |
+
self._top = None
|
2164 |
+
|
2165 |
+
|
2166 |
+
##//////////////////////////////////////////////////////
|
2167 |
+
## Colorized List
|
2168 |
+
##//////////////////////////////////////////////////////
|
2169 |
+
|
2170 |
+
|
2171 |
+
class ColorizedList:
|
2172 |
+
"""
|
2173 |
+
An abstract base class for displaying a colorized list of items.
|
2174 |
+
Subclasses should define:
|
2175 |
+
|
2176 |
+
- ``_init_colortags``, which sets up Text color tags that
|
2177 |
+
will be used by the list.
|
2178 |
+
- ``_item_repr``, which returns a list of (text,colortag)
|
2179 |
+
tuples that make up the colorized representation of the
|
2180 |
+
item.
|
2181 |
+
|
2182 |
+
:note: Typically, you will want to register a callback for
|
2183 |
+
``'select'`` that calls ``mark`` on the given item.
|
2184 |
+
"""
|
2185 |
+
|
2186 |
+
def __init__(self, parent, items=[], **options):
|
2187 |
+
"""
|
2188 |
+
Construct a new list.
|
2189 |
+
|
2190 |
+
:param parent: The Tk widget that contains the colorized list
|
2191 |
+
:param items: The initial contents of the colorized list.
|
2192 |
+
:param options:
|
2193 |
+
"""
|
2194 |
+
self._parent = parent
|
2195 |
+
self._callbacks = {}
|
2196 |
+
|
2197 |
+
# Which items are marked?
|
2198 |
+
self._marks = {}
|
2199 |
+
|
2200 |
+
# Initialize the Tkinter frames.
|
2201 |
+
self._init_itemframe(options.copy())
|
2202 |
+
|
2203 |
+
# Set up key & mouse bindings.
|
2204 |
+
self._textwidget.bind("<KeyPress>", self._keypress)
|
2205 |
+
self._textwidget.bind("<ButtonPress>", self._buttonpress)
|
2206 |
+
|
2207 |
+
# Fill in the given CFG's items.
|
2208 |
+
self._items = None
|
2209 |
+
self.set(items)
|
2210 |
+
|
2211 |
+
# ////////////////////////////////////////////////////////////
|
2212 |
+
# Abstract methods
|
2213 |
+
# ////////////////////////////////////////////////////////////
|
2214 |
+
@abstractmethod
|
2215 |
+
def _init_colortags(self, textwidget, options):
|
2216 |
+
"""
|
2217 |
+
Set up any colortags that will be used by this colorized list.
|
2218 |
+
E.g.:
|
2219 |
+
textwidget.tag_config('terminal', foreground='black')
|
2220 |
+
"""
|
2221 |
+
|
2222 |
+
@abstractmethod
|
2223 |
+
def _item_repr(self, item):
|
2224 |
+
"""
|
2225 |
+
Return a list of (text, colortag) tuples that make up the
|
2226 |
+
colorized representation of the item. Colorized
|
2227 |
+
representations may not span multiple lines. I.e., the text
|
2228 |
+
strings returned may not contain newline characters.
|
2229 |
+
"""
|
2230 |
+
|
2231 |
+
# ////////////////////////////////////////////////////////////
|
2232 |
+
# Item Access
|
2233 |
+
# ////////////////////////////////////////////////////////////
|
2234 |
+
|
2235 |
+
def get(self, index=None):
|
2236 |
+
"""
|
2237 |
+
:return: A list of the items contained by this list.
|
2238 |
+
"""
|
2239 |
+
if index is None:
|
2240 |
+
return self._items[:]
|
2241 |
+
else:
|
2242 |
+
return self._items[index]
|
2243 |
+
|
2244 |
+
def set(self, items):
|
2245 |
+
"""
|
2246 |
+
Modify the list of items contained by this list.
|
2247 |
+
"""
|
2248 |
+
items = list(items)
|
2249 |
+
if self._items == items:
|
2250 |
+
return
|
2251 |
+
self._items = list(items)
|
2252 |
+
|
2253 |
+
self._textwidget["state"] = "normal"
|
2254 |
+
self._textwidget.delete("1.0", "end")
|
2255 |
+
for item in items:
|
2256 |
+
for (text, colortag) in self._item_repr(item):
|
2257 |
+
assert "\n" not in text, "item repr may not contain newline"
|
2258 |
+
self._textwidget.insert("end", text, colortag)
|
2259 |
+
self._textwidget.insert("end", "\n")
|
2260 |
+
# Remove the final newline
|
2261 |
+
self._textwidget.delete("end-1char", "end")
|
2262 |
+
self._textwidget.mark_set("insert", "1.0")
|
2263 |
+
self._textwidget["state"] = "disabled"
|
2264 |
+
# Clear all marks
|
2265 |
+
self._marks.clear()
|
2266 |
+
|
2267 |
+
def unmark(self, item=None):
|
2268 |
+
"""
|
2269 |
+
Remove highlighting from the given item; or from every item,
|
2270 |
+
if no item is given.
|
2271 |
+
:raise ValueError: If ``item`` is not contained in the list.
|
2272 |
+
:raise KeyError: If ``item`` is not marked.
|
2273 |
+
"""
|
2274 |
+
if item is None:
|
2275 |
+
self._marks.clear()
|
2276 |
+
self._textwidget.tag_remove("highlight", "1.0", "end+1char")
|
2277 |
+
else:
|
2278 |
+
index = self._items.index(item)
|
2279 |
+
del self._marks[item]
|
2280 |
+
(start, end) = ("%d.0" % (index + 1), "%d.0" % (index + 2))
|
2281 |
+
self._textwidget.tag_remove("highlight", start, end)
|
2282 |
+
|
2283 |
+
def mark(self, item):
|
2284 |
+
"""
|
2285 |
+
Highlight the given item.
|
2286 |
+
:raise ValueError: If ``item`` is not contained in the list.
|
2287 |
+
"""
|
2288 |
+
self._marks[item] = 1
|
2289 |
+
index = self._items.index(item)
|
2290 |
+
(start, end) = ("%d.0" % (index + 1), "%d.0" % (index + 2))
|
2291 |
+
self._textwidget.tag_add("highlight", start, end)
|
2292 |
+
|
2293 |
+
def markonly(self, item):
|
2294 |
+
"""
|
2295 |
+
Remove any current highlighting, and mark the given item.
|
2296 |
+
:raise ValueError: If ``item`` is not contained in the list.
|
2297 |
+
"""
|
2298 |
+
self.unmark()
|
2299 |
+
self.mark(item)
|
2300 |
+
|
2301 |
+
def view(self, item):
|
2302 |
+
"""
|
2303 |
+
Adjust the view such that the given item is visible. If
|
2304 |
+
the item is already visible, then do nothing.
|
2305 |
+
"""
|
2306 |
+
index = self._items.index(item)
|
2307 |
+
self._textwidget.see("%d.0" % (index + 1))
|
2308 |
+
|
2309 |
+
# ////////////////////////////////////////////////////////////
|
2310 |
+
# Callbacks
|
2311 |
+
# ////////////////////////////////////////////////////////////
|
2312 |
+
|
2313 |
+
def add_callback(self, event, func):
|
2314 |
+
"""
|
2315 |
+
Register a callback function with the list. This function
|
2316 |
+
will be called whenever the given event occurs.
|
2317 |
+
|
2318 |
+
:param event: The event that will trigger the callback
|
2319 |
+
function. Valid events are: click1, click2, click3,
|
2320 |
+
space, return, select, up, down, next, prior, move
|
2321 |
+
:param func: The function that should be called when
|
2322 |
+
the event occurs. ``func`` will be called with a
|
2323 |
+
single item as its argument. (The item selected
|
2324 |
+
or the item moved to).
|
2325 |
+
"""
|
2326 |
+
if event == "select":
|
2327 |
+
events = ["click1", "space", "return"]
|
2328 |
+
elif event == "move":
|
2329 |
+
events = ["up", "down", "next", "prior"]
|
2330 |
+
else:
|
2331 |
+
events = [event]
|
2332 |
+
|
2333 |
+
for e in events:
|
2334 |
+
self._callbacks.setdefault(e, {})[func] = 1
|
2335 |
+
|
2336 |
+
def remove_callback(self, event, func=None):
|
2337 |
+
"""
|
2338 |
+
Deregister a callback function. If ``func`` is none, then
|
2339 |
+
all callbacks are removed for the given event.
|
2340 |
+
"""
|
2341 |
+
if event is None:
|
2342 |
+
events = list(self._callbacks.keys())
|
2343 |
+
elif event == "select":
|
2344 |
+
events = ["click1", "space", "return"]
|
2345 |
+
elif event == "move":
|
2346 |
+
events = ["up", "down", "next", "prior"]
|
2347 |
+
else:
|
2348 |
+
events = [event]
|
2349 |
+
|
2350 |
+
for e in events:
|
2351 |
+
if func is None:
|
2352 |
+
del self._callbacks[e]
|
2353 |
+
else:
|
2354 |
+
try:
|
2355 |
+
del self._callbacks[e][func]
|
2356 |
+
except:
|
2357 |
+
pass
|
2358 |
+
|
2359 |
+
# ////////////////////////////////////////////////////////////
|
2360 |
+
# Tkinter Methods
|
2361 |
+
# ////////////////////////////////////////////////////////////
|
2362 |
+
|
2363 |
+
def pack(self, cnf={}, **kw):
|
2364 |
+
# "@include: Tkinter.Pack.pack"
|
2365 |
+
self._itemframe.pack(cnf, **kw)
|
2366 |
+
|
2367 |
+
def grid(self, cnf={}, **kw):
|
2368 |
+
# "@include: Tkinter.Grid.grid"
|
2369 |
+
self._itemframe.grid(cnf, *kw)
|
2370 |
+
|
2371 |
+
def focus(self):
|
2372 |
+
# "@include: Tkinter.Widget.focus"
|
2373 |
+
self._textwidget.focus()
|
2374 |
+
|
2375 |
+
# ////////////////////////////////////////////////////////////
|
2376 |
+
# Internal Methods
|
2377 |
+
# ////////////////////////////////////////////////////////////
|
2378 |
+
|
2379 |
+
def _init_itemframe(self, options):
|
2380 |
+
self._itemframe = Frame(self._parent)
|
2381 |
+
|
2382 |
+
# Create the basic Text widget & scrollbar.
|
2383 |
+
options.setdefault("background", "#e0e0e0")
|
2384 |
+
self._textwidget = Text(self._itemframe, **options)
|
2385 |
+
self._textscroll = Scrollbar(self._itemframe, takefocus=0, orient="vertical")
|
2386 |
+
self._textwidget.config(yscrollcommand=self._textscroll.set)
|
2387 |
+
self._textscroll.config(command=self._textwidget.yview)
|
2388 |
+
self._textscroll.pack(side="right", fill="y")
|
2389 |
+
self._textwidget.pack(expand=1, fill="both", side="left")
|
2390 |
+
|
2391 |
+
# Initialize the colorization tags
|
2392 |
+
self._textwidget.tag_config(
|
2393 |
+
"highlight", background="#e0ffff", border="1", relief="raised"
|
2394 |
+
)
|
2395 |
+
self._init_colortags(self._textwidget, options)
|
2396 |
+
|
2397 |
+
# How do I want to mark keyboard selection?
|
2398 |
+
self._textwidget.tag_config("sel", foreground="")
|
2399 |
+
self._textwidget.tag_config(
|
2400 |
+
"sel", foreground="", background="", border="", underline=1
|
2401 |
+
)
|
2402 |
+
self._textwidget.tag_lower("highlight", "sel")
|
2403 |
+
|
2404 |
+
def _fire_callback(self, event, itemnum):
|
2405 |
+
if event not in self._callbacks:
|
2406 |
+
return
|
2407 |
+
if 0 <= itemnum < len(self._items):
|
2408 |
+
item = self._items[itemnum]
|
2409 |
+
else:
|
2410 |
+
item = None
|
2411 |
+
for cb_func in list(self._callbacks[event].keys()):
|
2412 |
+
cb_func(item)
|
2413 |
+
|
2414 |
+
def _buttonpress(self, event):
|
2415 |
+
clickloc = "@%d,%d" % (event.x, event.y)
|
2416 |
+
insert_point = self._textwidget.index(clickloc)
|
2417 |
+
itemnum = int(insert_point.split(".")[0]) - 1
|
2418 |
+
self._fire_callback("click%d" % event.num, itemnum)
|
2419 |
+
|
2420 |
+
def _keypress(self, event):
|
2421 |
+
if event.keysym == "Return" or event.keysym == "space":
|
2422 |
+
insert_point = self._textwidget.index("insert")
|
2423 |
+
itemnum = int(insert_point.split(".")[0]) - 1
|
2424 |
+
self._fire_callback(event.keysym.lower(), itemnum)
|
2425 |
+
return
|
2426 |
+
elif event.keysym == "Down":
|
2427 |
+
delta = "+1line"
|
2428 |
+
elif event.keysym == "Up":
|
2429 |
+
delta = "-1line"
|
2430 |
+
elif event.keysym == "Next":
|
2431 |
+
delta = "+10lines"
|
2432 |
+
elif event.keysym == "Prior":
|
2433 |
+
delta = "-10lines"
|
2434 |
+
else:
|
2435 |
+
return "continue"
|
2436 |
+
|
2437 |
+
self._textwidget.mark_set("insert", "insert" + delta)
|
2438 |
+
self._textwidget.see("insert")
|
2439 |
+
self._textwidget.tag_remove("sel", "1.0", "end+1char")
|
2440 |
+
self._textwidget.tag_add("sel", "insert linestart", "insert lineend")
|
2441 |
+
|
2442 |
+
insert_point = self._textwidget.index("insert")
|
2443 |
+
itemnum = int(insert_point.split(".")[0]) - 1
|
2444 |
+
self._fire_callback(event.keysym.lower(), itemnum)
|
2445 |
+
|
2446 |
+
return "break"
|
2447 |
+
|
2448 |
+
|
2449 |
+
##//////////////////////////////////////////////////////
|
2450 |
+
## Improved OptionMenu
|
2451 |
+
##//////////////////////////////////////////////////////
|
2452 |
+
|
2453 |
+
|
2454 |
+
class MutableOptionMenu(Menubutton):
|
2455 |
+
def __init__(self, master, values, **options):
|
2456 |
+
self._callback = options.get("command")
|
2457 |
+
if "command" in options:
|
2458 |
+
del options["command"]
|
2459 |
+
|
2460 |
+
# Create a variable
|
2461 |
+
self._variable = variable = StringVar()
|
2462 |
+
if len(values) > 0:
|
2463 |
+
variable.set(values[0])
|
2464 |
+
|
2465 |
+
kw = {
|
2466 |
+
"borderwidth": 2,
|
2467 |
+
"textvariable": variable,
|
2468 |
+
"indicatoron": 1,
|
2469 |
+
"relief": RAISED,
|
2470 |
+
"anchor": "c",
|
2471 |
+
"highlightthickness": 2,
|
2472 |
+
}
|
2473 |
+
kw.update(options)
|
2474 |
+
Widget.__init__(self, master, "menubutton", kw)
|
2475 |
+
self.widgetName = "tk_optionMenu"
|
2476 |
+
self._menu = Menu(self, name="menu", tearoff=0)
|
2477 |
+
self.menuname = self._menu._w
|
2478 |
+
|
2479 |
+
self._values = []
|
2480 |
+
for value in values:
|
2481 |
+
self.add(value)
|
2482 |
+
|
2483 |
+
self["menu"] = self._menu
|
2484 |
+
|
2485 |
+
def add(self, value):
|
2486 |
+
if value in self._values:
|
2487 |
+
return
|
2488 |
+
|
2489 |
+
def set(value=value):
|
2490 |
+
self.set(value)
|
2491 |
+
|
2492 |
+
self._menu.add_command(label=value, command=set)
|
2493 |
+
self._values.append(value)
|
2494 |
+
|
2495 |
+
def set(self, value):
|
2496 |
+
self._variable.set(value)
|
2497 |
+
if self._callback:
|
2498 |
+
self._callback(value)
|
2499 |
+
|
2500 |
+
def remove(self, value):
|
2501 |
+
# Might raise indexerror: pass to parent.
|
2502 |
+
i = self._values.index(value)
|
2503 |
+
del self._values[i]
|
2504 |
+
self._menu.delete(i, i)
|
2505 |
+
|
2506 |
+
def __getitem__(self, name):
|
2507 |
+
if name == "menu":
|
2508 |
+
return self.__menu
|
2509 |
+
return Widget.__getitem__(self, name)
|
2510 |
+
|
2511 |
+
def destroy(self):
|
2512 |
+
"""Destroy this widget and the associated menu."""
|
2513 |
+
Menubutton.destroy(self)
|
2514 |
+
self._menu = None
|
2515 |
+
|
2516 |
+
|
2517 |
+
##//////////////////////////////////////////////////////
|
2518 |
+
## Test code.
|
2519 |
+
##//////////////////////////////////////////////////////
|
2520 |
+
|
2521 |
+
|
2522 |
+
def demo():
|
2523 |
+
"""
|
2524 |
+
A simple demonstration showing how to use canvas widgets.
|
2525 |
+
"""
|
2526 |
+
|
2527 |
+
def fill(cw):
|
2528 |
+
from random import randint
|
2529 |
+
|
2530 |
+
cw["fill"] = "#00%04d" % randint(0, 9999)
|
2531 |
+
|
2532 |
+
def color(cw):
|
2533 |
+
from random import randint
|
2534 |
+
|
2535 |
+
cw["color"] = "#ff%04d" % randint(0, 9999)
|
2536 |
+
|
2537 |
+
cf = CanvasFrame(closeenough=10, width=300, height=300)
|
2538 |
+
c = cf.canvas()
|
2539 |
+
ct3 = TextWidget(c, "hiya there", draggable=1)
|
2540 |
+
ct2 = TextWidget(c, "o o\n||\n___\n U", draggable=1, justify="center")
|
2541 |
+
co = OvalWidget(c, ct2, outline="red")
|
2542 |
+
ct = TextWidget(c, "o o\n||\n\\___/", draggable=1, justify="center")
|
2543 |
+
cp = ParenWidget(c, ct, color="red")
|
2544 |
+
cb = BoxWidget(c, cp, fill="cyan", draggable=1, width=3, margin=10)
|
2545 |
+
equation = SequenceWidget(
|
2546 |
+
c,
|
2547 |
+
SymbolWidget(c, "forall"),
|
2548 |
+
TextWidget(c, "x"),
|
2549 |
+
SymbolWidget(c, "exists"),
|
2550 |
+
TextWidget(c, "y: "),
|
2551 |
+
TextWidget(c, "x"),
|
2552 |
+
SymbolWidget(c, "notequal"),
|
2553 |
+
TextWidget(c, "y"),
|
2554 |
+
)
|
2555 |
+
space = SpaceWidget(c, 0, 30)
|
2556 |
+
cstack = StackWidget(c, cb, ct3, space, co, equation, align="center")
|
2557 |
+
prompt_msg = TextWidget(
|
2558 |
+
c, "try clicking\nand dragging", draggable=1, justify="center"
|
2559 |
+
)
|
2560 |
+
cs = SequenceWidget(c, cstack, prompt_msg)
|
2561 |
+
zz = BracketWidget(c, cs, color="green4", width=3)
|
2562 |
+
cf.add_widget(zz, 60, 30)
|
2563 |
+
|
2564 |
+
cb.bind_click(fill)
|
2565 |
+
ct.bind_click(color)
|
2566 |
+
co.bind_click(fill)
|
2567 |
+
ct2.bind_click(color)
|
2568 |
+
ct3.bind_click(color)
|
2569 |
+
|
2570 |
+
cf.mainloop()
|
2571 |
+
# ShowText(None, 'title', ((('this is text'*150)+'\n')*5))
|
2572 |
+
|
2573 |
+
|
2574 |
+
if __name__ == "__main__":
|
2575 |
+
demo()
|
env-llmeval/lib/python3.10/site-packages/nltk/lm/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (7.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/nltk/lm/__pycache__/api.cpython-310.pyc
ADDED
Binary file (8.26 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/nltk/lm/__pycache__/counter.cpython-310.pyc
ADDED
Binary file (5.48 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/nltk/lm/__pycache__/models.cpython-310.pyc
ADDED
Binary file (5.37 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/nltk/lm/__pycache__/preprocessing.cpython-310.pyc
ADDED
Binary file (1.83 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/nltk/lm/__pycache__/smoothing.cpython-310.pyc
ADDED
Binary file (5.34 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/nltk/lm/__pycache__/util.cpython-310.pyc
ADDED
Binary file (507 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/nltk/lm/__pycache__/vocabulary.cpython-310.pyc
ADDED
Binary file (7.9 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/nltk/lm/smoothing.py
ADDED
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Language Model Unit Tests
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Ilia Kurenkov <[email protected]>
|
5 |
+
# Manu Joseph <[email protected]>
|
6 |
+
# URL: <https://www.nltk.org/>
|
7 |
+
# For license information, see LICENSE.TXT
|
8 |
+
"""Smoothing algorithms for language modeling.
|
9 |
+
|
10 |
+
According to Chen & Goodman 1995 these should work with both Backoff and
|
11 |
+
Interpolation.
|
12 |
+
"""
|
13 |
+
from operator import methodcaller
|
14 |
+
|
15 |
+
from nltk.lm.api import Smoothing
|
16 |
+
from nltk.probability import ConditionalFreqDist
|
17 |
+
|
18 |
+
|
19 |
+
def _count_values_gt_zero(distribution):
|
20 |
+
"""Count values that are greater than zero in a distribution.
|
21 |
+
|
22 |
+
Assumes distribution is either a mapping with counts as values or
|
23 |
+
an instance of `nltk.ConditionalFreqDist`.
|
24 |
+
"""
|
25 |
+
as_count = (
|
26 |
+
methodcaller("N")
|
27 |
+
if isinstance(distribution, ConditionalFreqDist)
|
28 |
+
else lambda count: count
|
29 |
+
)
|
30 |
+
# We explicitly check that values are > 0 to guard against negative counts.
|
31 |
+
return sum(
|
32 |
+
1 for dist_or_count in distribution.values() if as_count(dist_or_count) > 0
|
33 |
+
)
|
34 |
+
|
35 |
+
|
36 |
+
class WittenBell(Smoothing):
|
37 |
+
"""Witten-Bell smoothing."""
|
38 |
+
|
39 |
+
def __init__(self, vocabulary, counter, **kwargs):
|
40 |
+
super().__init__(vocabulary, counter, **kwargs)
|
41 |
+
|
42 |
+
def alpha_gamma(self, word, context):
|
43 |
+
alpha = self.counts[context].freq(word)
|
44 |
+
gamma = self._gamma(context)
|
45 |
+
return (1.0 - gamma) * alpha, gamma
|
46 |
+
|
47 |
+
def _gamma(self, context):
|
48 |
+
n_plus = _count_values_gt_zero(self.counts[context])
|
49 |
+
return n_plus / (n_plus + self.counts[context].N())
|
50 |
+
|
51 |
+
def unigram_score(self, word):
|
52 |
+
return self.counts.unigrams.freq(word)
|
53 |
+
|
54 |
+
|
55 |
+
class AbsoluteDiscounting(Smoothing):
|
56 |
+
"""Smoothing with absolute discount."""
|
57 |
+
|
58 |
+
def __init__(self, vocabulary, counter, discount=0.75, **kwargs):
|
59 |
+
super().__init__(vocabulary, counter, **kwargs)
|
60 |
+
self.discount = discount
|
61 |
+
|
62 |
+
def alpha_gamma(self, word, context):
|
63 |
+
alpha = (
|
64 |
+
max(self.counts[context][word] - self.discount, 0)
|
65 |
+
/ self.counts[context].N()
|
66 |
+
)
|
67 |
+
gamma = self._gamma(context)
|
68 |
+
return alpha, gamma
|
69 |
+
|
70 |
+
def _gamma(self, context):
|
71 |
+
n_plus = _count_values_gt_zero(self.counts[context])
|
72 |
+
return (self.discount * n_plus) / self.counts[context].N()
|
73 |
+
|
74 |
+
def unigram_score(self, word):
|
75 |
+
return self.counts.unigrams.freq(word)
|
76 |
+
|
77 |
+
|
78 |
+
class KneserNey(Smoothing):
|
79 |
+
"""Kneser-Ney Smoothing.
|
80 |
+
|
81 |
+
This is an extension of smoothing with a discount.
|
82 |
+
|
83 |
+
Resources:
|
84 |
+
- https://pages.ucsd.edu/~rlevy/lign256/winter2008/kneser_ney_mini_example.pdf
|
85 |
+
- https://www.youtube.com/watch?v=ody1ysUTD7o
|
86 |
+
- https://medium.com/@dennyc/a-simple-numerical-example-for-kneser-ney-smoothing-nlp-4600addf38b8
|
87 |
+
- https://www.cl.uni-heidelberg.de/courses/ss15/smt/scribe6.pdf
|
88 |
+
- https://www-i6.informatik.rwth-aachen.de/publications/download/951/Kneser-ICASSP-1995.pdf
|
89 |
+
"""
|
90 |
+
|
91 |
+
def __init__(self, vocabulary, counter, order, discount=0.1, **kwargs):
|
92 |
+
super().__init__(vocabulary, counter, **kwargs)
|
93 |
+
self.discount = discount
|
94 |
+
self._order = order
|
95 |
+
|
96 |
+
def unigram_score(self, word):
|
97 |
+
word_continuation_count, total_count = self._continuation_counts(word)
|
98 |
+
return word_continuation_count / total_count
|
99 |
+
|
100 |
+
def alpha_gamma(self, word, context):
|
101 |
+
prefix_counts = self.counts[context]
|
102 |
+
word_continuation_count, total_count = (
|
103 |
+
(prefix_counts[word], prefix_counts.N())
|
104 |
+
if len(context) + 1 == self._order
|
105 |
+
else self._continuation_counts(word, context)
|
106 |
+
)
|
107 |
+
alpha = max(word_continuation_count - self.discount, 0.0) / total_count
|
108 |
+
gamma = self.discount * _count_values_gt_zero(prefix_counts) / total_count
|
109 |
+
return alpha, gamma
|
110 |
+
|
111 |
+
def _continuation_counts(self, word, context=tuple()):
|
112 |
+
"""Count continuations that end with context and word.
|
113 |
+
|
114 |
+
Continuations track unique ngram "types", regardless of how many
|
115 |
+
instances were observed for each "type".
|
116 |
+
This is different than raw ngram counts which track number of instances.
|
117 |
+
"""
|
118 |
+
higher_order_ngrams_with_context = (
|
119 |
+
counts
|
120 |
+
for prefix_ngram, counts in self.counts[len(context) + 2].items()
|
121 |
+
if prefix_ngram[1:] == context
|
122 |
+
)
|
123 |
+
higher_order_ngrams_with_word_count, total = 0, 0
|
124 |
+
for counts in higher_order_ngrams_with_context:
|
125 |
+
higher_order_ngrams_with_word_count += int(counts[word] > 0)
|
126 |
+
total += _count_values_gt_zero(counts)
|
127 |
+
return higher_order_ngrams_with_word_count, total
|
env-llmeval/lib/python3.10/site-packages/nltk/sem/__pycache__/boxer.cpython-310.pyc
ADDED
Binary file (45.3 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/nltk/sem/__pycache__/cooper_storage.cpython-310.pyc
ADDED
Binary file (3.85 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/nltk/sem/__pycache__/evaluate.cpython-310.pyc
ADDED
Binary file (21.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/nltk/sem/__pycache__/glue.cpython-310.pyc
ADDED
Binary file (19.7 kB). View file
|
|