| 1 |
from collections import defaultdict |
| 2 |
import logging |
| 3 |
from typing import Callable, Dict, List, Set |
| 4 |
|
| 5 |
from lunr.exceptions import BaseLunrException |
| 6 |
from lunr.token import Token |
| 7 |
|
| 8 |
log = logging.getLogger(__name__) |
| 9 |
|
| 10 |
|
| 11 |
class Pipeline: |
| 12 |
"""lunr.Pipelines maintain a list of functions to be applied to all tokens |
| 13 |
in documents entering the search index and queries ran agains the index. |
| 14 |
|
| 15 |
""" |
| 16 |
|
| 17 |
registered_functions: Dict[str, Callable] = {} |
| 18 |
|
| 19 |
def __init__(self): |
| 20 |
self._stack: List[Callable] = [] |
| 21 |
self._skip: Dict[Callable, Set[str]] = defaultdict(set) |
| 22 |
|
| 23 |
def __len__(self): |
| 24 |
return len(self._stack) |
| 25 |
|
| 26 |
def __repr__(self): |
| 27 |
return '<Pipeline stack="{}">'.format(",".join(fn.label for fn in self._stack)) |
| 28 |
|
| 29 |
# TODO: add iterator methods? |
| 30 |
|
| 31 |
@classmethod |
| 32 |
def register_function(cls, fn, label=None): |
| 33 |
"""Register a function with the pipeline.""" |
| 34 |
label = label or fn.__name__ |
| 35 |
if label in cls.registered_functions: |
| 36 |
log.warning("Overwriting existing registered function %s", label) |
| 37 |
|
| 38 |
fn.label = label |
| 39 |
cls.registered_functions[fn.label] = fn |
| 40 |
|
| 41 |
@classmethod |
| 42 |
def load(cls, serialised): |
| 43 |
"""Loads a previously serialised pipeline.""" |
| 44 |
pipeline = cls() |
| 45 |
for fn_name in serialised: |
| 46 |
try: |
| 47 |
fn = cls.registered_functions[fn_name] |
| 48 |
except KeyError: |
| 49 |
raise BaseLunrException( |
| 50 |
"Cannot load unregistered function {}".format(fn_name) |
| 51 |
) |
| 52 |
else: |
| 53 |
pipeline.add(fn) |
| 54 |
|
| 55 |
return pipeline |
| 56 |
|
| 57 |
def add(self, *args): |
| 58 |
"""Adds new functions to the end of the pipeline. |
| 59 |
|
| 60 |
Functions must accept three arguments: |
| 61 |
- Token: A lunr.Token object which will be updated |
| 62 |
- i: The index of the token in the set |
| 63 |
- tokens: A list of tokens representing the set |
| 64 |
""" |
| 65 |
for fn in args: |
| 66 |
self.warn_if_function_not_registered(fn) |
| 67 |
self._stack.append(fn) |
| 68 |
|
| 69 |
def warn_if_function_not_registered(self, fn): |
| 70 |
try: |
| 71 |
return fn.label in self.registered_functions |
| 72 |
except AttributeError: |
| 73 |
log.warning( |
| 74 |
'Function "{}" is not registered with pipeline. ' |
| 75 |
"This may cause problems when serialising the index.".format( |
| 76 |
getattr(fn, "label", fn) |
| 77 |
) |
| 78 |
) |
| 79 |
|
| 80 |
def after(self, existing_fn, new_fn): |
| 81 |
"""Adds a single function after a function that already exists in the |
| 82 |
pipeline.""" |
| 83 |
self.warn_if_function_not_registered(new_fn) |
| 84 |
try: |
| 85 |
index = self._stack.index(existing_fn) |
| 86 |
self._stack.insert(index + 1, new_fn) |
| 87 |
except ValueError as e: |
| 88 |
raise BaseLunrException("Cannot find existing_fn") from e |
| 89 |
|
| 90 |
def before(self, existing_fn, new_fn): |
| 91 |
"""Adds a single function before a function that already exists in the |
| 92 |
pipeline. |
| 93 |
|
| 94 |
""" |
| 95 |
self.warn_if_function_not_registered(new_fn) |
| 96 |
try: |
| 97 |
index = self._stack.index(existing_fn) |
| 98 |
self._stack.insert(index, new_fn) |
| 99 |
except ValueError as e: |
| 100 |
raise BaseLunrException("Cannot find existing_fn") from e |
| 101 |
|
| 102 |
def remove(self, fn): |
| 103 |
"""Removes a function from the pipeline.""" |
| 104 |
try: |
| 105 |
self._stack.remove(fn) |
| 106 |
except ValueError: |
| 107 |
pass |
| 108 |
|
| 109 |
def skip(self, fn: Callable, field_names: List[str]): |
| 110 |
""" |
| 111 |
Make the pipeline skip the function based on field name we're processing. |
| 112 |
|
| 113 |
This relies on passing the field name to Pipeline.run(). |
| 114 |
""" |
| 115 |
self._skip[fn].update(field_names) |
| 116 |
|
| 117 |
def run(self, tokens, field_name=None): |
| 118 |
""" |
| 119 |
Runs the current list of functions that make up the pipeline against |
| 120 |
the passed tokens. |
| 121 |
|
| 122 |
:param tokens: The tokens to process. |
| 123 |
:param field_name: The name of the field these tokens belongs to, can be ommited. |
| 124 |
Used to skip some functions based on field names. |
| 125 |
""" |
| 126 |
for fn in self._stack: |
| 127 |
# Skip the function based on field name. |
| 128 |
if field_name and field_name in self._skip[fn]: |
| 129 |
continue |
| 130 |
results = [] |
| 131 |
for i, token in enumerate(tokens): |
| 132 |
# JS ignores additional arguments to the functions but we |
| 133 |
# force pipeline functions to declare (token, i, tokens) |
| 134 |
# or *args |
| 135 |
result = fn(token, i, tokens) |
| 136 |
if not result: |
| 137 |
continue |
| 138 |
if isinstance(result, (list, tuple)): # simulate Array.concat |
| 139 |
results.extend(result) |
| 140 |
else: |
| 141 |
results.append(result) |
| 142 |
tokens = results |
| 143 |
|
| 144 |
return tokens |
| 145 |
|
| 146 |
def run_string(self, string, metadata=None): |
| 147 |
"""Convenience method for passing a string through a pipeline and |
| 148 |
getting strings out. This method takes care of wrapping the passed |
| 149 |
string in a token and mapping the resulting tokens back to strings. |
| 150 |
|
| 151 |
.. note:: This ignores the skipped functions since we can't |
| 152 |
access field names from this context. |
| 153 |
""" |
| 154 |
token = Token(string, metadata) |
| 155 |
return [str(tkn) for tkn in self.run([token])] |
| 156 |
|
| 157 |
def reset(self): |
| 158 |
self._stack = [] |
| 159 |
|
| 160 |
def serialize(self): |
| 161 |
return [fn.label for fn in self._stack] |