mirror of
https://github.com/evennia/evennia.git
synced 2026-03-16 21:06:30 +01:00
Add verb conjugation module
This commit is contained in:
parent
2c7163ba74
commit
24a6d2cfab
10 changed files with 10193 additions and 22 deletions
|
|
@ -42,6 +42,8 @@
|
|||
user davewiththenicehat. Also add new doc string.
|
||||
- Add central `FuncParser` as a much more powerful replacement for the old `parse_inlinefunc`
|
||||
function.
|
||||
- Add `evennia/utils/verb_conjugation` for automatic verb conjugation (English only). This
|
||||
is useful for implementing actor-stance emoting for sending a string to different targets.
|
||||
|
||||
### Evennia 0.9.5 (2019-2020)
|
||||
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ from evennia.utils.ansi import raw as ansi_raw
|
|||
|
||||
COMMAND_DEFAULT_CLASS = class_from_module(settings.COMMAND_DEFAULT_CLASS)
|
||||
|
||||
_FUNCPARSER = funcparser.FuncParser(settings.INLINEFUNC_MODULES)
|
||||
_FUNCPARSER = None
|
||||
|
||||
# limit symbol import for API
|
||||
__all__ = (
|
||||
|
|
@ -2381,6 +2381,10 @@ class CmdExamine(ObjManipCommand):
|
|||
value (any): Attribute value.
|
||||
Returns:
|
||||
"""
|
||||
global _FUNCPARSER
|
||||
if not _FUNCPARSER:
|
||||
_FUNCPARSER = funcparser.FuncParser(settings.INLINEFUNC_MODULES)
|
||||
|
||||
if attr is None:
|
||||
return "No such attribute was found."
|
||||
value = utils.to_str(value)
|
||||
|
|
|
|||
|
|
@ -24,7 +24,6 @@ def funcname(*args, **kwargs):
|
|||
...
|
||||
return something
|
||||
|
||||
|
||||
```
|
||||
|
||||
Usage:
|
||||
|
|
@ -43,9 +42,16 @@ The `FuncParser` also accepts a direct dict mapping of `{'name': callable, ...}`
|
|||
"""
|
||||
import dataclasses
|
||||
import inspect
|
||||
import random
|
||||
from django.conf import settings
|
||||
from ast import literal_eval
|
||||
from simpleeval import simple_eval
|
||||
from evennia.utils import logger
|
||||
from evennia.utils.utils import make_iter, callables_from_module
|
||||
from evennia.utils.utils import (
|
||||
make_iter, callables_from_module, variable_from_module, pad, crop, justify)
|
||||
from evennia.utils import search
|
||||
|
||||
_CLIENT_DEFAULT_WIDTH = settings.CLIENT_DEFAULT_WIDTH
|
||||
_MAX_NESTING = 20
|
||||
|
||||
_ESCAPE_CHAR = "\\"
|
||||
|
|
@ -95,7 +101,7 @@ class FuncParser:
|
|||
"""
|
||||
|
||||
def __init__(self,
|
||||
safe_callables,
|
||||
callables,
|
||||
start_char=_START_CHAR,
|
||||
escape_char=_ESCAPE_CHAR,
|
||||
max_nesting=_MAX_NESTING,
|
||||
|
|
@ -104,15 +110,16 @@ class FuncParser:
|
|||
Initialize the parser.
|
||||
|
||||
Args:
|
||||
safe_callables (str, module, list or dict): Where to find
|
||||
'safe' functions to make available in the parser. All callables
|
||||
in provided modules (whose names don't start with an
|
||||
underscore) are considered valid functions to access as
|
||||
`$funcname(*args, **kwags)` during parsing. If a `str`, this
|
||||
should be the path to such a module. A `list` can either be a
|
||||
list of paths or module objects. If a `dict`, this should be a
|
||||
mapping `{"funcname": callable, ...}` - this will be used
|
||||
directly as valid parseable functions.
|
||||
callables (str, module, list or dict): Where to find
|
||||
'safe' functions to make available in the parser. These modules
|
||||
can have a dict `FUNCPARSER_CALLABLES = {"funcname": callable, ...}`.
|
||||
If no such dict exists, all callables in provided modules (whose names
|
||||
don't start with an underscore) will be loaded as callables. Each
|
||||
callable will will be available to call as `$funcname(*args, **kwags)`
|
||||
during parsing. If `callables` is a `str`, this should be the path
|
||||
to such a module. A `list` can either be a list of paths or module
|
||||
objects. If a `dict`, this should be a direct mapping
|
||||
`{"funcname": callable, ...}` to use.
|
||||
start_char (str, optional): A character used to identify the beginning
|
||||
of a parseable function. Default is `$`.
|
||||
escape_char (str, optional): Prepend characters with this to have
|
||||
|
|
@ -127,17 +134,29 @@ class FuncParser:
|
|||
into `.parse` as `**reserved_kwargs` instead.
|
||||
|
||||
"""
|
||||
if isinstance(safe_callables, dict):
|
||||
callables = {**safe_callables}
|
||||
if isinstance(callables, dict):
|
||||
loaded_callables = {**callables}
|
||||
else:
|
||||
# load all modules/paths in sequence. Later-added will override
|
||||
# earlier same-named callables (allows for overriding evennia defaults)
|
||||
callables = {}
|
||||
for safe_callable in make_iter(safe_callables):
|
||||
# callables_from_module handles both paths and module instances
|
||||
callables.update(callables_from_module(safe_callable))
|
||||
self.validate_callables(callables)
|
||||
self.callables = callables
|
||||
loaded_callables = {}
|
||||
for module_or_path in make_iter(callables):
|
||||
callables_mapping = variable_from_module(
|
||||
module_or_path, variable="FUNCPARSER_CALLABLES")
|
||||
if callables_mapping:
|
||||
try:
|
||||
# mapping supplied in variable
|
||||
loaded_callables.update(callables_mapping)
|
||||
except ValueError:
|
||||
raise ParsingError(
|
||||
f"Failure to parse - {module_or_path}.FUNCPARSER_CALLABLES "
|
||||
"(must be a dict {'funcname': callable, ...})")
|
||||
else:
|
||||
# use all top-level variables
|
||||
# (handles both paths and module instances
|
||||
loaded_callables.update(callables_from_module(module_or_path))
|
||||
self.validate_callables(loaded_callables)
|
||||
self.callables = loaded_callables
|
||||
self.escape_char = escape_char
|
||||
self.start_char = start_char
|
||||
self.default_kwargs = default_kwargs
|
||||
|
|
@ -555,3 +574,593 @@ class FuncParser:
|
|||
return_str=False, **reserved_kwargs)
|
||||
|
||||
|
||||
#
|
||||
# Default funcparser callables. These are made available from this module's
|
||||
# FUNCPARSER_CALLABLES.
|
||||
#
|
||||
|
||||
def funcparser_callable_eval(*args, **kwargs):
|
||||
"""
|
||||
Funcparser callable. This will combine safe evaluations to try to parse the
|
||||
incoming string into a python object. If it fails, the return will be same
|
||||
as the input.
|
||||
|
||||
Args
|
||||
string (str): The string to parse. Only simple literals or operators are allowed.
|
||||
|
||||
Returns:
|
||||
any: The string parsed into its Python form, or the same as input.
|
||||
|
||||
Example:
|
||||
`$py(1)`
|
||||
`$py([1,2,3,4])`
|
||||
`$py(3 + 4)`
|
||||
|
||||
"""
|
||||
if not args:
|
||||
return ''
|
||||
inp = args[0]
|
||||
if not isinstance(inp, str):
|
||||
# already converted
|
||||
return inp
|
||||
try:
|
||||
return literal_eval(inp)
|
||||
except Exception:
|
||||
try:
|
||||
return simple_eval(inp)
|
||||
except Exception:
|
||||
return inp
|
||||
|
||||
|
||||
def funcparser_callable_toint(*args, **kwargs):
|
||||
"""Usage: toint(43.0) -> 43"""
|
||||
inp = funcparser_callable_eval(*args, **kwargs)
|
||||
try:
|
||||
return int(inp)
|
||||
except TypeError:
|
||||
return inp
|
||||
|
||||
|
||||
def _apply_operation_two_elements(*args, operator="+", **kwargs):
|
||||
"""
|
||||
Helper operating on two arguments
|
||||
|
||||
Args:
|
||||
val1 (any): First value to operate on.
|
||||
val2 (any): Second value to operate on.
|
||||
|
||||
Return:
|
||||
any: The result of val1 + val2. Values must be
|
||||
valid simple Python structures possible to add,
|
||||
such as numbers, lists etc. The $eval is usually
|
||||
better for non-list arithmetic.
|
||||
|
||||
"""
|
||||
if not len(args) > 1:
|
||||
return ''
|
||||
val1, val2 = args[0], args[1]
|
||||
# try to convert to python structures, otherwise, keep as strings
|
||||
if isinstance(val1, str):
|
||||
try:
|
||||
val1 = literal_eval(val1.strip())
|
||||
except Exception:
|
||||
pass
|
||||
if isinstance(val2, str):
|
||||
try:
|
||||
val2 = literal_eval(val2.strip())
|
||||
except Exception:
|
||||
pass
|
||||
if operator == "+":
|
||||
return val1 + val2
|
||||
elif operator == "-":
|
||||
return val1 - val2
|
||||
elif operator == "*":
|
||||
return val1 * val2
|
||||
elif operator == "/":
|
||||
return val1 / val2
|
||||
|
||||
|
||||
def funcparser_callable_add(*args, **kwargs):
|
||||
"""Usage: $add(val1, val2) -> val1 + val2"""
|
||||
return _apply_operation_two_elements(*args, operator='+', **kwargs)
|
||||
|
||||
|
||||
def funcparser_callable_sub(*args, **kwargs):
|
||||
"""Usage: $sub(val1, val2) -> val1 - val2"""
|
||||
return _apply_operation_two_elements(*args, operator='-', **kwargs)
|
||||
|
||||
|
||||
def funcparser_callable_mult(*args, **kwargs):
|
||||
"""Usage: $mult(val1, val2) -> val1 * val2"""
|
||||
return _apply_operation_two_elements(*args, operator='*', **kwargs)
|
||||
|
||||
|
||||
def funcparser_callable_div(*args, **kwargs):
|
||||
"""Usage: $mult(val1, val2) -> val1 / val2"""
|
||||
return _apply_operation_two_elements(*args, operator='/', **kwargs)
|
||||
|
||||
|
||||
def funcparser_callable_round(*args, **kwargs):
|
||||
"""
|
||||
Funcparser callable. Rounds an incoming float to a
|
||||
certain number of significant digits.
|
||||
|
||||
Args:
|
||||
inp (str or number): If a string, it will attempt
|
||||
to be converted to a number first.
|
||||
significant (int): The number of significant digits. Default is None -
|
||||
this will turn the result into an int.
|
||||
|
||||
Returns:
|
||||
any: The rounded value or inp if inp was not a number.
|
||||
|
||||
Examples:
|
||||
- `$round(3.5434343, 3)` - gives 3.543
|
||||
- `$round($random(), 2)` - rounds random result, e.g 0.22
|
||||
|
||||
"""
|
||||
if not args:
|
||||
return ''
|
||||
inp, *significant = args
|
||||
significant = significant[0] if significant else '0'
|
||||
lit_inp = inp
|
||||
if isinstance(inp, str):
|
||||
try:
|
||||
lit_inp = literal_eval(inp)
|
||||
except Exception:
|
||||
return inp
|
||||
try:
|
||||
int(significant)
|
||||
except Exception:
|
||||
significant = 0
|
||||
try:
|
||||
round(lit_inp, significant)
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
def funcparser_callable_random(*args, **kwargs):
|
||||
"""
|
||||
Funcparser callable. Returns a random number between 0 and 1, from 0 to a
|
||||
maximum value, or within a given range (inclusive).
|
||||
|
||||
Args:
|
||||
minval (str, optional): Minimum value. If not given, assumed 0.
|
||||
maxval (str, optional): Maximum value.
|
||||
|
||||
Notes:
|
||||
If either of the min/maxvalue has a '.' in it, a floating-point random
|
||||
value will be returned. Otherwise it will be an
|
||||
integer value in the given range.
|
||||
|
||||
Examples:
|
||||
- `$random()` - random value [0 .. 1) (float).
|
||||
- `$random(5)` - random value [0..5] (int)
|
||||
- `$random(5.0)` - random value [0..5] (float)
|
||||
- `$random(5, 10)` - random value [5..10] (int)
|
||||
- `$random(5, 10.0)` - random value [5..10] (float)
|
||||
|
||||
"""
|
||||
nargs = len(args)
|
||||
if nargs == 1:
|
||||
# only maxval given
|
||||
minval, maxval = "0", args[0]
|
||||
elif nargs > 1:
|
||||
minval, maxval = args[:2]
|
||||
else:
|
||||
minval, maxval = ("0", "1")
|
||||
|
||||
if "." in minval or "." in maxval:
|
||||
# float mode
|
||||
try:
|
||||
minval, maxval = float(minval), float(maxval)
|
||||
except ValueError:
|
||||
minval, maxval = 0, 1
|
||||
return minval + maxval * random.random()
|
||||
else:
|
||||
# int mode
|
||||
try:
|
||||
minval, maxval = int(minval), int(maxval)
|
||||
except ValueError:
|
||||
minval, maxval = 0, 1
|
||||
return random.randint(minval, maxval)
|
||||
|
||||
def funcparser_callable_randint(*args, **kwargs):
|
||||
"""
|
||||
Usage: $randint(start, end):
|
||||
|
||||
Legacy alias - alwas returns integers.
|
||||
|
||||
"""
|
||||
return int(funcparser_callable_random(*args, **kwargs))
|
||||
|
||||
|
||||
def funcparser_callable_choice(*args, **kwargs):
|
||||
"""
|
||||
FuncParser callable. Picks a random choice from a list.
|
||||
|
||||
Args:
|
||||
listing (list): A list of items to randomly choose between.
|
||||
This will be converted from a string to a real list.
|
||||
|
||||
Returns:
|
||||
any: The randomly chosen element.
|
||||
|
||||
Example:
|
||||
- `$choice([key, flower, house])`
|
||||
- `$choice([1, 2, 3, 4])`
|
||||
|
||||
"""
|
||||
if not args:
|
||||
return ''
|
||||
inp = args[0]
|
||||
if not isinstance(inp, str):
|
||||
inp = literal_eval(inp)
|
||||
return random.choice(inp)
|
||||
|
||||
|
||||
def funcparser_callable_pad(*args, **kwargs):
|
||||
"""
|
||||
FuncParser callable. Pads text to given width, optionally with fill-characters
|
||||
|
||||
Args:
|
||||
text (str): Text to pad.
|
||||
width (int): Width of padding.
|
||||
align (str, optional): Alignment of padding; one of 'c', 'l' or 'r'.
|
||||
fillchar (str, optional): Character used for padding. Defaults to a space.
|
||||
|
||||
Example:
|
||||
- `$pad(text, 12, l, ' ')`
|
||||
- `$pad(text, width=12, align=c, fillchar=-)`
|
||||
|
||||
"""
|
||||
if not args:
|
||||
return ''
|
||||
text, *rest = args
|
||||
nargs = len(args)
|
||||
try:
|
||||
width = int(kwargs.get("width", rest[0] if nargs > 0 else _CLIENT_DEFAULT_WIDTH))
|
||||
except TypeError:
|
||||
width = _CLIENT_DEFAULT_WIDTH
|
||||
align = kwargs.get("align", rest[1] if nargs > 1 else 'c')
|
||||
fillchar = kwargs.get("fillchar", rest[2] if nargs > 2 else ' ')
|
||||
if fillchar not in ('c', 'l', 'r'):
|
||||
fillchar = 'c'
|
||||
return pad(str(text), width=width, align=align, fillchar=fillchar)
|
||||
|
||||
|
||||
def funcparser_callable_space(*args, **kwarg):
|
||||
"""
|
||||
Usage: $space(43)
|
||||
|
||||
Insert a length of space.
|
||||
|
||||
"""
|
||||
if not args:
|
||||
return ''
|
||||
try:
|
||||
width = int(args[0])
|
||||
except TypeError:
|
||||
width = 1
|
||||
return " " * width
|
||||
|
||||
|
||||
def funcparser_callable_crop(*args, **kwargs):
|
||||
"""
|
||||
FuncParser callable. Crops ingoing text to given widths.
|
||||
|
||||
Args:
|
||||
text (str, optional): Text to crop.
|
||||
width (str, optional): Will be converted to an integer. Width of
|
||||
crop in characters.
|
||||
suffix (str, optional): End string to mark the fact that a part
|
||||
of the string was cropped. Defaults to `[...]`.
|
||||
|
||||
Example:
|
||||
`$crop(text, 78, [...])`
|
||||
`$crop(text, width=78, suffix='[...]')`
|
||||
|
||||
"""
|
||||
if not args:
|
||||
return ''
|
||||
text, *rest = args
|
||||
nargs = len(args)
|
||||
try:
|
||||
width = int(kwargs.get("width", rest[0] if nargs > 0 else _CLIENT_DEFAULT_WIDTH))
|
||||
except TypeError:
|
||||
width = _CLIENT_DEFAULT_WIDTH
|
||||
suffix = kwargs.get('suffix', rest[1] if nargs > 1 else "[...]")
|
||||
return crop(str(text), width=width, suffix=str(suffix))
|
||||
|
||||
|
||||
def funcparser_callable_justify(*args, **kwargs):
|
||||
"""
|
||||
Justify text across a width, default across screen width.
|
||||
|
||||
Args:
|
||||
text (str): Text to justify.
|
||||
width (int, optional): Defaults to default screen width.
|
||||
align (str, optional): One of 'l', 'c', 'r' or 'f' for 'full'.
|
||||
indent (int, optional): Intendation of text block, if any.
|
||||
|
||||
Returns:
|
||||
str: The justified text.
|
||||
|
||||
Examples:
|
||||
- $just(text, width=40)
|
||||
- $just(text, align=r, indent=2)
|
||||
|
||||
"""
|
||||
if not args:
|
||||
return ''
|
||||
text = args[0]
|
||||
try:
|
||||
width = int(kwargs.get("width", _CLIENT_DEFAULT_WIDTH))
|
||||
except TypeError:
|
||||
width = _CLIENT_DEFAULT_WIDTH
|
||||
align = str(kwargs.get("align", 'f'))
|
||||
try:
|
||||
indent = int(kwargs.get("indent", 0))
|
||||
except TypeError:
|
||||
indent = 0
|
||||
return justify(str(text), width=width, align=align, indent=indent)
|
||||
|
||||
|
||||
# legacy for backwards compatibility
|
||||
def funcparser_callable_left_justify(*args, **kwargs):
|
||||
"Usage: $ljust(text)"
|
||||
return funcparser_callable_justify(*args, justify='l', **kwargs)
|
||||
|
||||
|
||||
def funcparser_callable_right_justify(*args, **kwargs):
|
||||
"Usage: $rjust(text)"
|
||||
return funcparser_callable_justify(*args, justify='r', **kwargs)
|
||||
|
||||
|
||||
def funcparser_callable_center_justify(*args, **kwargs):
|
||||
"Usage: $cjust(text)"
|
||||
return funcparser_callable_justify(*args, justify='c', **kwargs)
|
||||
|
||||
|
||||
def funcparser_callable_clr(*args, **kwargs):
|
||||
"""
|
||||
FuncParser callable. Colorizes nested text.
|
||||
|
||||
Args:
|
||||
startclr (str, optional): An ANSI color abbreviation without the
|
||||
prefix `|`, such as `r` (red foreground) or `[r` (red background).
|
||||
text (str, optional): Text
|
||||
endclr (str, optional): The color to use at the end of the string. Defaults
|
||||
to `|n` (reset-color).
|
||||
Kwargs:
|
||||
color (str, optional): If given,
|
||||
|
||||
Example:
|
||||
- `$clr(r, text, n)`
|
||||
- `$clr(r, text)`
|
||||
- `$clr(text, start=r, end=n)`
|
||||
|
||||
"""
|
||||
if not args:
|
||||
return ''
|
||||
startclr, text, endclr = '', '', ''
|
||||
if len(args) > 1:
|
||||
# $clr(pre, text, post))
|
||||
startclr, *rest = args
|
||||
if rest:
|
||||
text, *endclr = rest
|
||||
if endclr:
|
||||
endclr = endclr[0]
|
||||
else:
|
||||
# $clr(text, start=pre, end=post)
|
||||
text = args[0]
|
||||
startclr = kwargs.get("start", '')
|
||||
endclr = kwargs.get("end", '')
|
||||
|
||||
startclr = "|" + startclr if startclr else ""
|
||||
endclr = "|" + endclr if endclr else ("|n" if startclr else '')
|
||||
return f"{startclr}{text}{endclr}"
|
||||
|
||||
|
||||
def funcparser_callable_search(*args, caller=None, access="control", **kwargs):
|
||||
"""
|
||||
FuncParser callable. Finds an object based on name or #dbref. Note that
|
||||
this requries the parser be called with the caller's Session for proper
|
||||
security. If called without session, the call is aborted.
|
||||
|
||||
Args:
|
||||
query (str): The key or dbref to search for.
|
||||
|
||||
Kwargs:
|
||||
return_list (bool): If set, return a list of objects with
|
||||
0, 1 or more matches to `query`. Defaults to False.
|
||||
type (str): One of 'obj', 'account', 'script'
|
||||
caller (Entity): Supplied to Parser. This is required and will
|
||||
be passed into the access check for the entity being searched for.
|
||||
The 'control' permission is required.
|
||||
access (str): Which locktype access to check. Unset to disable the
|
||||
security check.
|
||||
|
||||
Returns:
|
||||
any: An entity match or None if no match or a list if `return_list` is set.
|
||||
|
||||
Raise:
|
||||
ParsingError: If zero/multimatch and `return_list` is False.
|
||||
|
||||
Examples:
|
||||
- "$search(#233)"
|
||||
- "$search(Tom, type=account)"
|
||||
- "$search(meadow, return_list=True)"
|
||||
|
||||
"""
|
||||
return_list = bool(kwargs.get("return_list", "False"))
|
||||
|
||||
if not (args and caller):
|
||||
return [] if return_list else None
|
||||
|
||||
query = str(args[0])
|
||||
|
||||
typ = kwargs.get("type", "obj")
|
||||
targets = []
|
||||
if typ == "obj":
|
||||
targets = search.search_object(query)
|
||||
elif typ == "account":
|
||||
targets = search.search_account(query)
|
||||
elif typ == "script":
|
||||
targets = search.search_script(query)
|
||||
|
||||
if not targets:
|
||||
if return_list:
|
||||
return []
|
||||
raise ParsingError(f"$search: Query '{query}' gave no matches.")
|
||||
|
||||
if len(targets) > 1 and not return_list:
|
||||
raise ParsingError("$search: Query '{query}' found {num} matches. "
|
||||
"Set return_list=True to accept a list".format(
|
||||
query=query, num=len(targets)))
|
||||
|
||||
for target in targets:
|
||||
if not target.access(caller, target, access):
|
||||
raise ParsingError('$search Cannot add found entity - access failure.')
|
||||
|
||||
return list(targets) if return_list else targets[0]
|
||||
|
||||
|
||||
def funcparser_callable_search_list(*args, caller=None, access="control", **kwargs):
|
||||
"""
|
||||
Usage: $objlist(#123)
|
||||
|
||||
Legacy alias for search with a return_list=True kwarg preset.
|
||||
|
||||
"""
|
||||
return funcparser_callable_search(*args, caller=caller, access=access,
|
||||
return_list=True, **kwargs)
|
||||
|
||||
|
||||
def funcparser_callable_you(*args, you_obj=None, you_target=None, capitalize=False, **kwargs):
|
||||
"""
|
||||
Usage: %you()
|
||||
|
||||
Replaces with you for the caller of the string, with the display_name
|
||||
of the caller for others.
|
||||
|
||||
Kwargs:
|
||||
you_obj (Object): The object who represents 'you' in the string.
|
||||
you_target (Object): The recipient of the string.
|
||||
capitalize (bool): Passed by the You helper, to capitalize you.
|
||||
|
||||
Returns:
|
||||
str: The parsed string.
|
||||
|
||||
Raises:
|
||||
ParsingError: If `you_obj` and `you_target` were not supplied.
|
||||
|
||||
Notes:
|
||||
The kwargs must be supplied to the parse method. If not given,
|
||||
the parsing will be aborted. Note that it will not capitalize
|
||||
|
||||
Examples:
|
||||
This can be used by the say or emote hooks to pass actor stance
|
||||
strings. This should usually be combined with the $inflect() callable.
|
||||
|
||||
- `With a grin, $you() $conj(jump).`
|
||||
|
||||
The You-object will see "With a grin, you jump."
|
||||
Others will see "With a grin, CharName jumps."
|
||||
|
||||
"""
|
||||
if not (you_obj and you_target):
|
||||
raise ParsingError("No you_obj/target supplied to $you callable")
|
||||
capitalize = bool(capitalize)
|
||||
if you_obj == you_target:
|
||||
return "You" if capitalize else "you"
|
||||
return you_obj.get_display_name(looker=you_target)
|
||||
|
||||
|
||||
def funcparser_callable_You(*args, you_obj=None, you_target=None, capitalize=True, **kwargs):
|
||||
"""
|
||||
Usage: $You() - capitalizes the 'you' output.
|
||||
|
||||
"""
|
||||
return funcparser_callable_you(
|
||||
*args, you_obj=you_obj, you_target=you_target, capitalize=capitalize, **kwargs)
|
||||
|
||||
|
||||
def funcparser_callable_conjugate(*args, you_obj=None, you_target=None, **kwargs):
|
||||
"""
|
||||
Conjugate a verb according to if it should be 2nd or third person. The
|
||||
mlconjug3 package supports French, English, Italian, Portugese and Romanian
|
||||
(see https://pypi.org/project/mlconjug3/). The function will pick the
|
||||
language from settings.LANGUAGE_CODE, or English if an unsupported language
|
||||
was found.
|
||||
|
||||
Kwargs:
|
||||
you_obj (Object): The object who represents 'you' in the string.
|
||||
you_target (Object): The recipient of the string.
|
||||
|
||||
Returns:
|
||||
str: The parsed string.
|
||||
|
||||
Raises:
|
||||
ParsingError: If `you_obj` and `you_target` were not supplied.
|
||||
|
||||
Notes:
|
||||
The kwargs must be supplied to the parse method. If not given,
|
||||
the parsing will be aborted. Note that it will not capitalize
|
||||
|
||||
Exampels:
|
||||
This is often used in combination with the $you/You( callables.
|
||||
|
||||
- `With a grin, $you() $conj(jump)`
|
||||
|
||||
The You-object will see "With a grin, you jump."
|
||||
Others will see "With a grin, CharName jumps."
|
||||
|
||||
"""
|
||||
|
||||
if not (you_obj and you_target):
|
||||
raise ParsingError("No you_obj/target supplied to $conj callable")
|
||||
return ''
|
||||
|
||||
|
||||
# these are made available as callables by adding 'evennia.utils.funcparser' as
|
||||
# a callable-path when initializing the FuncParser.
|
||||
|
||||
FUNCPARSER_CALLABLES = {
|
||||
# eval and arithmetic
|
||||
"eval": funcparser_callable_eval,
|
||||
"add": funcparser_callable_add,
|
||||
"sub": funcparser_callable_sub,
|
||||
"mult": funcparser_callable_mult,
|
||||
"div": funcparser_callable_div,
|
||||
"round": funcparser_callable_round,
|
||||
"toint": funcparser_callable_toint,
|
||||
|
||||
# randomizers
|
||||
"random": funcparser_callable_random,
|
||||
"randint": funcparser_callable_randint,
|
||||
"choice": funcparser_callable_choice,
|
||||
|
||||
# string manip
|
||||
"pad": funcparser_callable_pad,
|
||||
"crop": funcparser_callable_crop,
|
||||
"just": funcparser_callable_justify,
|
||||
"ljust": funcparser_callable_left_justify,
|
||||
"rjust": funcparser_callable_right_justify,
|
||||
"cjust": funcparser_callable_center_justify,
|
||||
"justify": funcparser_callable_justify, # aliases for backwards compat
|
||||
"justify_left": funcparser_callable_left_justify,
|
||||
"justify_right": funcparser_callable_right_justify,
|
||||
"justify_center": funcparser_callable_center_justify,
|
||||
"space": funcparser_callable_space,
|
||||
"clr": funcparser_callable_clr,
|
||||
|
||||
# seaching
|
||||
"search": funcparser_callable_search,
|
||||
"obj": funcparser_callable_search, # aliases for backwards compat
|
||||
"objlist": funcparser_callable_search_list,
|
||||
"dbref": funcparser_callable_search,
|
||||
|
||||
# referencing
|
||||
"you": funcparser_callable_you,
|
||||
"You": funcparser_callable_You,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -267,8 +267,29 @@ class TestFuncParser(TestCase):
|
|||
ret = parser.parse("This is a $foo(foo=moo) string", foo="bar")
|
||||
self.assertEqual("This is a _test(test=foo, foo=bar) string", ret)
|
||||
|
||||
|
||||
class TestDefaultCallables(TestCase):
|
||||
"""
|
||||
Test default callables.
|
||||
|
||||
"""
|
||||
@override_settings(INLINEFUNC_MODULES=["evennia.utils.funcparser"])
|
||||
def setUp(self):
|
||||
from django.conf import settings
|
||||
self.parser = funcparser.FuncParser(settings.INLINEFUNC_MODULES)
|
||||
|
||||
@parameterized.expand([
|
||||
("Test py1 $py('')", "Test py1 ''"),
|
||||
])
|
||||
def test_callable(self, string, expected):
|
||||
"""
|
||||
Test callables with various input strings
|
||||
|
||||
"""
|
||||
ret = self.parser.parse(string, raise_errors=True)
|
||||
self.assertEqual(expected, ret)
|
||||
|
||||
|
||||
class TestOldDefaultCallables(TestCase):
|
||||
"""
|
||||
Test default callables
|
||||
|
||||
|
|
|
|||
340
evennia/utils/verb_conjugation/LICENSE.txt
Normal file
340
evennia/utils/verb_conjugation/LICENSE.txt
Normal file
|
|
@ -0,0 +1,340 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
|
||||
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Library General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1989
|
||||
Ty Coon, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Library General
|
||||
Public License instead of this License.
|
||||
0
evennia/utils/verb_conjugation/__init__.py
Normal file
0
evennia/utils/verb_conjugation/__init__.py
Normal file
387
evennia/utils/verb_conjugation/conjugate.py
Normal file
387
evennia/utils/verb_conjugation/conjugate.py
Normal file
|
|
@ -0,0 +1,387 @@
|
|||
"""
|
||||
English verb conjugation
|
||||
|
||||
Original Author: Tom De Smedt <tomdesmedt@organisms.be> of Nodebox
|
||||
Refactored by Griatch 2021, for Evennia.
|
||||
|
||||
This is distributed under the GPL2 license. See ./LICENSE.txt for details.
|
||||
|
||||
The verb.txt morphology was adopted from the XTAG morph_englis.flat:
|
||||
http://www.cis.upenn.edu/~xtag/
|
||||
|
||||
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
_VERBS_FILE = "verbs.txt"
|
||||
|
||||
# Each verb and its tenses is a list in verbs.txt,
|
||||
# indexed according to the following keys:
|
||||
# the negated forms (for supported verbs) are ind+11.
|
||||
|
||||
verb_tenses_keys = {
|
||||
"infinitive": 0,
|
||||
"1st singular present": 1,
|
||||
"2nd singular present": 2,
|
||||
"3rd singular present": 3,
|
||||
"present plural": 4,
|
||||
"present participle": 5,
|
||||
"1st singular past": 6,
|
||||
"2nd singular past": 7,
|
||||
"3rd singular past": 8,
|
||||
"past plural": 9,
|
||||
"past": 10,
|
||||
"past participle": 11,
|
||||
}
|
||||
|
||||
# allow to specify tenses with a shorter notation
|
||||
verb_tenses_aliases = {
|
||||
"inf": "infinitive",
|
||||
"1sgpres": "1st singular present",
|
||||
"2sgpres": "2nd singular present",
|
||||
"3sgpres": "3rd singular present",
|
||||
"pl": "present plural",
|
||||
"prog": "present participle",
|
||||
"1sgpast": "1st singular past",
|
||||
"2sgpast": "2nd singular past",
|
||||
"3sgpast": "3rd singular past",
|
||||
"pastpl": "past plural",
|
||||
"ppart": "past participle",
|
||||
}
|
||||
|
||||
# Each verb has morphs for infinitve,
|
||||
# 3rd singular present, present participle,
|
||||
# past and past participle.
|
||||
# Verbs like "be" have other morphs as well
|
||||
# (i.e. I am, you are, she is, they aren't)
|
||||
# Additionally, the following verbs can be negated:
|
||||
# be, can, do, will, must, have, may, need, dare, ought.
|
||||
|
||||
# load the conjugation forms from ./verbs.txt
|
||||
verb_tenses = {}
|
||||
|
||||
path = os.path.join(os.path.dirname(__file__), _VERBS_FILE)
|
||||
with open(path) as fil:
|
||||
for line in fil.readlines():
|
||||
wordlist = [part.strip() for part in line.split(",")]
|
||||
verb_tenses[wordlist[0]] = wordlist
|
||||
|
||||
# Each verb can be lemmatised:
|
||||
# inflected morphs of the verb point
|
||||
# to its infinitive in this dictionary.
|
||||
verb_lemmas = {}
|
||||
for infinitive in verb_tenses:
|
||||
for tense in verb_tenses[infinitive]:
|
||||
if tense:
|
||||
verb_lemmas[tense] = infinitive
|
||||
|
||||
|
||||
def verb_infinitive(verb):
|
||||
"""
|
||||
Returns the uninflected form of the verb, like 'are' -> 'be'
|
||||
|
||||
Args:
|
||||
verb (str): The verb to get the uninflected form of.
|
||||
|
||||
Returns:
|
||||
str: The uninflected verb form of `verb`.
|
||||
|
||||
"""
|
||||
|
||||
return verb_lemmas.get(verb, '')
|
||||
|
||||
|
||||
def verb_conjugate(verb, tense="infinitive", negate=False):
|
||||
"""
|
||||
Inflects the verb to the given tense.
|
||||
|
||||
Args:
|
||||
verb (str): The single verb to conjugate.
|
||||
tense (str): The tense to convert to. This can be given either as a long or short form
|
||||
- "infinitive" ("inf") - be
|
||||
- "1st/2nd/3rd singular present" ("1/2/3sgpres") - am/are/is
|
||||
- "present plural" ("pl") - are
|
||||
- "present participle" ("prog") - being
|
||||
- "1st/2nd/3rd singular past" ("1/2/3sgpast") - was/were/was
|
||||
- "past plural" ("pastpl") - were
|
||||
- "past" - were
|
||||
- "past participle" ("ppart") - been
|
||||
negate (bool): Negates the verb. This only supported
|
||||
for a limited number of verbs: be, can, do, will, must, have, may,
|
||||
need, dare, ought.
|
||||
|
||||
Returns:
|
||||
str: The conjugated verb. If conjugation fails, the original verb is returned.
|
||||
|
||||
Examples:
|
||||
The verb 'be':
|
||||
- present: I am, you are, she is,
|
||||
- present participle: being,
|
||||
- past: I was, you were, he was,
|
||||
- past participle: been,
|
||||
- negated present: I am not, you aren't, it isn't.
|
||||
|
||||
"""
|
||||
tense = verb_tenses_aliases.get(tense, tense)
|
||||
verb = verb_infinitive(verb)
|
||||
ind = verb_tenses_keys[tense]
|
||||
if negate:
|
||||
ind += len(verb_tenses_keys)
|
||||
try:
|
||||
return verb_tenses[verb][ind]
|
||||
except IndexError:
|
||||
# TODO implement simple algorithm here with +s for certain tenses?
|
||||
return verb
|
||||
|
||||
|
||||
def verb_present(verb, person="", negate=False):
|
||||
"""
|
||||
Inflects the verb in the present tense.
|
||||
|
||||
Args:
|
||||
person (str or int): This can be 1, 2, 3, "1st", "2nd", "3rd", "plural" or "*".
|
||||
negate (bool): Some verbs like be, have, must, can be negated.
|
||||
|
||||
Returns:
|
||||
str: The present tense verb.
|
||||
|
||||
Example:
|
||||
had -> have
|
||||
|
||||
"""
|
||||
|
||||
person = str(person).replace("pl", "*").strip("stndrgural")
|
||||
mapping = {
|
||||
"1": "1st singular present",
|
||||
"2": "2nd singular present",
|
||||
"3": "3rd singular present",
|
||||
"*": "present plural",
|
||||
}
|
||||
if person in mapping and verb_conjugate(verb, mapping[person], negate) != "":
|
||||
return verb_conjugate(verb, mapping[person], negate)
|
||||
|
||||
return verb_conjugate(verb, "infinitive", negate)
|
||||
|
||||
|
||||
def verb_present_participle(verb):
|
||||
"""
|
||||
Inflects the verb in the present participle.
|
||||
|
||||
Args:
|
||||
verb (str): The verb to inflect.
|
||||
|
||||
Returns:
|
||||
str: The inflected verb.
|
||||
|
||||
Examples:
|
||||
give -> giving, be -> being, swim -> swimming
|
||||
|
||||
"""
|
||||
return verb_conjugate(verb, "present participle")
|
||||
|
||||
|
||||
def verb_past(verb, person="", negate=False):
|
||||
"""
|
||||
|
||||
Inflects the verb in the past tense.
|
||||
|
||||
Args:
|
||||
verb (str): The verb to inflect.
|
||||
person (str, optional): The person can be specified with 1, 2, 3,
|
||||
"1st", "2nd", "3rd", "plural", "*".
|
||||
negate (bool, optional): Some verbs like be, have, must, can be negated.
|
||||
|
||||
Returns:
|
||||
str: The inflected verb.
|
||||
|
||||
Examples:
|
||||
give -> gave, be -> was, swim -> swam
|
||||
|
||||
"""
|
||||
|
||||
person = str(person).replace("pl", "*").strip("stndrgural")
|
||||
mapping = {
|
||||
"1": "1st singular past",
|
||||
"2": "2nd singular past",
|
||||
"3": "3rd singular past",
|
||||
"*": "past plural",
|
||||
}
|
||||
if person in mapping and verb_conjugate(verb, mapping[person], negate) != "":
|
||||
return verb_conjugate(verb, mapping[person], negate)
|
||||
|
||||
return verb_conjugate(verb, "past", negate=negate)
|
||||
|
||||
|
||||
def verb_past_participle(verb):
|
||||
"""
|
||||
Inflects the verb in the present participle.
|
||||
|
||||
Args:
|
||||
verb (str): The verb to inflect.
|
||||
|
||||
Returns:
|
||||
str: The inflected verb.
|
||||
|
||||
Examples:
|
||||
give -> given, be -> been, swim -> swum
|
||||
|
||||
"""
|
||||
return verb_conjugate(verb, "past participle")
|
||||
|
||||
|
||||
def verb_all_tenses():
|
||||
"""
|
||||
Get all all possible verb tenses.
|
||||
|
||||
Returns:
|
||||
list: A list if string names.
|
||||
|
||||
"""
|
||||
|
||||
return list(verb_tenses_keys.keys())
|
||||
|
||||
|
||||
def verb_tense(verb):
|
||||
"""
|
||||
Returns a string from verb_tenses_keys representing the verb's tense.
|
||||
|
||||
Args:
|
||||
verb (str): The verb to check the tense of.
|
||||
|
||||
Returns:
|
||||
str: The tense.
|
||||
|
||||
Example:
|
||||
given -> "past participle"
|
||||
|
||||
"""
|
||||
infinitive = verb_infinitive(verb)
|
||||
data = verb_tenses[infinitive]
|
||||
for tense in verb_tenses_keys:
|
||||
if data[verb_tenses_keys[tense]] == verb:
|
||||
return tense
|
||||
if data[verb_tenses_keys[tense] + len(verb_tenses_keys)] == verb:
|
||||
return tense
|
||||
|
||||
|
||||
def verb_is_tense(verb, tense):
|
||||
"""
|
||||
Checks whether the verb is in the given tense.
|
||||
|
||||
Args:
|
||||
verb (str): The verb to check.
|
||||
tense (str): The tense to check.
|
||||
|
||||
Return:
|
||||
bool: If verb matches given tense.
|
||||
|
||||
"""
|
||||
tense = verb_tenses_aliases.get(tense, tense)
|
||||
return verb_tense(verb) == tense
|
||||
|
||||
|
||||
def verb_is_present(verb, person="", negated=False):
|
||||
"""
|
||||
Checks whether the verb is in the present tense.
|
||||
|
||||
Args:
|
||||
verb (str): The verb to check.
|
||||
person (str): Check which person.
|
||||
negated (bool): Check if verb was negated.
|
||||
|
||||
Returns:
|
||||
bool: If verb was in present tense.
|
||||
|
||||
"""
|
||||
|
||||
person = str(person).replace("*", "plural")
|
||||
tense = verb_tense(verb)
|
||||
if tense is not None:
|
||||
if "present" in tense and person in tense:
|
||||
if not negated:
|
||||
return True
|
||||
elif "n't" in verb or " not" in verb:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def verb_is_present_participle(verb):
|
||||
"""
|
||||
Checks whether the verb is in present participle.
|
||||
|
||||
Args:
|
||||
verb (str): The verb to check.
|
||||
|
||||
Returns:
|
||||
bool: Result of check.
|
||||
|
||||
"""
|
||||
|
||||
tense = verb_tense(verb)
|
||||
return tense == "present participle"
|
||||
|
||||
|
||||
|
||||
def verb_is_past(verb, person="", negated=False):
|
||||
"""
|
||||
Checks whether the verb is in the past tense.
|
||||
|
||||
Args:
|
||||
verb (str): The verb to check.
|
||||
person (str): The person to check.
|
||||
negated (bool): Check if verb is negated.
|
||||
|
||||
Returns:
|
||||
bool: Result of check.
|
||||
|
||||
"""
|
||||
|
||||
person = str(person).replace("*", "plural")
|
||||
tense = verb_tense(verb)
|
||||
if tense is not None:
|
||||
if "past" in tense and person in tense:
|
||||
if not negated:
|
||||
return True
|
||||
elif "n't" in verb or " not" in verb:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def verb_is_past_participle(verb):
|
||||
"""
|
||||
Checks whether the verb is in past participle.
|
||||
|
||||
Args:
|
||||
verb (str): The verb to check.
|
||||
|
||||
Returns:
|
||||
bool: The result of the check.
|
||||
|
||||
"""
|
||||
tense = verb_tense(verb)
|
||||
return tense == "past participle"
|
||||
|
||||
|
||||
def verb_actor_stance_components(verb):
|
||||
"""
|
||||
Figure out actor stance components of a verb.
|
||||
|
||||
Args:
|
||||
verb (str): The verb to analyze
|
||||
|
||||
Returns:
|
||||
tuple: The 2nd person (you) and 3rd person forms of the verb,
|
||||
in the same tense as the ingoing verb.
|
||||
|
||||
"""
|
||||
tense = verb_tense(verb)
|
||||
if "participle" in tense or "plural" in tense:
|
||||
return (verb, verb)
|
||||
if tense == "infinitive" or "present" in tense:
|
||||
return (verb_present(verb, person="2"),
|
||||
verb_present(verb, person="3"))
|
||||
else:
|
||||
return (verb_past(verb, person="2"),
|
||||
verb_past(verb, person="3"))
|
||||
237
evennia/utils/verb_conjugation/tests.py
Normal file
237
evennia/utils/verb_conjugation/tests.py
Normal file
|
|
@ -0,0 +1,237 @@
|
|||
"""
|
||||
Unit tests for verb conjugation.
|
||||
|
||||
"""
|
||||
|
||||
from parameterized import parameterized
|
||||
from django.test import TestCase
|
||||
from . import conjugate
|
||||
|
||||
|
||||
class TestVerbConjugate(TestCase):
|
||||
"""
|
||||
Test the conjugation.
|
||||
|
||||
"""
|
||||
@parameterized.expand([
|
||||
("have", "have"),
|
||||
("swim", "swim"),
|
||||
("give", "give"),
|
||||
("given", "give"),
|
||||
("am", "be"),
|
||||
("doing", "do"),
|
||||
("are", "be"),
|
||||
])
|
||||
def test_verb_infinitive(self, verb, expected):
|
||||
"""
|
||||
Test the infinite-getter.
|
||||
"""
|
||||
self.assertEqual(expected, conjugate.verb_infinitive(verb))
|
||||
|
||||
@parameterized.expand([
|
||||
("inf", "have", "have"),
|
||||
("inf", "swim", "swim"),
|
||||
("inf", "give", "give"),
|
||||
("inf", "given", "give"),
|
||||
("inf", "am", "be"),
|
||||
("inf", "doing", "do"),
|
||||
("inf", "are", "be"),
|
||||
("2sgpres", "am", "are"),
|
||||
("3sgpres", "am", "is"),
|
||||
])
|
||||
def test_verb_conjugate(self, tense, verb, expected):
|
||||
"""
|
||||
Test conjugation for different tenses.
|
||||
|
||||
"""
|
||||
self.assertEqual(expected, conjugate.verb_conjugate(verb, tense=tense))
|
||||
|
||||
@parameterized.expand([
|
||||
("1st", "have", "have"),
|
||||
("1st", "swim", "swim"),
|
||||
("1st", "give", "give"),
|
||||
("1st", "given", "give"),
|
||||
("1st", "am", "am"),
|
||||
("1st", "doing", "do"),
|
||||
("1st", "are", "am"),
|
||||
("2nd", "were", "are"),
|
||||
("3rd", "am", "is"),
|
||||
])
|
||||
def test_verb_present(self, person, verb, expected):
|
||||
"""
|
||||
Test the present.
|
||||
|
||||
"""
|
||||
self.assertEqual(expected, conjugate.verb_present(verb, person=person))
|
||||
|
||||
@parameterized.expand([
|
||||
("have", "having"),
|
||||
("swim", "swimming"),
|
||||
("give", "giving"),
|
||||
("given", "giving"),
|
||||
("am", "being"),
|
||||
("doing", "doing"),
|
||||
("are", "being"),
|
||||
])
|
||||
def test_verb_present_participle(self, verb, expected):
|
||||
"""
|
||||
Test the present_participle
|
||||
|
||||
"""
|
||||
self.assertEqual(expected, conjugate.verb_present_participle(verb))
|
||||
|
||||
@parameterized.expand([
|
||||
("1st", "have", "had"),
|
||||
("1st", "swim", "swam"),
|
||||
("1st", "give", "gave"),
|
||||
("1st", "given", "gave"),
|
||||
("1st", "am", "was"),
|
||||
("1st", "doing", "did"),
|
||||
("1st", "are", "was"),
|
||||
("2nd", "were", "were"),
|
||||
])
|
||||
def test_verb_past(self, person, verb, expected):
|
||||
"""
|
||||
Test the past getter.
|
||||
|
||||
"""
|
||||
self.assertEqual(expected, conjugate.verb_past(verb, person=person))
|
||||
|
||||
@parameterized.expand([
|
||||
("have", "had"),
|
||||
("swim", "swum"),
|
||||
("give", "given"),
|
||||
("given", "given"),
|
||||
("am", "been"),
|
||||
("doing", "done"),
|
||||
("are", "been"),
|
||||
])
|
||||
def test_verb_past_participle(self, verb, expected):
|
||||
"""
|
||||
Test the past participle.
|
||||
|
||||
"""
|
||||
self.assertEqual(expected, conjugate.verb_past_participle(verb))
|
||||
|
||||
def test_verb_get_all_tenses(self):
|
||||
"""
|
||||
Test getting all tenses.
|
||||
|
||||
"""
|
||||
self.assertEqual(list(conjugate.verb_tenses_keys.keys()), conjugate.verb_all_tenses())
|
||||
|
||||
@parameterized.expand([
|
||||
("have", "infinitive"),
|
||||
("swim", "infinitive"),
|
||||
("give", "infinitive"),
|
||||
("given", "past participle"),
|
||||
("am", "1st singular present"),
|
||||
("doing", "present participle"),
|
||||
("are", "2nd singular present"),
|
||||
])
|
||||
def test_verb_tense(self, verb, expected):
|
||||
"""
|
||||
Test the tense retriever.
|
||||
|
||||
"""
|
||||
self.assertEqual(expected, conjugate.verb_tense(verb))
|
||||
|
||||
@parameterized.expand([
|
||||
("inf", "have", True),
|
||||
("inf", "swim", True),
|
||||
("inf", "give", True),
|
||||
("inf", "given", False),
|
||||
("inf", "am", False),
|
||||
("inf", "doing", False),
|
||||
("inf", "are", False),
|
||||
])
|
||||
def test_verb_is_tense(self, tense, verb, expected):
|
||||
"""
|
||||
Test the tense-checker
|
||||
|
||||
"""
|
||||
self.assertEqual(expected, conjugate.verb_is_tense(verb, tense))
|
||||
|
||||
@parameterized.expand([
|
||||
("1st", "have", False),
|
||||
("1st", "swim", False),
|
||||
("1st", "give", False),
|
||||
("1st", "given", False),
|
||||
("1st", "am", True),
|
||||
("1st", "doing", False),
|
||||
("1st", "are", False),
|
||||
("1st", "had", False),
|
||||
])
|
||||
def test_verb_is_present(self, person, verb, expected):
|
||||
"""
|
||||
Test the tense-checker
|
||||
|
||||
"""
|
||||
self.assertEqual(expected, conjugate.verb_is_present(verb, person=person))
|
||||
|
||||
@parameterized.expand([
|
||||
("have", False),
|
||||
("swim", False),
|
||||
("give", False),
|
||||
("given", False),
|
||||
("am", False),
|
||||
("doing", True),
|
||||
("are", False),
|
||||
])
|
||||
def test_verb_is_present_participle(self, verb, expected):
|
||||
"""
|
||||
Test the tense-checker
|
||||
|
||||
"""
|
||||
self.assertEqual(expected, conjugate.verb_is_present_participle(verb))
|
||||
|
||||
@parameterized.expand([
|
||||
("1st", "have", False),
|
||||
("1st", "swim", False),
|
||||
("1st", "give", False),
|
||||
("1st", "given", False),
|
||||
("1st", "am", False),
|
||||
("1st", "doing", False),
|
||||
("1st", "are", False),
|
||||
("2nd", "were", True),
|
||||
])
|
||||
def test_verb_is_past(self, person, verb, expected):
|
||||
"""
|
||||
Test the tense-checker
|
||||
|
||||
"""
|
||||
self.assertEqual(expected, conjugate.verb_is_past(verb, person=person))
|
||||
|
||||
@parameterized.expand([
|
||||
("have", False),
|
||||
("swimming", False),
|
||||
("give", False),
|
||||
("given", True),
|
||||
("am", False),
|
||||
("doing", False),
|
||||
("are", False),
|
||||
("had", False),
|
||||
])
|
||||
def test_verb_is_past_participle(self, verb, expected):
|
||||
"""
|
||||
Test the tense-checker
|
||||
|
||||
"""
|
||||
self.assertEqual(expected, conjugate.verb_is_past_participle(verb))
|
||||
|
||||
@parameterized.expand([
|
||||
("have", ("have", "has")),
|
||||
("swimming", ("swimming", "swimming")),
|
||||
("give", ("give", "gives")),
|
||||
("given", ("given", "given")),
|
||||
("am", ("are", "is")),
|
||||
("doing", ("doing", "doing")),
|
||||
("are", ("are", "is")),
|
||||
("had", ("had", "had")),
|
||||
])
|
||||
def test_verb_actor_stance_components(self, verb, expected):
|
||||
"""
|
||||
Test the tense-checker
|
||||
|
||||
"""
|
||||
self.assertEqual(expected, conjugate.verb_actor_stance_components(verb))
|
||||
8567
evennia/utils/verb_conjugation/verbs.txt
Normal file
8567
evennia/utils/verb_conjugation/verbs.txt
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -13,6 +13,10 @@ autobahn >= 17.9.3
|
|||
lunr == 0.5.6
|
||||
simpleeval <= 1.0
|
||||
|
||||
# conjugation library, py3 version
|
||||
git+https://github.com/markrogersjr/nodebox_linguistics_extended.git
|
||||
|
||||
|
||||
# try to resolve dependency issue in py3.7
|
||||
attrs >= 19.2.0
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue