Debian Codegraph @

lunr/token_set.py

raw
1 class TokenSet:
2 """
3 A token set is used to store the unique list of all tokens
4 within an index. Token sets are also used to represent an
5 incoming query to the index, this query token set and index
6 token set are then intersected to find which tokens to look
7 up in the inverted index.
8
9 A token set can hold multiple tokens, as in the case of the
10 index token set, or it can hold a single token as in the
11 case of a simple query token set.
12
13 Additionally token sets are used to perform wildcard matching.
14 Leading, contained and trailing wildcards are supported, and
15 from this edit distance matching can also be provided.
16
17 Token sets are implemented as a minimal finite state automata,
18 where both common prefixes and suffixes are shared between tokens.
19 This helps to reduce the space used for storing the token set.
20
21 TODO: consider https://github.com/glyph/automat
22 """
23
24 _next_id = 1
25
26 def __init__(self):
27 self.final = False
28 self.edges = {}
29 self.id = self._next_id
30 self.__class__._next_id += 1
31
32 def __str__(self):
33 try:
34 return self._string
35 except AttributeError:
36 pass
37
38 string = "1" if self.final else "0"
39 for label in sorted(list(self.edges.keys())):
40 node = self.edges[label]
41 try:
42 node_id = str(node.id)
43 except AttributeError:
44 # TODO: JS seems to rely on undefined for the id attribute?
45 node_id = ""
46
47 string = string + label + node_id
48
49 return string
50
51 def __repr__(self):
52 return '<TokenSet "{}">'.format(str(self))
53
54 @classmethod
55 def from_string(self, string):
56 """Creates a TokenSet from a string.
57
58 The string may contain one or more wildcard characters (*) that will
59 allow wildcard matching when intersecting with another TokenSet
60 """
61 node = TokenSet()
62 root = node
63
64 # Iterates throough all characters in the passed string appending
65 # a node for each character.
66 # When a wildcard character is found then a self referencing edge
67 # is introduced to continually match any number of characters
68 for i, char in enumerate(string):
69 final = i == len(string) - 1
70 if char == "*":
71 node.edges[char] = node
72 node.final = final
73 else:
74 next_ = TokenSet()
75 next_.final = final
76 node.edges[char] = next_
77 node = next_
78
79 return root
80
81 @classmethod
82 def from_fuzzy_string(cls, string, edit_distance):
83 """Creates a token set representing a single string with a specified
84 edit distance.
85
86 Insertions, deletions, substitutions and transpositions are each
87 treated as an edit distance of 1.
88
89 Increasing the allowed edit distance will have a dramatic impact
90 on the performance of both creating and intersecting these TokenSets.
91 It is advised to keep the edit distance less than 3.
92 """
93 root = TokenSet()
94
95 stack = [{"node": root, "edits_remaining": edit_distance, "string": string}]
96
97 while stack:
98 frame = stack.pop()
99 # no edit
100 if len(frame["string"]) > 0:
101 char = frame["string"][0]
102 no_edit_node = None
103 if char in frame["node"].edges:
104 no_edit_node = frame["node"].edges[char]
105 else:
106 no_edit_node = TokenSet()
107 frame["node"].edges[char] = no_edit_node
108
109 if len(frame["string"]) == 1:
110 no_edit_node.final = True
111
112 stack.append(
113 {
114 "node": no_edit_node,
115 "edits_remaining": frame["edits_remaining"],
116 "string": frame["string"][1:],
117 }
118 )
119
120 if frame["edits_remaining"] == 0:
121 continue
122
123 # insertion, can only do insertion if there are edits remaining
124 if "*" in frame["node"].edges:
125 insertion_node = frame["node"].edges["*"]
126 else:
127 insertion_node = TokenSet()
128 frame["node"].edges["*"] = insertion_node
129
130 if len(frame["string"]) == 0:
131 insertion_node.final = True
132
133 stack.append(
134 {
135 "node": insertion_node,
136 "edits_remaining": frame["edits_remaining"] - 1,
137 "string": frame["string"],
138 }
139 )
140
141 # deletion, can only do a deletion if we have enough edits
142 # remaining and if there are characters left to delete in the string
143 if len(frame["string"]) > 1:
144 stack.append(
145 {
146 "node": frame["node"],
147 "edits_remaining": frame["edits_remaining"] - 1,
148 "string": frame["string"][1:],
149 }
150 )
151
152 # deletion, just removing the last character of the string
153 if len(frame["string"]) == 1:
154 frame["node"].final = True
155
156 # substitution, can only do a substitution if we have enough edits
157 # remaining and there are characters left to substitute
158 if len(frame["string"]) >= 1:
159 if "*" in frame["node"].edges:
160 substitution_node = frame["node"].edges["*"]
161 else:
162 substitution_node = TokenSet()
163 frame["node"].edges["*"] = substitution_node
164
165 if len(frame["string"]) == 1:
166 substitution_node.final = True
167
168 stack.append(
169 {
170 "node": substitution_node,
171 "edits_remaining": frame["edits_remaining"] - 1,
172 "string": frame["string"][1:],
173 }
174 )
175
176 # transposition, can only do a transposition if there are edits
177 # remaining and there are enough characters to transpose
178 if frame["edits_remaining"] and len(frame["string"]) > 1:
179 char_a = frame["string"][0]
180 char_b = frame["string"][1]
181 transpose_node = None
182
183 if char_b in frame["node"].edges:
184 transpose_node = frame["node"].edges[char_b]
185 else:
186 transpose_node = TokenSet()
187 frame["node"].edges[char_b] = transpose_node
188
189 if len(frame["string"]) == 1:
190 transpose_node.final = True
191
192 stack.append(
193 {
194 "node": transpose_node,
195 "edits_remaining": frame["edits_remaining"] - 1,
196 "string": char_a + frame["string"][2:],
197 }
198 )
199
200 return root
201
202 @classmethod
203 def from_list(cls, list_of_words):
204 from lunr.token_set_builder import TokenSetBuilder
205
206 builder = TokenSetBuilder()
207 for word in list_of_words:
208 builder.insert(word)
209
210 builder.finish()
211 return builder.root
212
213 @classmethod
214 def from_clause(cls, clause):
215 if clause.edit_distance:
216 return cls.from_fuzzy_string(clause.term, clause.edit_distance)
217 else:
218 return cls.from_string(clause.term)
219
220 def to_list(self):
221 words = []
222 stack = [{"prefix": "", "node": self}]
223
224 while stack:
225 frame = stack.pop()
226 if frame["node"].final:
227 words.append(frame["prefix"])
228
229 for edge in frame["node"].edges.keys():
230 stack.append(
231 {
232 "prefix": frame["prefix"] + str(edge),
233 "node": frame["node"].edges[edge],
234 }
235 )
236
237 return words
238
239 def intersect(self, other):
240 """Returns a new TokenSet that is the intersection of this TokenSet
241 and the passed TokenSet.
242
243 This intersection will take into account any wildcards contained within
244 the TokenSet.
245 """
246 output = TokenSet()
247 stack = [{"node": self, "q_node": other, "output": output}]
248
249 while stack:
250 frame = stack.pop()
251 for q_edge in frame["q_node"].edges.keys():
252 for n_edge in frame["node"].edges.keys():
253 if n_edge == q_edge or q_edge == "*":
254 node = frame["node"].edges[n_edge]
255 q_node = frame["q_node"].edges[q_edge]
256 final = node.final and q_node.final
257 next_ = None
258
259 if n_edge in frame["output"].edges:
260 next_ = frame["output"].edges[n_edge]
261 next_.final = next_.final or final
262 else:
263 next_ = TokenSet()
264 next_.final = final
265 frame["output"].edges[n_edge] = next_
266
267 stack.append({"node": node, "q_node": q_node, "output": next_})
268
269 return output