Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- llmeval-env/lib/python3.10/site-packages/click/__init__.py +73 -0
- llmeval-env/lib/python3.10/site-packages/click/_textwrap.py +49 -0
- llmeval-env/lib/python3.10/site-packages/click/core.py +0 -0
- llmeval-env/lib/python3.10/site-packages/click/parser.py +529 -0
- llmeval-env/lib/python3.10/site-packages/click/py.typed +0 -0
- llmeval-env/lib/python3.10/site-packages/click/types.py +1089 -0
- llmeval-env/lib/python3.10/site-packages/nltk/draw/__init__.py +27 -0
- llmeval-env/lib/python3.10/site-packages/nltk/draw/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/draw/__pycache__/cfg.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/draw/__pycache__/dispersion.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/draw/__pycache__/table.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/draw/__pycache__/tree.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/draw/__pycache__/util.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/draw/cfg.py +859 -0
- llmeval-env/lib/python3.10/site-packages/nltk/draw/dispersion.py +63 -0
- llmeval-env/lib/python3.10/site-packages/nltk/draw/table.py +1177 -0
- llmeval-env/lib/python3.10/site-packages/nltk/draw/tree.py +1129 -0
- llmeval-env/lib/python3.10/site-packages/nltk/draw/util.py +2575 -0
- llmeval-env/lib/python3.10/site-packages/nltk/lm/__init__.py +235 -0
- llmeval-env/lib/python3.10/site-packages/nltk/lm/__pycache__/api.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/lm/__pycache__/counter.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/lm/__pycache__/models.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/lm/__pycache__/preprocessing.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/lm/__pycache__/smoothing.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/lm/api.py +235 -0
- llmeval-env/lib/python3.10/site-packages/nltk/lm/counter.py +163 -0
- llmeval-env/lib/python3.10/site-packages/nltk/lm/models.py +141 -0
- llmeval-env/lib/python3.10/site-packages/nltk/lm/preprocessing.py +51 -0
- llmeval-env/lib/python3.10/site-packages/nltk/lm/smoothing.py +127 -0
- llmeval-env/lib/python3.10/site-packages/nltk/lm/util.py +19 -0
- llmeval-env/lib/python3.10/site-packages/nltk/lm/vocabulary.py +218 -0
- llmeval-env/lib/python3.10/site-packages/nltk/sentiment/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/sentiment/__pycache__/sentiment_analyzer.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/sentiment/__pycache__/util.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/sentiment/__pycache__/vader.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/sentiment/sentiment_analyzer.py +255 -0
- llmeval-env/lib/python3.10/site-packages/nltk/sentiment/util.py +887 -0
- llmeval-env/lib/python3.10/site-packages/nltk/sentiment/vader.py +633 -0
- llmeval-env/lib/python3.10/site-packages/nltk/tbl/__init__.py +31 -0
- llmeval-env/lib/python3.10/site-packages/nltk/tbl/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/tbl/__pycache__/api.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/tbl/__pycache__/demo.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/tbl/__pycache__/erroranalysis.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/tbl/__pycache__/feature.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/tbl/__pycache__/rule.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/tbl/__pycache__/template.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/tbl/api.py +0 -0
- llmeval-env/lib/python3.10/site-packages/nltk/tbl/demo.py +418 -0
- llmeval-env/lib/python3.10/site-packages/nltk/tbl/erroranalysis.py +38 -0
- llmeval-env/lib/python3.10/site-packages/nltk/tbl/feature.py +267 -0
llmeval-env/lib/python3.10/site-packages/click/__init__.py
ADDED
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Click is a simple Python module inspired by the stdlib optparse to make
|
3 |
+
writing command line scripts fun. Unlike other modules, it's based
|
4 |
+
around a simple API that does not come with too much magic and is
|
5 |
+
composable.
|
6 |
+
"""
|
7 |
+
from .core import Argument as Argument
|
8 |
+
from .core import BaseCommand as BaseCommand
|
9 |
+
from .core import Command as Command
|
10 |
+
from .core import CommandCollection as CommandCollection
|
11 |
+
from .core import Context as Context
|
12 |
+
from .core import Group as Group
|
13 |
+
from .core import MultiCommand as MultiCommand
|
14 |
+
from .core import Option as Option
|
15 |
+
from .core import Parameter as Parameter
|
16 |
+
from .decorators import argument as argument
|
17 |
+
from .decorators import command as command
|
18 |
+
from .decorators import confirmation_option as confirmation_option
|
19 |
+
from .decorators import group as group
|
20 |
+
from .decorators import help_option as help_option
|
21 |
+
from .decorators import make_pass_decorator as make_pass_decorator
|
22 |
+
from .decorators import option as option
|
23 |
+
from .decorators import pass_context as pass_context
|
24 |
+
from .decorators import pass_obj as pass_obj
|
25 |
+
from .decorators import password_option as password_option
|
26 |
+
from .decorators import version_option as version_option
|
27 |
+
from .exceptions import Abort as Abort
|
28 |
+
from .exceptions import BadArgumentUsage as BadArgumentUsage
|
29 |
+
from .exceptions import BadOptionUsage as BadOptionUsage
|
30 |
+
from .exceptions import BadParameter as BadParameter
|
31 |
+
from .exceptions import ClickException as ClickException
|
32 |
+
from .exceptions import FileError as FileError
|
33 |
+
from .exceptions import MissingParameter as MissingParameter
|
34 |
+
from .exceptions import NoSuchOption as NoSuchOption
|
35 |
+
from .exceptions import UsageError as UsageError
|
36 |
+
from .formatting import HelpFormatter as HelpFormatter
|
37 |
+
from .formatting import wrap_text as wrap_text
|
38 |
+
from .globals import get_current_context as get_current_context
|
39 |
+
from .parser import OptionParser as OptionParser
|
40 |
+
from .termui import clear as clear
|
41 |
+
from .termui import confirm as confirm
|
42 |
+
from .termui import echo_via_pager as echo_via_pager
|
43 |
+
from .termui import edit as edit
|
44 |
+
from .termui import getchar as getchar
|
45 |
+
from .termui import launch as launch
|
46 |
+
from .termui import pause as pause
|
47 |
+
from .termui import progressbar as progressbar
|
48 |
+
from .termui import prompt as prompt
|
49 |
+
from .termui import secho as secho
|
50 |
+
from .termui import style as style
|
51 |
+
from .termui import unstyle as unstyle
|
52 |
+
from .types import BOOL as BOOL
|
53 |
+
from .types import Choice as Choice
|
54 |
+
from .types import DateTime as DateTime
|
55 |
+
from .types import File as File
|
56 |
+
from .types import FLOAT as FLOAT
|
57 |
+
from .types import FloatRange as FloatRange
|
58 |
+
from .types import INT as INT
|
59 |
+
from .types import IntRange as IntRange
|
60 |
+
from .types import ParamType as ParamType
|
61 |
+
from .types import Path as Path
|
62 |
+
from .types import STRING as STRING
|
63 |
+
from .types import Tuple as Tuple
|
64 |
+
from .types import UNPROCESSED as UNPROCESSED
|
65 |
+
from .types import UUID as UUID
|
66 |
+
from .utils import echo as echo
|
67 |
+
from .utils import format_filename as format_filename
|
68 |
+
from .utils import get_app_dir as get_app_dir
|
69 |
+
from .utils import get_binary_stream as get_binary_stream
|
70 |
+
from .utils import get_text_stream as get_text_stream
|
71 |
+
from .utils import open_file as open_file
|
72 |
+
|
73 |
+
__version__ = "8.1.7"
|
llmeval-env/lib/python3.10/site-packages/click/_textwrap.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import textwrap
|
2 |
+
import typing as t
|
3 |
+
from contextlib import contextmanager
|
4 |
+
|
5 |
+
|
6 |
+
class TextWrapper(textwrap.TextWrapper):
|
7 |
+
def _handle_long_word(
|
8 |
+
self,
|
9 |
+
reversed_chunks: t.List[str],
|
10 |
+
cur_line: t.List[str],
|
11 |
+
cur_len: int,
|
12 |
+
width: int,
|
13 |
+
) -> None:
|
14 |
+
space_left = max(width - cur_len, 1)
|
15 |
+
|
16 |
+
if self.break_long_words:
|
17 |
+
last = reversed_chunks[-1]
|
18 |
+
cut = last[:space_left]
|
19 |
+
res = last[space_left:]
|
20 |
+
cur_line.append(cut)
|
21 |
+
reversed_chunks[-1] = res
|
22 |
+
elif not cur_line:
|
23 |
+
cur_line.append(reversed_chunks.pop())
|
24 |
+
|
25 |
+
@contextmanager
|
26 |
+
def extra_indent(self, indent: str) -> t.Iterator[None]:
|
27 |
+
old_initial_indent = self.initial_indent
|
28 |
+
old_subsequent_indent = self.subsequent_indent
|
29 |
+
self.initial_indent += indent
|
30 |
+
self.subsequent_indent += indent
|
31 |
+
|
32 |
+
try:
|
33 |
+
yield
|
34 |
+
finally:
|
35 |
+
self.initial_indent = old_initial_indent
|
36 |
+
self.subsequent_indent = old_subsequent_indent
|
37 |
+
|
38 |
+
def indent_only(self, text: str) -> str:
|
39 |
+
rv = []
|
40 |
+
|
41 |
+
for idx, line in enumerate(text.splitlines()):
|
42 |
+
indent = self.initial_indent
|
43 |
+
|
44 |
+
if idx > 0:
|
45 |
+
indent = self.subsequent_indent
|
46 |
+
|
47 |
+
rv.append(f"{indent}{line}")
|
48 |
+
|
49 |
+
return "\n".join(rv)
|
llmeval-env/lib/python3.10/site-packages/click/core.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
llmeval-env/lib/python3.10/site-packages/click/parser.py
ADDED
@@ -0,0 +1,529 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This module started out as largely a copy paste from the stdlib's
|
3 |
+
optparse module with the features removed that we do not need from
|
4 |
+
optparse because we implement them in Click on a higher level (for
|
5 |
+
instance type handling, help formatting and a lot more).
|
6 |
+
|
7 |
+
The plan is to remove more and more from here over time.
|
8 |
+
|
9 |
+
The reason this is a different module and not optparse from the stdlib
|
10 |
+
is that there are differences in 2.x and 3.x about the error messages
|
11 |
+
generated and optparse in the stdlib uses gettext for no good reason
|
12 |
+
and might cause us issues.
|
13 |
+
|
14 |
+
Click uses parts of optparse written by Gregory P. Ward and maintained
|
15 |
+
by the Python Software Foundation. This is limited to code in parser.py.
|
16 |
+
|
17 |
+
Copyright 2001-2006 Gregory P. Ward. All rights reserved.
|
18 |
+
Copyright 2002-2006 Python Software Foundation. All rights reserved.
|
19 |
+
"""
|
20 |
+
# This code uses parts of optparse written by Gregory P. Ward and
|
21 |
+
# maintained by the Python Software Foundation.
|
22 |
+
# Copyright 2001-2006 Gregory P. Ward
|
23 |
+
# Copyright 2002-2006 Python Software Foundation
|
24 |
+
import typing as t
|
25 |
+
from collections import deque
|
26 |
+
from gettext import gettext as _
|
27 |
+
from gettext import ngettext
|
28 |
+
|
29 |
+
from .exceptions import BadArgumentUsage
|
30 |
+
from .exceptions import BadOptionUsage
|
31 |
+
from .exceptions import NoSuchOption
|
32 |
+
from .exceptions import UsageError
|
33 |
+
|
34 |
+
if t.TYPE_CHECKING:
|
35 |
+
import typing_extensions as te
|
36 |
+
from .core import Argument as CoreArgument
|
37 |
+
from .core import Context
|
38 |
+
from .core import Option as CoreOption
|
39 |
+
from .core import Parameter as CoreParameter
|
40 |
+
|
41 |
+
V = t.TypeVar("V")
|
42 |
+
|
43 |
+
# Sentinel value that indicates an option was passed as a flag without a
|
44 |
+
# value but is not a flag option. Option.consume_value uses this to
|
45 |
+
# prompt or use the flag_value.
|
46 |
+
_flag_needs_value = object()
|
47 |
+
|
48 |
+
|
49 |
+
def _unpack_args(
|
50 |
+
args: t.Sequence[str], nargs_spec: t.Sequence[int]
|
51 |
+
) -> t.Tuple[t.Sequence[t.Union[str, t.Sequence[t.Optional[str]], None]], t.List[str]]:
|
52 |
+
"""Given an iterable of arguments and an iterable of nargs specifications,
|
53 |
+
it returns a tuple with all the unpacked arguments at the first index
|
54 |
+
and all remaining arguments as the second.
|
55 |
+
|
56 |
+
The nargs specification is the number of arguments that should be consumed
|
57 |
+
or `-1` to indicate that this position should eat up all the remainders.
|
58 |
+
|
59 |
+
Missing items are filled with `None`.
|
60 |
+
"""
|
61 |
+
args = deque(args)
|
62 |
+
nargs_spec = deque(nargs_spec)
|
63 |
+
rv: t.List[t.Union[str, t.Tuple[t.Optional[str], ...], None]] = []
|
64 |
+
spos: t.Optional[int] = None
|
65 |
+
|
66 |
+
def _fetch(c: "te.Deque[V]") -> t.Optional[V]:
|
67 |
+
try:
|
68 |
+
if spos is None:
|
69 |
+
return c.popleft()
|
70 |
+
else:
|
71 |
+
return c.pop()
|
72 |
+
except IndexError:
|
73 |
+
return None
|
74 |
+
|
75 |
+
while nargs_spec:
|
76 |
+
nargs = _fetch(nargs_spec)
|
77 |
+
|
78 |
+
if nargs is None:
|
79 |
+
continue
|
80 |
+
|
81 |
+
if nargs == 1:
|
82 |
+
rv.append(_fetch(args))
|
83 |
+
elif nargs > 1:
|
84 |
+
x = [_fetch(args) for _ in range(nargs)]
|
85 |
+
|
86 |
+
# If we're reversed, we're pulling in the arguments in reverse,
|
87 |
+
# so we need to turn them around.
|
88 |
+
if spos is not None:
|
89 |
+
x.reverse()
|
90 |
+
|
91 |
+
rv.append(tuple(x))
|
92 |
+
elif nargs < 0:
|
93 |
+
if spos is not None:
|
94 |
+
raise TypeError("Cannot have two nargs < 0")
|
95 |
+
|
96 |
+
spos = len(rv)
|
97 |
+
rv.append(None)
|
98 |
+
|
99 |
+
# spos is the position of the wildcard (star). If it's not `None`,
|
100 |
+
# we fill it with the remainder.
|
101 |
+
if spos is not None:
|
102 |
+
rv[spos] = tuple(args)
|
103 |
+
args = []
|
104 |
+
rv[spos + 1 :] = reversed(rv[spos + 1 :])
|
105 |
+
|
106 |
+
return tuple(rv), list(args)
|
107 |
+
|
108 |
+
|
109 |
+
def split_opt(opt: str) -> t.Tuple[str, str]:
|
110 |
+
first = opt[:1]
|
111 |
+
if first.isalnum():
|
112 |
+
return "", opt
|
113 |
+
if opt[1:2] == first:
|
114 |
+
return opt[:2], opt[2:]
|
115 |
+
return first, opt[1:]
|
116 |
+
|
117 |
+
|
118 |
+
def normalize_opt(opt: str, ctx: t.Optional["Context"]) -> str:
|
119 |
+
if ctx is None or ctx.token_normalize_func is None:
|
120 |
+
return opt
|
121 |
+
prefix, opt = split_opt(opt)
|
122 |
+
return f"{prefix}{ctx.token_normalize_func(opt)}"
|
123 |
+
|
124 |
+
|
125 |
+
def split_arg_string(string: str) -> t.List[str]:
|
126 |
+
"""Split an argument string as with :func:`shlex.split`, but don't
|
127 |
+
fail if the string is incomplete. Ignores a missing closing quote or
|
128 |
+
incomplete escape sequence and uses the partial token as-is.
|
129 |
+
|
130 |
+
.. code-block:: python
|
131 |
+
|
132 |
+
split_arg_string("example 'my file")
|
133 |
+
["example", "my file"]
|
134 |
+
|
135 |
+
split_arg_string("example my\\")
|
136 |
+
["example", "my"]
|
137 |
+
|
138 |
+
:param string: String to split.
|
139 |
+
"""
|
140 |
+
import shlex
|
141 |
+
|
142 |
+
lex = shlex.shlex(string, posix=True)
|
143 |
+
lex.whitespace_split = True
|
144 |
+
lex.commenters = ""
|
145 |
+
out = []
|
146 |
+
|
147 |
+
try:
|
148 |
+
for token in lex:
|
149 |
+
out.append(token)
|
150 |
+
except ValueError:
|
151 |
+
# Raised when end-of-string is reached in an invalid state. Use
|
152 |
+
# the partial token as-is. The quote or escape character is in
|
153 |
+
# lex.state, not lex.token.
|
154 |
+
out.append(lex.token)
|
155 |
+
|
156 |
+
return out
|
157 |
+
|
158 |
+
|
159 |
+
class Option:
|
160 |
+
def __init__(
|
161 |
+
self,
|
162 |
+
obj: "CoreOption",
|
163 |
+
opts: t.Sequence[str],
|
164 |
+
dest: t.Optional[str],
|
165 |
+
action: t.Optional[str] = None,
|
166 |
+
nargs: int = 1,
|
167 |
+
const: t.Optional[t.Any] = None,
|
168 |
+
):
|
169 |
+
self._short_opts = []
|
170 |
+
self._long_opts = []
|
171 |
+
self.prefixes: t.Set[str] = set()
|
172 |
+
|
173 |
+
for opt in opts:
|
174 |
+
prefix, value = split_opt(opt)
|
175 |
+
if not prefix:
|
176 |
+
raise ValueError(f"Invalid start character for option ({opt})")
|
177 |
+
self.prefixes.add(prefix[0])
|
178 |
+
if len(prefix) == 1 and len(value) == 1:
|
179 |
+
self._short_opts.append(opt)
|
180 |
+
else:
|
181 |
+
self._long_opts.append(opt)
|
182 |
+
self.prefixes.add(prefix)
|
183 |
+
|
184 |
+
if action is None:
|
185 |
+
action = "store"
|
186 |
+
|
187 |
+
self.dest = dest
|
188 |
+
self.action = action
|
189 |
+
self.nargs = nargs
|
190 |
+
self.const = const
|
191 |
+
self.obj = obj
|
192 |
+
|
193 |
+
@property
|
194 |
+
def takes_value(self) -> bool:
|
195 |
+
return self.action in ("store", "append")
|
196 |
+
|
197 |
+
def process(self, value: t.Any, state: "ParsingState") -> None:
|
198 |
+
if self.action == "store":
|
199 |
+
state.opts[self.dest] = value # type: ignore
|
200 |
+
elif self.action == "store_const":
|
201 |
+
state.opts[self.dest] = self.const # type: ignore
|
202 |
+
elif self.action == "append":
|
203 |
+
state.opts.setdefault(self.dest, []).append(value) # type: ignore
|
204 |
+
elif self.action == "append_const":
|
205 |
+
state.opts.setdefault(self.dest, []).append(self.const) # type: ignore
|
206 |
+
elif self.action == "count":
|
207 |
+
state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 # type: ignore
|
208 |
+
else:
|
209 |
+
raise ValueError(f"unknown action '{self.action}'")
|
210 |
+
state.order.append(self.obj)
|
211 |
+
|
212 |
+
|
213 |
+
class Argument:
|
214 |
+
def __init__(self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1):
|
215 |
+
self.dest = dest
|
216 |
+
self.nargs = nargs
|
217 |
+
self.obj = obj
|
218 |
+
|
219 |
+
def process(
|
220 |
+
self,
|
221 |
+
value: t.Union[t.Optional[str], t.Sequence[t.Optional[str]]],
|
222 |
+
state: "ParsingState",
|
223 |
+
) -> None:
|
224 |
+
if self.nargs > 1:
|
225 |
+
assert value is not None
|
226 |
+
holes = sum(1 for x in value if x is None)
|
227 |
+
if holes == len(value):
|
228 |
+
value = None
|
229 |
+
elif holes != 0:
|
230 |
+
raise BadArgumentUsage(
|
231 |
+
_("Argument {name!r} takes {nargs} values.").format(
|
232 |
+
name=self.dest, nargs=self.nargs
|
233 |
+
)
|
234 |
+
)
|
235 |
+
|
236 |
+
if self.nargs == -1 and self.obj.envvar is not None and value == ():
|
237 |
+
# Replace empty tuple with None so that a value from the
|
238 |
+
# environment may be tried.
|
239 |
+
value = None
|
240 |
+
|
241 |
+
state.opts[self.dest] = value # type: ignore
|
242 |
+
state.order.append(self.obj)
|
243 |
+
|
244 |
+
|
245 |
+
class ParsingState:
|
246 |
+
def __init__(self, rargs: t.List[str]) -> None:
|
247 |
+
self.opts: t.Dict[str, t.Any] = {}
|
248 |
+
self.largs: t.List[str] = []
|
249 |
+
self.rargs = rargs
|
250 |
+
self.order: t.List["CoreParameter"] = []
|
251 |
+
|
252 |
+
|
253 |
+
class OptionParser:
|
254 |
+
"""The option parser is an internal class that is ultimately used to
|
255 |
+
parse options and arguments. It's modelled after optparse and brings
|
256 |
+
a similar but vastly simplified API. It should generally not be used
|
257 |
+
directly as the high level Click classes wrap it for you.
|
258 |
+
|
259 |
+
It's not nearly as extensible as optparse or argparse as it does not
|
260 |
+
implement features that are implemented on a higher level (such as
|
261 |
+
types or defaults).
|
262 |
+
|
263 |
+
:param ctx: optionally the :class:`~click.Context` where this parser
|
264 |
+
should go with.
|
265 |
+
"""
|
266 |
+
|
267 |
+
def __init__(self, ctx: t.Optional["Context"] = None) -> None:
|
268 |
+
#: The :class:`~click.Context` for this parser. This might be
|
269 |
+
#: `None` for some advanced use cases.
|
270 |
+
self.ctx = ctx
|
271 |
+
#: This controls how the parser deals with interspersed arguments.
|
272 |
+
#: If this is set to `False`, the parser will stop on the first
|
273 |
+
#: non-option. Click uses this to implement nested subcommands
|
274 |
+
#: safely.
|
275 |
+
self.allow_interspersed_args: bool = True
|
276 |
+
#: This tells the parser how to deal with unknown options. By
|
277 |
+
#: default it will error out (which is sensible), but there is a
|
278 |
+
#: second mode where it will ignore it and continue processing
|
279 |
+
#: after shifting all the unknown options into the resulting args.
|
280 |
+
self.ignore_unknown_options: bool = False
|
281 |
+
|
282 |
+
if ctx is not None:
|
283 |
+
self.allow_interspersed_args = ctx.allow_interspersed_args
|
284 |
+
self.ignore_unknown_options = ctx.ignore_unknown_options
|
285 |
+
|
286 |
+
self._short_opt: t.Dict[str, Option] = {}
|
287 |
+
self._long_opt: t.Dict[str, Option] = {}
|
288 |
+
self._opt_prefixes = {"-", "--"}
|
289 |
+
self._args: t.List[Argument] = []
|
290 |
+
|
291 |
+
def add_option(
|
292 |
+
self,
|
293 |
+
obj: "CoreOption",
|
294 |
+
opts: t.Sequence[str],
|
295 |
+
dest: t.Optional[str],
|
296 |
+
action: t.Optional[str] = None,
|
297 |
+
nargs: int = 1,
|
298 |
+
const: t.Optional[t.Any] = None,
|
299 |
+
) -> None:
|
300 |
+
"""Adds a new option named `dest` to the parser. The destination
|
301 |
+
is not inferred (unlike with optparse) and needs to be explicitly
|
302 |
+
provided. Action can be any of ``store``, ``store_const``,
|
303 |
+
``append``, ``append_const`` or ``count``.
|
304 |
+
|
305 |
+
The `obj` can be used to identify the option in the order list
|
306 |
+
that is returned from the parser.
|
307 |
+
"""
|
308 |
+
opts = [normalize_opt(opt, self.ctx) for opt in opts]
|
309 |
+
option = Option(obj, opts, dest, action=action, nargs=nargs, const=const)
|
310 |
+
self._opt_prefixes.update(option.prefixes)
|
311 |
+
for opt in option._short_opts:
|
312 |
+
self._short_opt[opt] = option
|
313 |
+
for opt in option._long_opts:
|
314 |
+
self._long_opt[opt] = option
|
315 |
+
|
316 |
+
def add_argument(
|
317 |
+
self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1
|
318 |
+
) -> None:
|
319 |
+
"""Adds a positional argument named `dest` to the parser.
|
320 |
+
|
321 |
+
The `obj` can be used to identify the option in the order list
|
322 |
+
that is returned from the parser.
|
323 |
+
"""
|
324 |
+
self._args.append(Argument(obj, dest=dest, nargs=nargs))
|
325 |
+
|
326 |
+
def parse_args(
|
327 |
+
self, args: t.List[str]
|
328 |
+
) -> t.Tuple[t.Dict[str, t.Any], t.List[str], t.List["CoreParameter"]]:
|
329 |
+
"""Parses positional arguments and returns ``(values, args, order)``
|
330 |
+
for the parsed options and arguments as well as the leftover
|
331 |
+
arguments if there are any. The order is a list of objects as they
|
332 |
+
appear on the command line. If arguments appear multiple times they
|
333 |
+
will be memorized multiple times as well.
|
334 |
+
"""
|
335 |
+
state = ParsingState(args)
|
336 |
+
try:
|
337 |
+
self._process_args_for_options(state)
|
338 |
+
self._process_args_for_args(state)
|
339 |
+
except UsageError:
|
340 |
+
if self.ctx is None or not self.ctx.resilient_parsing:
|
341 |
+
raise
|
342 |
+
return state.opts, state.largs, state.order
|
343 |
+
|
344 |
+
def _process_args_for_args(self, state: ParsingState) -> None:
|
345 |
+
pargs, args = _unpack_args(
|
346 |
+
state.largs + state.rargs, [x.nargs for x in self._args]
|
347 |
+
)
|
348 |
+
|
349 |
+
for idx, arg in enumerate(self._args):
|
350 |
+
arg.process(pargs[idx], state)
|
351 |
+
|
352 |
+
state.largs = args
|
353 |
+
state.rargs = []
|
354 |
+
|
355 |
+
def _process_args_for_options(self, state: ParsingState) -> None:
|
356 |
+
while state.rargs:
|
357 |
+
arg = state.rargs.pop(0)
|
358 |
+
arglen = len(arg)
|
359 |
+
# Double dashes always handled explicitly regardless of what
|
360 |
+
# prefixes are valid.
|
361 |
+
if arg == "--":
|
362 |
+
return
|
363 |
+
elif arg[:1] in self._opt_prefixes and arglen > 1:
|
364 |
+
self._process_opts(arg, state)
|
365 |
+
elif self.allow_interspersed_args:
|
366 |
+
state.largs.append(arg)
|
367 |
+
else:
|
368 |
+
state.rargs.insert(0, arg)
|
369 |
+
return
|
370 |
+
|
371 |
+
# Say this is the original argument list:
|
372 |
+
# [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
|
373 |
+
# ^
|
374 |
+
# (we are about to process arg(i)).
|
375 |
+
#
|
376 |
+
# Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
|
377 |
+
# [arg0, ..., arg(i-1)] (any options and their arguments will have
|
378 |
+
# been removed from largs).
|
379 |
+
#
|
380 |
+
# The while loop will usually consume 1 or more arguments per pass.
|
381 |
+
# If it consumes 1 (eg. arg is an option that takes no arguments),
|
382 |
+
# then after _process_arg() is done the situation is:
|
383 |
+
#
|
384 |
+
# largs = subset of [arg0, ..., arg(i)]
|
385 |
+
# rargs = [arg(i+1), ..., arg(N-1)]
|
386 |
+
#
|
387 |
+
# If allow_interspersed_args is false, largs will always be
|
388 |
+
# *empty* -- still a subset of [arg0, ..., arg(i-1)], but
|
389 |
+
# not a very interesting subset!
|
390 |
+
|
391 |
+
def _match_long_opt(
|
392 |
+
self, opt: str, explicit_value: t.Optional[str], state: ParsingState
|
393 |
+
) -> None:
|
394 |
+
if opt not in self._long_opt:
|
395 |
+
from difflib import get_close_matches
|
396 |
+
|
397 |
+
possibilities = get_close_matches(opt, self._long_opt)
|
398 |
+
raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)
|
399 |
+
|
400 |
+
option = self._long_opt[opt]
|
401 |
+
if option.takes_value:
|
402 |
+
# At this point it's safe to modify rargs by injecting the
|
403 |
+
# explicit value, because no exception is raised in this
|
404 |
+
# branch. This means that the inserted value will be fully
|
405 |
+
# consumed.
|
406 |
+
if explicit_value is not None:
|
407 |
+
state.rargs.insert(0, explicit_value)
|
408 |
+
|
409 |
+
value = self._get_value_from_state(opt, option, state)
|
410 |
+
|
411 |
+
elif explicit_value is not None:
|
412 |
+
raise BadOptionUsage(
|
413 |
+
opt, _("Option {name!r} does not take a value.").format(name=opt)
|
414 |
+
)
|
415 |
+
|
416 |
+
else:
|
417 |
+
value = None
|
418 |
+
|
419 |
+
option.process(value, state)
|
420 |
+
|
421 |
+
def _match_short_opt(self, arg: str, state: ParsingState) -> None:
|
422 |
+
stop = False
|
423 |
+
i = 1
|
424 |
+
prefix = arg[0]
|
425 |
+
unknown_options = []
|
426 |
+
|
427 |
+
for ch in arg[1:]:
|
428 |
+
opt = normalize_opt(f"{prefix}{ch}", self.ctx)
|
429 |
+
option = self._short_opt.get(opt)
|
430 |
+
i += 1
|
431 |
+
|
432 |
+
if not option:
|
433 |
+
if self.ignore_unknown_options:
|
434 |
+
unknown_options.append(ch)
|
435 |
+
continue
|
436 |
+
raise NoSuchOption(opt, ctx=self.ctx)
|
437 |
+
if option.takes_value:
|
438 |
+
# Any characters left in arg? Pretend they're the
|
439 |
+
# next arg, and stop consuming characters of arg.
|
440 |
+
if i < len(arg):
|
441 |
+
state.rargs.insert(0, arg[i:])
|
442 |
+
stop = True
|
443 |
+
|
444 |
+
value = self._get_value_from_state(opt, option, state)
|
445 |
+
|
446 |
+
else:
|
447 |
+
value = None
|
448 |
+
|
449 |
+
option.process(value, state)
|
450 |
+
|
451 |
+
if stop:
|
452 |
+
break
|
453 |
+
|
454 |
+
# If we got any unknown options we recombine the string of the
|
455 |
+
# remaining options and re-attach the prefix, then report that
|
456 |
+
# to the state as new larg. This way there is basic combinatorics
|
457 |
+
# that can be achieved while still ignoring unknown arguments.
|
458 |
+
if self.ignore_unknown_options and unknown_options:
|
459 |
+
state.largs.append(f"{prefix}{''.join(unknown_options)}")
|
460 |
+
|
461 |
+
def _get_value_from_state(
|
462 |
+
self, option_name: str, option: Option, state: ParsingState
|
463 |
+
) -> t.Any:
|
464 |
+
nargs = option.nargs
|
465 |
+
|
466 |
+
if len(state.rargs) < nargs:
|
467 |
+
if option.obj._flag_needs_value:
|
468 |
+
# Option allows omitting the value.
|
469 |
+
value = _flag_needs_value
|
470 |
+
else:
|
471 |
+
raise BadOptionUsage(
|
472 |
+
option_name,
|
473 |
+
ngettext(
|
474 |
+
"Option {name!r} requires an argument.",
|
475 |
+
"Option {name!r} requires {nargs} arguments.",
|
476 |
+
nargs,
|
477 |
+
).format(name=option_name, nargs=nargs),
|
478 |
+
)
|
479 |
+
elif nargs == 1:
|
480 |
+
next_rarg = state.rargs[0]
|
481 |
+
|
482 |
+
if (
|
483 |
+
option.obj._flag_needs_value
|
484 |
+
and isinstance(next_rarg, str)
|
485 |
+
and next_rarg[:1] in self._opt_prefixes
|
486 |
+
and len(next_rarg) > 1
|
487 |
+
):
|
488 |
+
# The next arg looks like the start of an option, don't
|
489 |
+
# use it as the value if omitting the value is allowed.
|
490 |
+
value = _flag_needs_value
|
491 |
+
else:
|
492 |
+
value = state.rargs.pop(0)
|
493 |
+
else:
|
494 |
+
value = tuple(state.rargs[:nargs])
|
495 |
+
del state.rargs[:nargs]
|
496 |
+
|
497 |
+
return value
|
498 |
+
|
499 |
+
def _process_opts(self, arg: str, state: ParsingState) -> None:
|
500 |
+
explicit_value = None
|
501 |
+
# Long option handling happens in two parts. The first part is
|
502 |
+
# supporting explicitly attached values. In any case, we will try
|
503 |
+
# to long match the option first.
|
504 |
+
if "=" in arg:
|
505 |
+
long_opt, explicit_value = arg.split("=", 1)
|
506 |
+
else:
|
507 |
+
long_opt = arg
|
508 |
+
norm_long_opt = normalize_opt(long_opt, self.ctx)
|
509 |
+
|
510 |
+
# At this point we will match the (assumed) long option through
|
511 |
+
# the long option matching code. Note that this allows options
|
512 |
+
# like "-foo" to be matched as long options.
|
513 |
+
try:
|
514 |
+
self._match_long_opt(norm_long_opt, explicit_value, state)
|
515 |
+
except NoSuchOption:
|
516 |
+
# At this point the long option matching failed, and we need
|
517 |
+
# to try with short options. However there is a special rule
|
518 |
+
# which says, that if we have a two character options prefix
|
519 |
+
# (applies to "--foo" for instance), we do not dispatch to the
|
520 |
+
# short option code and will instead raise the no option
|
521 |
+
# error.
|
522 |
+
if arg[:2] not in self._opt_prefixes:
|
523 |
+
self._match_short_opt(arg, state)
|
524 |
+
return
|
525 |
+
|
526 |
+
if not self.ignore_unknown_options:
|
527 |
+
raise
|
528 |
+
|
529 |
+
state.largs.append(arg)
|
llmeval-env/lib/python3.10/site-packages/click/py.typed
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/click/types.py
ADDED
@@ -0,0 +1,1089 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
import sys
|
4 |
+
import typing as t
|
5 |
+
from datetime import datetime
|
6 |
+
from gettext import gettext as _
|
7 |
+
from gettext import ngettext
|
8 |
+
|
9 |
+
from ._compat import _get_argv_encoding
|
10 |
+
from ._compat import open_stream
|
11 |
+
from .exceptions import BadParameter
|
12 |
+
from .utils import format_filename
|
13 |
+
from .utils import LazyFile
|
14 |
+
from .utils import safecall
|
15 |
+
|
16 |
+
if t.TYPE_CHECKING:
|
17 |
+
import typing_extensions as te
|
18 |
+
from .core import Context
|
19 |
+
from .core import Parameter
|
20 |
+
from .shell_completion import CompletionItem
|
21 |
+
|
22 |
+
|
23 |
+
class ParamType:
|
24 |
+
"""Represents the type of a parameter. Validates and converts values
|
25 |
+
from the command line or Python into the correct type.
|
26 |
+
|
27 |
+
To implement a custom type, subclass and implement at least the
|
28 |
+
following:
|
29 |
+
|
30 |
+
- The :attr:`name` class attribute must be set.
|
31 |
+
- Calling an instance of the type with ``None`` must return
|
32 |
+
``None``. This is already implemented by default.
|
33 |
+
- :meth:`convert` must convert string values to the correct type.
|
34 |
+
- :meth:`convert` must accept values that are already the correct
|
35 |
+
type.
|
36 |
+
- It must be able to convert a value if the ``ctx`` and ``param``
|
37 |
+
arguments are ``None``. This can occur when converting prompt
|
38 |
+
input.
|
39 |
+
"""
|
40 |
+
|
41 |
+
is_composite: t.ClassVar[bool] = False
|
42 |
+
arity: t.ClassVar[int] = 1
|
43 |
+
|
44 |
+
#: the descriptive name of this type
|
45 |
+
name: str
|
46 |
+
|
47 |
+
#: if a list of this type is expected and the value is pulled from a
|
48 |
+
#: string environment variable, this is what splits it up. `None`
|
49 |
+
#: means any whitespace. For all parameters the general rule is that
|
50 |
+
#: whitespace splits them up. The exception are paths and files which
|
51 |
+
#: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on
|
52 |
+
#: Windows).
|
53 |
+
envvar_list_splitter: t.ClassVar[t.Optional[str]] = None
|
54 |
+
|
55 |
+
def to_info_dict(self) -> t.Dict[str, t.Any]:
|
56 |
+
"""Gather information that could be useful for a tool generating
|
57 |
+
user-facing documentation.
|
58 |
+
|
59 |
+
Use :meth:`click.Context.to_info_dict` to traverse the entire
|
60 |
+
CLI structure.
|
61 |
+
|
62 |
+
.. versionadded:: 8.0
|
63 |
+
"""
|
64 |
+
# The class name without the "ParamType" suffix.
|
65 |
+
param_type = type(self).__name__.partition("ParamType")[0]
|
66 |
+
param_type = param_type.partition("ParameterType")[0]
|
67 |
+
|
68 |
+
# Custom subclasses might not remember to set a name.
|
69 |
+
if hasattr(self, "name"):
|
70 |
+
name = self.name
|
71 |
+
else:
|
72 |
+
name = param_type
|
73 |
+
|
74 |
+
return {"param_type": param_type, "name": name}
|
75 |
+
|
76 |
+
def __call__(
|
77 |
+
self,
|
78 |
+
value: t.Any,
|
79 |
+
param: t.Optional["Parameter"] = None,
|
80 |
+
ctx: t.Optional["Context"] = None,
|
81 |
+
) -> t.Any:
|
82 |
+
if value is not None:
|
83 |
+
return self.convert(value, param, ctx)
|
84 |
+
|
85 |
+
def get_metavar(self, param: "Parameter") -> t.Optional[str]:
|
86 |
+
"""Returns the metavar default for this param if it provides one."""
|
87 |
+
|
88 |
+
def get_missing_message(self, param: "Parameter") -> t.Optional[str]:
|
89 |
+
"""Optionally might return extra information about a missing
|
90 |
+
parameter.
|
91 |
+
|
92 |
+
.. versionadded:: 2.0
|
93 |
+
"""
|
94 |
+
|
95 |
+
def convert(
|
96 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
97 |
+
) -> t.Any:
|
98 |
+
"""Convert the value to the correct type. This is not called if
|
99 |
+
the value is ``None`` (the missing value).
|
100 |
+
|
101 |
+
This must accept string values from the command line, as well as
|
102 |
+
values that are already the correct type. It may also convert
|
103 |
+
other compatible types.
|
104 |
+
|
105 |
+
The ``param`` and ``ctx`` arguments may be ``None`` in certain
|
106 |
+
situations, such as when converting prompt input.
|
107 |
+
|
108 |
+
If the value cannot be converted, call :meth:`fail` with a
|
109 |
+
descriptive message.
|
110 |
+
|
111 |
+
:param value: The value to convert.
|
112 |
+
:param param: The parameter that is using this type to convert
|
113 |
+
its value. May be ``None``.
|
114 |
+
:param ctx: The current context that arrived at this value. May
|
115 |
+
be ``None``.
|
116 |
+
"""
|
117 |
+
return value
|
118 |
+
|
119 |
+
def split_envvar_value(self, rv: str) -> t.Sequence[str]:
|
120 |
+
"""Given a value from an environment variable this splits it up
|
121 |
+
into small chunks depending on the defined envvar list splitter.
|
122 |
+
|
123 |
+
If the splitter is set to `None`, which means that whitespace splits,
|
124 |
+
then leading and trailing whitespace is ignored. Otherwise, leading
|
125 |
+
and trailing splitters usually lead to empty items being included.
|
126 |
+
"""
|
127 |
+
return (rv or "").split(self.envvar_list_splitter)
|
128 |
+
|
129 |
+
def fail(
|
130 |
+
self,
|
131 |
+
message: str,
|
132 |
+
param: t.Optional["Parameter"] = None,
|
133 |
+
ctx: t.Optional["Context"] = None,
|
134 |
+
) -> "t.NoReturn":
|
135 |
+
"""Helper method to fail with an invalid value message."""
|
136 |
+
raise BadParameter(message, ctx=ctx, param=param)
|
137 |
+
|
138 |
+
def shell_complete(
|
139 |
+
self, ctx: "Context", param: "Parameter", incomplete: str
|
140 |
+
) -> t.List["CompletionItem"]:
|
141 |
+
"""Return a list of
|
142 |
+
:class:`~click.shell_completion.CompletionItem` objects for the
|
143 |
+
incomplete value. Most types do not provide completions, but
|
144 |
+
some do, and this allows custom types to provide custom
|
145 |
+
completions as well.
|
146 |
+
|
147 |
+
:param ctx: Invocation context for this command.
|
148 |
+
:param param: The parameter that is requesting completion.
|
149 |
+
:param incomplete: Value being completed. May be empty.
|
150 |
+
|
151 |
+
.. versionadded:: 8.0
|
152 |
+
"""
|
153 |
+
return []
|
154 |
+
|
155 |
+
|
156 |
+
class CompositeParamType(ParamType):
|
157 |
+
is_composite = True
|
158 |
+
|
159 |
+
@property
|
160 |
+
def arity(self) -> int: # type: ignore
|
161 |
+
raise NotImplementedError()
|
162 |
+
|
163 |
+
|
164 |
+
class FuncParamType(ParamType):
|
165 |
+
def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None:
|
166 |
+
self.name: str = func.__name__
|
167 |
+
self.func = func
|
168 |
+
|
169 |
+
def to_info_dict(self) -> t.Dict[str, t.Any]:
|
170 |
+
info_dict = super().to_info_dict()
|
171 |
+
info_dict["func"] = self.func
|
172 |
+
return info_dict
|
173 |
+
|
174 |
+
def convert(
|
175 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
176 |
+
) -> t.Any:
|
177 |
+
try:
|
178 |
+
return self.func(value)
|
179 |
+
except ValueError:
|
180 |
+
try:
|
181 |
+
value = str(value)
|
182 |
+
except UnicodeError:
|
183 |
+
value = value.decode("utf-8", "replace")
|
184 |
+
|
185 |
+
self.fail(value, param, ctx)
|
186 |
+
|
187 |
+
|
188 |
+
class UnprocessedParamType(ParamType):
|
189 |
+
name = "text"
|
190 |
+
|
191 |
+
def convert(
|
192 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
193 |
+
) -> t.Any:
|
194 |
+
return value
|
195 |
+
|
196 |
+
def __repr__(self) -> str:
|
197 |
+
return "UNPROCESSED"
|
198 |
+
|
199 |
+
|
200 |
+
class StringParamType(ParamType):
|
201 |
+
name = "text"
|
202 |
+
|
203 |
+
def convert(
|
204 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
205 |
+
) -> t.Any:
|
206 |
+
if isinstance(value, bytes):
|
207 |
+
enc = _get_argv_encoding()
|
208 |
+
try:
|
209 |
+
value = value.decode(enc)
|
210 |
+
except UnicodeError:
|
211 |
+
fs_enc = sys.getfilesystemencoding()
|
212 |
+
if fs_enc != enc:
|
213 |
+
try:
|
214 |
+
value = value.decode(fs_enc)
|
215 |
+
except UnicodeError:
|
216 |
+
value = value.decode("utf-8", "replace")
|
217 |
+
else:
|
218 |
+
value = value.decode("utf-8", "replace")
|
219 |
+
return value
|
220 |
+
return str(value)
|
221 |
+
|
222 |
+
def __repr__(self) -> str:
|
223 |
+
return "STRING"
|
224 |
+
|
225 |
+
|
226 |
+
class Choice(ParamType):
|
227 |
+
"""The choice type allows a value to be checked against a fixed set
|
228 |
+
of supported values. All of these values have to be strings.
|
229 |
+
|
230 |
+
You should only pass a list or tuple of choices. Other iterables
|
231 |
+
(like generators) may lead to surprising results.
|
232 |
+
|
233 |
+
The resulting value will always be one of the originally passed choices
|
234 |
+
regardless of ``case_sensitive`` or any ``ctx.token_normalize_func``
|
235 |
+
being specified.
|
236 |
+
|
237 |
+
See :ref:`choice-opts` for an example.
|
238 |
+
|
239 |
+
:param case_sensitive: Set to false to make choices case
|
240 |
+
insensitive. Defaults to true.
|
241 |
+
"""
|
242 |
+
|
243 |
+
name = "choice"
|
244 |
+
|
245 |
+
def __init__(self, choices: t.Sequence[str], case_sensitive: bool = True) -> None:
|
246 |
+
self.choices = choices
|
247 |
+
self.case_sensitive = case_sensitive
|
248 |
+
|
249 |
+
def to_info_dict(self) -> t.Dict[str, t.Any]:
|
250 |
+
info_dict = super().to_info_dict()
|
251 |
+
info_dict["choices"] = self.choices
|
252 |
+
info_dict["case_sensitive"] = self.case_sensitive
|
253 |
+
return info_dict
|
254 |
+
|
255 |
+
def get_metavar(self, param: "Parameter") -> str:
|
256 |
+
choices_str = "|".join(self.choices)
|
257 |
+
|
258 |
+
# Use curly braces to indicate a required argument.
|
259 |
+
if param.required and param.param_type_name == "argument":
|
260 |
+
return f"{{{choices_str}}}"
|
261 |
+
|
262 |
+
# Use square braces to indicate an option or optional argument.
|
263 |
+
return f"[{choices_str}]"
|
264 |
+
|
265 |
+
def get_missing_message(self, param: "Parameter") -> str:
|
266 |
+
return _("Choose from:\n\t{choices}").format(choices=",\n\t".join(self.choices))
|
267 |
+
|
268 |
+
def convert(
|
269 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
270 |
+
) -> t.Any:
|
271 |
+
# Match through normalization and case sensitivity
|
272 |
+
# first do token_normalize_func, then lowercase
|
273 |
+
# preserve original `value` to produce an accurate message in
|
274 |
+
# `self.fail`
|
275 |
+
normed_value = value
|
276 |
+
normed_choices = {choice: choice for choice in self.choices}
|
277 |
+
|
278 |
+
if ctx is not None and ctx.token_normalize_func is not None:
|
279 |
+
normed_value = ctx.token_normalize_func(value)
|
280 |
+
normed_choices = {
|
281 |
+
ctx.token_normalize_func(normed_choice): original
|
282 |
+
for normed_choice, original in normed_choices.items()
|
283 |
+
}
|
284 |
+
|
285 |
+
if not self.case_sensitive:
|
286 |
+
normed_value = normed_value.casefold()
|
287 |
+
normed_choices = {
|
288 |
+
normed_choice.casefold(): original
|
289 |
+
for normed_choice, original in normed_choices.items()
|
290 |
+
}
|
291 |
+
|
292 |
+
if normed_value in normed_choices:
|
293 |
+
return normed_choices[normed_value]
|
294 |
+
|
295 |
+
choices_str = ", ".join(map(repr, self.choices))
|
296 |
+
self.fail(
|
297 |
+
ngettext(
|
298 |
+
"{value!r} is not {choice}.",
|
299 |
+
"{value!r} is not one of {choices}.",
|
300 |
+
len(self.choices),
|
301 |
+
).format(value=value, choice=choices_str, choices=choices_str),
|
302 |
+
param,
|
303 |
+
ctx,
|
304 |
+
)
|
305 |
+
|
306 |
+
def __repr__(self) -> str:
|
307 |
+
return f"Choice({list(self.choices)})"
|
308 |
+
|
309 |
+
def shell_complete(
|
310 |
+
self, ctx: "Context", param: "Parameter", incomplete: str
|
311 |
+
) -> t.List["CompletionItem"]:
|
312 |
+
"""Complete choices that start with the incomplete value.
|
313 |
+
|
314 |
+
:param ctx: Invocation context for this command.
|
315 |
+
:param param: The parameter that is requesting completion.
|
316 |
+
:param incomplete: Value being completed. May be empty.
|
317 |
+
|
318 |
+
.. versionadded:: 8.0
|
319 |
+
"""
|
320 |
+
from click.shell_completion import CompletionItem
|
321 |
+
|
322 |
+
str_choices = map(str, self.choices)
|
323 |
+
|
324 |
+
if self.case_sensitive:
|
325 |
+
matched = (c for c in str_choices if c.startswith(incomplete))
|
326 |
+
else:
|
327 |
+
incomplete = incomplete.lower()
|
328 |
+
matched = (c for c in str_choices if c.lower().startswith(incomplete))
|
329 |
+
|
330 |
+
return [CompletionItem(c) for c in matched]
|
331 |
+
|
332 |
+
|
333 |
+
class DateTime(ParamType):
|
334 |
+
"""The DateTime type converts date strings into `datetime` objects.
|
335 |
+
|
336 |
+
The format strings which are checked are configurable, but default to some
|
337 |
+
common (non-timezone aware) ISO 8601 formats.
|
338 |
+
|
339 |
+
When specifying *DateTime* formats, you should only pass a list or a tuple.
|
340 |
+
Other iterables, like generators, may lead to surprising results.
|
341 |
+
|
342 |
+
The format strings are processed using ``datetime.strptime``, and this
|
343 |
+
consequently defines the format strings which are allowed.
|
344 |
+
|
345 |
+
Parsing is tried using each format, in order, and the first format which
|
346 |
+
parses successfully is used.
|
347 |
+
|
348 |
+
:param formats: A list or tuple of date format strings, in the order in
|
349 |
+
which they should be tried. Defaults to
|
350 |
+
``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``,
|
351 |
+
``'%Y-%m-%d %H:%M:%S'``.
|
352 |
+
"""
|
353 |
+
|
354 |
+
name = "datetime"
|
355 |
+
|
356 |
+
def __init__(self, formats: t.Optional[t.Sequence[str]] = None):
|
357 |
+
self.formats: t.Sequence[str] = formats or [
|
358 |
+
"%Y-%m-%d",
|
359 |
+
"%Y-%m-%dT%H:%M:%S",
|
360 |
+
"%Y-%m-%d %H:%M:%S",
|
361 |
+
]
|
362 |
+
|
363 |
+
def to_info_dict(self) -> t.Dict[str, t.Any]:
|
364 |
+
info_dict = super().to_info_dict()
|
365 |
+
info_dict["formats"] = self.formats
|
366 |
+
return info_dict
|
367 |
+
|
368 |
+
def get_metavar(self, param: "Parameter") -> str:
|
369 |
+
return f"[{'|'.join(self.formats)}]"
|
370 |
+
|
371 |
+
def _try_to_convert_date(self, value: t.Any, format: str) -> t.Optional[datetime]:
|
372 |
+
try:
|
373 |
+
return datetime.strptime(value, format)
|
374 |
+
except ValueError:
|
375 |
+
return None
|
376 |
+
|
377 |
+
def convert(
|
378 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
379 |
+
) -> t.Any:
|
380 |
+
if isinstance(value, datetime):
|
381 |
+
return value
|
382 |
+
|
383 |
+
for format in self.formats:
|
384 |
+
converted = self._try_to_convert_date(value, format)
|
385 |
+
|
386 |
+
if converted is not None:
|
387 |
+
return converted
|
388 |
+
|
389 |
+
formats_str = ", ".join(map(repr, self.formats))
|
390 |
+
self.fail(
|
391 |
+
ngettext(
|
392 |
+
"{value!r} does not match the format {format}.",
|
393 |
+
"{value!r} does not match the formats {formats}.",
|
394 |
+
len(self.formats),
|
395 |
+
).format(value=value, format=formats_str, formats=formats_str),
|
396 |
+
param,
|
397 |
+
ctx,
|
398 |
+
)
|
399 |
+
|
400 |
+
def __repr__(self) -> str:
|
401 |
+
return "DateTime"
|
402 |
+
|
403 |
+
|
404 |
+
class _NumberParamTypeBase(ParamType):
|
405 |
+
_number_class: t.ClassVar[t.Type[t.Any]]
|
406 |
+
|
407 |
+
def convert(
|
408 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
409 |
+
) -> t.Any:
|
410 |
+
try:
|
411 |
+
return self._number_class(value)
|
412 |
+
except ValueError:
|
413 |
+
self.fail(
|
414 |
+
_("{value!r} is not a valid {number_type}.").format(
|
415 |
+
value=value, number_type=self.name
|
416 |
+
),
|
417 |
+
param,
|
418 |
+
ctx,
|
419 |
+
)
|
420 |
+
|
421 |
+
|
422 |
+
class _NumberRangeBase(_NumberParamTypeBase):
|
423 |
+
def __init__(
|
424 |
+
self,
|
425 |
+
min: t.Optional[float] = None,
|
426 |
+
max: t.Optional[float] = None,
|
427 |
+
min_open: bool = False,
|
428 |
+
max_open: bool = False,
|
429 |
+
clamp: bool = False,
|
430 |
+
) -> None:
|
431 |
+
self.min = min
|
432 |
+
self.max = max
|
433 |
+
self.min_open = min_open
|
434 |
+
self.max_open = max_open
|
435 |
+
self.clamp = clamp
|
436 |
+
|
437 |
+
def to_info_dict(self) -> t.Dict[str, t.Any]:
|
438 |
+
info_dict = super().to_info_dict()
|
439 |
+
info_dict.update(
|
440 |
+
min=self.min,
|
441 |
+
max=self.max,
|
442 |
+
min_open=self.min_open,
|
443 |
+
max_open=self.max_open,
|
444 |
+
clamp=self.clamp,
|
445 |
+
)
|
446 |
+
return info_dict
|
447 |
+
|
448 |
+
def convert(
|
449 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
450 |
+
) -> t.Any:
|
451 |
+
import operator
|
452 |
+
|
453 |
+
rv = super().convert(value, param, ctx)
|
454 |
+
lt_min: bool = self.min is not None and (
|
455 |
+
operator.le if self.min_open else operator.lt
|
456 |
+
)(rv, self.min)
|
457 |
+
gt_max: bool = self.max is not None and (
|
458 |
+
operator.ge if self.max_open else operator.gt
|
459 |
+
)(rv, self.max)
|
460 |
+
|
461 |
+
if self.clamp:
|
462 |
+
if lt_min:
|
463 |
+
return self._clamp(self.min, 1, self.min_open) # type: ignore
|
464 |
+
|
465 |
+
if gt_max:
|
466 |
+
return self._clamp(self.max, -1, self.max_open) # type: ignore
|
467 |
+
|
468 |
+
if lt_min or gt_max:
|
469 |
+
self.fail(
|
470 |
+
_("{value} is not in the range {range}.").format(
|
471 |
+
value=rv, range=self._describe_range()
|
472 |
+
),
|
473 |
+
param,
|
474 |
+
ctx,
|
475 |
+
)
|
476 |
+
|
477 |
+
return rv
|
478 |
+
|
479 |
+
def _clamp(self, bound: float, dir: "te.Literal[1, -1]", open: bool) -> float:
|
480 |
+
"""Find the valid value to clamp to bound in the given
|
481 |
+
direction.
|
482 |
+
|
483 |
+
:param bound: The boundary value.
|
484 |
+
:param dir: 1 or -1 indicating the direction to move.
|
485 |
+
:param open: If true, the range does not include the bound.
|
486 |
+
"""
|
487 |
+
raise NotImplementedError
|
488 |
+
|
489 |
+
def _describe_range(self) -> str:
|
490 |
+
"""Describe the range for use in help text."""
|
491 |
+
if self.min is None:
|
492 |
+
op = "<" if self.max_open else "<="
|
493 |
+
return f"x{op}{self.max}"
|
494 |
+
|
495 |
+
if self.max is None:
|
496 |
+
op = ">" if self.min_open else ">="
|
497 |
+
return f"x{op}{self.min}"
|
498 |
+
|
499 |
+
lop = "<" if self.min_open else "<="
|
500 |
+
rop = "<" if self.max_open else "<="
|
501 |
+
return f"{self.min}{lop}x{rop}{self.max}"
|
502 |
+
|
503 |
+
def __repr__(self) -> str:
|
504 |
+
clamp = " clamped" if self.clamp else ""
|
505 |
+
return f"<{type(self).__name__} {self._describe_range()}{clamp}>"
|
506 |
+
|
507 |
+
|
508 |
+
class IntParamType(_NumberParamTypeBase):
|
509 |
+
name = "integer"
|
510 |
+
_number_class = int
|
511 |
+
|
512 |
+
def __repr__(self) -> str:
|
513 |
+
return "INT"
|
514 |
+
|
515 |
+
|
516 |
+
class IntRange(_NumberRangeBase, IntParamType):
|
517 |
+
"""Restrict an :data:`click.INT` value to a range of accepted
|
518 |
+
values. See :ref:`ranges`.
|
519 |
+
|
520 |
+
If ``min`` or ``max`` are not passed, any value is accepted in that
|
521 |
+
direction. If ``min_open`` or ``max_open`` are enabled, the
|
522 |
+
corresponding boundary is not included in the range.
|
523 |
+
|
524 |
+
If ``clamp`` is enabled, a value outside the range is clamped to the
|
525 |
+
boundary instead of failing.
|
526 |
+
|
527 |
+
.. versionchanged:: 8.0
|
528 |
+
Added the ``min_open`` and ``max_open`` parameters.
|
529 |
+
"""
|
530 |
+
|
531 |
+
name = "integer range"
|
532 |
+
|
533 |
+
def _clamp( # type: ignore
|
534 |
+
self, bound: int, dir: "te.Literal[1, -1]", open: bool
|
535 |
+
) -> int:
|
536 |
+
if not open:
|
537 |
+
return bound
|
538 |
+
|
539 |
+
return bound + dir
|
540 |
+
|
541 |
+
|
542 |
+
class FloatParamType(_NumberParamTypeBase):
|
543 |
+
name = "float"
|
544 |
+
_number_class = float
|
545 |
+
|
546 |
+
def __repr__(self) -> str:
|
547 |
+
return "FLOAT"
|
548 |
+
|
549 |
+
|
550 |
+
class FloatRange(_NumberRangeBase, FloatParamType):
|
551 |
+
"""Restrict a :data:`click.FLOAT` value to a range of accepted
|
552 |
+
values. See :ref:`ranges`.
|
553 |
+
|
554 |
+
If ``min`` or ``max`` are not passed, any value is accepted in that
|
555 |
+
direction. If ``min_open`` or ``max_open`` are enabled, the
|
556 |
+
corresponding boundary is not included in the range.
|
557 |
+
|
558 |
+
If ``clamp`` is enabled, a value outside the range is clamped to the
|
559 |
+
boundary instead of failing. This is not supported if either
|
560 |
+
boundary is marked ``open``.
|
561 |
+
|
562 |
+
.. versionchanged:: 8.0
|
563 |
+
Added the ``min_open`` and ``max_open`` parameters.
|
564 |
+
"""
|
565 |
+
|
566 |
+
name = "float range"
|
567 |
+
|
568 |
+
def __init__(
|
569 |
+
self,
|
570 |
+
min: t.Optional[float] = None,
|
571 |
+
max: t.Optional[float] = None,
|
572 |
+
min_open: bool = False,
|
573 |
+
max_open: bool = False,
|
574 |
+
clamp: bool = False,
|
575 |
+
) -> None:
|
576 |
+
super().__init__(
|
577 |
+
min=min, max=max, min_open=min_open, max_open=max_open, clamp=clamp
|
578 |
+
)
|
579 |
+
|
580 |
+
if (min_open or max_open) and clamp:
|
581 |
+
raise TypeError("Clamping is not supported for open bounds.")
|
582 |
+
|
583 |
+
def _clamp(self, bound: float, dir: "te.Literal[1, -1]", open: bool) -> float:
|
584 |
+
if not open:
|
585 |
+
return bound
|
586 |
+
|
587 |
+
# Could use Python 3.9's math.nextafter here, but clamping an
|
588 |
+
# open float range doesn't seem to be particularly useful. It's
|
589 |
+
# left up to the user to write a callback to do it if needed.
|
590 |
+
raise RuntimeError("Clamping is not supported for open bounds.")
|
591 |
+
|
592 |
+
|
593 |
+
class BoolParamType(ParamType):
|
594 |
+
name = "boolean"
|
595 |
+
|
596 |
+
def convert(
|
597 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
598 |
+
) -> t.Any:
|
599 |
+
if value in {False, True}:
|
600 |
+
return bool(value)
|
601 |
+
|
602 |
+
norm = value.strip().lower()
|
603 |
+
|
604 |
+
if norm in {"1", "true", "t", "yes", "y", "on"}:
|
605 |
+
return True
|
606 |
+
|
607 |
+
if norm in {"0", "false", "f", "no", "n", "off"}:
|
608 |
+
return False
|
609 |
+
|
610 |
+
self.fail(
|
611 |
+
_("{value!r} is not a valid boolean.").format(value=value), param, ctx
|
612 |
+
)
|
613 |
+
|
614 |
+
def __repr__(self) -> str:
|
615 |
+
return "BOOL"
|
616 |
+
|
617 |
+
|
618 |
+
class UUIDParameterType(ParamType):
|
619 |
+
name = "uuid"
|
620 |
+
|
621 |
+
def convert(
|
622 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
623 |
+
) -> t.Any:
|
624 |
+
import uuid
|
625 |
+
|
626 |
+
if isinstance(value, uuid.UUID):
|
627 |
+
return value
|
628 |
+
|
629 |
+
value = value.strip()
|
630 |
+
|
631 |
+
try:
|
632 |
+
return uuid.UUID(value)
|
633 |
+
except ValueError:
|
634 |
+
self.fail(
|
635 |
+
_("{value!r} is not a valid UUID.").format(value=value), param, ctx
|
636 |
+
)
|
637 |
+
|
638 |
+
def __repr__(self) -> str:
|
639 |
+
return "UUID"
|
640 |
+
|
641 |
+
|
642 |
+
class File(ParamType):
|
643 |
+
"""Declares a parameter to be a file for reading or writing. The file
|
644 |
+
is automatically closed once the context tears down (after the command
|
645 |
+
finished working).
|
646 |
+
|
647 |
+
Files can be opened for reading or writing. The special value ``-``
|
648 |
+
indicates stdin or stdout depending on the mode.
|
649 |
+
|
650 |
+
By default, the file is opened for reading text data, but it can also be
|
651 |
+
opened in binary mode or for writing. The encoding parameter can be used
|
652 |
+
to force a specific encoding.
|
653 |
+
|
654 |
+
The `lazy` flag controls if the file should be opened immediately or upon
|
655 |
+
first IO. The default is to be non-lazy for standard input and output
|
656 |
+
streams as well as files opened for reading, `lazy` otherwise. When opening a
|
657 |
+
file lazily for reading, it is still opened temporarily for validation, but
|
658 |
+
will not be held open until first IO. lazy is mainly useful when opening
|
659 |
+
for writing to avoid creating the file until it is needed.
|
660 |
+
|
661 |
+
Starting with Click 2.0, files can also be opened atomically in which
|
662 |
+
case all writes go into a separate file in the same folder and upon
|
663 |
+
completion the file will be moved over to the original location. This
|
664 |
+
is useful if a file regularly read by other users is modified.
|
665 |
+
|
666 |
+
See :ref:`file-args` for more information.
|
667 |
+
"""
|
668 |
+
|
669 |
+
name = "filename"
|
670 |
+
envvar_list_splitter: t.ClassVar[str] = os.path.pathsep
|
671 |
+
|
672 |
+
def __init__(
|
673 |
+
self,
|
674 |
+
mode: str = "r",
|
675 |
+
encoding: t.Optional[str] = None,
|
676 |
+
errors: t.Optional[str] = "strict",
|
677 |
+
lazy: t.Optional[bool] = None,
|
678 |
+
atomic: bool = False,
|
679 |
+
) -> None:
|
680 |
+
self.mode = mode
|
681 |
+
self.encoding = encoding
|
682 |
+
self.errors = errors
|
683 |
+
self.lazy = lazy
|
684 |
+
self.atomic = atomic
|
685 |
+
|
686 |
+
def to_info_dict(self) -> t.Dict[str, t.Any]:
|
687 |
+
info_dict = super().to_info_dict()
|
688 |
+
info_dict.update(mode=self.mode, encoding=self.encoding)
|
689 |
+
return info_dict
|
690 |
+
|
691 |
+
def resolve_lazy_flag(self, value: "t.Union[str, os.PathLike[str]]") -> bool:
|
692 |
+
if self.lazy is not None:
|
693 |
+
return self.lazy
|
694 |
+
if os.fspath(value) == "-":
|
695 |
+
return False
|
696 |
+
elif "w" in self.mode:
|
697 |
+
return True
|
698 |
+
return False
|
699 |
+
|
700 |
+
def convert(
|
701 |
+
self,
|
702 |
+
value: t.Union[str, "os.PathLike[str]", t.IO[t.Any]],
|
703 |
+
param: t.Optional["Parameter"],
|
704 |
+
ctx: t.Optional["Context"],
|
705 |
+
) -> t.IO[t.Any]:
|
706 |
+
if _is_file_like(value):
|
707 |
+
return value
|
708 |
+
|
709 |
+
value = t.cast("t.Union[str, os.PathLike[str]]", value)
|
710 |
+
|
711 |
+
try:
|
712 |
+
lazy = self.resolve_lazy_flag(value)
|
713 |
+
|
714 |
+
if lazy:
|
715 |
+
lf = LazyFile(
|
716 |
+
value, self.mode, self.encoding, self.errors, atomic=self.atomic
|
717 |
+
)
|
718 |
+
|
719 |
+
if ctx is not None:
|
720 |
+
ctx.call_on_close(lf.close_intelligently)
|
721 |
+
|
722 |
+
return t.cast(t.IO[t.Any], lf)
|
723 |
+
|
724 |
+
f, should_close = open_stream(
|
725 |
+
value, self.mode, self.encoding, self.errors, atomic=self.atomic
|
726 |
+
)
|
727 |
+
|
728 |
+
# If a context is provided, we automatically close the file
|
729 |
+
# at the end of the context execution (or flush out). If a
|
730 |
+
# context does not exist, it's the caller's responsibility to
|
731 |
+
# properly close the file. This for instance happens when the
|
732 |
+
# type is used with prompts.
|
733 |
+
if ctx is not None:
|
734 |
+
if should_close:
|
735 |
+
ctx.call_on_close(safecall(f.close))
|
736 |
+
else:
|
737 |
+
ctx.call_on_close(safecall(f.flush))
|
738 |
+
|
739 |
+
return f
|
740 |
+
except OSError as e: # noqa: B014
|
741 |
+
self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)
|
742 |
+
|
743 |
+
def shell_complete(
|
744 |
+
self, ctx: "Context", param: "Parameter", incomplete: str
|
745 |
+
) -> t.List["CompletionItem"]:
|
746 |
+
"""Return a special completion marker that tells the completion
|
747 |
+
system to use the shell to provide file path completions.
|
748 |
+
|
749 |
+
:param ctx: Invocation context for this command.
|
750 |
+
:param param: The parameter that is requesting completion.
|
751 |
+
:param incomplete: Value being completed. May be empty.
|
752 |
+
|
753 |
+
.. versionadded:: 8.0
|
754 |
+
"""
|
755 |
+
from click.shell_completion import CompletionItem
|
756 |
+
|
757 |
+
return [CompletionItem(incomplete, type="file")]
|
758 |
+
|
759 |
+
|
760 |
+
def _is_file_like(value: t.Any) -> "te.TypeGuard[t.IO[t.Any]]":
|
761 |
+
return hasattr(value, "read") or hasattr(value, "write")
|
762 |
+
|
763 |
+
|
764 |
+
class Path(ParamType):
|
765 |
+
"""The ``Path`` type is similar to the :class:`File` type, but
|
766 |
+
returns the filename instead of an open file. Various checks can be
|
767 |
+
enabled to validate the type of file and permissions.
|
768 |
+
|
769 |
+
:param exists: The file or directory needs to exist for the value to
|
770 |
+
be valid. If this is not set to ``True``, and the file does not
|
771 |
+
exist, then all further checks are silently skipped.
|
772 |
+
:param file_okay: Allow a file as a value.
|
773 |
+
:param dir_okay: Allow a directory as a value.
|
774 |
+
:param readable: if true, a readable check is performed.
|
775 |
+
:param writable: if true, a writable check is performed.
|
776 |
+
:param executable: if true, an executable check is performed.
|
777 |
+
:param resolve_path: Make the value absolute and resolve any
|
778 |
+
symlinks. A ``~`` is not expanded, as this is supposed to be
|
779 |
+
done by the shell only.
|
780 |
+
:param allow_dash: Allow a single dash as a value, which indicates
|
781 |
+
a standard stream (but does not open it). Use
|
782 |
+
:func:`~click.open_file` to handle opening this value.
|
783 |
+
:param path_type: Convert the incoming path value to this type. If
|
784 |
+
``None``, keep Python's default, which is ``str``. Useful to
|
785 |
+
convert to :class:`pathlib.Path`.
|
786 |
+
|
787 |
+
.. versionchanged:: 8.1
|
788 |
+
Added the ``executable`` parameter.
|
789 |
+
|
790 |
+
.. versionchanged:: 8.0
|
791 |
+
Allow passing ``path_type=pathlib.Path``.
|
792 |
+
|
793 |
+
.. versionchanged:: 6.0
|
794 |
+
Added the ``allow_dash`` parameter.
|
795 |
+
"""
|
796 |
+
|
797 |
+
envvar_list_splitter: t.ClassVar[str] = os.path.pathsep
|
798 |
+
|
799 |
+
def __init__(
|
800 |
+
self,
|
801 |
+
exists: bool = False,
|
802 |
+
file_okay: bool = True,
|
803 |
+
dir_okay: bool = True,
|
804 |
+
writable: bool = False,
|
805 |
+
readable: bool = True,
|
806 |
+
resolve_path: bool = False,
|
807 |
+
allow_dash: bool = False,
|
808 |
+
path_type: t.Optional[t.Type[t.Any]] = None,
|
809 |
+
executable: bool = False,
|
810 |
+
):
|
811 |
+
self.exists = exists
|
812 |
+
self.file_okay = file_okay
|
813 |
+
self.dir_okay = dir_okay
|
814 |
+
self.readable = readable
|
815 |
+
self.writable = writable
|
816 |
+
self.executable = executable
|
817 |
+
self.resolve_path = resolve_path
|
818 |
+
self.allow_dash = allow_dash
|
819 |
+
self.type = path_type
|
820 |
+
|
821 |
+
if self.file_okay and not self.dir_okay:
|
822 |
+
self.name: str = _("file")
|
823 |
+
elif self.dir_okay and not self.file_okay:
|
824 |
+
self.name = _("directory")
|
825 |
+
else:
|
826 |
+
self.name = _("path")
|
827 |
+
|
828 |
+
def to_info_dict(self) -> t.Dict[str, t.Any]:
|
829 |
+
info_dict = super().to_info_dict()
|
830 |
+
info_dict.update(
|
831 |
+
exists=self.exists,
|
832 |
+
file_okay=self.file_okay,
|
833 |
+
dir_okay=self.dir_okay,
|
834 |
+
writable=self.writable,
|
835 |
+
readable=self.readable,
|
836 |
+
allow_dash=self.allow_dash,
|
837 |
+
)
|
838 |
+
return info_dict
|
839 |
+
|
840 |
+
def coerce_path_result(
|
841 |
+
self, value: "t.Union[str, os.PathLike[str]]"
|
842 |
+
) -> "t.Union[str, bytes, os.PathLike[str]]":
|
843 |
+
if self.type is not None and not isinstance(value, self.type):
|
844 |
+
if self.type is str:
|
845 |
+
return os.fsdecode(value)
|
846 |
+
elif self.type is bytes:
|
847 |
+
return os.fsencode(value)
|
848 |
+
else:
|
849 |
+
return t.cast("os.PathLike[str]", self.type(value))
|
850 |
+
|
851 |
+
return value
|
852 |
+
|
853 |
+
def convert(
|
854 |
+
self,
|
855 |
+
value: "t.Union[str, os.PathLike[str]]",
|
856 |
+
param: t.Optional["Parameter"],
|
857 |
+
ctx: t.Optional["Context"],
|
858 |
+
) -> "t.Union[str, bytes, os.PathLike[str]]":
|
859 |
+
rv = value
|
860 |
+
|
861 |
+
is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")
|
862 |
+
|
863 |
+
if not is_dash:
|
864 |
+
if self.resolve_path:
|
865 |
+
# os.path.realpath doesn't resolve symlinks on Windows
|
866 |
+
# until Python 3.8. Use pathlib for now.
|
867 |
+
import pathlib
|
868 |
+
|
869 |
+
rv = os.fsdecode(pathlib.Path(rv).resolve())
|
870 |
+
|
871 |
+
try:
|
872 |
+
st = os.stat(rv)
|
873 |
+
except OSError:
|
874 |
+
if not self.exists:
|
875 |
+
return self.coerce_path_result(rv)
|
876 |
+
self.fail(
|
877 |
+
_("{name} {filename!r} does not exist.").format(
|
878 |
+
name=self.name.title(), filename=format_filename(value)
|
879 |
+
),
|
880 |
+
param,
|
881 |
+
ctx,
|
882 |
+
)
|
883 |
+
|
884 |
+
if not self.file_okay and stat.S_ISREG(st.st_mode):
|
885 |
+
self.fail(
|
886 |
+
_("{name} {filename!r} is a file.").format(
|
887 |
+
name=self.name.title(), filename=format_filename(value)
|
888 |
+
),
|
889 |
+
param,
|
890 |
+
ctx,
|
891 |
+
)
|
892 |
+
if not self.dir_okay and stat.S_ISDIR(st.st_mode):
|
893 |
+
self.fail(
|
894 |
+
_("{name} '{filename}' is a directory.").format(
|
895 |
+
name=self.name.title(), filename=format_filename(value)
|
896 |
+
),
|
897 |
+
param,
|
898 |
+
ctx,
|
899 |
+
)
|
900 |
+
|
901 |
+
if self.readable and not os.access(rv, os.R_OK):
|
902 |
+
self.fail(
|
903 |
+
_("{name} {filename!r} is not readable.").format(
|
904 |
+
name=self.name.title(), filename=format_filename(value)
|
905 |
+
),
|
906 |
+
param,
|
907 |
+
ctx,
|
908 |
+
)
|
909 |
+
|
910 |
+
if self.writable and not os.access(rv, os.W_OK):
|
911 |
+
self.fail(
|
912 |
+
_("{name} {filename!r} is not writable.").format(
|
913 |
+
name=self.name.title(), filename=format_filename(value)
|
914 |
+
),
|
915 |
+
param,
|
916 |
+
ctx,
|
917 |
+
)
|
918 |
+
|
919 |
+
if self.executable and not os.access(value, os.X_OK):
|
920 |
+
self.fail(
|
921 |
+
_("{name} {filename!r} is not executable.").format(
|
922 |
+
name=self.name.title(), filename=format_filename(value)
|
923 |
+
),
|
924 |
+
param,
|
925 |
+
ctx,
|
926 |
+
)
|
927 |
+
|
928 |
+
return self.coerce_path_result(rv)
|
929 |
+
|
930 |
+
def shell_complete(
|
931 |
+
self, ctx: "Context", param: "Parameter", incomplete: str
|
932 |
+
) -> t.List["CompletionItem"]:
|
933 |
+
"""Return a special completion marker that tells the completion
|
934 |
+
system to use the shell to provide path completions for only
|
935 |
+
directories or any paths.
|
936 |
+
|
937 |
+
:param ctx: Invocation context for this command.
|
938 |
+
:param param: The parameter that is requesting completion.
|
939 |
+
:param incomplete: Value being completed. May be empty.
|
940 |
+
|
941 |
+
.. versionadded:: 8.0
|
942 |
+
"""
|
943 |
+
from click.shell_completion import CompletionItem
|
944 |
+
|
945 |
+
type = "dir" if self.dir_okay and not self.file_okay else "file"
|
946 |
+
return [CompletionItem(incomplete, type=type)]
|
947 |
+
|
948 |
+
|
949 |
+
class Tuple(CompositeParamType):
|
950 |
+
"""The default behavior of Click is to apply a type on a value directly.
|
951 |
+
This works well in most cases, except for when `nargs` is set to a fixed
|
952 |
+
count and different types should be used for different items. In this
|
953 |
+
case the :class:`Tuple` type can be used. This type can only be used
|
954 |
+
if `nargs` is set to a fixed number.
|
955 |
+
|
956 |
+
For more information see :ref:`tuple-type`.
|
957 |
+
|
958 |
+
This can be selected by using a Python tuple literal as a type.
|
959 |
+
|
960 |
+
:param types: a list of types that should be used for the tuple items.
|
961 |
+
"""
|
962 |
+
|
963 |
+
def __init__(self, types: t.Sequence[t.Union[t.Type[t.Any], ParamType]]) -> None:
|
964 |
+
self.types: t.Sequence[ParamType] = [convert_type(ty) for ty in types]
|
965 |
+
|
966 |
+
def to_info_dict(self) -> t.Dict[str, t.Any]:
|
967 |
+
info_dict = super().to_info_dict()
|
968 |
+
info_dict["types"] = [t.to_info_dict() for t in self.types]
|
969 |
+
return info_dict
|
970 |
+
|
971 |
+
@property
|
972 |
+
def name(self) -> str: # type: ignore
|
973 |
+
return f"<{' '.join(ty.name for ty in self.types)}>"
|
974 |
+
|
975 |
+
@property
|
976 |
+
def arity(self) -> int: # type: ignore
|
977 |
+
return len(self.types)
|
978 |
+
|
979 |
+
def convert(
|
980 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
981 |
+
) -> t.Any:
|
982 |
+
len_type = len(self.types)
|
983 |
+
len_value = len(value)
|
984 |
+
|
985 |
+
if len_value != len_type:
|
986 |
+
self.fail(
|
987 |
+
ngettext(
|
988 |
+
"{len_type} values are required, but {len_value} was given.",
|
989 |
+
"{len_type} values are required, but {len_value} were given.",
|
990 |
+
len_value,
|
991 |
+
).format(len_type=len_type, len_value=len_value),
|
992 |
+
param=param,
|
993 |
+
ctx=ctx,
|
994 |
+
)
|
995 |
+
|
996 |
+
return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))
|
997 |
+
|
998 |
+
|
999 |
+
def convert_type(ty: t.Optional[t.Any], default: t.Optional[t.Any] = None) -> ParamType:
|
1000 |
+
"""Find the most appropriate :class:`ParamType` for the given Python
|
1001 |
+
type. If the type isn't provided, it can be inferred from a default
|
1002 |
+
value.
|
1003 |
+
"""
|
1004 |
+
guessed_type = False
|
1005 |
+
|
1006 |
+
if ty is None and default is not None:
|
1007 |
+
if isinstance(default, (tuple, list)):
|
1008 |
+
# If the default is empty, ty will remain None and will
|
1009 |
+
# return STRING.
|
1010 |
+
if default:
|
1011 |
+
item = default[0]
|
1012 |
+
|
1013 |
+
# A tuple of tuples needs to detect the inner types.
|
1014 |
+
# Can't call convert recursively because that would
|
1015 |
+
# incorrectly unwind the tuple to a single type.
|
1016 |
+
if isinstance(item, (tuple, list)):
|
1017 |
+
ty = tuple(map(type, item))
|
1018 |
+
else:
|
1019 |
+
ty = type(item)
|
1020 |
+
else:
|
1021 |
+
ty = type(default)
|
1022 |
+
|
1023 |
+
guessed_type = True
|
1024 |
+
|
1025 |
+
if isinstance(ty, tuple):
|
1026 |
+
return Tuple(ty)
|
1027 |
+
|
1028 |
+
if isinstance(ty, ParamType):
|
1029 |
+
return ty
|
1030 |
+
|
1031 |
+
if ty is str or ty is None:
|
1032 |
+
return STRING
|
1033 |
+
|
1034 |
+
if ty is int:
|
1035 |
+
return INT
|
1036 |
+
|
1037 |
+
if ty is float:
|
1038 |
+
return FLOAT
|
1039 |
+
|
1040 |
+
if ty is bool:
|
1041 |
+
return BOOL
|
1042 |
+
|
1043 |
+
if guessed_type:
|
1044 |
+
return STRING
|
1045 |
+
|
1046 |
+
if __debug__:
|
1047 |
+
try:
|
1048 |
+
if issubclass(ty, ParamType):
|
1049 |
+
raise AssertionError(
|
1050 |
+
f"Attempted to use an uninstantiated parameter type ({ty})."
|
1051 |
+
)
|
1052 |
+
except TypeError:
|
1053 |
+
# ty is an instance (correct), so issubclass fails.
|
1054 |
+
pass
|
1055 |
+
|
1056 |
+
return FuncParamType(ty)
|
1057 |
+
|
1058 |
+
|
1059 |
+
#: A dummy parameter type that just does nothing. From a user's
|
1060 |
+
#: perspective this appears to just be the same as `STRING` but
|
1061 |
+
#: internally no string conversion takes place if the input was bytes.
|
1062 |
+
#: This is usually useful when working with file paths as they can
|
1063 |
+
#: appear in bytes and unicode.
|
1064 |
+
#:
|
1065 |
+
#: For path related uses the :class:`Path` type is a better choice but
|
1066 |
+
#: there are situations where an unprocessed type is useful which is why
|
1067 |
+
#: it is is provided.
|
1068 |
+
#:
|
1069 |
+
#: .. versionadded:: 4.0
|
1070 |
+
UNPROCESSED = UnprocessedParamType()
|
1071 |
+
|
1072 |
+
#: A unicode string parameter type which is the implicit default. This
|
1073 |
+
#: can also be selected by using ``str`` as type.
|
1074 |
+
STRING = StringParamType()
|
1075 |
+
|
1076 |
+
#: An integer parameter. This can also be selected by using ``int`` as
|
1077 |
+
#: type.
|
1078 |
+
INT = IntParamType()
|
1079 |
+
|
1080 |
+
#: A floating point value parameter. This can also be selected by using
|
1081 |
+
#: ``float`` as type.
|
1082 |
+
FLOAT = FloatParamType()
|
1083 |
+
|
1084 |
+
#: A boolean parameter. This is the default for boolean flags. This can
|
1085 |
+
#: also be selected by using ``bool`` as a type.
|
1086 |
+
BOOL = BoolParamType()
|
1087 |
+
|
1088 |
+
#: A UUID parameter.
|
1089 |
+
UUID = UUIDParameterType()
|
llmeval-env/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
|
llmeval-env/lib/python3.10/site-packages/nltk/draw/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (688 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/draw/__pycache__/cfg.cpython-310.pyc
ADDED
Binary file (20.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/draw/__pycache__/dispersion.cpython-310.pyc
ADDED
Binary file (1.84 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/draw/__pycache__/table.cpython-310.pyc
ADDED
Binary file (38.3 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/draw/__pycache__/tree.cpython-310.pyc
ADDED
Binary file (28 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/draw/__pycache__/util.cpython-310.pyc
ADDED
Binary file (77.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/draw/cfg.py
ADDED
@@ -0,0 +1,859 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: CFG visualization
|
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()
|
llmeval-env/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 |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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()
|
llmeval-env/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 |
+
|
1127 |
+
|
1128 |
+
if __name__ == "__main__":
|
1129 |
+
demo()
|
llmeval-env/lib/python3.10/site-packages/nltk/draw/util.py
ADDED
@@ -0,0 +1,2575 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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__":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natural Language Toolkit: Language Models
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Authors: Ilia Kurenkov <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
"""
|
8 |
+
NLTK Language Modeling Module.
|
9 |
+
------------------------------
|
10 |
+
|
11 |
+
Currently this module covers only ngram language models, but it should be easy
|
12 |
+
to extend to neural models.
|
13 |
+
|
14 |
+
|
15 |
+
Preparing Data
|
16 |
+
==============
|
17 |
+
|
18 |
+
Before we train our ngram models it is necessary to make sure the data we put in
|
19 |
+
them is in the right format.
|
20 |
+
Let's say we have a text that is a list of sentences, where each sentence is
|
21 |
+
a list of strings. For simplicity we just consider a text consisting of
|
22 |
+
characters instead of words.
|
23 |
+
|
24 |
+
>>> text = [['a', 'b', 'c'], ['a', 'c', 'd', 'c', 'e', 'f']]
|
25 |
+
|
26 |
+
If we want to train a bigram model, we need to turn this text into bigrams.
|
27 |
+
Here's what the first sentence of our text would look like if we use a function
|
28 |
+
from NLTK for this.
|
29 |
+
|
30 |
+
>>> from nltk.util import bigrams
|
31 |
+
>>> list(bigrams(text[0]))
|
32 |
+
[('a', 'b'), ('b', 'c')]
|
33 |
+
|
34 |
+
Notice how "b" occurs both as the first and second member of different bigrams
|
35 |
+
but "a" and "c" don't? Wouldn't it be nice to somehow indicate how often sentences
|
36 |
+
start with "a" and end with "c"?
|
37 |
+
A standard way to deal with this is to add special "padding" symbols to the
|
38 |
+
sentence before splitting it into ngrams.
|
39 |
+
Fortunately, NLTK also has a function for that, let's see what it does to the
|
40 |
+
first sentence.
|
41 |
+
|
42 |
+
>>> from nltk.util import pad_sequence
|
43 |
+
>>> list(pad_sequence(text[0],
|
44 |
+
... pad_left=True,
|
45 |
+
... left_pad_symbol="<s>",
|
46 |
+
... pad_right=True,
|
47 |
+
... right_pad_symbol="</s>",
|
48 |
+
... n=2))
|
49 |
+
['<s>', 'a', 'b', 'c', '</s>']
|
50 |
+
|
51 |
+
Note the `n` argument, that tells the function we need padding for bigrams.
|
52 |
+
Now, passing all these parameters every time is tedious and in most cases they
|
53 |
+
can be safely assumed as defaults anyway.
|
54 |
+
Thus our module provides a convenience function that has all these arguments
|
55 |
+
already set while the other arguments remain the same as for `pad_sequence`.
|
56 |
+
|
57 |
+
>>> from nltk.lm.preprocessing import pad_both_ends
|
58 |
+
>>> list(pad_both_ends(text[0], n=2))
|
59 |
+
['<s>', 'a', 'b', 'c', '</s>']
|
60 |
+
|
61 |
+
Combining the two parts discussed so far we get the following preparation steps
|
62 |
+
for one sentence.
|
63 |
+
|
64 |
+
>>> list(bigrams(pad_both_ends(text[0], n=2)))
|
65 |
+
[('<s>', 'a'), ('a', 'b'), ('b', 'c'), ('c', '</s>')]
|
66 |
+
|
67 |
+
To make our model more robust we could also train it on unigrams (single words)
|
68 |
+
as well as bigrams, its main source of information.
|
69 |
+
NLTK once again helpfully provides a function called `everygrams`.
|
70 |
+
While not the most efficient, it is conceptually simple.
|
71 |
+
|
72 |
+
|
73 |
+
>>> from nltk.util import everygrams
|
74 |
+
>>> padded_bigrams = list(pad_both_ends(text[0], n=2))
|
75 |
+
>>> list(everygrams(padded_bigrams, max_len=2))
|
76 |
+
[('<s>',), ('<s>', 'a'), ('a',), ('a', 'b'), ('b',), ('b', 'c'), ('c',), ('c', '</s>'), ('</s>',)]
|
77 |
+
|
78 |
+
We are almost ready to start counting ngrams, just one more step left.
|
79 |
+
During training and evaluation our model will rely on a vocabulary that
|
80 |
+
defines which words are "known" to the model.
|
81 |
+
To create this vocabulary we need to pad our sentences (just like for counting
|
82 |
+
ngrams) and then combine the sentences into one flat stream of words.
|
83 |
+
|
84 |
+
>>> from nltk.lm.preprocessing import flatten
|
85 |
+
>>> list(flatten(pad_both_ends(sent, n=2) for sent in text))
|
86 |
+
['<s>', 'a', 'b', 'c', '</s>', '<s>', 'a', 'c', 'd', 'c', 'e', 'f', '</s>']
|
87 |
+
|
88 |
+
In most cases we want to use the same text as the source for both vocabulary
|
89 |
+
and ngram counts.
|
90 |
+
Now that we understand what this means for our preprocessing, we can simply import
|
91 |
+
a function that does everything for us.
|
92 |
+
|
93 |
+
>>> from nltk.lm.preprocessing import padded_everygram_pipeline
|
94 |
+
>>> train, vocab = padded_everygram_pipeline(2, text)
|
95 |
+
|
96 |
+
So as to avoid re-creating the text in memory, both `train` and `vocab` are lazy
|
97 |
+
iterators. They are evaluated on demand at training time.
|
98 |
+
|
99 |
+
|
100 |
+
Training
|
101 |
+
========
|
102 |
+
Having prepared our data we are ready to start training a model.
|
103 |
+
As a simple example, let us train a Maximum Likelihood Estimator (MLE).
|
104 |
+
We only need to specify the highest ngram order to instantiate it.
|
105 |
+
|
106 |
+
>>> from nltk.lm import MLE
|
107 |
+
>>> lm = MLE(2)
|
108 |
+
|
109 |
+
This automatically creates an empty vocabulary...
|
110 |
+
|
111 |
+
>>> len(lm.vocab)
|
112 |
+
0
|
113 |
+
|
114 |
+
... which gets filled as we fit the model.
|
115 |
+
|
116 |
+
>>> lm.fit(train, vocab)
|
117 |
+
>>> print(lm.vocab)
|
118 |
+
<Vocabulary with cutoff=1 unk_label='<UNK>' and 9 items>
|
119 |
+
>>> len(lm.vocab)
|
120 |
+
9
|
121 |
+
|
122 |
+
The vocabulary helps us handle words that have not occurred during training.
|
123 |
+
|
124 |
+
>>> lm.vocab.lookup(text[0])
|
125 |
+
('a', 'b', 'c')
|
126 |
+
>>> lm.vocab.lookup(["aliens", "from", "Mars"])
|
127 |
+
('<UNK>', '<UNK>', '<UNK>')
|
128 |
+
|
129 |
+
Moreover, in some cases we want to ignore words that we did see during training
|
130 |
+
but that didn't occur frequently enough, to provide us useful information.
|
131 |
+
You can tell the vocabulary to ignore such words.
|
132 |
+
To find out how that works, check out the docs for the `Vocabulary` class.
|
133 |
+
|
134 |
+
|
135 |
+
Using a Trained Model
|
136 |
+
=====================
|
137 |
+
When it comes to ngram models the training boils down to counting up the ngrams
|
138 |
+
from the training corpus.
|
139 |
+
|
140 |
+
>>> print(lm.counts)
|
141 |
+
<NgramCounter with 2 ngram orders and 24 ngrams>
|
142 |
+
|
143 |
+
This provides a convenient interface to access counts for unigrams...
|
144 |
+
|
145 |
+
>>> lm.counts['a']
|
146 |
+
2
|
147 |
+
|
148 |
+
...and bigrams (in this case "a b")
|
149 |
+
|
150 |
+
>>> lm.counts[['a']]['b']
|
151 |
+
1
|
152 |
+
|
153 |
+
And so on. However, the real purpose of training a language model is to have it
|
154 |
+
score how probable words are in certain contexts.
|
155 |
+
This being MLE, the model returns the item's relative frequency as its score.
|
156 |
+
|
157 |
+
>>> lm.score("a")
|
158 |
+
0.15384615384615385
|
159 |
+
|
160 |
+
Items that are not seen during training are mapped to the vocabulary's
|
161 |
+
"unknown label" token. This is "<UNK>" by default.
|
162 |
+
|
163 |
+
>>> lm.score("<UNK>") == lm.score("aliens")
|
164 |
+
True
|
165 |
+
|
166 |
+
Here's how you get the score for a word given some preceding context.
|
167 |
+
For example we want to know what is the chance that "b" is preceded by "a".
|
168 |
+
|
169 |
+
>>> lm.score("b", ["a"])
|
170 |
+
0.5
|
171 |
+
|
172 |
+
To avoid underflow when working with many small score values it makes sense to
|
173 |
+
take their logarithm.
|
174 |
+
For convenience this can be done with the `logscore` method.
|
175 |
+
|
176 |
+
>>> lm.logscore("a")
|
177 |
+
-2.700439718141092
|
178 |
+
|
179 |
+
Building on this method, we can also evaluate our model's cross-entropy and
|
180 |
+
perplexity with respect to sequences of ngrams.
|
181 |
+
|
182 |
+
>>> test = [('a', 'b'), ('c', 'd')]
|
183 |
+
>>> lm.entropy(test)
|
184 |
+
1.292481250360578
|
185 |
+
>>> lm.perplexity(test)
|
186 |
+
2.449489742783178
|
187 |
+
|
188 |
+
It is advisable to preprocess your test text exactly the same way as you did
|
189 |
+
the training text.
|
190 |
+
|
191 |
+
One cool feature of ngram models is that they can be used to generate text.
|
192 |
+
|
193 |
+
>>> lm.generate(1, random_seed=3)
|
194 |
+
'<s>'
|
195 |
+
>>> lm.generate(5, random_seed=3)
|
196 |
+
['<s>', 'a', 'b', 'c', 'd']
|
197 |
+
|
198 |
+
Provide `random_seed` if you want to consistently reproduce the same text all
|
199 |
+
other things being equal. Here we are using it to test the examples.
|
200 |
+
|
201 |
+
You can also condition your generation on some preceding text with the `context`
|
202 |
+
argument.
|
203 |
+
|
204 |
+
>>> lm.generate(5, text_seed=['c'], random_seed=3)
|
205 |
+
['</s>', 'c', 'd', 'c', 'd']
|
206 |
+
|
207 |
+
Note that an ngram model is restricted in how much preceding context it can
|
208 |
+
take into account. For example, a trigram model can only condition its output
|
209 |
+
on 2 preceding words. If you pass in a 4-word context, the first two words
|
210 |
+
will be ignored.
|
211 |
+
"""
|
212 |
+
|
213 |
+
from nltk.lm.counter import NgramCounter
|
214 |
+
from nltk.lm.models import (
|
215 |
+
MLE,
|
216 |
+
AbsoluteDiscountingInterpolated,
|
217 |
+
KneserNeyInterpolated,
|
218 |
+
Laplace,
|
219 |
+
Lidstone,
|
220 |
+
StupidBackoff,
|
221 |
+
WittenBellInterpolated,
|
222 |
+
)
|
223 |
+
from nltk.lm.vocabulary import Vocabulary
|
224 |
+
|
225 |
+
__all__ = [
|
226 |
+
"Vocabulary",
|
227 |
+
"NgramCounter",
|
228 |
+
"MLE",
|
229 |
+
"Lidstone",
|
230 |
+
"Laplace",
|
231 |
+
"WittenBellInterpolated",
|
232 |
+
"KneserNeyInterpolated",
|
233 |
+
"AbsoluteDiscountingInterpolated",
|
234 |
+
"StupidBackoff",
|
235 |
+
]
|
llmeval-env/lib/python3.10/site-packages/nltk/lm/__pycache__/api.cpython-310.pyc
ADDED
Binary file (8.27 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/lm/__pycache__/counter.cpython-310.pyc
ADDED
Binary file (5.49 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/lm/__pycache__/models.cpython-310.pyc
ADDED
Binary file (5.38 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/lm/__pycache__/preprocessing.cpython-310.pyc
ADDED
Binary file (1.84 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/lm/__pycache__/smoothing.cpython-310.pyc
ADDED
Binary file (5.34 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/lm/api.py
ADDED
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Language Models
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Authors: Ilia Kurenkov <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
"""Language Model Interface."""
|
8 |
+
|
9 |
+
import random
|
10 |
+
import warnings
|
11 |
+
from abc import ABCMeta, abstractmethod
|
12 |
+
from bisect import bisect
|
13 |
+
from itertools import accumulate
|
14 |
+
|
15 |
+
from nltk.lm.counter import NgramCounter
|
16 |
+
from nltk.lm.util import log_base2
|
17 |
+
from nltk.lm.vocabulary import Vocabulary
|
18 |
+
|
19 |
+
|
20 |
+
class Smoothing(metaclass=ABCMeta):
|
21 |
+
"""Ngram Smoothing Interface
|
22 |
+
|
23 |
+
Implements Chen & Goodman 1995's idea that all smoothing algorithms have
|
24 |
+
certain features in common. This should ideally allow smoothing algorithms to
|
25 |
+
work both with Backoff and Interpolation.
|
26 |
+
"""
|
27 |
+
|
28 |
+
def __init__(self, vocabulary, counter):
|
29 |
+
"""
|
30 |
+
:param vocabulary: The Ngram vocabulary object.
|
31 |
+
:type vocabulary: nltk.lm.vocab.Vocabulary
|
32 |
+
:param counter: The counts of the vocabulary items.
|
33 |
+
:type counter: nltk.lm.counter.NgramCounter
|
34 |
+
"""
|
35 |
+
self.vocab = vocabulary
|
36 |
+
self.counts = counter
|
37 |
+
|
38 |
+
@abstractmethod
|
39 |
+
def unigram_score(self, word):
|
40 |
+
raise NotImplementedError()
|
41 |
+
|
42 |
+
@abstractmethod
|
43 |
+
def alpha_gamma(self, word, context):
|
44 |
+
raise NotImplementedError()
|
45 |
+
|
46 |
+
|
47 |
+
def _mean(items):
|
48 |
+
"""Return average (aka mean) for sequence of items."""
|
49 |
+
return sum(items) / len(items)
|
50 |
+
|
51 |
+
|
52 |
+
def _random_generator(seed_or_generator):
|
53 |
+
if isinstance(seed_or_generator, random.Random):
|
54 |
+
return seed_or_generator
|
55 |
+
return random.Random(seed_or_generator)
|
56 |
+
|
57 |
+
|
58 |
+
def _weighted_choice(population, weights, random_generator=None):
|
59 |
+
"""Like random.choice, but with weights.
|
60 |
+
|
61 |
+
Heavily inspired by python 3.6 `random.choices`.
|
62 |
+
"""
|
63 |
+
if not population:
|
64 |
+
raise ValueError("Can't choose from empty population")
|
65 |
+
if len(population) != len(weights):
|
66 |
+
raise ValueError("The number of weights does not match the population")
|
67 |
+
cum_weights = list(accumulate(weights))
|
68 |
+
total = cum_weights[-1]
|
69 |
+
threshold = random_generator.random()
|
70 |
+
return population[bisect(cum_weights, total * threshold)]
|
71 |
+
|
72 |
+
|
73 |
+
class LanguageModel(metaclass=ABCMeta):
|
74 |
+
"""ABC for Language Models.
|
75 |
+
|
76 |
+
Cannot be directly instantiated itself.
|
77 |
+
|
78 |
+
"""
|
79 |
+
|
80 |
+
def __init__(self, order, vocabulary=None, counter=None):
|
81 |
+
"""Creates new LanguageModel.
|
82 |
+
|
83 |
+
:param vocabulary: If provided, this vocabulary will be used instead
|
84 |
+
of creating a new one when training.
|
85 |
+
:type vocabulary: `nltk.lm.Vocabulary` or None
|
86 |
+
:param counter: If provided, use this object to count ngrams.
|
87 |
+
:type counter: `nltk.lm.NgramCounter` or None
|
88 |
+
:param ngrams_fn: If given, defines how sentences in training text are turned to ngram
|
89 |
+
sequences.
|
90 |
+
:type ngrams_fn: function or None
|
91 |
+
:param pad_fn: If given, defines how sentences in training text are padded.
|
92 |
+
:type pad_fn: function or None
|
93 |
+
"""
|
94 |
+
self.order = order
|
95 |
+
if vocabulary and not isinstance(vocabulary, Vocabulary):
|
96 |
+
warnings.warn(
|
97 |
+
f"The `vocabulary` argument passed to {self.__class__.__name__!r} "
|
98 |
+
"must be an instance of `nltk.lm.Vocabulary`.",
|
99 |
+
stacklevel=3,
|
100 |
+
)
|
101 |
+
self.vocab = Vocabulary() if vocabulary is None else vocabulary
|
102 |
+
self.counts = NgramCounter() if counter is None else counter
|
103 |
+
|
104 |
+
def fit(self, text, vocabulary_text=None):
|
105 |
+
"""Trains the model on a text.
|
106 |
+
|
107 |
+
:param text: Training text as a sequence of sentences.
|
108 |
+
|
109 |
+
"""
|
110 |
+
if not self.vocab:
|
111 |
+
if vocabulary_text is None:
|
112 |
+
raise ValueError(
|
113 |
+
"Cannot fit without a vocabulary or text to create it from."
|
114 |
+
)
|
115 |
+
self.vocab.update(vocabulary_text)
|
116 |
+
self.counts.update(self.vocab.lookup(sent) for sent in text)
|
117 |
+
|
118 |
+
def score(self, word, context=None):
|
119 |
+
"""Masks out of vocab (OOV) words and computes their model score.
|
120 |
+
|
121 |
+
For model-specific logic of calculating scores, see the `unmasked_score`
|
122 |
+
method.
|
123 |
+
"""
|
124 |
+
return self.unmasked_score(
|
125 |
+
self.vocab.lookup(word), self.vocab.lookup(context) if context else None
|
126 |
+
)
|
127 |
+
|
128 |
+
@abstractmethod
|
129 |
+
def unmasked_score(self, word, context=None):
|
130 |
+
"""Score a word given some optional context.
|
131 |
+
|
132 |
+
Concrete models are expected to provide an implementation.
|
133 |
+
Note that this method does not mask its arguments with the OOV label.
|
134 |
+
Use the `score` method for that.
|
135 |
+
|
136 |
+
:param str word: Word for which we want the score
|
137 |
+
:param tuple(str) context: Context the word is in.
|
138 |
+
If `None`, compute unigram score.
|
139 |
+
:param context: tuple(str) or None
|
140 |
+
:rtype: float
|
141 |
+
"""
|
142 |
+
raise NotImplementedError()
|
143 |
+
|
144 |
+
def logscore(self, word, context=None):
|
145 |
+
"""Evaluate the log score of this word in this context.
|
146 |
+
|
147 |
+
The arguments are the same as for `score` and `unmasked_score`.
|
148 |
+
|
149 |
+
"""
|
150 |
+
return log_base2(self.score(word, context))
|
151 |
+
|
152 |
+
def context_counts(self, context):
|
153 |
+
"""Helper method for retrieving counts for a given context.
|
154 |
+
|
155 |
+
Assumes context has been checked and oov words in it masked.
|
156 |
+
:type context: tuple(str) or None
|
157 |
+
|
158 |
+
"""
|
159 |
+
return (
|
160 |
+
self.counts[len(context) + 1][context] if context else self.counts.unigrams
|
161 |
+
)
|
162 |
+
|
163 |
+
def entropy(self, text_ngrams):
|
164 |
+
"""Calculate cross-entropy of model for given evaluation text.
|
165 |
+
|
166 |
+
:param Iterable(tuple(str)) text_ngrams: A sequence of ngram tuples.
|
167 |
+
:rtype: float
|
168 |
+
|
169 |
+
"""
|
170 |
+
return -1 * _mean(
|
171 |
+
[self.logscore(ngram[-1], ngram[:-1]) for ngram in text_ngrams]
|
172 |
+
)
|
173 |
+
|
174 |
+
def perplexity(self, text_ngrams):
|
175 |
+
"""Calculates the perplexity of the given text.
|
176 |
+
|
177 |
+
This is simply 2 ** cross-entropy for the text, so the arguments are the same.
|
178 |
+
|
179 |
+
"""
|
180 |
+
return pow(2.0, self.entropy(text_ngrams))
|
181 |
+
|
182 |
+
def generate(self, num_words=1, text_seed=None, random_seed=None):
|
183 |
+
"""Generate words from the model.
|
184 |
+
|
185 |
+
:param int num_words: How many words to generate. By default 1.
|
186 |
+
:param text_seed: Generation can be conditioned on preceding context.
|
187 |
+
:param random_seed: A random seed or an instance of `random.Random`. If provided,
|
188 |
+
makes the random sampling part of generation reproducible.
|
189 |
+
:return: One (str) word or a list of words generated from model.
|
190 |
+
|
191 |
+
Examples:
|
192 |
+
|
193 |
+
>>> from nltk.lm import MLE
|
194 |
+
>>> lm = MLE(2)
|
195 |
+
>>> lm.fit([[("a", "b"), ("b", "c")]], vocabulary_text=['a', 'b', 'c'])
|
196 |
+
>>> lm.fit([[("a",), ("b",), ("c",)]])
|
197 |
+
>>> lm.generate(random_seed=3)
|
198 |
+
'a'
|
199 |
+
>>> lm.generate(text_seed=['a'])
|
200 |
+
'b'
|
201 |
+
|
202 |
+
"""
|
203 |
+
text_seed = [] if text_seed is None else list(text_seed)
|
204 |
+
random_generator = _random_generator(random_seed)
|
205 |
+
# This is the base recursion case.
|
206 |
+
if num_words == 1:
|
207 |
+
context = (
|
208 |
+
text_seed[-self.order + 1 :]
|
209 |
+
if len(text_seed) >= self.order
|
210 |
+
else text_seed
|
211 |
+
)
|
212 |
+
samples = self.context_counts(self.vocab.lookup(context))
|
213 |
+
while context and not samples:
|
214 |
+
context = context[1:] if len(context) > 1 else []
|
215 |
+
samples = self.context_counts(self.vocab.lookup(context))
|
216 |
+
# Sorting samples achieves two things:
|
217 |
+
# - reproducible randomness when sampling
|
218 |
+
# - turns Mapping into Sequence which `_weighted_choice` expects
|
219 |
+
samples = sorted(samples)
|
220 |
+
return _weighted_choice(
|
221 |
+
samples,
|
222 |
+
tuple(self.score(w, context) for w in samples),
|
223 |
+
random_generator,
|
224 |
+
)
|
225 |
+
# We build up text one word at a time using the preceding context.
|
226 |
+
generated = []
|
227 |
+
for _ in range(num_words):
|
228 |
+
generated.append(
|
229 |
+
self.generate(
|
230 |
+
num_words=1,
|
231 |
+
text_seed=text_seed + generated,
|
232 |
+
random_seed=random_generator,
|
233 |
+
)
|
234 |
+
)
|
235 |
+
return generated
|
llmeval-env/lib/python3.10/site-packages/nltk/lm/counter.py
ADDED
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Ilia Kurenkov <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
"""
|
8 |
+
Language Model Counter
|
9 |
+
----------------------
|
10 |
+
"""
|
11 |
+
|
12 |
+
from collections import defaultdict
|
13 |
+
from collections.abc import Sequence
|
14 |
+
|
15 |
+
from nltk.probability import ConditionalFreqDist, FreqDist
|
16 |
+
|
17 |
+
|
18 |
+
class NgramCounter:
|
19 |
+
"""Class for counting ngrams.
|
20 |
+
|
21 |
+
Will count any ngram sequence you give it ;)
|
22 |
+
|
23 |
+
First we need to make sure we are feeding the counter sentences of ngrams.
|
24 |
+
|
25 |
+
>>> text = [["a", "b", "c", "d"], ["a", "c", "d", "c"]]
|
26 |
+
>>> from nltk.util import ngrams
|
27 |
+
>>> text_bigrams = [ngrams(sent, 2) for sent in text]
|
28 |
+
>>> text_unigrams = [ngrams(sent, 1) for sent in text]
|
29 |
+
|
30 |
+
The counting itself is very simple.
|
31 |
+
|
32 |
+
>>> from nltk.lm import NgramCounter
|
33 |
+
>>> ngram_counts = NgramCounter(text_bigrams + text_unigrams)
|
34 |
+
|
35 |
+
You can conveniently access ngram counts using standard python dictionary notation.
|
36 |
+
String keys will give you unigram counts.
|
37 |
+
|
38 |
+
>>> ngram_counts['a']
|
39 |
+
2
|
40 |
+
>>> ngram_counts['aliens']
|
41 |
+
0
|
42 |
+
|
43 |
+
If you want to access counts for higher order ngrams, use a list or a tuple.
|
44 |
+
These are treated as "context" keys, so what you get is a frequency distribution
|
45 |
+
over all continuations after the given context.
|
46 |
+
|
47 |
+
>>> sorted(ngram_counts[['a']].items())
|
48 |
+
[('b', 1), ('c', 1)]
|
49 |
+
>>> sorted(ngram_counts[('a',)].items())
|
50 |
+
[('b', 1), ('c', 1)]
|
51 |
+
|
52 |
+
This is equivalent to specifying explicitly the order of the ngram (in this case
|
53 |
+
2 for bigram) and indexing on the context.
|
54 |
+
|
55 |
+
>>> ngram_counts[2][('a',)] is ngram_counts[['a']]
|
56 |
+
True
|
57 |
+
|
58 |
+
Note that the keys in `ConditionalFreqDist` cannot be lists, only tuples!
|
59 |
+
It is generally advisable to use the less verbose and more flexible square
|
60 |
+
bracket notation.
|
61 |
+
|
62 |
+
To get the count of the full ngram "a b", do this:
|
63 |
+
|
64 |
+
>>> ngram_counts[['a']]['b']
|
65 |
+
1
|
66 |
+
|
67 |
+
Specifying the ngram order as a number can be useful for accessing all ngrams
|
68 |
+
in that order.
|
69 |
+
|
70 |
+
>>> ngram_counts[2]
|
71 |
+
<ConditionalFreqDist with 4 conditions>
|
72 |
+
|
73 |
+
The keys of this `ConditionalFreqDist` are the contexts we discussed earlier.
|
74 |
+
Unigrams can also be accessed with a human-friendly alias.
|
75 |
+
|
76 |
+
>>> ngram_counts.unigrams is ngram_counts[1]
|
77 |
+
True
|
78 |
+
|
79 |
+
Similarly to `collections.Counter`, you can update counts after initialization.
|
80 |
+
|
81 |
+
>>> ngram_counts['e']
|
82 |
+
0
|
83 |
+
>>> ngram_counts.update([ngrams(["d", "e", "f"], 1)])
|
84 |
+
>>> ngram_counts['e']
|
85 |
+
1
|
86 |
+
|
87 |
+
"""
|
88 |
+
|
89 |
+
def __init__(self, ngram_text=None):
|
90 |
+
"""Creates a new NgramCounter.
|
91 |
+
|
92 |
+
If `ngram_text` is specified, counts ngrams from it, otherwise waits for
|
93 |
+
`update` method to be called explicitly.
|
94 |
+
|
95 |
+
:param ngram_text: Optional text containing sentences of ngrams, as for `update` method.
|
96 |
+
:type ngram_text: Iterable(Iterable(tuple(str))) or None
|
97 |
+
|
98 |
+
"""
|
99 |
+
self._counts = defaultdict(ConditionalFreqDist)
|
100 |
+
self._counts[1] = self.unigrams = FreqDist()
|
101 |
+
|
102 |
+
if ngram_text:
|
103 |
+
self.update(ngram_text)
|
104 |
+
|
105 |
+
def update(self, ngram_text):
|
106 |
+
"""Updates ngram counts from `ngram_text`.
|
107 |
+
|
108 |
+
Expects `ngram_text` to be a sequence of sentences (sequences).
|
109 |
+
Each sentence consists of ngrams as tuples of strings.
|
110 |
+
|
111 |
+
:param Iterable(Iterable(tuple(str))) ngram_text: Text containing sentences of ngrams.
|
112 |
+
:raises TypeError: if the ngrams are not tuples.
|
113 |
+
|
114 |
+
"""
|
115 |
+
|
116 |
+
for sent in ngram_text:
|
117 |
+
for ngram in sent:
|
118 |
+
if not isinstance(ngram, tuple):
|
119 |
+
raise TypeError(
|
120 |
+
"Ngram <{}> isn't a tuple, " "but {}".format(ngram, type(ngram))
|
121 |
+
)
|
122 |
+
|
123 |
+
ngram_order = len(ngram)
|
124 |
+
if ngram_order == 1:
|
125 |
+
self.unigrams[ngram[0]] += 1
|
126 |
+
continue
|
127 |
+
|
128 |
+
context, word = ngram[:-1], ngram[-1]
|
129 |
+
self[ngram_order][context][word] += 1
|
130 |
+
|
131 |
+
def N(self):
|
132 |
+
"""Returns grand total number of ngrams stored.
|
133 |
+
|
134 |
+
This includes ngrams from all orders, so some duplication is expected.
|
135 |
+
:rtype: int
|
136 |
+
|
137 |
+
>>> from nltk.lm import NgramCounter
|
138 |
+
>>> counts = NgramCounter([[("a", "b"), ("c",), ("d", "e")]])
|
139 |
+
>>> counts.N()
|
140 |
+
3
|
141 |
+
|
142 |
+
"""
|
143 |
+
return sum(val.N() for val in self._counts.values())
|
144 |
+
|
145 |
+
def __getitem__(self, item):
|
146 |
+
"""User-friendly access to ngram counts."""
|
147 |
+
if isinstance(item, int):
|
148 |
+
return self._counts[item]
|
149 |
+
elif isinstance(item, str):
|
150 |
+
return self._counts.__getitem__(1)[item]
|
151 |
+
elif isinstance(item, Sequence):
|
152 |
+
return self._counts.__getitem__(len(item) + 1)[tuple(item)]
|
153 |
+
|
154 |
+
def __str__(self):
|
155 |
+
return "<{} with {} ngram orders and {} ngrams>".format(
|
156 |
+
self.__class__.__name__, len(self._counts), self.N()
|
157 |
+
)
|
158 |
+
|
159 |
+
def __len__(self):
|
160 |
+
return self._counts.__len__()
|
161 |
+
|
162 |
+
def __contains__(self, item):
|
163 |
+
return item in self._counts
|
llmeval-env/lib/python3.10/site-packages/nltk/lm/models.py
ADDED
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Language Models
|
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 |
+
"""Language Models"""
|
9 |
+
|
10 |
+
from nltk.lm.api import LanguageModel, Smoothing
|
11 |
+
from nltk.lm.smoothing import AbsoluteDiscounting, KneserNey, WittenBell
|
12 |
+
|
13 |
+
|
14 |
+
class MLE(LanguageModel):
|
15 |
+
"""Class for providing MLE ngram model scores.
|
16 |
+
|
17 |
+
Inherits initialization from BaseNgramModel.
|
18 |
+
"""
|
19 |
+
|
20 |
+
def unmasked_score(self, word, context=None):
|
21 |
+
"""Returns the MLE score for a word given a context.
|
22 |
+
|
23 |
+
Args:
|
24 |
+
- word is expected to be a string
|
25 |
+
- context is expected to be something reasonably convertible to a tuple
|
26 |
+
"""
|
27 |
+
return self.context_counts(context).freq(word)
|
28 |
+
|
29 |
+
|
30 |
+
class Lidstone(LanguageModel):
|
31 |
+
"""Provides Lidstone-smoothed scores.
|
32 |
+
|
33 |
+
In addition to initialization arguments from BaseNgramModel also requires
|
34 |
+
a number by which to increase the counts, gamma.
|
35 |
+
"""
|
36 |
+
|
37 |
+
def __init__(self, gamma, *args, **kwargs):
|
38 |
+
super().__init__(*args, **kwargs)
|
39 |
+
self.gamma = gamma
|
40 |
+
|
41 |
+
def unmasked_score(self, word, context=None):
|
42 |
+
"""Add-one smoothing: Lidstone or Laplace.
|
43 |
+
|
44 |
+
To see what kind, look at `gamma` attribute on the class.
|
45 |
+
|
46 |
+
"""
|
47 |
+
counts = self.context_counts(context)
|
48 |
+
word_count = counts[word]
|
49 |
+
norm_count = counts.N()
|
50 |
+
return (word_count + self.gamma) / (norm_count + len(self.vocab) * self.gamma)
|
51 |
+
|
52 |
+
|
53 |
+
class Laplace(Lidstone):
|
54 |
+
"""Implements Laplace (add one) smoothing.
|
55 |
+
|
56 |
+
Initialization identical to BaseNgramModel because gamma is always 1.
|
57 |
+
"""
|
58 |
+
|
59 |
+
def __init__(self, *args, **kwargs):
|
60 |
+
super().__init__(1, *args, **kwargs)
|
61 |
+
|
62 |
+
|
63 |
+
class StupidBackoff(LanguageModel):
|
64 |
+
"""Provides StupidBackoff scores.
|
65 |
+
|
66 |
+
In addition to initialization arguments from BaseNgramModel also requires
|
67 |
+
a parameter alpha with which we scale the lower order probabilities.
|
68 |
+
Note that this is not a true probability distribution as scores for ngrams
|
69 |
+
of the same order do not sum up to unity.
|
70 |
+
"""
|
71 |
+
|
72 |
+
def __init__(self, alpha=0.4, *args, **kwargs):
|
73 |
+
super().__init__(*args, **kwargs)
|
74 |
+
self.alpha = alpha
|
75 |
+
|
76 |
+
def unmasked_score(self, word, context=None):
|
77 |
+
if not context:
|
78 |
+
# Base recursion
|
79 |
+
return self.counts.unigrams.freq(word)
|
80 |
+
counts = self.context_counts(context)
|
81 |
+
word_count = counts[word]
|
82 |
+
norm_count = counts.N()
|
83 |
+
if word_count > 0:
|
84 |
+
return word_count / norm_count
|
85 |
+
else:
|
86 |
+
return self.alpha * self.unmasked_score(word, context[1:])
|
87 |
+
|
88 |
+
|
89 |
+
class InterpolatedLanguageModel(LanguageModel):
|
90 |
+
"""Logic common to all interpolated language models.
|
91 |
+
|
92 |
+
The idea to abstract this comes from Chen & Goodman 1995.
|
93 |
+
Do not instantiate this class directly!
|
94 |
+
"""
|
95 |
+
|
96 |
+
def __init__(self, smoothing_cls, order, **kwargs):
|
97 |
+
params = kwargs.pop("params", {})
|
98 |
+
super().__init__(order, **kwargs)
|
99 |
+
self.estimator = smoothing_cls(self.vocab, self.counts, **params)
|
100 |
+
|
101 |
+
def unmasked_score(self, word, context=None):
|
102 |
+
if not context:
|
103 |
+
# The base recursion case: no context, we only have a unigram.
|
104 |
+
return self.estimator.unigram_score(word)
|
105 |
+
if not self.counts[context]:
|
106 |
+
# It can also happen that we have no data for this context.
|
107 |
+
# In that case we defer to the lower-order ngram.
|
108 |
+
# This is the same as setting alpha to 0 and gamma to 1.
|
109 |
+
alpha, gamma = 0, 1
|
110 |
+
else:
|
111 |
+
alpha, gamma = self.estimator.alpha_gamma(word, context)
|
112 |
+
return alpha + gamma * self.unmasked_score(word, context[1:])
|
113 |
+
|
114 |
+
|
115 |
+
class WittenBellInterpolated(InterpolatedLanguageModel):
|
116 |
+
"""Interpolated version of Witten-Bell smoothing."""
|
117 |
+
|
118 |
+
def __init__(self, order, **kwargs):
|
119 |
+
super().__init__(WittenBell, order, **kwargs)
|
120 |
+
|
121 |
+
|
122 |
+
class AbsoluteDiscountingInterpolated(InterpolatedLanguageModel):
|
123 |
+
"""Interpolated version of smoothing with absolute discount."""
|
124 |
+
|
125 |
+
def __init__(self, order, discount=0.75, **kwargs):
|
126 |
+
super().__init__(
|
127 |
+
AbsoluteDiscounting, order, params={"discount": discount}, **kwargs
|
128 |
+
)
|
129 |
+
|
130 |
+
|
131 |
+
class KneserNeyInterpolated(InterpolatedLanguageModel):
|
132 |
+
"""Interpolated version of Kneser-Ney smoothing."""
|
133 |
+
|
134 |
+
def __init__(self, order, discount=0.1, **kwargs):
|
135 |
+
if not (0 <= discount <= 1):
|
136 |
+
raise ValueError(
|
137 |
+
"Discount must be between 0 and 1 for probabilities to sum to unity."
|
138 |
+
)
|
139 |
+
super().__init__(
|
140 |
+
KneserNey, order, params={"discount": discount, "order": order}, **kwargs
|
141 |
+
)
|
llmeval-env/lib/python3.10/site-packages/nltk/lm/preprocessing.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Language Model Unit Tests
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Ilia Kurenkov <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
from functools import partial
|
8 |
+
from itertools import chain
|
9 |
+
|
10 |
+
from nltk.util import everygrams, pad_sequence
|
11 |
+
|
12 |
+
flatten = chain.from_iterable
|
13 |
+
pad_both_ends = partial(
|
14 |
+
pad_sequence,
|
15 |
+
pad_left=True,
|
16 |
+
left_pad_symbol="<s>",
|
17 |
+
pad_right=True,
|
18 |
+
right_pad_symbol="</s>",
|
19 |
+
)
|
20 |
+
pad_both_ends.__doc__ = """Pads both ends of a sentence to length specified by ngram order.
|
21 |
+
|
22 |
+
Following convention <s> pads the start of sentence </s> pads its end.
|
23 |
+
"""
|
24 |
+
|
25 |
+
|
26 |
+
def padded_everygrams(order, sentence):
|
27 |
+
"""Helper with some useful defaults.
|
28 |
+
|
29 |
+
Applies pad_both_ends to sentence and follows it up with everygrams.
|
30 |
+
"""
|
31 |
+
return everygrams(list(pad_both_ends(sentence, n=order)), max_len=order)
|
32 |
+
|
33 |
+
|
34 |
+
def padded_everygram_pipeline(order, text):
|
35 |
+
"""Default preprocessing for a sequence of sentences.
|
36 |
+
|
37 |
+
Creates two iterators:
|
38 |
+
|
39 |
+
- sentences padded and turned into sequences of `nltk.util.everygrams`
|
40 |
+
- sentences padded as above and chained together for a flat stream of words
|
41 |
+
|
42 |
+
:param order: Largest ngram length produced by `everygrams`.
|
43 |
+
:param text: Text to iterate over. Expected to be an iterable of sentences.
|
44 |
+
:type text: Iterable[Iterable[str]]
|
45 |
+
:return: iterator over text as ngrams, iterator over text as vocabulary data
|
46 |
+
"""
|
47 |
+
padding_fn = partial(pad_both_ends, n=order)
|
48 |
+
return (
|
49 |
+
(everygrams(list(padding_fn(sent)), max_len=order) for sent in text),
|
50 |
+
flatten(map(padding_fn, text)),
|
51 |
+
)
|
llmeval-env/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
|
llmeval-env/lib/python3.10/site-packages/nltk/lm/util.py
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Ilia Kurenkov <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
"""Language Model Utilities"""
|
8 |
+
|
9 |
+
from math import log
|
10 |
+
|
11 |
+
NEG_INF = float("-inf")
|
12 |
+
POS_INF = float("inf")
|
13 |
+
|
14 |
+
|
15 |
+
def log_base2(score):
|
16 |
+
"""Convenience function for computing logarithms with base 2."""
|
17 |
+
if score == 0.0:
|
18 |
+
return NEG_INF
|
19 |
+
return log(score, 2)
|
llmeval-env/lib/python3.10/site-packages/nltk/lm/vocabulary.py
ADDED
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Ilia Kurenkov <[email protected]>
|
5 |
+
# URL: <https://www.nltk.org/>
|
6 |
+
# For license information, see LICENSE.TXT
|
7 |
+
"""Language Model Vocabulary"""
|
8 |
+
|
9 |
+
import sys
|
10 |
+
from collections import Counter
|
11 |
+
from collections.abc import Iterable
|
12 |
+
from functools import singledispatch
|
13 |
+
from itertools import chain
|
14 |
+
|
15 |
+
|
16 |
+
@singledispatch
|
17 |
+
def _dispatched_lookup(words, vocab):
|
18 |
+
raise TypeError(f"Unsupported type for looking up in vocabulary: {type(words)}")
|
19 |
+
|
20 |
+
|
21 |
+
@_dispatched_lookup.register(Iterable)
|
22 |
+
def _(words, vocab):
|
23 |
+
"""Look up a sequence of words in the vocabulary.
|
24 |
+
|
25 |
+
Returns an iterator over looked up words.
|
26 |
+
|
27 |
+
"""
|
28 |
+
return tuple(_dispatched_lookup(w, vocab) for w in words)
|
29 |
+
|
30 |
+
|
31 |
+
@_dispatched_lookup.register(str)
|
32 |
+
def _string_lookup(word, vocab):
|
33 |
+
"""Looks up one word in the vocabulary."""
|
34 |
+
return word if word in vocab else vocab.unk_label
|
35 |
+
|
36 |
+
|
37 |
+
class Vocabulary:
|
38 |
+
"""Stores language model vocabulary.
|
39 |
+
|
40 |
+
Satisfies two common language modeling requirements for a vocabulary:
|
41 |
+
|
42 |
+
- When checking membership and calculating its size, filters items
|
43 |
+
by comparing their counts to a cutoff value.
|
44 |
+
- Adds a special "unknown" token which unseen words are mapped to.
|
45 |
+
|
46 |
+
>>> words = ['a', 'c', '-', 'd', 'c', 'a', 'b', 'r', 'a', 'c', 'd']
|
47 |
+
>>> from nltk.lm import Vocabulary
|
48 |
+
>>> vocab = Vocabulary(words, unk_cutoff=2)
|
49 |
+
|
50 |
+
Tokens with counts greater than or equal to the cutoff value will
|
51 |
+
be considered part of the vocabulary.
|
52 |
+
|
53 |
+
>>> vocab['c']
|
54 |
+
3
|
55 |
+
>>> 'c' in vocab
|
56 |
+
True
|
57 |
+
>>> vocab['d']
|
58 |
+
2
|
59 |
+
>>> 'd' in vocab
|
60 |
+
True
|
61 |
+
|
62 |
+
Tokens with frequency counts less than the cutoff value will be considered not
|
63 |
+
part of the vocabulary even though their entries in the count dictionary are
|
64 |
+
preserved.
|
65 |
+
|
66 |
+
>>> vocab['b']
|
67 |
+
1
|
68 |
+
>>> 'b' in vocab
|
69 |
+
False
|
70 |
+
>>> vocab['aliens']
|
71 |
+
0
|
72 |
+
>>> 'aliens' in vocab
|
73 |
+
False
|
74 |
+
|
75 |
+
Keeping the count entries for seen words allows us to change the cutoff value
|
76 |
+
without having to recalculate the counts.
|
77 |
+
|
78 |
+
>>> vocab2 = Vocabulary(vocab.counts, unk_cutoff=1)
|
79 |
+
>>> "b" in vocab2
|
80 |
+
True
|
81 |
+
|
82 |
+
The cutoff value influences not only membership checking but also the result of
|
83 |
+
getting the size of the vocabulary using the built-in `len`.
|
84 |
+
Note that while the number of keys in the vocabulary's counter stays the same,
|
85 |
+
the items in the vocabulary differ depending on the cutoff.
|
86 |
+
We use `sorted` to demonstrate because it keeps the order consistent.
|
87 |
+
|
88 |
+
>>> sorted(vocab2.counts)
|
89 |
+
['-', 'a', 'b', 'c', 'd', 'r']
|
90 |
+
>>> sorted(vocab2)
|
91 |
+
['-', '<UNK>', 'a', 'b', 'c', 'd', 'r']
|
92 |
+
>>> sorted(vocab.counts)
|
93 |
+
['-', 'a', 'b', 'c', 'd', 'r']
|
94 |
+
>>> sorted(vocab)
|
95 |
+
['<UNK>', 'a', 'c', 'd']
|
96 |
+
|
97 |
+
In addition to items it gets populated with, the vocabulary stores a special
|
98 |
+
token that stands in for so-called "unknown" items. By default it's "<UNK>".
|
99 |
+
|
100 |
+
>>> "<UNK>" in vocab
|
101 |
+
True
|
102 |
+
|
103 |
+
We can look up words in a vocabulary using its `lookup` method.
|
104 |
+
"Unseen" words (with counts less than cutoff) are looked up as the unknown label.
|
105 |
+
If given one word (a string) as an input, this method will return a string.
|
106 |
+
|
107 |
+
>>> vocab.lookup("a")
|
108 |
+
'a'
|
109 |
+
>>> vocab.lookup("aliens")
|
110 |
+
'<UNK>'
|
111 |
+
|
112 |
+
If given a sequence, it will return an tuple of the looked up words.
|
113 |
+
|
114 |
+
>>> vocab.lookup(["p", 'a', 'r', 'd', 'b', 'c'])
|
115 |
+
('<UNK>', 'a', '<UNK>', 'd', '<UNK>', 'c')
|
116 |
+
|
117 |
+
It's possible to update the counts after the vocabulary has been created.
|
118 |
+
In general, the interface is the same as that of `collections.Counter`.
|
119 |
+
|
120 |
+
>>> vocab['b']
|
121 |
+
1
|
122 |
+
>>> vocab.update(["b", "b", "c"])
|
123 |
+
>>> vocab['b']
|
124 |
+
3
|
125 |
+
"""
|
126 |
+
|
127 |
+
def __init__(self, counts=None, unk_cutoff=1, unk_label="<UNK>"):
|
128 |
+
"""Create a new Vocabulary.
|
129 |
+
|
130 |
+
:param counts: Optional iterable or `collections.Counter` instance to
|
131 |
+
pre-seed the Vocabulary. In case it is iterable, counts
|
132 |
+
are calculated.
|
133 |
+
:param int unk_cutoff: Words that occur less frequently than this value
|
134 |
+
are not considered part of the vocabulary.
|
135 |
+
:param unk_label: Label for marking words not part of vocabulary.
|
136 |
+
|
137 |
+
"""
|
138 |
+
self.unk_label = unk_label
|
139 |
+
if unk_cutoff < 1:
|
140 |
+
raise ValueError(f"Cutoff value cannot be less than 1. Got: {unk_cutoff}")
|
141 |
+
self._cutoff = unk_cutoff
|
142 |
+
|
143 |
+
self.counts = Counter()
|
144 |
+
self.update(counts if counts is not None else "")
|
145 |
+
|
146 |
+
@property
|
147 |
+
def cutoff(self):
|
148 |
+
"""Cutoff value.
|
149 |
+
|
150 |
+
Items with count below this value are not considered part of vocabulary.
|
151 |
+
|
152 |
+
"""
|
153 |
+
return self._cutoff
|
154 |
+
|
155 |
+
def update(self, *counter_args, **counter_kwargs):
|
156 |
+
"""Update vocabulary counts.
|
157 |
+
|
158 |
+
Wraps `collections.Counter.update` method.
|
159 |
+
|
160 |
+
"""
|
161 |
+
self.counts.update(*counter_args, **counter_kwargs)
|
162 |
+
self._len = sum(1 for _ in self)
|
163 |
+
|
164 |
+
def lookup(self, words):
|
165 |
+
"""Look up one or more words in the vocabulary.
|
166 |
+
|
167 |
+
If passed one word as a string will return that word or `self.unk_label`.
|
168 |
+
Otherwise will assume it was passed a sequence of words, will try to look
|
169 |
+
each of them up and return an iterator over the looked up words.
|
170 |
+
|
171 |
+
:param words: Word(s) to look up.
|
172 |
+
:type words: Iterable(str) or str
|
173 |
+
:rtype: generator(str) or str
|
174 |
+
:raises: TypeError for types other than strings or iterables
|
175 |
+
|
176 |
+
>>> from nltk.lm import Vocabulary
|
177 |
+
>>> vocab = Vocabulary(["a", "b", "c", "a", "b"], unk_cutoff=2)
|
178 |
+
>>> vocab.lookup("a")
|
179 |
+
'a'
|
180 |
+
>>> vocab.lookup("aliens")
|
181 |
+
'<UNK>'
|
182 |
+
>>> vocab.lookup(["a", "b", "c", ["x", "b"]])
|
183 |
+
('a', 'b', '<UNK>', ('<UNK>', 'b'))
|
184 |
+
|
185 |
+
"""
|
186 |
+
return _dispatched_lookup(words, self)
|
187 |
+
|
188 |
+
def __getitem__(self, item):
|
189 |
+
return self._cutoff if item == self.unk_label else self.counts[item]
|
190 |
+
|
191 |
+
def __contains__(self, item):
|
192 |
+
"""Only consider items with counts GE to cutoff as being in the
|
193 |
+
vocabulary."""
|
194 |
+
return self[item] >= self.cutoff
|
195 |
+
|
196 |
+
def __iter__(self):
|
197 |
+
"""Building on membership check define how to iterate over
|
198 |
+
vocabulary."""
|
199 |
+
return chain(
|
200 |
+
(item for item in self.counts if item in self),
|
201 |
+
[self.unk_label] if self.counts else [],
|
202 |
+
)
|
203 |
+
|
204 |
+
def __len__(self):
|
205 |
+
"""Computing size of vocabulary reflects the cutoff."""
|
206 |
+
return self._len
|
207 |
+
|
208 |
+
def __eq__(self, other):
|
209 |
+
return (
|
210 |
+
self.unk_label == other.unk_label
|
211 |
+
and self.cutoff == other.cutoff
|
212 |
+
and self.counts == other.counts
|
213 |
+
)
|
214 |
+
|
215 |
+
def __str__(self):
|
216 |
+
return "<{} with cutoff={} unk_label='{}' and {} items>".format(
|
217 |
+
self.__class__.__name__, self.cutoff, self.unk_label, len(self)
|
218 |
+
)
|
llmeval-env/lib/python3.10/site-packages/nltk/sentiment/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (384 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/sentiment/__pycache__/sentiment_analyzer.cpython-310.pyc
ADDED
Binary file (9.83 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/sentiment/__pycache__/util.cpython-310.pyc
ADDED
Binary file (22.2 kB). View file
|
|
llmeval-env/lib/python3.10/site-pack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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# Natural Language Toolkit: Sentiment Analyzer
|
3 |
+
#
|
4 |
+
# Copyright (C) 2001-2023 NLTK Project
|
5 |
+
# Author: Pierpaolo Pantone <[email protected]>
|
6 |
+
# URL: <https://www.nltk.org/>
|
7 |
+
# For license information, see LICENSE.TXT
|
8 |
+
|
9 |
+
"""
|
10 |
+
A SentimentAnalyzer is a tool to implement and facilitate Sentiment Analysis tasks
|
11 |
+
using NLTK features and classifiers, especially for teaching and demonstrative
|
12 |
+
purposes.
|
13 |
+
"""
|
14 |
+
|
15 |
+
import sys
|
16 |
+
from collections import defaultdict
|
17 |
+
|
18 |
+
from nltk.classify.util import accuracy as eval_accuracy
|
19 |
+
from nltk.classify.util import apply_features
|
20 |
+
from nltk.collocations import BigramCollocationFinder
|
21 |
+
from nltk.metrics import BigramAssocMeasures
|
22 |
+
from nltk.metrics import f_measure as eval_f_measure
|
23 |
+
from nltk.metrics import precision as eval_precision
|
24 |
+
from nltk.metrics import recall as eval_recall
|
25 |
+
from nltk.probability import FreqDist
|
26 |
+
|
27 |
+
|
28 |
+
class SentimentAnalyzer:
|
29 |
+
"""
|
30 |
+
A Sentiment Analysis tool based on machine learning approaches.
|
31 |
+
"""
|
32 |
+
|
33 |
+
def __init__(self, classifier=None):
|
34 |
+
self.feat_extractors = defaultdict(list)
|
35 |
+
self.classifier = classifier
|
36 |
+
|
37 |
+
def all_words(self, documents, labeled=None):
|
38 |
+
"""
|
39 |
+
Return all words/tokens from the documents (with duplicates).
|
40 |
+
|
41 |
+
:param documents: a list of (words, label) tuples.
|
42 |
+
:param labeled: if `True`, assume that each document is represented by a
|
43 |
+
(words, label) tuple: (list(str), str). If `False`, each document is
|
44 |
+
considered as being a simple list of strings: list(str).
|
45 |
+
:rtype: list(str)
|
46 |
+
:return: A list of all words/tokens in `documents`.
|
47 |
+
"""
|
48 |
+
all_words = []
|
49 |
+
if labeled is None:
|
50 |
+
labeled = documents and isinstance(documents[0], tuple)
|
51 |
+
if labeled:
|
52 |
+
for words, _sentiment in documents:
|
53 |
+
all_words.extend(words)
|
54 |
+
elif not labeled:
|
55 |
+
for words in documents:
|
56 |
+
all_words.extend(words)
|
57 |
+
return all_words
|
58 |
+
|
59 |
+
def apply_features(self, documents, labeled=None):
|
60 |
+
"""
|
61 |
+
Apply all feature extractor functions to the documents. This is a wrapper
|
62 |
+
around `nltk.classify.util.apply_features`.
|
63 |
+
|
64 |
+
If `labeled=False`, return featuresets as:
|
65 |
+
[feature_func(doc) for doc in documents]
|
66 |
+
If `labeled=True`, return featuresets as:
|
67 |
+
[(feature_func(tok), label) for (tok, label) in toks]
|
68 |
+
|
69 |
+
:param documents: a list of documents. `If labeled=True`, the method expects
|
70 |
+
a list of (words, label) tuples.
|
71 |
+
:rtype: LazyMap
|
72 |
+
"""
|
73 |
+
return apply_features(self.extract_features, documents, labeled)
|
74 |
+
|
75 |
+
def unigram_word_feats(self, words, top_n=None, min_freq=0):
|
76 |
+
"""
|
77 |
+
Return most common top_n word features.
|
78 |
+
|
79 |
+
:param words: a list of words/tokens.
|
80 |
+
:param top_n: number of best words/tokens to use, sorted by frequency.
|
81 |
+
:rtype: list(str)
|
82 |
+
:return: A list of `top_n` words/tokens (with no duplicates) sorted by
|
83 |
+
frequency.
|
84 |
+
"""
|
85 |
+
# Stopwords are not removed
|
86 |
+
unigram_feats_freqs = FreqDist(word for word in words)
|
87 |
+
return [
|
88 |
+
w
|
89 |
+
for w, f in unigram_feats_freqs.most_common(top_n)
|
90 |
+
if unigram_feats_freqs[w] > min_freq
|
91 |
+
]
|
92 |
+
|
93 |
+
def bigram_collocation_feats(
|
94 |
+
self, documents, top_n=None, min_freq=3, assoc_measure=BigramAssocMeasures.pmi
|
95 |
+
):
|
96 |
+
"""
|
97 |
+
Return `top_n` bigram features (using `assoc_measure`).
|
98 |
+
Note that this method is based on bigram collocations measures, and not
|
99 |
+
on simple bigram frequency.
|
100 |
+
|
101 |
+
:param documents: a list (or iterable) of tokens.
|
102 |
+
:param top_n: number of best words/tokens to use, sorted by association
|
103 |
+
measure.
|
104 |
+
:param assoc_measure: bigram association measure to use as score function.
|
105 |
+
:param min_freq: the minimum number of occurrencies of bigrams to take
|
106 |
+
into consideration.
|
107 |
+
|
108 |
+
:return: `top_n` ngrams scored by the given association measure.
|
109 |
+
"""
|
110 |
+
finder = BigramCollocationFinder.from_documents(documents)
|
111 |
+
finder.apply_freq_filter(min_freq)
|
112 |
+
return finder.nbest(assoc_measure, top_n)
|
113 |
+
|
114 |
+
def classify(self, instance):
|
115 |
+
"""
|
116 |
+
Classify a single instance applying the features that have already been
|
117 |
+
stored in the SentimentAnalyzer.
|
118 |
+
|
119 |
+
:param instance: a list (or iterable) of tokens.
|
120 |
+
:return: the classification result given by applying the classifier.
|
121 |
+
"""
|
122 |
+
instance_feats = self.apply_features([instance], labeled=False)
|
123 |
+
return self.classifier.classify(instance_feats[0])
|
124 |
+
|
125 |
+
def add_feat_extractor(self, function, **kwargs):
|
126 |
+
"""
|
127 |
+
Add a new function to extract features from a document. This function will
|
128 |
+
be used in extract_features().
|
129 |
+
Important: in this step our kwargs are only representing additional parameters,
|
130 |
+
and NOT the document we have to parse. The document will always be the first
|
131 |
+
parameter in the parameter list, and it will be added in the extract_features()
|
132 |
+
function.
|
133 |
+
|
134 |
+
:param function: the extractor function to add to the list of feature extractors.
|
135 |
+
:param kwargs: additional parameters required by the `function` function.
|
136 |
+
"""
|
137 |
+
self.feat_extractors[function].append(kwargs)
|
138 |
+
|
139 |
+
def extract_features(self, document):
|
140 |
+
"""
|
141 |
+
Apply extractor functions (and their parameters) to the present document.
|
142 |
+
We pass `document` as the first parameter of the extractor functions.
|
143 |
+
If we want to use the same extractor function multiple times, we have to
|
144 |
+
add it to the extractors with `add_feat_extractor` using multiple sets of
|
145 |
+
parameters (one for each call of the extractor function).
|
146 |
+
|
147 |
+
:param document: the document that will be passed as argument to the
|
148 |
+
feature extractor functions.
|
149 |
+
:return: A dictionary of populated features extracted from the document.
|
150 |
+
:rtype: dict
|
151 |
+
"""
|
152 |
+
all_features = {}
|
153 |
+
for extractor in self.feat_extractors:
|
154 |
+
for param_set in self.feat_extractors[extractor]:
|
155 |
+
feats = extractor(document, **param_set)
|
156 |
+
all_features.update(feats)
|
157 |
+
return all_features
|
158 |
+
|
159 |
+
def train(self, trainer, training_set, save_classifier=None, **kwargs):
|
160 |
+
"""
|
161 |
+
Train classifier on the training set, optionally saving the output in the
|
162 |
+
file specified by `save_classifier`.
|
163 |
+
Additional arguments depend on the specific trainer used. For example,
|
164 |
+
a MaxentClassifier can use `max_iter` parameter to specify the number
|
165 |
+
of iterations, while a NaiveBayesClassifier cannot.
|
166 |
+
|
167 |
+
:param trainer: `train` method of a classifier.
|
168 |
+
E.g.: NaiveBayesClassifier.train
|
169 |
+
:param training_set: the training set to be passed as argument to the
|
170 |
+
classifier `train` method.
|
171 |
+
:param save_classifier: the filename of the file where the classifier
|
172 |
+
will be stored (optional).
|
173 |
+
:param kwargs: additional parameters that will be passed as arguments to
|
174 |
+
the classifier `train` function.
|
175 |
+
:return: A classifier instance trained on the training set.
|
176 |
+
:rtype:
|
177 |
+
"""
|
178 |
+
print("Training classifier")
|
179 |
+
self.classifier = trainer(training_set, **kwargs)
|
180 |
+
if save_classifier:
|
181 |
+
self.save_file(self.classifier, save_classifier)
|
182 |
+
|
183 |
+
return self.classifier
|
184 |
+
|
185 |
+
def save_file(self, content, filename):
|
186 |
+
"""
|
187 |
+
Store `content` in `filename`. Can be used to store a SentimentAnalyzer.
|
188 |
+
"""
|
189 |
+
print("Saving", filename, file=sys.stderr)
|
190 |
+
with open(filename, "wb") as storage_file:
|
191 |
+
import pickle
|
192 |
+
|
193 |
+
# The protocol=2 parameter is for python2 compatibility
|
194 |
+
pickle.dump(content, storage_file, protocol=2)
|
195 |
+
|
196 |
+
def evaluate(
|
197 |
+
self,
|
198 |
+
test_set,
|
199 |
+
classifier=None,
|
200 |
+
accuracy=True,
|
201 |
+
f_measure=True,
|
202 |
+
precision=True,
|
203 |
+
recall=True,
|
204 |
+
verbose=False,
|
205 |
+
):
|
206 |
+
"""
|
207 |
+
Evaluate and print classifier performance on the test set.
|
208 |
+
|
209 |
+
:param test_set: A list of (tokens, label) tuples to use as gold set.
|
210 |
+
:param classifier: a classifier instance (previously trained).
|
211 |
+
:param accuracy: if `True`, evaluate classifier accuracy.
|
212 |
+
:param f_measure: if `True`, evaluate classifier f_measure.
|
213 |
+
:param precision: if `True`, evaluate classifier precision.
|
214 |
+
:param recall: if `True`, evaluate classifier recall.
|
215 |
+
:return: evaluation results.
|
216 |
+
:rtype: dict(str): float
|
217 |
+
"""
|
218 |
+
if classifier is None:
|
219 |
+
classifier = self.classifier
|
220 |
+
print(f"Evaluating {type(classifier).__name__} results...")
|
221 |
+
metrics_results = {}
|
222 |
+
if accuracy:
|
223 |
+
accuracy_score = eval_accuracy(classifier, test_set)
|
224 |
+
metrics_results["Accuracy"] = accuracy_score
|
225 |
+
|
226 |
+
gold_results = defaultdict(set)
|
227 |
+
test_results = defaultdict(set)
|
228 |
+
labels = set()
|
229 |
+
for i, (feats, label) in enumerate(test_set):
|
230 |
+
labels.add(label)
|
231 |
+
gold_results[label].add(i)
|
232 |
+
observed = classifier.classify(feats)
|
233 |
+
test_results[observed].add(i)
|
234 |
+
|
235 |
+
for label in labels:
|
236 |
+
if precision:
|
237 |
+
precision_score = eval_precision(
|
238 |
+
gold_results[label], test_results[label]
|
239 |
+
)
|
240 |
+
metrics_results[f"Precision [{label}]"] = precision_score
|
241 |
+
if recall:
|
242 |
+
recall_score = eval_recall(gold_results[label], test_results[label])
|
243 |
+
metrics_results[f"Recall [{label}]"] = recall_score
|
244 |
+
if f_measure:
|
245 |
+
f_measure_score = eval_f_measure(
|
246 |
+
gold_results[label], test_results[label]
|
247 |
+
)
|
248 |
+
metrics_results[f"F-measure [{label}]"] = f_measure_score
|
249 |
+
|
250 |
+
# Print evaluation results (in alphabetical order)
|
251 |
+
if verbose:
|
252 |
+
for result in sorted(metrics_results):
|
253 |
+
print(f"{result}: {metrics_results[result]}")
|
254 |
+
|
255 |
+
return metrics_results
|
llmeval-env/lib/python3.10/site-packages/nltk/sentiment/util.py
ADDED
@@ -0,0 +1,887 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# Natural Language Toolkit: Sentiment Analyzer
|
3 |
+
#
|
4 |
+
# Copyright (C) 2001-2023 NLTK Project
|
5 |
+
# Author: Pierpaolo Pantone <[email protected]>
|
6 |
+
# URL: <https://www.nltk.org/>
|
7 |
+
# For license information, see LICENSE.TXT
|
8 |
+
|
9 |
+
"""
|
10 |
+
Utility methods for Sentiment Analysis.
|
11 |
+
"""
|
12 |
+
|
13 |
+
import codecs
|
14 |
+
import csv
|
15 |
+
import json
|
16 |
+
import pickle
|
17 |
+
import random
|
18 |
+
import re
|
19 |
+
import sys
|
20 |
+
import time
|
21 |
+
from copy import deepcopy
|
22 |
+
|
23 |
+
import nltk
|
24 |
+
from nltk.corpus import CategorizedPlaintextCorpusReader
|
25 |
+
from nltk.data import load
|
26 |
+
from nltk.tokenize.casual import EMOTICON_RE
|
27 |
+
|
28 |
+
# ////////////////////////////////////////////////////////////
|
29 |
+
# { Regular expressions
|
30 |
+
# ////////////////////////////////////////////////////////////
|
31 |
+
|
32 |
+
# Regular expression for negation by Christopher Potts
|
33 |
+
NEGATION = r"""
|
34 |
+
(?:
|
35 |
+
^(?:never|no|nothing|nowhere|noone|none|not|
|
36 |
+
havent|hasnt|hadnt|cant|couldnt|shouldnt|
|
37 |
+
wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint
|
38 |
+
)$
|
39 |
+
)
|
40 |
+
|
|
41 |
+
n't"""
|
42 |
+
|
43 |
+
NEGATION_RE = re.compile(NEGATION, re.VERBOSE)
|
44 |
+
|
45 |
+
CLAUSE_PUNCT = r"^[.:;!?]$"
|
46 |
+
CLAUSE_PUNCT_RE = re.compile(CLAUSE_PUNCT)
|
47 |
+
|
48 |
+
# Happy and sad emoticons
|
49 |
+
|
50 |
+
HAPPY = {
|
51 |
+
":-)",
|
52 |
+
":)",
|
53 |
+
";)",
|
54 |
+
":o)",
|
55 |
+
":]",
|
56 |
+
":3",
|
57 |
+
":c)",
|
58 |
+
":>",
|
59 |
+
"=]",
|
60 |
+
"8)",
|
61 |
+
"=)",
|
62 |
+
":}",
|
63 |
+
":^)",
|
64 |
+
":-D",
|
65 |
+
":D",
|
66 |
+
"8-D",
|
67 |
+
"8D",
|
68 |
+
"x-D",
|
69 |
+
"xD",
|
70 |
+
"X-D",
|
71 |
+
"XD",
|
72 |
+
"=-D",
|
73 |
+
"=D",
|
74 |
+
"=-3",
|
75 |
+
"=3",
|
76 |
+
":-))",
|
77 |
+
":'-)",
|
78 |
+
":')",
|
79 |
+
":*",
|
80 |
+
":^*",
|
81 |
+
">:P",
|
82 |
+
":-P",
|
83 |
+
":P",
|
84 |
+
"X-P",
|
85 |
+
"x-p",
|
86 |
+
"xp",
|
87 |
+
"XP",
|
88 |
+
":-p",
|
89 |
+
":p",
|
90 |
+
"=p",
|
91 |
+
":-b",
|
92 |
+
":b",
|
93 |
+
">:)",
|
94 |
+
">;)",
|
95 |
+
">:-)",
|
96 |
+
"<3",
|
97 |
+
}
|
98 |
+
|
99 |
+
SAD = {
|
100 |
+
":L",
|
101 |
+
":-/",
|
102 |
+
">:/",
|
103 |
+
":S",
|
104 |
+
">:[",
|
105 |
+
":@",
|
106 |
+
":-(",
|
107 |
+
":[",
|
108 |
+
":-||",
|
109 |
+
"=L",
|
110 |
+
":<",
|
111 |
+
":-[",
|
112 |
+
":-<",
|
113 |
+
"=\\",
|
114 |
+
"=/",
|
115 |
+
">:(",
|
116 |
+
":(",
|
117 |
+
">.<",
|
118 |
+
":'-(",
|
119 |
+
":'(",
|
120 |
+
":\\",
|
121 |
+
":-c",
|
122 |
+
":c",
|
123 |
+
":{",
|
124 |
+
">:\\",
|
125 |
+
";(",
|
126 |
+
}
|
127 |
+
|
128 |
+
|
129 |
+
def timer(method):
|
130 |
+
"""
|
131 |
+
A timer decorator to measure execution performance of methods.
|
132 |
+
"""
|
133 |
+
|
134 |
+
def timed(*args, **kw):
|
135 |
+
start = time.time()
|
136 |
+
result = method(*args, **kw)
|
137 |
+
end = time.time()
|
138 |
+
tot_time = end - start
|
139 |
+
hours = tot_time // 3600
|
140 |
+
mins = tot_time // 60 % 60
|
141 |
+
# in Python 2.x round() will return a float, so we convert it to int
|
142 |
+
secs = int(round(tot_time % 60))
|
143 |
+
if hours == 0 and mins == 0 and secs < 10:
|
144 |
+
print(f"[TIMER] {method.__name__}(): {method.__name__:.3f} seconds")
|
145 |
+
else:
|
146 |
+
print(f"[TIMER] {method.__name__}(): {hours}h {mins}m {secs}s")
|
147 |
+
return result
|
148 |
+
|
149 |
+
return timed
|
150 |
+
|
151 |
+
|
152 |
+
# ////////////////////////////////////////////////////////////
|
153 |
+
# { Feature extractor functions
|
154 |
+
# ////////////////////////////////////////////////////////////
|
155 |
+
"""
|
156 |
+
Feature extractor functions are declared outside the SentimentAnalyzer class.
|
157 |
+
Users should have the possibility to create their own feature extractors
|
158 |
+
without modifying SentimentAnalyzer.
|
159 |
+
"""
|
160 |
+
|
161 |
+
|
162 |
+
def extract_unigram_feats(document, unigrams, handle_negation=False):
|
163 |
+
"""
|
164 |
+
Populate a dictionary of unigram features, reflecting the presence/absence in
|
165 |
+
the document of each of the tokens in `unigrams`.
|
166 |
+
|
167 |
+
:param document: a list of words/tokens.
|
168 |
+
:param unigrams: a list of words/tokens whose presence/absence has to be
|
169 |
+
checked in `document`.
|
170 |
+
:param handle_negation: if `handle_negation == True` apply `mark_negation`
|
171 |
+
method to `document` before checking for unigram presence/absence.
|
172 |
+
:return: a dictionary of unigram features {unigram : boolean}.
|
173 |
+
|
174 |
+
>>> words = ['ice', 'police', 'riot']
|
175 |
+
>>> document = 'ice is melting due to global warming'.split()
|
176 |
+
>>> sorted(extract_unigram_feats(document, words).items())
|
177 |
+
[('contains(ice)', True), ('contains(police)', False), ('contains(riot)', False)]
|
178 |
+
"""
|
179 |
+
features = {}
|
180 |
+
if handle_negation:
|
181 |
+
document = mark_negation(document)
|
182 |
+
for word in unigrams:
|
183 |
+
features[f"contains({word})"] = word in set(document)
|
184 |
+
return features
|
185 |
+
|
186 |
+
|
187 |
+
def extract_bigram_feats(document, bigrams):
|
188 |
+
"""
|
189 |
+
Populate a dictionary of bigram features, reflecting the presence/absence in
|
190 |
+
the document of each of the tokens in `bigrams`. This extractor function only
|
191 |
+
considers contiguous bigrams obtained by `nltk.bigrams`.
|
192 |
+
|
193 |
+
:param document: a list of words/tokens.
|
194 |
+
:param unigrams: a list of bigrams whose presence/absence has to be
|
195 |
+
checked in `document`.
|
196 |
+
:return: a dictionary of bigram features {bigram : boolean}.
|
197 |
+
|
198 |
+
>>> bigrams = [('global', 'warming'), ('police', 'prevented'), ('love', 'you')]
|
199 |
+
>>> document = 'ice is melting due to global warming'.split()
|
200 |
+
>>> sorted(extract_bigram_feats(document, bigrams).items()) # doctest: +NORMALIZE_WHITESPACE
|
201 |
+
[('contains(global - warming)', True), ('contains(love - you)', False),
|
202 |
+
('contains(police - prevented)', False)]
|
203 |
+
"""
|
204 |
+
features = {}
|
205 |
+
for bigr in bigrams:
|
206 |
+
features[f"contains({bigr[0]} - {bigr[1]})"] = bigr in nltk.bigrams(document)
|
207 |
+
return features
|
208 |
+
|
209 |
+
|
210 |
+
# ////////////////////////////////////////////////////////////
|
211 |
+
# { Helper Functions
|
212 |
+
# ////////////////////////////////////////////////////////////
|
213 |
+
|
214 |
+
|
215 |
+
def mark_negation(document, double_neg_flip=False, shallow=False):
|
216 |
+
"""
|
217 |
+
Append _NEG suffix to words that appear in the scope between a negation
|
218 |
+
and a punctuation mark.
|
219 |
+
|
220 |
+
:param document: a list of words/tokens, or a tuple (words, label).
|
221 |
+
:param shallow: if True, the method will modify the original document in place.
|
222 |
+
:param double_neg_flip: if True, double negation is considered affirmation
|
223 |
+
(we activate/deactivate negation scope every time we find a negation).
|
224 |
+
:return: if `shallow == True` the method will modify the original document
|
225 |
+
and return it. If `shallow == False` the method will return a modified
|
226 |
+
document, leaving the original unmodified.
|
227 |
+
|
228 |
+
>>> sent = "I didn't like this movie . It was bad .".split()
|
229 |
+
>>> mark_negation(sent)
|
230 |
+
['I', "didn't", 'like_NEG', 'this_NEG', 'movie_NEG', '.', 'It', 'was', 'bad', '.']
|
231 |
+
"""
|
232 |
+
if not shallow:
|
233 |
+
document = deepcopy(document)
|
234 |
+
# check if the document is labeled. If so, do not consider the label.
|
235 |
+
labeled = document and isinstance(document[0], (tuple, list))
|
236 |
+
if labeled:
|
237 |
+
doc = document[0]
|
238 |
+
else:
|
239 |
+
doc = document
|
240 |
+
neg_scope = False
|
241 |
+
for i, word in enumerate(doc):
|
242 |
+
if NEGATION_RE.search(word):
|
243 |
+
if not neg_scope or (neg_scope and double_neg_flip):
|
244 |
+
neg_scope = not neg_scope
|
245 |
+
continue
|
246 |
+
else:
|
247 |
+
doc[i] += "_NEG"
|
248 |
+
elif neg_scope and CLAUSE_PUNCT_RE.search(word):
|
249 |
+
neg_scope = not neg_scope
|
250 |
+
elif neg_scope and not CLAUSE_PUNCT_RE.search(word):
|
251 |
+
doc[i] += "_NEG"
|
252 |
+
|
253 |
+
return document
|
254 |
+
|
255 |
+
|
256 |
+
def output_markdown(filename, **kwargs):
|
257 |
+
"""
|
258 |
+
Write the output of an analysis to a file.
|
259 |
+
"""
|
260 |
+
with codecs.open(filename, "at") as outfile:
|
261 |
+
text = "\n*** \n\n"
|
262 |
+
text += "{} \n\n".format(time.strftime("%d/%m/%Y, %H:%M"))
|
263 |
+
for k in sorted(kwargs):
|
264 |
+
if isinstance(kwargs[k], dict):
|
265 |
+
dictionary = kwargs[k]
|
266 |
+
text += f" - **{k}:**\n"
|
267 |
+
for entry in sorted(dictionary):
|
268 |
+
text += f" - {entry}: {dictionary[entry]} \n"
|
269 |
+
elif isinstance(kwargs[k], list):
|
270 |
+
text += f" - **{k}:**\n"
|
271 |
+
for entry in kwargs[k]:
|
272 |
+
text += f" - {entry}\n"
|
273 |
+
else:
|
274 |
+
text += f" - **{k}:** {kwargs[k]} \n"
|
275 |
+
outfile.write(text)
|
276 |
+
|
277 |
+
|
278 |
+
def split_train_test(all_instances, n=None):
|
279 |
+
"""
|
280 |
+
Randomly split `n` instances of the dataset into train and test sets.
|
281 |
+
|
282 |
+
:param all_instances: a list of instances (e.g. documents) that will be split.
|
283 |
+
:param n: the number of instances to consider (in case we want to use only a
|
284 |
+
subset).
|
285 |
+
:return: two lists of instances. Train set is 8/10 of the total and test set
|
286 |
+
is 2/10 of the total.
|
287 |
+
"""
|
288 |
+
random.seed(12345)
|
289 |
+
random.shuffle(all_instances)
|
290 |
+
if not n or n > len(all_instances):
|
291 |
+
n = len(all_instances)
|
292 |
+
train_set = all_instances[: int(0.8 * n)]
|
293 |
+
test_set = all_instances[int(0.8 * n) : n]
|
294 |
+
|
295 |
+
return train_set, test_set
|
296 |
+
|
297 |
+
|
298 |
+
def _show_plot(x_values, y_values, x_labels=None, y_labels=None):
|
299 |
+
try:
|
300 |
+
import matplotlib.pyplot as plt
|
301 |
+
except ImportError as e:
|
302 |
+
raise ImportError(
|
303 |
+
"The plot function requires matplotlib to be installed."
|
304 |
+
"See https://matplotlib.org/"
|
305 |
+
) from e
|
306 |
+
|
307 |
+
plt.locator_params(axis="y", nbins=3)
|
308 |
+
axes = plt.axes()
|
309 |
+
axes.yaxis.grid()
|
310 |
+
plt.plot(x_values, y_values, "ro", color="red")
|
311 |
+
plt.ylim(ymin=-1.2, ymax=1.2)
|
312 |
+
plt.tight_layout(pad=5)
|
313 |
+
if x_labels:
|
314 |
+
plt.xticks(x_values, x_labels, rotation="vertical")
|
315 |
+
if y_labels:
|
316 |
+
plt.yticks([-1, 0, 1], y_labels, rotation="horizontal")
|
317 |
+
# Pad margins so that markers are not clipped by the axes
|
318 |
+
plt.margins(0.2)
|
319 |
+
plt.show()
|
320 |
+
|
321 |
+
|
322 |
+
# ////////////////////////////////////////////////////////////
|
323 |
+
# { Parsing and conversion functions
|
324 |
+
# ////////////////////////////////////////////////////////////
|
325 |
+
|
326 |
+
|
327 |
+
def json2csv_preprocess(
|
328 |
+
json_file,
|
329 |
+
outfile,
|
330 |
+
fields,
|
331 |
+
encoding="utf8",
|
332 |
+
errors="replace",
|
333 |
+
gzip_compress=False,
|
334 |
+
skip_retweets=True,
|
335 |
+
skip_tongue_tweets=True,
|
336 |
+
skip_ambiguous_tweets=True,
|
337 |
+
strip_off_emoticons=True,
|
338 |
+
remove_duplicates=True,
|
339 |
+
limit=None,
|
340 |
+
):
|
341 |
+
"""
|
342 |
+
Convert json file to csv file, preprocessing each row to obtain a suitable
|
343 |
+
dataset for tweets Semantic Analysis.
|
344 |
+
|
345 |
+
:param json_file: the original json file containing tweets.
|
346 |
+
:param outfile: the output csv filename.
|
347 |
+
:param fields: a list of fields that will be extracted from the json file and
|
348 |
+
kept in the output csv file.
|
349 |
+
:param encoding: the encoding of the files.
|
350 |
+
:param errors: the error handling strategy for the output writer.
|
351 |
+
:param gzip_compress: if True, create a compressed GZIP file.
|
352 |
+
|
353 |
+
:param skip_retweets: if True, remove retweets.
|
354 |
+
:param skip_tongue_tweets: if True, remove tweets containing ":P" and ":-P"
|
355 |
+
emoticons.
|
356 |
+
:param skip_ambiguous_tweets: if True, remove tweets containing both happy
|
357 |
+
and sad emoticons.
|
358 |
+
:param strip_off_emoticons: if True, strip off emoticons from all tweets.
|
359 |
+
:param remove_duplicates: if True, remove tweets appearing more than once.
|
360 |
+
:param limit: an integer to set the number of tweets to convert. After the
|
361 |
+
limit is reached the conversion will stop. It can be useful to create
|
362 |
+
subsets of the original tweets json data.
|
363 |
+
"""
|
364 |
+
with codecs.open(json_file, encoding=encoding) as fp:
|
365 |
+
(writer, outf) = _outf_writer(outfile, encoding, errors, gzip_compress)
|
366 |
+
# write the list of fields as header
|
367 |
+
writer.writerow(fields)
|
368 |
+
|
369 |
+
if remove_duplicates == True:
|
370 |
+
tweets_cache = []
|
371 |
+
i = 0
|
372 |
+
for line in fp:
|
373 |
+
tweet = json.loads(line)
|
374 |
+
row = extract_fields(tweet, fields)
|
375 |
+
try:
|
376 |
+
text = row[fields.index("text")]
|
377 |
+
# Remove retweets
|
378 |
+
if skip_retweets == True:
|
379 |
+
if re.search(r"\bRT\b", text):
|
380 |
+
continue
|
381 |
+
# Remove tweets containing ":P" and ":-P" emoticons
|
382 |
+
if skip_tongue_tweets == True:
|
383 |
+
if re.search(r"\:\-?P\b", text):
|
384 |
+
continue
|
385 |
+
# Remove tweets containing both happy and sad emoticons
|
386 |
+
if skip_ambiguous_tweets == True:
|
387 |
+
all_emoticons = EMOTICON_RE.findall(text)
|
388 |
+
if all_emoticons:
|
389 |
+
if (set(all_emoticons) & HAPPY) and (set(all_emoticons) & SAD):
|
390 |
+
continue
|
391 |
+
# Strip off emoticons from all tweets
|
392 |
+
if strip_off_emoticons == True:
|
393 |
+
row[fields.index("text")] = re.sub(
|
394 |
+
r"(?!\n)\s+", " ", EMOTICON_RE.sub("", text)
|
395 |
+
)
|
396 |
+
# Remove duplicate tweets
|
397 |
+
if remove_duplicates == True:
|
398 |
+
if row[fields.index("text")] in tweets_cache:
|
399 |
+
continue
|
400 |
+
else:
|
401 |
+
tweets_cache.append(row[fields.index("text")])
|
402 |
+
except ValueError:
|
403 |
+
pass
|
404 |
+
writer.writerow(row)
|
405 |
+
i += 1
|
406 |
+
if limit and i >= limit:
|
407 |
+
break
|
408 |
+
outf.close()
|
409 |
+
|
410 |
+
|
411 |
+
def parse_tweets_set(
|
412 |
+
filename, label, word_tokenizer=None, sent_tokenizer=None, skip_header=True
|
413 |
+
):
|
414 |
+
"""
|
415 |
+
Parse csv file containing tweets and output data a list of (text, label) tuples.
|
416 |
+
|
417 |
+
:param filename: the input csv filename.
|
418 |
+
:param label: the label to be appended to each tweet contained in the csv file.
|
419 |
+
:param word_tokenizer: the tokenizer instance that will be used to tokenize
|
420 |
+
each sentence into tokens (e.g. WordPunctTokenizer() or BlanklineTokenizer()).
|
421 |
+
If no word_tokenizer is specified, tweets will not be tokenized.
|
422 |
+
:param sent_tokenizer: the tokenizer that will be used to split each tweet into
|
423 |
+
sentences.
|
424 |
+
:param skip_header: if True, skip the first line of the csv file (which usually
|
425 |
+
contains headers).
|
426 |
+
|
427 |
+
:return: a list of (text, label) tuples.
|
428 |
+
"""
|
429 |
+
tweets = []
|
430 |
+
if not sent_tokenizer:
|
431 |
+
sent_tokenizer = load("tokenizers/punkt/english.pickle")
|
432 |
+
|
433 |
+
with codecs.open(filename, "rt") as csvfile:
|
434 |
+
reader = csv.reader(csvfile)
|
435 |
+
if skip_header == True:
|
436 |
+
next(reader, None) # skip the header
|
437 |
+
i = 0
|
438 |
+
for tweet_id, text in reader:
|
439 |
+
# text = text[1]
|
440 |
+
i += 1
|
441 |
+
sys.stdout.write(f"Loaded {i} tweets\r")
|
442 |
+
# Apply sentence and word tokenizer to text
|
443 |
+
if word_tokenizer:
|
444 |
+
tweet = [
|
445 |
+
w
|
446 |
+
for sent in sent_tokenizer.tokenize(text)
|
447 |
+
for w in word_tokenizer.tokenize(sent)
|
448 |
+
]
|
449 |
+
else:
|
450 |
+
tweet = text
|
451 |
+
tweets.append((tweet, label))
|
452 |
+
|
453 |
+
print(f"Loaded {i} tweets")
|
454 |
+
return tweets
|
455 |
+
|
456 |
+
|
457 |
+
# ////////////////////////////////////////////////////////////
|
458 |
+
# { Demos
|
459 |
+
# ////////////////////////////////////////////////////////////
|
460 |
+
|
461 |
+
|
462 |
+
def demo_tweets(trainer, n_instances=None, output=None):
|
463 |
+
"""
|
464 |
+
Train and test Naive Bayes classifier on 10000 tweets, tokenized using
|
465 |
+
TweetTokenizer.
|
466 |
+
Features are composed of:
|
467 |
+
|
468 |
+
- 1000 most frequent unigrams
|
469 |
+
- 100 top bigrams (using BigramAssocMeasures.pmi)
|
470 |
+
|
471 |
+
:param trainer: `train` method of a classifier.
|
472 |
+
:param n_instances: the number of total tweets that have to be used for
|
473 |
+
training and testing. Tweets will be equally split between positive and
|
474 |
+
negative.
|
475 |
+
:param output: the output file where results have to be reported.
|
476 |
+
"""
|
477 |
+
from nltk.corpus import stopwords, twitter_samples
|
478 |
+
from nltk.sentiment import SentimentAnalyzer
|
479 |
+
from nltk.tokenize import TweetTokenizer
|
480 |
+
|
481 |
+
# Different customizations for the TweetTokenizer
|
482 |
+
tokenizer = TweetTokenizer(preserve_case=False)
|
483 |
+
# tokenizer = TweetTokenizer(preserve_case=True, strip_handles=True)
|
484 |
+
# tokenizer = TweetTokenizer(reduce_len=True, strip_handles=True)
|
485 |
+
|
486 |
+
if n_instances is not None:
|
487 |
+
n_instances = int(n_instances / 2)
|
488 |
+
|
489 |
+
fields = ["id", "text"]
|
490 |
+
positive_json = twitter_samples.abspath("positive_tweets.json")
|
491 |
+
positive_csv = "positive_tweets.csv"
|
492 |
+
json2csv_preprocess(positive_json, positive_csv, fields, limit=n_instances)
|
493 |
+
|
494 |
+
negative_json = twitter_samples.abspath("negative_tweets.json")
|
495 |
+
negative_csv = "negative_tweets.csv"
|
496 |
+
json2csv_preprocess(negative_json, negative_csv, fields, limit=n_instances)
|
497 |
+
|
498 |
+
neg_docs = parse_tweets_set(negative_csv, label="neg", word_tokenizer=tokenizer)
|
499 |
+
pos_docs = parse_tweets_set(positive_csv, label="pos", word_tokenizer=tokenizer)
|
500 |
+
|
501 |
+
# We separately split subjective and objective instances to keep a balanced
|
502 |
+
# uniform class distribution in both train and test sets.
|
503 |
+
train_pos_docs, test_pos_docs = split_train_test(pos_docs)
|
504 |
+
train_neg_docs, test_neg_docs = split_train_test(neg_docs)
|
505 |
+
|
506 |
+
training_tweets = train_pos_docs + train_neg_docs
|
507 |
+
testing_tweets = test_pos_docs + test_neg_docs
|
508 |
+
|
509 |
+
sentim_analyzer = SentimentAnalyzer()
|
510 |
+
# stopwords = stopwords.words('english')
|
511 |
+
# all_words = [word for word in sentim_analyzer.all_words(training_tweets) if word.lower() not in stopwords]
|
512 |
+
all_words = [word for word in sentim_analyzer.all_words(training_tweets)]
|
513 |
+
|
514 |
+
# Add simple unigram word features
|
515 |
+
unigram_feats = sentim_analyzer.unigram_word_feats(all_words, top_n=1000)
|
516 |
+
sentim_analyzer.add_feat_extractor(extract_unigram_feats, unigrams=unigram_feats)
|
517 |
+
|
518 |
+
# Add bigram collocation features
|
519 |
+
bigram_collocs_feats = sentim_analyzer.bigram_collocation_feats(
|
520 |
+
[tweet[0] for tweet in training_tweets], top_n=100, min_freq=12
|
521 |
+
)
|
522 |
+
sentim_analyzer.add_feat_extractor(
|
523 |
+
extract_bigram_feats, bigrams=bigram_collocs_feats
|
524 |
+
)
|
525 |
+
|
526 |
+
training_set = sentim_analyzer.apply_features(training_tweets)
|
527 |
+
test_set = sentim_analyzer.apply_features(testing_tweets)
|
528 |
+
|
529 |
+
classifier = sentim_analyzer.train(trainer, training_set)
|
530 |
+
# classifier = sentim_analyzer.train(trainer, training_set, max_iter=4)
|
531 |
+
try:
|
532 |
+
classifier.show_most_informative_features()
|
533 |
+
except AttributeError:
|
534 |
+
print(
|
535 |
+
"Your classifier does not provide a show_most_informative_features() method."
|
536 |
+
)
|
537 |
+
results = sentim_analyzer.evaluate(test_set)
|
538 |
+
|
539 |
+
if output:
|
540 |
+
extr = [f.__name__ for f in sentim_analyzer.feat_extractors]
|
541 |
+
output_markdown(
|
542 |
+
output,
|
543 |
+
Dataset="labeled_tweets",
|
544 |
+
Classifier=type(classifier).__name__,
|
545 |
+
Tokenizer=tokenizer.__class__.__name__,
|
546 |
+
Feats=extr,
|
547 |
+
Results=results,
|
548 |
+
Instances=n_instances,
|
549 |
+
)
|
550 |
+
|
551 |
+
|
552 |
+
def demo_movie_reviews(trainer, n_instances=None, output=None):
|
553 |
+
"""
|
554 |
+
Train classifier on all instances of the Movie Reviews dataset.
|
555 |
+
The corpus has been preprocessed using the default sentence tokenizer and
|
556 |
+
WordPunctTokenizer.
|
557 |
+
Features are composed of:
|
558 |
+
|
559 |
+
- most frequent unigrams
|
560 |
+
|
561 |
+
:param trainer: `train` method of a classifier.
|
562 |
+
:param n_instances: the number of total reviews that have to be used for
|
563 |
+
training and testing. Reviews will be equally split between positive and
|
564 |
+
negative.
|
565 |
+
:param output: the output file where results have to be reported.
|
566 |
+
"""
|
567 |
+
from nltk.corpus import movie_reviews
|
568 |
+
from nltk.sentiment import SentimentAnalyzer
|
569 |
+
|
570 |
+
if n_instances is not None:
|
571 |
+
n_instances = int(n_instances / 2)
|
572 |
+
|
573 |
+
pos_docs = [
|
574 |
+
(list(movie_reviews.words(pos_id)), "pos")
|
575 |
+
for pos_id in movie_reviews.fileids("pos")[:n_instances]
|
576 |
+
]
|
577 |
+
neg_docs = [
|
578 |
+
(list(movie_reviews.words(neg_id)), "neg")
|
579 |
+
for neg_id in movie_reviews.fileids("neg")[:n_instances]
|
580 |
+
]
|
581 |
+
# We separately split positive and negative instances to keep a balanced
|
582 |
+
# uniform class distribution in both train and test sets.
|
583 |
+
train_pos_docs, test_pos_docs = split_train_test(pos_docs)
|
584 |
+
train_neg_docs, test_neg_docs = split_train_test(neg_docs)
|
585 |
+
|
586 |
+
training_docs = train_pos_docs + train_neg_docs
|
587 |
+
testing_docs = test_pos_docs + test_neg_docs
|
588 |
+
|
589 |
+
sentim_analyzer = SentimentAnalyzer()
|
590 |
+
all_words = sentim_analyzer.all_words(training_docs)
|
591 |
+
|
592 |
+
# Add simple unigram word features
|
593 |
+
unigram_feats = sentim_analyzer.unigram_word_feats(all_words, min_freq=4)
|
594 |
+
sentim_analyzer.add_feat_extractor(extract_unigram_feats, unigrams=unigram_feats)
|
595 |
+
# Apply features to obtain a feature-value representation of our datasets
|
596 |
+
training_set = sentim_analyzer.apply_features(training_docs)
|
597 |
+
test_set = sentim_analyzer.apply_features(testing_docs)
|
598 |
+
|
599 |
+
classifier = sentim_analyzer.train(trainer, training_set)
|
600 |
+
try:
|
601 |
+
classifier.show_most_informative_features()
|
602 |
+
except AttributeError:
|
603 |
+
print(
|
604 |
+
"Your classifier does not provide a show_most_informative_features() method."
|
605 |
+
)
|
606 |
+
results = sentim_analyzer.evaluate(test_set)
|
607 |
+
|
608 |
+
if output:
|
609 |
+
extr = [f.__name__ for f in sentim_analyzer.feat_extractors]
|
610 |
+
output_markdown(
|
611 |
+
output,
|
612 |
+
Dataset="Movie_reviews",
|
613 |
+
Classifier=type(classifier).__name__,
|
614 |
+
Tokenizer="WordPunctTokenizer",
|
615 |
+
Feats=extr,
|
616 |
+
Results=results,
|
617 |
+
Instances=n_instances,
|
618 |
+
)
|
619 |
+
|
620 |
+
|
621 |
+
def demo_subjectivity(trainer, save_analyzer=False, n_instances=None, output=None):
|
622 |
+
"""
|
623 |
+
Train and test a classifier on instances of the Subjective Dataset by Pang and
|
624 |
+
Lee. The dataset is made of 5000 subjective and 5000 objective sentences.
|
625 |
+
All tokens (words and punctuation marks) are separated by a whitespace, so
|
626 |
+
we use the basic WhitespaceTokenizer to parse the data.
|
627 |
+
|
628 |
+
:param trainer: `train` method of a classifier.
|
629 |
+
:param save_analyzer: if `True`, store the SentimentAnalyzer in a pickle file.
|
630 |
+
:param n_instances: the number of total sentences that have to be used for
|
631 |
+
training and testing. Sentences will be equally split between positive
|
632 |
+
and negative.
|
633 |
+
:param output: the output file where results have to be reported.
|
634 |
+
"""
|
635 |
+
from nltk.corpus import subjectivity
|
636 |
+
from nltk.sentiment import SentimentAnalyzer
|
637 |
+
|
638 |
+
if n_instances is not None:
|
639 |
+
n_instances = int(n_instances / 2)
|
640 |
+
|
641 |
+
subj_docs = [
|
642 |
+
(sent, "subj") for sent in subjectivity.sents(categories="subj")[:n_instances]
|
643 |
+
]
|
644 |
+
obj_docs = [
|
645 |
+
(sent, "obj") for sent in subjectivity.sents(categories="obj")[:n_instances]
|
646 |
+
]
|
647 |
+
|
648 |
+
# We separately split subjective and objective instances to keep a balanced
|
649 |
+
# uniform class distribution in both train and test sets.
|
650 |
+
train_subj_docs, test_subj_docs = split_train_test(subj_docs)
|
651 |
+
train_obj_docs, test_obj_docs = split_train_test(obj_docs)
|
652 |
+
|
653 |
+
training_docs = train_subj_docs + train_obj_docs
|
654 |
+
testing_docs = test_subj_docs + test_obj_docs
|
655 |
+
|
656 |
+
sentim_analyzer = SentimentAnalyzer()
|
657 |
+
all_words_neg = sentim_analyzer.all_words(
|
658 |
+
[mark_negation(doc) for doc in training_docs]
|
659 |
+
)
|
660 |
+
|
661 |
+
# Add simple unigram word features handling negation
|
662 |
+
unigram_feats = sentim_analyzer.unigram_word_feats(all_words_neg, min_freq=4)
|
663 |
+
sentim_analyzer.add_feat_extractor(extract_unigram_feats, unigrams=unigram_feats)
|
664 |
+
|
665 |
+
# Apply features to obtain a feature-value representation of our datasets
|
666 |
+
training_set = sentim_analyzer.apply_features(training_docs)
|
667 |
+
test_set = sentim_analyzer.apply_features(testing_docs)
|
668 |
+
|
669 |
+
classifier = sentim_analyzer.train(trainer, training_set)
|
670 |
+
try:
|
671 |
+
classifier.show_most_informative_features()
|
672 |
+
except AttributeError:
|
673 |
+
print(
|
674 |
+
"Your classifier does not provide a show_most_informative_features() method."
|
675 |
+
)
|
676 |
+
results = sentim_analyzer.evaluate(test_set)
|
677 |
+
|
678 |
+
if save_analyzer == True:
|
679 |
+
sentim_analyzer.save_file(sentim_analyzer, "sa_subjectivity.pickle")
|
680 |
+
|
681 |
+
if output:
|
682 |
+
extr = [f.__name__ for f in sentim_analyzer.feat_extractors]
|
683 |
+
output_markdown(
|
684 |
+
output,
|
685 |
+
Dataset="subjectivity",
|
686 |
+
Classifier=type(classifier).__name__,
|
687 |
+
Tokenizer="WhitespaceTokenizer",
|
688 |
+
Feats=extr,
|
689 |
+
Instances=n_instances,
|
690 |
+
Results=results,
|
691 |
+
)
|
692 |
+
|
693 |
+
return sentim_analyzer
|
694 |
+
|
695 |
+
|
696 |
+
def demo_sent_subjectivity(text):
|
697 |
+
"""
|
698 |
+
Classify a single sentence as subjective or objective using a stored
|
699 |
+
SentimentAnalyzer.
|
700 |
+
|
701 |
+
:param text: a sentence whose subjectivity has to be classified.
|
702 |
+
"""
|
703 |
+
from nltk.classify import NaiveBayesClassifier
|
704 |
+
from nltk.tokenize import regexp
|
705 |
+
|
706 |
+
word_tokenizer = regexp.WhitespaceTokenizer()
|
707 |
+
try:
|
708 |
+
sentim_analyzer = load("sa_subjectivity.pickle")
|
709 |
+
except LookupError:
|
710 |
+
print("Cannot find the sentiment analyzer you want to load.")
|
711 |
+
print("Training a new one using NaiveBayesClassifier.")
|
712 |
+
sentim_analyzer = demo_subjectivity(NaiveBayesClassifier.train, True)
|
713 |
+
|
714 |
+
# Tokenize and convert to lower case
|
715 |
+
tokenized_text = [word.lower() for word in word_tokenizer.tokenize(text)]
|
716 |
+
print(sentim_analyzer.classify(tokenized_text))
|
717 |
+
|
718 |
+
|
719 |
+
def demo_liu_hu_lexicon(sentence, plot=False):
|
720 |
+
"""
|
721 |
+
Basic example of sentiment classification using Liu and Hu opinion lexicon.
|
722 |
+
This function simply counts the number of positive, negative and neutral words
|
723 |
+
in the sentence and classifies it depending on which polarity is more represented.
|
724 |
+
Words that do not appear in the lexicon are considered as neutral.
|
725 |
+
|
726 |
+
:param sentence: a sentence whose polarity has to be classified.
|
727 |
+
:param plot: if True, plot a visual representation of the sentence polarity.
|
728 |
+
"""
|
729 |
+
from nltk.corpus import opinion_lexicon
|
730 |
+
from nltk.tokenize import treebank
|
731 |
+
|
732 |
+
tokenizer = treebank.TreebankWordTokenizer()
|
733 |
+
pos_words = 0
|
734 |
+
neg_words = 0
|
735 |
+
tokenized_sent = [word.lower() for word in tokenizer.tokenize(sentence)]
|
736 |
+
|
737 |
+
x = list(range(len(tokenized_sent))) # x axis for the plot
|
738 |
+
y = []
|
739 |
+
|
740 |
+
for word in tokenized_sent:
|
741 |
+
if word in opinion_lexicon.positive():
|
742 |
+
pos_words += 1
|
743 |
+
y.append(1) # positive
|
744 |
+
elif word in opinion_lexicon.negative():
|
745 |
+
neg_words += 1
|
746 |
+
y.append(-1) # negative
|
747 |
+
else:
|
748 |
+
y.append(0) # neutral
|
749 |
+
|
750 |
+
if pos_words > neg_words:
|
751 |
+
print("Positive")
|
752 |
+
elif pos_words < neg_words:
|
753 |
+
print("Negative")
|
754 |
+
elif pos_words == neg_words:
|
755 |
+
print("Neutral")
|
756 |
+
|
757 |
+
if plot == True:
|
758 |
+
_show_plot(
|
759 |
+
x, y, x_labels=tokenized_sent, y_labels=["Negative", "Neutral", "Positive"]
|
760 |
+
)
|
761 |
+
|
762 |
+
|
763 |
+
def demo_vader_instance(text):
|
764 |
+
"""
|
765 |
+
Output polarity scores for a text using Vader approach.
|
766 |
+
|
767 |
+
:param text: a text whose polarity has to be evaluated.
|
768 |
+
"""
|
769 |
+
from nltk.sentiment import SentimentIntensityAnalyzer
|
770 |
+
|
771 |
+
vader_analyzer = SentimentIntensityAnalyzer()
|
772 |
+
print(vader_analyzer.polarity_scores(text))
|
773 |
+
|
774 |
+
|
775 |
+
def demo_vader_tweets(n_instances=None, output=None):
|
776 |
+
"""
|
777 |
+
Classify 10000 positive and negative tweets using Vader approach.
|
778 |
+
|
779 |
+
:param n_instances: the number of total tweets that have to be classified.
|
780 |
+
:param output: the output file where results have to be reported.
|
781 |
+
"""
|
782 |
+
from collections import defaultdict
|
783 |
+
|
784 |
+
from nltk.corpus import twitter_samples
|
785 |
+
from nltk.metrics import accuracy as eval_accuracy
|
786 |
+
from nltk.metrics import f_measure as eval_f_measure
|
787 |
+
from nltk.metrics import precision as eval_precision
|
788 |
+
from nltk.metrics import recall as eval_recall
|
789 |
+
from nltk.sentiment import SentimentIntensityAnalyzer
|
790 |
+
|
791 |
+
if n_instances is not None:
|
792 |
+
n_instances = int(n_instances / 2)
|
793 |
+
|
794 |
+
fields = ["id", "text"]
|
795 |
+
positive_json = twitter_samples.abspath("positive_tweets.json")
|
796 |
+
positive_csv = "positive_tweets.csv"
|
797 |
+
json2csv_preprocess(
|
798 |
+
positive_json,
|
799 |
+
positive_csv,
|
800 |
+
fields,
|
801 |
+
strip_off_emoticons=False,
|
802 |
+
limit=n_instances,
|
803 |
+
)
|
804 |
+
|
805 |
+
negative_json = twitter_samples.abspath("negative_tweets.json")
|
806 |
+
negative_csv = "negative_tweets.csv"
|
807 |
+
json2csv_preprocess(
|
808 |
+
negative_json,
|
809 |
+
negative_csv,
|
810 |
+
fields,
|
811 |
+
strip_off_emoticons=False,
|
812 |
+
limit=n_instances,
|
813 |
+
)
|
814 |
+
|
815 |
+
pos_docs = parse_tweets_set(positive_csv, label="pos")
|
816 |
+
neg_docs = parse_tweets_set(negative_csv, label="neg")
|
817 |
+
|
818 |
+
# We separately split subjective and objective instances to keep a balanced
|
819 |
+
# uniform class distribution in both train and test sets.
|
820 |
+
train_pos_docs, test_pos_docs = split_train_test(pos_docs)
|
821 |
+
train_neg_docs, test_neg_docs = split_train_test(neg_docs)
|
822 |
+
|
823 |
+
training_tweets = train_pos_docs + train_neg_docs
|
824 |
+
testing_tweets = test_pos_docs + test_neg_docs
|
825 |
+
|
826 |
+
vader_analyzer = SentimentIntensityAnalyzer()
|
827 |
+
|
828 |
+
gold_results = defaultdict(set)
|
829 |
+
test_results = defaultdict(set)
|
830 |
+
acc_gold_results = []
|
831 |
+
acc_test_results = []
|
832 |
+
labels = set()
|
833 |
+
num = 0
|
834 |
+
for i, (text, label) in enumerate(testing_tweets):
|
835 |
+
labels.add(label)
|
836 |
+
gold_results[label].add(i)
|
837 |
+
acc_gold_results.append(label)
|
838 |
+
score = vader_analyzer.polarity_scores(text)["compound"]
|
839 |
+
if score > 0:
|
840 |
+
observed = "pos"
|
841 |
+
else:
|
842 |
+
observed = "neg"
|
843 |
+
num += 1
|
844 |
+
acc_test_results.append(observed)
|
845 |
+
test_results[observed].add(i)
|
846 |
+
metrics_results = {}
|
847 |
+
for label in labels:
|
848 |
+
accuracy_score = eval_accuracy(acc_gold_results, acc_test_results)
|
849 |
+
metrics_results["Accuracy"] = accuracy_score
|
850 |
+
precision_score = eval_precision(gold_results[label], test_results[label])
|
851 |
+
metrics_results[f"Precision [{label}]"] = precision_score
|
852 |
+
recall_score = eval_recall(gold_results[label], test_results[label])
|
853 |
+
metrics_results[f"Recall [{label}]"] = recall_score
|
854 |
+
f_measure_score = eval_f_measure(gold_results[label], test_results[label])
|
855 |
+
metrics_results[f"F-measure [{label}]"] = f_measure_score
|
856 |
+
|
857 |
+
for result in sorted(metrics_results):
|
858 |
+
print(f"{result}: {metrics_results[result]}")
|
859 |
+
|
860 |
+
if output:
|
861 |
+
output_markdown(
|
862 |
+
output,
|
863 |
+
Approach="Vader",
|
864 |
+
Dataset="labeled_tweets",
|
865 |
+
Instances=n_instances,
|
866 |
+
Results=metrics_results,
|
867 |
+
)
|
868 |
+
|
869 |
+
|
870 |
+
if __name__ == "__main__":
|
871 |
+
from sklearn.svm import LinearSVC
|
872 |
+
|
873 |
+
from nltk.classify import MaxentClassifier, NaiveBayesClassifier
|
874 |
+
from nltk.classify.scikitlearn import SklearnClassifier
|
875 |
+
from nltk.twitter.common import _outf_writer, extract_fields
|
876 |
+
|
877 |
+
naive_bayes = NaiveBayesClassifier.train
|
878 |
+
svm = SklearnClassifier(LinearSVC()).train
|
879 |
+
maxent = MaxentClassifier.train
|
880 |
+
|
881 |
+
demo_tweets(naive_bayes)
|
882 |
+
# demo_movie_reviews(svm)
|
883 |
+
# demo_subjectivity(svm)
|
884 |
+
# demo_sent_subjectivity("she's an artist , but hasn't picked up a brush in a year . ")
|
885 |
+
# demo_liu_hu_lexicon("This movie was actually neither that funny, nor super witty.", plot=True)
|
886 |
+
# demo_vader_instance("This movie was actually neither that funny, nor super witty.")
|
887 |
+
# demo_vader_tweets()
|
llmeval-env/lib/python3.10/site-packages/nltk/sentiment/vader.py
ADDED
@@ -0,0 +1,633 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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(modifications)
|
6 |
+
# Pierpaolo Pantone <[email protected]> (modifications)
|
7 |
+
# George Berry <[email protected]> (modifications)
|
8 |
+
# Malavika Suresh <[email protected]> (modifications)
|
9 |
+
# URL: <https://www.nltk.org/>
|
10 |
+
# For license information, see LICENSE.TXT
|
11 |
+
#
|
12 |
+
# Modifications to the original VADER code have been made in order to
|
13 |
+
# integrate it into NLTK. These have involved changes to
|
14 |
+
# ensure Python 3 compatibility, and refactoring to achieve greater modularity.
|
15 |
+
|
16 |
+
"""
|
17 |
+
If you use the VADER sentiment analysis tools, please cite:
|
18 |
+
|
19 |
+
Hutto, C.J. & Gilbert, E.E. (2014). VADER: A Parsimonious Rule-based Model for
|
20 |
+
Sentiment Analysis of Social Media Text. Eighth International Conference on
|
21 |
+
Weblogs and Social Media (ICWSM-14). Ann Arbor, MI, June 2014.
|
22 |
+
"""
|
23 |
+
|
24 |
+
import math
|
25 |
+
import re
|
26 |
+
import string
|
27 |
+
from itertools import product
|
28 |
+
|
29 |
+
import nltk.data
|
30 |
+
from nltk.util import pairwise
|
31 |
+
|
32 |
+
|
33 |
+
class VaderConstants:
|
34 |
+
"""
|
35 |
+
A class to keep the Vader lists and constants.
|
36 |
+
"""
|
37 |
+
|
38 |
+
##Constants##
|
39 |
+
# (empirically derived mean sentiment intensity rating increase for booster words)
|
40 |
+
B_INCR = 0.293
|
41 |
+
B_DECR = -0.293
|
42 |
+
|
43 |
+
# (empirically derived mean sentiment intensity rating increase for using
|
44 |
+
# ALLCAPs to emphasize a word)
|
45 |
+
C_INCR = 0.733
|
46 |
+
|
47 |
+
N_SCALAR = -0.74
|
48 |
+
|
49 |
+
NEGATE = {
|
50 |
+
"aint",
|
51 |
+
"arent",
|
52 |
+
"cannot",
|
53 |
+
"cant",
|
54 |
+
"couldnt",
|
55 |
+
"darent",
|
56 |
+
"didnt",
|
57 |
+
"doesnt",
|
58 |
+
"ain't",
|
59 |
+
"aren't",
|
60 |
+
"can't",
|
61 |
+
"couldn't",
|
62 |
+
"daren't",
|
63 |
+
"didn't",
|
64 |
+
"doesn't",
|
65 |
+
"dont",
|
66 |
+
"hadnt",
|
67 |
+
"hasnt",
|
68 |
+
"havent",
|
69 |
+
"isnt",
|
70 |
+
"mightnt",
|
71 |
+
"mustnt",
|
72 |
+
"neither",
|
73 |
+
"don't",
|
74 |
+
"hadn't",
|
75 |
+
"hasn't",
|
76 |
+
"haven't",
|
77 |
+
"isn't",
|
78 |
+
"mightn't",
|
79 |
+
"mustn't",
|
80 |
+
"neednt",
|
81 |
+
"needn't",
|
82 |
+
"never",
|
83 |
+
"none",
|
84 |
+
"nope",
|
85 |
+
"nor",
|
86 |
+
"not",
|
87 |
+
"nothing",
|
88 |
+
"nowhere",
|
89 |
+
"oughtnt",
|
90 |
+
"shant",
|
91 |
+
"shouldnt",
|
92 |
+
"uhuh",
|
93 |
+
"wasnt",
|
94 |
+
"werent",
|
95 |
+
"oughtn't",
|
96 |
+
"shan't",
|
97 |
+
"shouldn't",
|
98 |
+
"uh-uh",
|
99 |
+
"wasn't",
|
100 |
+
"weren't",
|
101 |
+
"without",
|
102 |
+
"wont",
|
103 |
+
"wouldnt",
|
104 |
+
"won't",
|
105 |
+
"wouldn't",
|
106 |
+
"rarely",
|
107 |
+
"seldom",
|
108 |
+
"despite",
|
109 |
+
}
|
110 |
+
|
111 |
+
# booster/dampener 'intensifiers' or 'degree adverbs'
|
112 |
+
# https://en.wiktionary.org/wiki/Category:English_degree_adverbs
|
113 |
+
|
114 |
+
BOOSTER_DICT = {
|
115 |
+
"absolutely": B_INCR,
|
116 |
+
"amazingly": B_INCR,
|
117 |
+
"awfully": B_INCR,
|
118 |
+
"completely": B_INCR,
|
119 |
+
"considerably": B_INCR,
|
120 |
+
"decidedly": B_INCR,
|
121 |
+
"deeply": B_INCR,
|
122 |
+
"effing": B_INCR,
|
123 |
+
"enormously": B_INCR,
|
124 |
+
"entirely": B_INCR,
|
125 |
+
"especially": B_INCR,
|
126 |
+
"exceptionally": B_INCR,
|
127 |
+
"extremely": B_INCR,
|
128 |
+
"fabulously": B_INCR,
|
129 |
+
"flipping": B_INCR,
|
130 |
+
"flippin": B_INCR,
|
131 |
+
"fricking": B_INCR,
|
132 |
+
"frickin": B_INCR,
|
133 |
+
"frigging": B_INCR,
|
134 |
+
"friggin": B_INCR,
|
135 |
+
"fully": B_INCR,
|
136 |
+
"fucking": B_INCR,
|
137 |
+
"greatly": B_INCR,
|
138 |
+
"hella": B_INCR,
|
139 |
+
"highly": B_INCR,
|
140 |
+
"hugely": B_INCR,
|
141 |
+
"incredibly": B_INCR,
|
142 |
+
"intensely": B_INCR,
|
143 |
+
"majorly": B_INCR,
|
144 |
+
"more": B_INCR,
|
145 |
+
"most": B_INCR,
|
146 |
+
"particularly": B_INCR,
|
147 |
+
"purely": B_INCR,
|
148 |
+
"quite": B_INCR,
|
149 |
+
"really": B_INCR,
|
150 |
+
"remarkably": B_INCR,
|
151 |
+
"so": B_INCR,
|
152 |
+
"substantially": B_INCR,
|
153 |
+
"thoroughly": B_INCR,
|
154 |
+
"totally": B_INCR,
|
155 |
+
"tremendously": B_INCR,
|
156 |
+
"uber": B_INCR,
|
157 |
+
"unbelievably": B_INCR,
|
158 |
+
"unusually": B_INCR,
|
159 |
+
"utterly": B_INCR,
|
160 |
+
"very": B_INCR,
|
161 |
+
"almost": B_DECR,
|
162 |
+
"barely": B_DECR,
|
163 |
+
"hardly": B_DECR,
|
164 |
+
"just enough": B_DECR,
|
165 |
+
"kind of": B_DECR,
|
166 |
+
"kinda": B_DECR,
|
167 |
+
"kindof": B_DECR,
|
168 |
+
"kind-of": B_DECR,
|
169 |
+
"less": B_DECR,
|
170 |
+
"little": B_DECR,
|
171 |
+
"marginally": B_DECR,
|
172 |
+
"occasionally": B_DECR,
|
173 |
+
"partly": B_DECR,
|
174 |
+
"scarcely": B_DECR,
|
175 |
+
"slightly": B_DECR,
|
176 |
+
"somewhat": B_DECR,
|
177 |
+
"sort of": B_DECR,
|
178 |
+
"sorta": B_DECR,
|
179 |
+
"sortof": B_DECR,
|
180 |
+
"sort-of": B_DECR,
|
181 |
+
}
|
182 |
+
|
183 |
+
# check for special case idioms using a sentiment-laden keyword known to SAGE
|
184 |
+
SPECIAL_CASE_IDIOMS = {
|
185 |
+
"the shit": 3,
|
186 |
+
"the bomb": 3,
|
187 |
+
"bad ass": 1.5,
|
188 |
+
"yeah right": -2,
|
189 |
+
"cut the mustard": 2,
|
190 |
+
"kiss of death": -1.5,
|
191 |
+
"hand to mouth": -2,
|
192 |
+
}
|
193 |
+
|
194 |
+
# for removing punctuation
|
195 |
+
REGEX_REMOVE_PUNCTUATION = re.compile(f"[{re.escape(string.punctuation)}]")
|
196 |
+
|
197 |
+
PUNC_LIST = [
|
198 |
+
".",
|
199 |
+
"!",
|
200 |
+
"?",
|
201 |
+
",",
|
202 |
+
";",
|
203 |
+
":",
|
204 |
+
"-",
|
205 |
+
"'",
|
206 |
+
'"',
|
207 |
+
"!!",
|
208 |
+
"!!!",
|
209 |
+
"??",
|
210 |
+
"???",
|
211 |
+
"?!?",
|
212 |
+
"!?!",
|
213 |
+
"?!?!",
|
214 |
+
"!?!?",
|
215 |
+
]
|
216 |
+
|
217 |
+
def __init__(self):
|
218 |
+
pass
|
219 |
+
|
220 |
+
def negated(self, input_words, include_nt=True):
|
221 |
+
"""
|
222 |
+
Determine if input contains negation words
|
223 |
+
"""
|
224 |
+
neg_words = self.NEGATE
|
225 |
+
if any(word.lower() in neg_words for word in input_words):
|
226 |
+
return True
|
227 |
+
if include_nt:
|
228 |
+
if any("n't" in word.lower() for word in input_words):
|
229 |
+
return True
|
230 |
+
for first, second in pairwise(input_words):
|
231 |
+
if second.lower() == "least" and first.lower() != "at":
|
232 |
+
return True
|
233 |
+
return False
|
234 |
+
|
235 |
+
def normalize(self, score, alpha=15):
|
236 |
+
"""
|
237 |
+
Normalize the score to be between -1 and 1 using an alpha that
|
238 |
+
approximates the max expected value
|
239 |
+
"""
|
240 |
+
norm_score = score / math.sqrt((score * score) + alpha)
|
241 |
+
return norm_score
|
242 |
+
|
243 |
+
def scalar_inc_dec(self, word, valence, is_cap_diff):
|
244 |
+
"""
|
245 |
+
Check if the preceding words increase, decrease, or negate/nullify the
|
246 |
+
valence
|
247 |
+
"""
|
248 |
+
scalar = 0.0
|
249 |
+
word_lower = word.lower()
|
250 |
+
if word_lower in self.BOOSTER_DICT:
|
251 |
+
scalar = self.BOOSTER_DICT[word_lower]
|
252 |
+
if valence < 0:
|
253 |
+
scalar *= -1
|
254 |
+
# check if booster/dampener word is in ALLCAPS (while others aren't)
|
255 |
+
if word.isupper() and is_cap_diff:
|
256 |
+
if valence > 0:
|
257 |
+
scalar += self.C_INCR
|
258 |
+
else:
|
259 |
+
scalar -= self.C_INCR
|
260 |
+
return scalar
|
261 |
+
|
262 |
+
|
263 |
+
class SentiText:
|
264 |
+
"""
|
265 |
+
Identify sentiment-relevant string-level properties of input text.
|
266 |
+
"""
|
267 |
+
|
268 |
+
def __init__(self, text, punc_list, regex_remove_punctuation):
|
269 |
+
if not isinstance(text, str):
|
270 |
+
text = str(text.encode("utf-8"))
|
271 |
+
self.text = text
|
272 |
+
self.PUNC_LIST = punc_list
|
273 |
+
self.REGEX_REMOVE_PUNCTUATION = regex_remove_punctuation
|
274 |
+
self.words_and_emoticons = self._words_and_emoticons()
|
275 |
+
# doesn't separate words from
|
276 |
+
# adjacent punctuation (keeps emoticons & contractions)
|
277 |
+
self.is_cap_diff = self.allcap_differential(self.words_and_emoticons)
|
278 |
+
|
279 |
+
def _words_plus_punc(self):
|
280 |
+
"""
|
281 |
+
Returns mapping of form:
|
282 |
+
{
|
283 |
+
'cat,': 'cat',
|
284 |
+
',cat': 'cat',
|
285 |
+
}
|
286 |
+
"""
|
287 |
+
no_punc_text = self.REGEX_REMOVE_PUNCTUATION.sub("", self.text)
|
288 |
+
# removes punctuation (but loses emoticons & contractions)
|
289 |
+
words_only = no_punc_text.split()
|
290 |
+
# remove singletons
|
291 |
+
words_only = {w for w in words_only if len(w) > 1}
|
292 |
+
# the product gives ('cat', ',') and (',', 'cat')
|
293 |
+
punc_before = {"".join(p): p[1] for p in product(self.PUNC_LIST, words_only)}
|
294 |
+
punc_after = {"".join(p): p[0] for p in product(words_only, self.PUNC_LIST)}
|
295 |
+
words_punc_dict = punc_before
|
296 |
+
words_punc_dict.update(punc_after)
|
297 |
+
return words_punc_dict
|
298 |
+
|
299 |
+
def _words_and_emoticons(self):
|
300 |
+
"""
|
301 |
+
Removes leading and trailing puncutation
|
302 |
+
Leaves contractions and most emoticons
|
303 |
+
Does not preserve punc-plus-letter emoticons (e.g. :D)
|
304 |
+
"""
|
305 |
+
wes = self.text.split()
|
306 |
+
words_punc_dict = self._words_plus_punc()
|
307 |
+
wes = [we for we in wes if len(we) > 1]
|
308 |
+
for i, we in enumerate(wes):
|
309 |
+
if we in words_punc_dict:
|
310 |
+
wes[i] = words_punc_dict[we]
|
311 |
+
return wes
|
312 |
+
|
313 |
+
def allcap_differential(self, words):
|
314 |
+
"""
|
315 |
+
Check whether just some words in the input are ALL CAPS
|
316 |
+
|
317 |
+
:param list words: The words to inspect
|
318 |
+
:returns: `True` if some but not all items in `words` are ALL CAPS
|
319 |
+
"""
|
320 |
+
is_different = False
|
321 |
+
allcap_words = 0
|
322 |
+
for word in words:
|
323 |
+
if word.isupper():
|
324 |
+
allcap_words += 1
|
325 |
+
cap_differential = len(words) - allcap_words
|
326 |
+
if 0 < cap_differential < len(words):
|
327 |
+
is_different = True
|
328 |
+
return is_different
|
329 |
+
|
330 |
+
|
331 |
+
class SentimentIntensityAnalyzer:
|
332 |
+
"""
|
333 |
+
Give a sentiment intensity score to sentences.
|
334 |
+
"""
|
335 |
+
|
336 |
+
def __init__(
|
337 |
+
self,
|
338 |
+
lexicon_file="sentiment/vader_lexicon.zip/vader_lexicon/vader_lexicon.txt",
|
339 |
+
):
|
340 |
+
self.lexicon_file = nltk.data.load(lexicon_file)
|
341 |
+
self.lexicon = self.make_lex_dict()
|
342 |
+
self.constants = VaderConstants()
|
343 |
+
|
344 |
+
def make_lex_dict(self):
|
345 |
+
"""
|
346 |
+
Convert lexicon file to a dictionary
|
347 |
+
"""
|
348 |
+
lex_dict = {}
|
349 |
+
for line in self.lexicon_file.split("\n"):
|
350 |
+
(word, measure) = line.strip().split("\t")[0:2]
|
351 |
+
lex_dict[word] = float(measure)
|
352 |
+
return lex_dict
|
353 |
+
|
354 |
+
def polarity_scores(self, text):
|
355 |
+
"""
|
356 |
+
Return a float for sentiment strength based on the input text.
|
357 |
+
Positive values are positive valence, negative value are negative
|
358 |
+
valence.
|
359 |
+
|
360 |
+
:note: Hashtags are not taken into consideration (e.g. #BAD is neutral). If you
|
361 |
+
are interested in processing the text in the hashtags too, then we recommend
|
362 |
+
preprocessing your data to remove the #, after which the hashtag text may be
|
363 |
+
matched as if it was a normal word in the sentence.
|
364 |
+
"""
|
365 |
+
# text, words_and_emoticons, is_cap_diff = self.preprocess(text)
|
366 |
+
sentitext = SentiText(
|
367 |
+
text, self.constants.PUNC_LIST, self.constants.REGEX_REMOVE_PUNCTUATION
|
368 |
+
)
|
369 |
+
sentiments = []
|
370 |
+
words_and_emoticons = sentitext.words_and_emoticons
|
371 |
+
for item in words_and_emoticons:
|
372 |
+
valence = 0
|
373 |
+
i = words_and_emoticons.index(item)
|
374 |
+
if (
|
375 |
+
i < len(words_and_emoticons) - 1
|
376 |
+
and item.lower() == "kind"
|
377 |
+
and words_and_emoticons[i + 1].lower() == "of"
|
378 |
+
) or item.lower() in self.constants.BOOSTER_DICT:
|
379 |
+
sentiments.append(valence)
|
380 |
+
continue
|
381 |
+
|
382 |
+
sentiments = self.sentiment_valence(valence, sentitext, item, i, sentiments)
|
383 |
+
|
384 |
+
sentiments = self._but_check(words_and_emoticons, sentiments)
|
385 |
+
|
386 |
+
return self.score_valence(sentiments, text)
|
387 |
+
|
388 |
+
def sentiment_valence(self, valence, sentitext, item, i, sentiments):
|
389 |
+
is_cap_diff = sentitext.is_cap_diff
|
390 |
+
words_and_emoticons = sentitext.words_and_emoticons
|
391 |
+
item_lowercase = item.lower()
|
392 |
+
if item_lowercase in self.lexicon:
|
393 |
+
# get the sentiment valence
|
394 |
+
valence = self.lexicon[item_lowercase]
|
395 |
+
|
396 |
+
# check if sentiment laden word is in ALL CAPS (while others aren't)
|
397 |
+
if item.isupper() and is_cap_diff:
|
398 |
+
if valence > 0:
|
399 |
+
valence += self.constants.C_INCR
|
400 |
+
else:
|
401 |
+
valence -= self.constants.C_INCR
|
402 |
+
|
403 |
+
for start_i in range(0, 3):
|
404 |
+
if (
|
405 |
+
i > start_i
|
406 |
+
and words_and_emoticons[i - (start_i + 1)].lower()
|
407 |
+
not in self.lexicon
|
408 |
+
):
|
409 |
+
# dampen the scalar modifier of preceding words and emoticons
|
410 |
+
# (excluding the ones that immediately preceed the item) based
|
411 |
+
# on their distance from the current item.
|
412 |
+
s = self.constants.scalar_inc_dec(
|
413 |
+
words_and_emoticons[i - (start_i + 1)], valence, is_cap_diff
|
414 |
+
)
|
415 |
+
if start_i == 1 and s != 0:
|
416 |
+
s = s * 0.95
|
417 |
+
if start_i == 2 and s != 0:
|
418 |
+
s = s * 0.9
|
419 |
+
valence = valence + s
|
420 |
+
valence = self._never_check(
|
421 |
+
valence, words_and_emoticons, start_i, i
|
422 |
+
)
|
423 |
+
if start_i == 2:
|
424 |
+
valence = self._idioms_check(valence, words_and_emoticons, i)
|
425 |
+
|
426 |
+
# future work: consider other sentiment-laden idioms
|
427 |
+
# other_idioms =
|
428 |
+
# {"back handed": -2, "blow smoke": -2, "blowing smoke": -2,
|
429 |
+
# "upper hand": 1, "break a leg": 2,
|
430 |
+
# "cooking with gas": 2, "in the black": 2, "in the red": -2,
|
431 |
+
# "on the ball": 2,"under the weather": -2}
|
432 |
+
|
433 |
+
valence = self._least_check(valence, words_and_emoticons, i)
|
434 |
+
|
435 |
+
sentiments.append(valence)
|
436 |
+
return sentiments
|
437 |
+
|
438 |
+
def _least_check(self, valence, words_and_emoticons, i):
|
439 |
+
# check for negation case using "least"
|
440 |
+
if (
|
441 |
+
i > 1
|
442 |
+
and words_and_emoticons[i - 1].lower() not in self.lexicon
|
443 |
+
and words_and_emoticons[i - 1].lower() == "least"
|
444 |
+
):
|
445 |
+
if (
|
446 |
+
words_and_emoticons[i - 2].lower() != "at"
|
447 |
+
and words_and_emoticons[i - 2].lower() != "very"
|
448 |
+
):
|
449 |
+
valence = valence * self.constants.N_SCALAR
|
450 |
+
elif (
|
451 |
+
i > 0
|
452 |
+
and words_and_emoticons[i - 1].lower() not in self.lexicon
|
453 |
+
and words_and_emoticons[i - 1].lower() == "least"
|
454 |
+
):
|
455 |
+
valence = valence * self.constants.N_SCALAR
|
456 |
+
return valence
|
457 |
+
|
458 |
+
def _but_check(self, words_and_emoticons, sentiments):
|
459 |
+
words_and_emoticons = [w_e.lower() for w_e in words_and_emoticons]
|
460 |
+
but = {"but"} & set(words_and_emoticons)
|
461 |
+
if but:
|
462 |
+
bi = words_and_emoticons.index(next(iter(but)))
|
463 |
+
for sidx, sentiment in enumerate(sentiments):
|
464 |
+
if sidx < bi:
|
465 |
+
sentiments[sidx] = sentiment * 0.5
|
466 |
+
elif sidx > bi:
|
467 |
+
sentiments[sidx] = sentiment * 1.5
|
468 |
+
return sentiments
|
469 |
+
|
470 |
+
def _idioms_check(self, valence, words_and_emoticons, i):
|
471 |
+
onezero = f"{words_and_emoticons[i - 1]} {words_and_emoticons[i]}"
|
472 |
+
|
473 |
+
twoonezero = "{} {} {}".format(
|
474 |
+
words_and_emoticons[i - 2],
|
475 |
+
words_and_emoticons[i - 1],
|
476 |
+
words_and_emoticons[i],
|
477 |
+
)
|
478 |
+
|
479 |
+
twoone = f"{words_and_emoticons[i - 2]} {words_and_emoticons[i - 1]}"
|
480 |
+
|
481 |
+
threetwoone = "{} {} {}".format(
|
482 |
+
words_and_emoticons[i - 3],
|
483 |
+
words_and_emoticons[i - 2],
|
484 |
+
words_and_emoticons[i - 1],
|
485 |
+
)
|
486 |
+
|
487 |
+
threetwo = "{} {}".format(
|
488 |
+
words_and_emoticons[i - 3], words_and_emoticons[i - 2]
|
489 |
+
)
|
490 |
+
|
491 |
+
sequences = [onezero, twoonezero, twoone, threetwoone, threetwo]
|
492 |
+
|
493 |
+
for seq in sequences:
|
494 |
+
if seq in self.constants.SPECIAL_CASE_IDIOMS:
|
495 |
+
valence = self.constants.SPECIAL_CASE_IDIOMS[seq]
|
496 |
+
break
|
497 |
+
|
498 |
+
if len(words_and_emoticons) - 1 > i:
|
499 |
+
zeroone = f"{words_and_emoticons[i]} {words_and_emoticons[i + 1]}"
|
500 |
+
if zeroone in self.constants.SPECIAL_CASE_IDIOMS:
|
501 |
+
valence = self.constants.SPECIAL_CASE_IDIOMS[zeroone]
|
502 |
+
if len(words_and_emoticons) - 1 > i + 1:
|
503 |
+
zeroonetwo = "{} {} {}".format(
|
504 |
+
words_and_emoticons[i],
|
505 |
+
words_and_emoticons[i + 1],
|
506 |
+
words_and_emoticons[i + 2],
|
507 |
+
)
|
508 |
+
if zeroonetwo in self.constants.SPECIAL_CASE_IDIOMS:
|
509 |
+
valence = self.constants.SPECIAL_CASE_IDIOMS[zeroonetwo]
|
510 |
+
|
511 |
+
# check for booster/dampener bi-grams such as 'sort of' or 'kind of'
|
512 |
+
if (
|
513 |
+
threetwo in self.constants.BOOSTER_DICT
|
514 |
+
or twoone in self.constants.BOOSTER_DICT
|
515 |
+
):
|
516 |
+
valence = valence + self.constants.B_DECR
|
517 |
+
return valence
|
518 |
+
|
519 |
+
def _never_check(self, valence, words_and_emoticons, start_i, i):
|
520 |
+
if start_i == 0:
|
521 |
+
if self.constants.negated([words_and_emoticons[i - 1]]):
|
522 |
+
valence = valence * self.constants.N_SCALAR
|
523 |
+
if start_i == 1:
|
524 |
+
if words_and_emoticons[i - 2] == "never" and (
|
525 |
+
words_and_emoticons[i - 1] == "so"
|
526 |
+
or words_and_emoticons[i - 1] == "this"
|
527 |
+
):
|
528 |
+
valence = valence * 1.5
|
529 |
+
elif self.constants.negated([words_and_emoticons[i - (start_i + 1)]]):
|
530 |
+
valence = valence * self.constants.N_SCALAR
|
531 |
+
if start_i == 2:
|
532 |
+
if (
|
533 |
+
words_and_emoticons[i - 3] == "never"
|
534 |
+
and (
|
535 |
+
words_and_emoticons[i - 2] == "so"
|
536 |
+
or words_and_emoticons[i - 2] == "this"
|
537 |
+
)
|
538 |
+
or (
|
539 |
+
words_and_emoticons[i - 1] == "so"
|
540 |
+
or words_and_emoticons[i - 1] == "this"
|
541 |
+
)
|
542 |
+
):
|
543 |
+
valence = valence * 1.25
|
544 |
+
elif self.constants.negated([words_and_emoticons[i - (start_i + 1)]]):
|
545 |
+
valence = valence * self.constants.N_SCALAR
|
546 |
+
return valence
|
547 |
+
|
548 |
+
def _punctuation_emphasis(self, sum_s, text):
|
549 |
+
# add emphasis from exclamation points and question marks
|
550 |
+
ep_amplifier = self._amplify_ep(text)
|
551 |
+
qm_amplifier = self._amplify_qm(text)
|
552 |
+
punct_emph_amplifier = ep_amplifier + qm_amplifier
|
553 |
+
return punct_emph_amplifier
|
554 |
+
|
555 |
+
def _amplify_ep(self, text):
|
556 |
+
# check for added emphasis resulting from exclamation points (up to 4 of them)
|
557 |
+
ep_count = text.count("!")
|
558 |
+
if ep_count > 4:
|
559 |
+
ep_count = 4
|
560 |
+
# (empirically derived mean sentiment intensity rating increase for
|
561 |
+
# exclamation points)
|
562 |
+
ep_amplifier = ep_count * 0.292
|
563 |
+
return ep_amplifier
|
564 |
+
|
565 |
+
def _amplify_qm(self, text):
|
566 |
+
# check for added emphasis resulting from question marks (2 or 3+)
|
567 |
+
qm_count = text.count("?")
|
568 |
+
qm_amplifier = 0
|
569 |
+
if qm_count > 1:
|
570 |
+
if qm_count <= 3:
|
571 |
+
# (empirically derived mean sentiment intensity rating increase for
|
572 |
+
# question marks)
|
573 |
+
qm_amplifier = qm_count * 0.18
|
574 |
+
else:
|
575 |
+
qm_amplifier = 0.96
|
576 |
+
return qm_amplifier
|
577 |
+
|
578 |
+
def _sift_sentiment_scores(self, sentiments):
|
579 |
+
# want separate positive versus negative sentiment scores
|
580 |
+
pos_sum = 0.0
|
581 |
+
neg_sum = 0.0
|
582 |
+
neu_count = 0
|
583 |
+
for sentiment_score in sentiments:
|
584 |
+
if sentiment_score > 0:
|
585 |
+
pos_sum += (
|
586 |
+
float(sentiment_score) + 1
|
587 |
+
) # compensates for neutral words that are counted as 1
|
588 |
+
if sentiment_score < 0:
|
589 |
+
neg_sum += (
|
590 |
+
float(sentiment_score) - 1
|
591 |
+
) # when used with math.fabs(), compensates for neutrals
|
592 |
+
if sentiment_score == 0:
|
593 |
+
neu_count += 1
|
594 |
+
return pos_sum, neg_sum, neu_count
|
595 |
+
|
596 |
+
def score_valence(self, sentiments, text):
|
597 |
+
if sentiments:
|
598 |
+
sum_s = float(sum(sentiments))
|
599 |
+
# compute and add emphasis from punctuation in text
|
600 |
+
punct_emph_amplifier = self._punctuation_emphasis(sum_s, text)
|
601 |
+
if sum_s > 0:
|
602 |
+
sum_s += punct_emph_amplifier
|
603 |
+
elif sum_s < 0:
|
604 |
+
sum_s -= punct_emph_amplifier
|
605 |
+
|
606 |
+
compound = self.constants.normalize(sum_s)
|
607 |
+
# discriminate between positive, negative and neutral sentiment scores
|
608 |
+
pos_sum, neg_sum, neu_count = self._sift_sentiment_scores(sentiments)
|
609 |
+
|
610 |
+
if pos_sum > math.fabs(neg_sum):
|
611 |
+
pos_sum += punct_emph_amplifier
|
612 |
+
elif pos_sum < math.fabs(neg_sum):
|
613 |
+
neg_sum -= punct_emph_amplifier
|
614 |
+
|
615 |
+
total = pos_sum + math.fabs(neg_sum) + neu_count
|
616 |
+
pos = math.fabs(pos_sum / total)
|
617 |
+
neg = math.fabs(neg_sum / total)
|
618 |
+
neu = math.fabs(neu_count / total)
|
619 |
+
|
620 |
+
else:
|
621 |
+
compound = 0.0
|
622 |
+
pos = 0.0
|
623 |
+
neg = 0.0
|
624 |
+
neu = 0.0
|
625 |
+
|
626 |
+
sentiment_dict = {
|
627 |
+
"neg": round(neg, 3),
|
628 |
+
"neu": round(neu, 3),
|
629 |
+
"pos": round(pos, 3),
|
630 |
+
"compound": round(compound, 4),
|
631 |
+
}
|
632 |
+
|
633 |
+
return sentiment_dict
|
llmeval-env/lib/python3.10/site-packages/nltk/tbl/__init__.py
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Transformation-based learning
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Marcus Uneson <[email protected]>
|
5 |
+
# based on previous (nltk2) version by
|
6 |
+
# Christopher Maloof, Edward Loper, Steven Bird
|
7 |
+
# URL: <https://www.nltk.org/>
|
8 |
+
# For license information, see LICENSE.TXT
|
9 |
+
|
10 |
+
"""
|
11 |
+
Transformation Based Learning
|
12 |
+
|
13 |
+
A general purpose package for Transformation Based Learning,
|
14 |
+
currently used by nltk.tag.BrillTagger.
|
15 |
+
|
16 |
+
isort:skip_file
|
17 |
+
"""
|
18 |
+
|
19 |
+
from nltk.tbl.template import Template
|
20 |
+
|
21 |
+
# API: Template(...), Template.expand(...)
|
22 |
+
|
23 |
+
from nltk.tbl.feature import Feature
|
24 |
+
|
25 |
+
# API: Feature(...), Feature.expand(...)
|
26 |
+
|
27 |
+
from nltk.tbl.rule import Rule
|
28 |
+
|
29 |
+
# API: Rule.format(...), Rule.templatetid
|
30 |
+
|
31 |
+
from nltk.tbl.erroranalysis import error_list
|
llmeval-env/lib/python3.10/site-packages/nltk/tbl/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (545 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/tbl/__pycache__/api.cpython-310.pyc
ADDED
Binary file (176 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/tbl/__pycache__/demo.cpython-310.pyc
ADDED
Binary file (12.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/tbl/__pycache__/erroranalysis.cpython-310.pyc
ADDED
Binary file (1.37 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/tbl/__pycache__/feature.cpython-310.pyc
ADDED
Binary file (9.86 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/tbl/__pycache__/rule.cpython-310.pyc
ADDED
Binary file (10.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/tbl/__pycache__/template.cpython-310.pyc
ADDED
Binary file (12.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/nltk/tbl/api.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/nltk/tbl/demo.py
ADDED
@@ -0,0 +1,418 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Transformation-based learning
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Marcus Uneson <[email protected]>
|
5 |
+
# based on previous (nltk2) version by
|
6 |
+
# Christopher Maloof, Edward Loper, Steven Bird
|
7 |
+
# URL: <https://www.nltk.org/>
|
8 |
+
# For license information, see LICENSE.TXT
|
9 |
+
|
10 |
+
import os
|
11 |
+
import pickle
|
12 |
+
import random
|
13 |
+
import time
|
14 |
+
|
15 |
+
from nltk.corpus import treebank
|
16 |
+
from nltk.tag import BrillTaggerTrainer, RegexpTagger, UnigramTagger
|
17 |
+
from nltk.tag.brill import Pos, Word
|
18 |
+
from nltk.tbl import Template, error_list
|
19 |
+
|
20 |
+
|
21 |
+
def demo():
|
22 |
+
"""
|
23 |
+
Run a demo with defaults. See source comments for details,
|
24 |
+
or docstrings of any of the more specific demo_* functions.
|
25 |
+
"""
|
26 |
+
postag()
|
27 |
+
|
28 |
+
|
29 |
+
def demo_repr_rule_format():
|
30 |
+
"""
|
31 |
+
Exemplify repr(Rule) (see also str(Rule) and Rule.format("verbose"))
|
32 |
+
"""
|
33 |
+
postag(ruleformat="repr")
|
34 |
+
|
35 |
+
|
36 |
+
def demo_str_rule_format():
|
37 |
+
"""
|
38 |
+
Exemplify repr(Rule) (see also str(Rule) and Rule.format("verbose"))
|
39 |
+
"""
|
40 |
+
postag(ruleformat="str")
|
41 |
+
|
42 |
+
|
43 |
+
def demo_verbose_rule_format():
|
44 |
+
"""
|
45 |
+
Exemplify Rule.format("verbose")
|
46 |
+
"""
|
47 |
+
postag(ruleformat="verbose")
|
48 |
+
|
49 |
+
|
50 |
+
def demo_multiposition_feature():
|
51 |
+
"""
|
52 |
+
The feature/s of a template takes a list of positions
|
53 |
+
relative to the current word where the feature should be
|
54 |
+
looked for, conceptually joined by logical OR. For instance,
|
55 |
+
Pos([-1, 1]), given a value V, will hold whenever V is found
|
56 |
+
one step to the left and/or one step to the right.
|
57 |
+
|
58 |
+
For contiguous ranges, a 2-arg form giving inclusive end
|
59 |
+
points can also be used: Pos(-3, -1) is the same as the arg
|
60 |
+
below.
|
61 |
+
"""
|
62 |
+
postag(templates=[Template(Pos([-3, -2, -1]))])
|
63 |
+
|
64 |
+
|
65 |
+
def demo_multifeature_template():
|
66 |
+
"""
|
67 |
+
Templates can have more than a single feature.
|
68 |
+
"""
|
69 |
+
postag(templates=[Template(Word([0]), Pos([-2, -1]))])
|
70 |
+
|
71 |
+
|
72 |
+
def demo_template_statistics():
|
73 |
+
"""
|
74 |
+
Show aggregate statistics per template. Little used templates are
|
75 |
+
candidates for deletion, much used templates may possibly be refined.
|
76 |
+
|
77 |
+
Deleting unused templates is mostly about saving time and/or space:
|
78 |
+
training is basically O(T) in the number of templates T
|
79 |
+
(also in terms of memory usage, which often will be the limiting factor).
|
80 |
+
"""
|
81 |
+
postag(incremental_stats=True, template_stats=True)
|
82 |
+
|
83 |
+
|
84 |
+
def demo_generated_templates():
|
85 |
+
"""
|
86 |
+
Template.expand and Feature.expand are class methods facilitating
|
87 |
+
generating large amounts of templates. See their documentation for
|
88 |
+
details.
|
89 |
+
|
90 |
+
Note: training with 500 templates can easily fill all available
|
91 |
+
even on relatively small corpora
|
92 |
+
"""
|
93 |
+
wordtpls = Word.expand([-1, 0, 1], [1, 2], excludezero=False)
|
94 |
+
tagtpls = Pos.expand([-2, -1, 0, 1], [1, 2], excludezero=True)
|
95 |
+
templates = list(Template.expand([wordtpls, tagtpls], combinations=(1, 3)))
|
96 |
+
print(
|
97 |
+
"Generated {} templates for transformation-based learning".format(
|
98 |
+
len(templates)
|
99 |
+
)
|
100 |
+
)
|
101 |
+
postag(templates=templates, incremental_stats=True, template_stats=True)
|
102 |
+
|
103 |
+
|
104 |
+
def demo_learning_curve():
|
105 |
+
"""
|
106 |
+
Plot a learning curve -- the contribution on tagging accuracy of
|
107 |
+
the individual rules.
|
108 |
+
Note: requires matplotlib
|
109 |
+
"""
|
110 |
+
postag(
|
111 |
+
incremental_stats=True,
|
112 |
+
separate_baseline_data=True,
|
113 |
+
learning_curve_output="learningcurve.png",
|
114 |
+
)
|
115 |
+
|
116 |
+
|
117 |
+
def demo_error_analysis():
|
118 |
+
"""
|
119 |
+
Writes a file with context for each erroneous word after tagging testing data
|
120 |
+
"""
|
121 |
+
postag(error_output="errors.txt")
|
122 |
+
|
123 |
+
|
124 |
+
def demo_serialize_tagger():
|
125 |
+
"""
|
126 |
+
Serializes the learned tagger to a file in pickle format; reloads it
|
127 |
+
and validates the process.
|
128 |
+
"""
|
129 |
+
postag(serialize_output="tagger.pcl")
|
130 |
+
|
131 |
+
|
132 |
+
def demo_high_accuracy_rules():
|
133 |
+
"""
|
134 |
+
Discard rules with low accuracy. This may hurt performance a bit,
|
135 |
+
but will often produce rules which are more interesting read to a human.
|
136 |
+
"""
|
137 |
+
postag(num_sents=3000, min_acc=0.96, min_score=10)
|
138 |
+
|
139 |
+
|
140 |
+
def postag(
|
141 |
+
templates=None,
|
142 |
+
tagged_data=None,
|
143 |
+
num_sents=1000,
|
144 |
+
max_rules=300,
|
145 |
+
min_score=3,
|
146 |
+
min_acc=None,
|
147 |
+
train=0.8,
|
148 |
+
trace=3,
|
149 |
+
randomize=False,
|
150 |
+
ruleformat="str",
|
151 |
+
incremental_stats=False,
|
152 |
+
template_stats=False,
|
153 |
+
error_output=None,
|
154 |
+
serialize_output=None,
|
155 |
+
learning_curve_output=None,
|
156 |
+
learning_curve_take=300,
|
157 |
+
baseline_backoff_tagger=None,
|
158 |
+
separate_baseline_data=False,
|
159 |
+
cache_baseline_tagger=None,
|
160 |
+
):
|
161 |
+
"""
|
162 |
+
Brill Tagger Demonstration
|
163 |
+
:param templates: how many sentences of training and testing data to use
|
164 |
+
:type templates: list of Template
|
165 |
+
|
166 |
+
:param tagged_data: maximum number of rule instances to create
|
167 |
+
:type tagged_data: C{int}
|
168 |
+
|
169 |
+
:param num_sents: how many sentences of training and testing data to use
|
170 |
+
:type num_sents: C{int}
|
171 |
+
|
172 |
+
:param max_rules: maximum number of rule instances to create
|
173 |
+
:type max_rules: C{int}
|
174 |
+
|
175 |
+
:param min_score: the minimum score for a rule in order for it to be considered
|
176 |
+
:type min_score: C{int}
|
177 |
+
|
178 |
+
:param min_acc: the minimum score for a rule in order for it to be considered
|
179 |
+
:type min_acc: C{float}
|
180 |
+
|
181 |
+
:param train: the fraction of the the corpus to be used for training (1=all)
|
182 |
+
:type train: C{float}
|
183 |
+
|
184 |
+
:param trace: the level of diagnostic tracing output to produce (0-4)
|
185 |
+
:type trace: C{int}
|
186 |
+
|
187 |
+
:param randomize: whether the training data should be a random subset of the corpus
|
188 |
+
:type randomize: C{bool}
|
189 |
+
|
190 |
+
:param ruleformat: rule output format, one of "str", "repr", "verbose"
|
191 |
+
:type ruleformat: C{str}
|
192 |
+
|
193 |
+
:param incremental_stats: if true, will tag incrementally and collect stats for each rule (rather slow)
|
194 |
+
:type incremental_stats: C{bool}
|
195 |
+
|
196 |
+
:param template_stats: if true, will print per-template statistics collected in training and (optionally) testing
|
197 |
+
:type template_stats: C{bool}
|
198 |
+
|
199 |
+
:param error_output: the file where errors will be saved
|
200 |
+
:type error_output: C{string}
|
201 |
+
|
202 |
+
:param serialize_output: the file where the learned tbl tagger will be saved
|
203 |
+
:type serialize_output: C{string}
|
204 |
+
|
205 |
+
:param learning_curve_output: filename of plot of learning curve(s) (train and also test, if available)
|
206 |
+
:type learning_curve_output: C{string}
|
207 |
+
|
208 |
+
:param learning_curve_take: how many rules plotted
|
209 |
+
:type learning_curve_take: C{int}
|
210 |
+
|
211 |
+
:param baseline_backoff_tagger: the file where rules will be saved
|
212 |
+
:type baseline_backoff_tagger: tagger
|
213 |
+
|
214 |
+
:param separate_baseline_data: use a fraction of the training data exclusively for training baseline
|
215 |
+
:type separate_baseline_data: C{bool}
|
216 |
+
|
217 |
+
:param cache_baseline_tagger: cache baseline tagger to this file (only interesting as a temporary workaround to get
|
218 |
+
deterministic output from the baseline unigram tagger between python versions)
|
219 |
+
:type cache_baseline_tagger: C{string}
|
220 |
+
|
221 |
+
|
222 |
+
Note on separate_baseline_data: if True, reuse training data both for baseline and rule learner. This
|
223 |
+
is fast and fine for a demo, but is likely to generalize worse on unseen data.
|
224 |
+
Also cannot be sensibly used for learning curves on training data (the baseline will be artificially high).
|
225 |
+
"""
|
226 |
+
|
227 |
+
# defaults
|
228 |
+
baseline_backoff_tagger = baseline_backoff_tagger or REGEXP_TAGGER
|
229 |
+
if templates is None:
|
230 |
+
from nltk.tag.brill import brill24, describe_template_sets
|
231 |
+
|
232 |
+
# some pre-built template sets taken from typical systems or publications are
|
233 |
+
# available. Print a list with describe_template_sets()
|
234 |
+
# for instance:
|
235 |
+
templates = brill24()
|
236 |
+
(training_data, baseline_data, gold_data, testing_data) = _demo_prepare_data(
|
237 |
+
tagged_data, train, num_sents, randomize, separate_baseline_data
|
238 |
+
)
|
239 |
+
|
240 |
+
# creating (or reloading from cache) a baseline tagger (unigram tagger)
|
241 |
+
# this is just a mechanism for getting deterministic output from the baseline between
|
242 |
+
# python versions
|
243 |
+
if cache_baseline_tagger:
|
244 |
+
if not os.path.exists(cache_baseline_tagger):
|
245 |
+
baseline_tagger = UnigramTagger(
|
246 |
+
baseline_data, backoff=baseline_backoff_tagger
|
247 |
+
)
|
248 |
+
with open(cache_baseline_tagger, "w") as print_rules:
|
249 |
+
pickle.dump(baseline_tagger, print_rules)
|
250 |
+
print(
|
251 |
+
"Trained baseline tagger, pickled it to {}".format(
|
252 |
+
cache_baseline_tagger
|
253 |
+
)
|
254 |
+
)
|
255 |
+
with open(cache_baseline_tagger) as print_rules:
|
256 |
+
baseline_tagger = pickle.load(print_rules)
|
257 |
+
print(f"Reloaded pickled tagger from {cache_baseline_tagger}")
|
258 |
+
else:
|
259 |
+
baseline_tagger = UnigramTagger(baseline_data, backoff=baseline_backoff_tagger)
|
260 |
+
print("Trained baseline tagger")
|
261 |
+
if gold_data:
|
262 |
+
print(
|
263 |
+
" Accuracy on test set: {:0.4f}".format(
|
264 |
+
baseline_tagger.accuracy(gold_data)
|
265 |
+
)
|
266 |
+
)
|
267 |
+
|
268 |
+
# creating a Brill tagger
|
269 |
+
tbrill = time.time()
|
270 |
+
trainer = BrillTaggerTrainer(
|
271 |
+
baseline_tagger, templates, trace, ruleformat=ruleformat
|
272 |
+
)
|
273 |
+
print("Training tbl tagger...")
|
274 |
+
brill_tagger = trainer.train(training_data, max_rules, min_score, min_acc)
|
275 |
+
print(f"Trained tbl tagger in {time.time() - tbrill:0.2f} seconds")
|
276 |
+
if gold_data:
|
277 |
+
print(" Accuracy on test set: %.4f" % brill_tagger.accuracy(gold_data))
|
278 |
+
|
279 |
+
# printing the learned rules, if learned silently
|
280 |
+
if trace == 1:
|
281 |
+
print("\nLearned rules: ")
|
282 |
+
for (ruleno, rule) in enumerate(brill_tagger.rules(), 1):
|
283 |
+
print(f"{ruleno:4d} {rule.format(ruleformat):s}")
|
284 |
+
|
285 |
+
# printing template statistics (optionally including comparison with the training data)
|
286 |
+
# note: if not separate_baseline_data, then baseline accuracy will be artificially high
|
287 |
+
if incremental_stats:
|
288 |
+
print(
|
289 |
+
"Incrementally tagging the test data, collecting individual rule statistics"
|
290 |
+
)
|
291 |
+
(taggedtest, teststats) = brill_tagger.batch_tag_incremental(
|
292 |
+
testing_data, gold_data
|
293 |
+
)
|
294 |
+
print(" Rule statistics collected")
|
295 |
+
if not separate_baseline_data:
|
296 |
+
print(
|
297 |
+
"WARNING: train_stats asked for separate_baseline_data=True; the baseline "
|
298 |
+
"will be artificially high"
|
299 |
+
)
|
300 |
+
trainstats = brill_tagger.train_stats()
|
301 |
+
if template_stats:
|
302 |
+
brill_tagger.print_template_statistics(teststats)
|
303 |
+
if learning_curve_output:
|
304 |
+
_demo_plot(
|
305 |
+
learning_curve_output, teststats, trainstats, take=learning_curve_take
|
306 |
+
)
|
307 |
+
print(f"Wrote plot of learning curve to {learning_curve_output}")
|
308 |
+
else:
|
309 |
+
print("Tagging the test data")
|
310 |
+
taggedtest = brill_tagger.tag_sents(testing_data)
|
311 |
+
if template_stats:
|
312 |
+
brill_tagger.print_template_statistics()
|
313 |
+
|
314 |
+
# writing error analysis to file
|
315 |
+
if error_output is not None:
|
316 |
+
with open(error_output, "w") as f:
|
317 |
+
f.write("Errors for Brill Tagger %r\n\n" % serialize_output)
|
318 |
+
f.write("\n".join(error_list(gold_data, taggedtest)).encode("utf-8") + "\n")
|
319 |
+
print(f"Wrote tagger errors including context to {error_output}")
|
320 |
+
|
321 |
+
# serializing the tagger to a pickle file and reloading (just to see it works)
|
322 |
+
if serialize_output is not None:
|
323 |
+
taggedtest = brill_tagger.tag_sents(testing_data)
|
324 |
+
with open(serialize_output, "w") as print_rules:
|
325 |
+
pickle.dump(brill_tagger, print_rules)
|
326 |
+
print(f"Wrote pickled tagger to {serialize_output}")
|
327 |
+
with open(serialize_output) as print_rules:
|
328 |
+
brill_tagger_reloaded = pickle.load(print_rules)
|
329 |
+
print(f"Reloaded pickled tagger from {serialize_output}")
|
330 |
+
taggedtest_reloaded = brill_tagger.tag_sents(testing_data)
|
331 |
+
if taggedtest == taggedtest_reloaded:
|
332 |
+
print("Reloaded tagger tried on test set, results identical")
|
333 |
+
else:
|
334 |
+
print("PROBLEM: Reloaded tagger gave different results on test set")
|
335 |
+
|
336 |
+
|
337 |
+
def _demo_prepare_data(
|
338 |
+
tagged_data, train, num_sents, randomize, separate_baseline_data
|
339 |
+
):
|
340 |
+
# train is the proportion of data used in training; the rest is reserved
|
341 |
+
# for testing.
|
342 |
+
if tagged_data is None:
|
343 |
+
print("Loading tagged data from treebank... ")
|
344 |
+
tagged_data = treebank.tagged_sents()
|
345 |
+
if num_sents is None or len(tagged_data) <= num_sents:
|
346 |
+
num_sents = len(tagged_data)
|
347 |
+
if randomize:
|
348 |
+
random.seed(len(tagged_data))
|
349 |
+
random.shuffle(tagged_data)
|
350 |
+
cutoff = int(num_sents * train)
|
351 |
+
training_data = tagged_data[:cutoff]
|
352 |
+
gold_data = tagged_data[cutoff:num_sents]
|
353 |
+
testing_data = [[t[0] for t in sent] for sent in gold_data]
|
354 |
+
if not separate_baseline_data:
|
355 |
+
baseline_data = training_data
|
356 |
+
else:
|
357 |
+
bl_cutoff = len(training_data) // 3
|
358 |
+
(baseline_data, training_data) = (
|
359 |
+
training_data[:bl_cutoff],
|
360 |
+
training_data[bl_cutoff:],
|
361 |
+
)
|
362 |
+
(trainseqs, traintokens) = corpus_size(training_data)
|
363 |
+
(testseqs, testtokens) = corpus_size(testing_data)
|
364 |
+
(bltrainseqs, bltraintokens) = corpus_size(baseline_data)
|
365 |
+
print(f"Read testing data ({testseqs:d} sents/{testtokens:d} wds)")
|
366 |
+
print(f"Read training data ({trainseqs:d} sents/{traintokens:d} wds)")
|
367 |
+
print(
|
368 |
+
"Read baseline data ({:d} sents/{:d} wds) {:s}".format(
|
369 |
+
bltrainseqs,
|
370 |
+
bltraintokens,
|
371 |
+
"" if separate_baseline_data else "[reused the training set]",
|
372 |
+
)
|
373 |
+
)
|
374 |
+
return (training_data, baseline_data, gold_data, testing_data)
|
375 |
+
|
376 |
+
|
377 |
+
def _demo_plot(learning_curve_output, teststats, trainstats=None, take=None):
|
378 |
+
testcurve = [teststats["initialerrors"]]
|
379 |
+
for rulescore in teststats["rulescores"]:
|
380 |
+
testcurve.append(testcurve[-1] - rulescore)
|
381 |
+
testcurve = [1 - x / teststats["tokencount"] for x in testcurve[:take]]
|
382 |
+
|
383 |
+
traincurve = [trainstats["initialerrors"]]
|
384 |
+
for rulescore in trainstats["rulescores"]:
|
385 |
+
traincurve.append(traincurve[-1] - rulescore)
|
386 |
+
traincurve = [1 - x / trainstats["tokencount"] for x in traincurve[:take]]
|
387 |
+
|
388 |
+
import matplotlib.pyplot as plt
|
389 |
+
|
390 |
+
r = list(range(len(testcurve)))
|
391 |
+
plt.plot(r, testcurve, r, traincurve)
|
392 |
+
plt.axis([None, None, None, 1.0])
|
393 |
+
plt.savefig(learning_curve_output)
|
394 |
+
|
395 |
+
|
396 |
+
NN_CD_TAGGER = RegexpTagger([(r"^-?[0-9]+(\.[0-9]+)?$", "CD"), (r".*", "NN")])
|
397 |
+
|
398 |
+
REGEXP_TAGGER = RegexpTagger(
|
399 |
+
[
|
400 |
+
(r"^-?[0-9]+(\.[0-9]+)?$", "CD"), # cardinal numbers
|
401 |
+
(r"(The|the|A|a|An|an)$", "AT"), # articles
|
402 |
+
(r".*able$", "JJ"), # adjectives
|
403 |
+
(r".*ness$", "NN"), # nouns formed from adjectives
|
404 |
+
(r".*ly$", "RB"), # adverbs
|
405 |
+
(r".*s$", "NNS"), # plural nouns
|
406 |
+
(r".*ing$", "VBG"), # gerunds
|
407 |
+
(r".*ed$", "VBD"), # past tense verbs
|
408 |
+
(r".*", "NN"), # nouns (default)
|
409 |
+
]
|
410 |
+
)
|
411 |
+
|
412 |
+
|
413 |
+
def corpus_size(seqs):
|
414 |
+
return (len(seqs), sum(len(x) for x in seqs))
|
415 |
+
|
416 |
+
|
417 |
+
if __name__ == "__main__":
|
418 |
+
demo_learning_curve()
|
llmeval-env/lib/python3.10/site-packages/nltk/tbl/erroranalysis.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Transformation-based learning
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Marcus Uneson <[email protected]>
|
5 |
+
# based on previous (nltk2) version by
|
6 |
+
# Christopher Maloof, Edward Loper, Steven Bird
|
7 |
+
# URL: <https://www.nltk.org/>
|
8 |
+
# For license information, see LICENSE.TXT
|
9 |
+
|
10 |
+
# returns a list of errors in string format
|
11 |
+
|
12 |
+
|
13 |
+
def error_list(train_sents, test_sents):
|
14 |
+
"""
|
15 |
+
Returns a list of human-readable strings indicating the errors in the
|
16 |
+
given tagging of the corpus.
|
17 |
+
|
18 |
+
:param train_sents: The correct tagging of the corpus
|
19 |
+
:type train_sents: list(tuple)
|
20 |
+
:param test_sents: The tagged corpus
|
21 |
+
:type test_sents: list(tuple)
|
22 |
+
"""
|
23 |
+
hdr = ("%25s | %s | %s\n" + "-" * 26 + "+" + "-" * 24 + "+" + "-" * 26) % (
|
24 |
+
"left context",
|
25 |
+
"word/test->gold".center(22),
|
26 |
+
"right context",
|
27 |
+
)
|
28 |
+
errors = [hdr]
|
29 |
+
for (train_sent, test_sent) in zip(train_sents, test_sents):
|
30 |
+
for wordnum, (word, train_pos) in enumerate(train_sent):
|
31 |
+
test_pos = test_sent[wordnum][1]
|
32 |
+
if train_pos != test_pos:
|
33 |
+
left = " ".join("%s/%s" % w for w in train_sent[:wordnum])
|
34 |
+
right = " ".join("%s/%s" % w for w in train_sent[wordnum + 1 :])
|
35 |
+
mid = f"{word}/{test_pos}->{train_pos}"
|
36 |
+
errors.append(f"{left[-25:]:>25} | {mid.center(22)} | {right[:25]}")
|
37 |
+
|
38 |
+
return errors
|
llmeval-env/lib/python3.10/site-packages/nltk/tbl/feature.py
ADDED
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Natural Language Toolkit: Transformation-based learning
|
2 |
+
#
|
3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
4 |
+
# Author: Marcus Uneson <[email protected]>
|
5 |
+
# based on previous (nltk2) version by
|
6 |
+
# Christopher Maloof, Edward Loper, Steven Bird
|
7 |
+
# URL: <https://www.nltk.org/>
|
8 |
+
# For license information, see LICENSE.TXT
|
9 |
+
|
10 |
+
from abc import ABCMeta, abstractmethod
|
11 |
+
|
12 |
+
|
13 |
+
class Feature(metaclass=ABCMeta):
|
14 |
+
"""
|
15 |
+
An abstract base class for Features. A Feature is a combination of
|
16 |
+
a specific property-computing method and a list of relative positions
|
17 |
+
to apply that method to.
|
18 |
+
|
19 |
+
The property-computing method, M{extract_property(tokens, index)},
|
20 |
+
must be implemented by every subclass. It extracts or computes a specific
|
21 |
+
property for the token at the current index. Typical extract_property()
|
22 |
+
methods return features such as the token text or tag; but more involved
|
23 |
+
methods may consider the entire sequence M{tokens} and
|
24 |
+
for instance compute the length of the sentence the token belongs to.
|
25 |
+
|
26 |
+
In addition, the subclass may have a PROPERTY_NAME, which is how
|
27 |
+
it will be printed (in Rules and Templates, etc). If not given, defaults
|
28 |
+
to the classname.
|
29 |
+
|
30 |
+
"""
|
31 |
+
|
32 |
+
json_tag = "nltk.tbl.Feature"
|
33 |
+
PROPERTY_NAME = None
|
34 |
+
|
35 |
+
def __init__(self, positions, end=None):
|
36 |
+
"""
|
37 |
+
Construct a Feature which may apply at C{positions}.
|
38 |
+
|
39 |
+
>>> # For instance, importing some concrete subclasses (Feature is abstract)
|
40 |
+
>>> from nltk.tag.brill import Word, Pos
|
41 |
+
|
42 |
+
>>> # Feature Word, applying at one of [-2, -1]
|
43 |
+
>>> Word([-2,-1])
|
44 |
+
Word([-2, -1])
|
45 |
+
|
46 |
+
>>> # Positions need not be contiguous
|
47 |
+
>>> Word([-2,-1, 1])
|
48 |
+
Word([-2, -1, 1])
|
49 |
+
|
50 |
+
>>> # Contiguous ranges can alternatively be specified giving the
|
51 |
+
>>> # two endpoints (inclusive)
|
52 |
+
>>> Pos(-3, -1)
|
53 |
+
Pos([-3, -2, -1])
|
54 |
+
|
55 |
+
>>> # In two-arg form, start <= end is enforced
|
56 |
+
>>> Pos(2, 1)
|
57 |
+
Traceback (most recent call last):
|
58 |
+
File "<stdin>", line 1, in <module>
|
59 |
+
File "nltk/tbl/template.py", line 306, in __init__
|
60 |
+
raise TypeError
|
61 |
+
ValueError: illegal interval specification: (start=2, end=1)
|
62 |
+
|
63 |
+
:type positions: list of int
|
64 |
+
:param positions: the positions at which this features should apply
|
65 |
+
:raises ValueError: illegal position specifications
|
66 |
+
|
67 |
+
An alternative calling convention, for contiguous positions only,
|
68 |
+
is Feature(start, end):
|
69 |
+
|
70 |
+
:type start: int
|
71 |
+
:param start: start of range where this feature should apply
|
72 |
+
:type end: int
|
73 |
+
:param end: end of range (NOTE: inclusive!) where this feature should apply
|
74 |
+
"""
|
75 |
+
self.positions = None # to avoid warnings
|
76 |
+
if end is None:
|
77 |
+
self.positions = tuple(sorted({int(i) for i in positions}))
|
78 |
+
else: # positions was actually not a list, but only the start index
|
79 |
+
try:
|
80 |
+
if positions > end:
|
81 |
+
raise TypeError
|
82 |
+
self.positions = tuple(range(positions, end + 1))
|
83 |
+
except TypeError as e:
|
84 |
+
# let any kind of erroneous spec raise ValueError
|
85 |
+
raise ValueError(
|
86 |
+
"illegal interval specification: (start={}, end={})".format(
|
87 |
+
positions, end
|
88 |
+
)
|
89 |
+
) from e
|
90 |
+
|
91 |
+
# set property name given in subclass, or otherwise name of subclass
|
92 |
+
self.PROPERTY_NAME = self.__class__.PROPERTY_NAME or self.__class__.__name__
|
93 |
+
|
94 |
+
def encode_json_obj(self):
|
95 |
+
return self.positions
|
96 |
+
|
97 |
+
@classmethod
|
98 |
+
def decode_json_obj(cls, obj):
|
99 |
+
positions = obj
|
100 |
+
return cls(positions)
|
101 |
+
|
102 |
+
def __repr__(self):
|
103 |
+
return f"{self.__class__.__name__}({list(self.positions)!r})"
|
104 |
+
|
105 |
+
@classmethod
|
106 |
+
def expand(cls, starts, winlens, excludezero=False):
|
107 |
+
"""
|
108 |
+
Return a list of features, one for each start point in starts
|
109 |
+
and for each window length in winlen. If excludezero is True,
|
110 |
+
no Features containing 0 in its positions will be generated
|
111 |
+
(many tbl trainers have a special representation for the
|
112 |
+
target feature at [0])
|
113 |
+
|
114 |
+
For instance, importing a concrete subclass (Feature is abstract)
|
115 |
+
|
116 |
+
>>> from nltk.tag.brill import Word
|
117 |
+
|
118 |
+
First argument gives the possible start positions, second the
|
119 |
+
possible window lengths
|
120 |
+
|
121 |
+
>>> Word.expand([-3,-2,-1], [1])
|
122 |
+
[Word([-3]), Word([-2]), Word([-1])]
|
123 |
+
|
124 |
+
>>> Word.expand([-2,-1], [1])
|
125 |
+
[Word([-2]), Word([-1])]
|
126 |
+
|
127 |
+
>>> Word.expand([-3,-2,-1], [1,2])
|
128 |
+
[Word([-3]), Word([-2]), Word([-1]), Word([-3, -2]), Word([-2, -1])]
|
129 |
+
|
130 |
+
>>> Word.expand([-2,-1], [1])
|
131 |
+
[Word([-2]), Word([-1])]
|
132 |
+
|
133 |
+
A third optional argument excludes all Features whose positions contain zero
|
134 |
+
|
135 |
+
>>> Word.expand([-2,-1,0], [1,2], excludezero=False)
|
136 |
+
[Word([-2]), Word([-1]), Word([0]), Word([-2, -1]), Word([-1, 0])]
|
137 |
+
|
138 |
+
>>> Word.expand([-2,-1,0], [1,2], excludezero=True)
|
139 |
+
[Word([-2]), Word([-1]), Word([-2, -1])]
|
140 |
+
|
141 |
+
All window lengths must be positive
|
142 |
+
|
143 |
+
>>> Word.expand([-2,-1], [0])
|
144 |
+
Traceback (most recent call last):
|
145 |
+
File "<stdin>", line 1, in <module>
|
146 |
+
File "nltk/tag/tbl/template.py", line 371, in expand
|
147 |
+
:param starts: where to start looking for Feature
|
148 |
+
ValueError: non-positive window length in [0]
|
149 |
+
|
150 |
+
:param starts: where to start looking for Feature
|
151 |
+
:type starts: list of ints
|
152 |
+
:param winlens: window lengths where to look for Feature
|
153 |
+
:type starts: list of ints
|
154 |
+
:param excludezero: do not output any Feature with 0 in any of its positions.
|
155 |
+
:type excludezero: bool
|
156 |
+
:returns: list of Features
|
157 |
+
:raises ValueError: for non-positive window lengths
|
158 |
+
"""
|
159 |
+
if not all(x > 0 for x in winlens):
|
160 |
+
raise ValueError(f"non-positive window length in {winlens}")
|
161 |
+
xs = (starts[i : i + w] for w in winlens for i in range(len(starts) - w + 1))
|
162 |
+
return [cls(x) for x in xs if not (excludezero and 0 in x)]
|
163 |
+
|
164 |
+
def issuperset(self, other):
|
165 |
+
"""
|
166 |
+
Return True if this Feature always returns True when other does
|
167 |
+
|
168 |
+
More precisely, return True if this feature refers to the same property as other;
|
169 |
+
and this Feature looks at all positions that other does (and possibly
|
170 |
+
other positions in addition).
|
171 |
+
|
172 |
+
#For instance, importing a concrete subclass (Feature is abstract)
|
173 |
+
>>> from nltk.tag.brill import Word, Pos
|
174 |
+
|
175 |
+
>>> Word([-3,-2,-1]).issuperset(Word([-3,-2]))
|
176 |
+
True
|
177 |
+
|
178 |
+
>>> Word([-3,-2,-1]).issuperset(Word([-3,-2, 0]))
|
179 |
+
False
|
180 |
+
|
181 |
+
#Feature subclasses must agree
|
182 |
+
>>> Word([-3,-2,-1]).issuperset(Pos([-3,-2]))
|
183 |
+
False
|
184 |
+
|
185 |
+
:param other: feature with which to compare
|
186 |
+
:type other: (subclass of) Feature
|
187 |
+
:return: True if this feature is superset, otherwise False
|
188 |
+
:rtype: bool
|
189 |
+
|
190 |
+
|
191 |
+
"""
|
192 |
+
return self.__class__ is other.__class__ and set(self.positions) >= set(
|
193 |
+
other.positions
|
194 |
+
)
|
195 |
+
|
196 |
+
def intersects(self, other):
|
197 |
+
"""
|
198 |
+
Return True if the positions of this Feature intersects with those of other
|
199 |
+
|
200 |
+
More precisely, return True if this feature refers to the same property as other;
|
201 |
+
and there is some overlap in the positions they look at.
|
202 |
+
|
203 |
+
#For instance, importing a concrete subclass (Feature is abstract)
|
204 |
+
>>> from nltk.tag.brill import Word, Pos
|
205 |
+
|
206 |
+
>>> Word([-3,-2,-1]).intersects(Word([-3,-2]))
|
207 |
+
True
|
208 |
+
|
209 |
+
>>> Word([-3,-2,-1]).intersects(Word([-3,-2, 0]))
|
210 |
+
True
|
211 |
+
|
212 |
+
>>> Word([-3,-2,-1]).intersects(Word([0]))
|
213 |
+
False
|
214 |
+
|
215 |
+
#Feature subclasses must agree
|
216 |
+
>>> Word([-3,-2,-1]).intersects(Pos([-3,-2]))
|
217 |
+
False
|
218 |
+
|
219 |
+
:param other: feature with which to compare
|
220 |
+
:type other: (subclass of) Feature
|
221 |
+
:return: True if feature classes agree and there is some overlap in the positions they look at
|
222 |
+
:rtype: bool
|
223 |
+
"""
|
224 |
+
|
225 |
+
return bool(
|
226 |
+
self.__class__ is other.__class__
|
227 |
+
and set(self.positions) & set(other.positions)
|
228 |
+
)
|
229 |
+
|
230 |
+
# Rich comparisons for Features. With @functools.total_ordering (Python 2.7+),
|
231 |
+
# it will be enough to define __lt__ and __eq__
|
232 |
+
def __eq__(self, other):
|
233 |
+
return self.__class__ is other.__class__ and self.positions == other.positions
|
234 |
+
|
235 |
+
def __lt__(self, other):
|
236 |
+
return (
|
237 |
+
self.__class__.__name__ < other.__class__.__name__
|
238 |
+
or
|
239 |
+
# self.positions is a sorted tuple of ints
|
240 |
+
self.positions < other.positions
|
241 |
+
)
|
242 |
+
|
243 |
+
def __ne__(self, other):
|
244 |
+
return not (self == other)
|
245 |
+
|
246 |
+
def __gt__(self, other):
|
247 |
+
return other < self
|
248 |
+
|
249 |
+
def __ge__(self, other):
|
250 |
+
return not self < other
|
251 |
+
|
252 |
+
def __le__(self, other):
|
253 |
+
return self < other or self == other
|
254 |
+
|
255 |
+
@staticmethod
|
256 |
+
@abstractmethod
|
257 |
+
def extract_property(tokens, index):
|
258 |
+
"""
|
259 |
+
Any subclass of Feature must define static method extract_property(tokens, index)
|
260 |
+
|
261 |
+
:param tokens: the sequence of tokens
|
262 |
+
:type tokens: list of tokens
|
263 |
+
:param index: the current index
|
264 |
+
:type index: int
|
265 |
+
:return: feature value
|
266 |
+
:rtype: any (but usually scalar)
|
267 |
+
"""
|