Debian Codegraph @

xl/trax/search.py

raw
1 # Copyright (C) 2008-2010 Adam Olsen
2 #
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2, or (at your option)
6 # any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 #
17 #
18 # The developers of the Exaile media player hereby grant permission
19 # for non-GPL compatible GStreamer and Exaile plugins to be used and
20 # distributed together with GStreamer and Exaile. This permission is
21 # above and beyond the permissions granted by the GPL license by which
22 # Exaile is covered. If you modify this code, you may extend this
23 # exception to your version of the code, but you are not obligated to
24 # do so. If you do not wish to do so, delete this exception statement
25 # from your version.
26
27 import re
28 from typing import Collection
29
30 from xl.unicode import shave_marks
31
32 __all__ = ['TracksMatcher', 'search_tracks']
33
34
35 class SearchResultTrack:
36 """
37 Holds a track with search result metadata included.
38
39 :param track: The Track object
40 """
41
42 __slots__ = ['track', 'on_tags']
43
44 def __init__(self, track):
45 self.track = track
46 self.on_tags = []
47
48
49 class _Matcher:
50 """
51 Base class for match conditions
52 """
53
54 __slots__ = ['tag', 'content', 'lower']
55
56 def __init__(self, tag, content, lower):
57 self.tag = tag
58 if content and not self.tag.startswith("__"):
59 content = lower(content)
60 self.content = content
61 self.lower = lower
62
63 def match(self, srtrack):
64 vals = srtrack.track.get_tag_search(self.tag, format=False)
65 if vals == '__null__':
66 vals = None
67 if not isinstance(vals, list):
68 vals = [vals]
69
70 for item in vals:
71 if item is not None:
72 item = self.lower(item)
73
74 if self._matches(item):
75 return True
76 return False
77
78 def _matches(self, value):
79 raise NotImplementedError
80
81
82 class _ExactMatcher(_Matcher):
83 """
84 Condition for exact matches
85 """
86
87 def _matches(self, value):
88 if self.tag.startswith("__"):
89 try:
90 newvalue = float(value)
91 newcontent = float(self.content)
92 return abs(newvalue - newcontent) < 0.0001
93 except (TypeError, ValueError):
94 newvalue = value
95 newcontent = self.content
96 else:
97 newvalue = value
98 newcontent = self.content
99 return newvalue == newcontent
100
101
102 class _InMatcher(_Matcher):
103 """
104 Condition for inexact (ie. containing) matches
105 """
106
107 def _matches(self, value):
108 if not value:
109 return False
110 try:
111 return self.content in value
112 except TypeError:
113 return False
114
115
116 class _RegexMatcher(_Matcher):
117 """
118 Condition for regular expression matches
119 """
120
121 def __init__(self, tag, content, lower):
122 _Matcher.__init__(self, tag, content, lower)
123 self._re = re.compile(content)
124
125 def _matches(self, value):
126 if not value:
127 return False
128 try:
129 return self._re.search(value) is not None
130 except TypeError:
131 return False
132
133
134 class _GtMatcher(_Matcher):
135 """
136 Condition for greater than matches.
137 """
138
139 def _matches(self, value):
140 try:
141 value = float(value)
142 content = float(self.content) # kinda inefficient
143 except (TypeError, ValueError):
144 return False
145 return value > content
146
147
148 class _LtMatcher(_Matcher):
149 """
150 Condition for less than matches.
151 """
152
153 def _matches(self, value):
154 try:
155 if value is None:
156 value = 0
157 else:
158 value = float(value)
159 content = float(self.content) # kinda inefficient
160 except (TypeError, ValueError):
161 return False
162 return value < content
163
164
165 class _NotMetaMatcher:
166 """
167 Condition for boolean NOT
168 """
169
170 __slots__ = ['matcher']
171 tag = None
172
173 def __init__(self, matcher):
174 self.matcher = matcher
175
176 def match(self, srtrack):
177 return not self.matcher.match(srtrack)
178
179
180 class _OrMetaMatcher:
181 """
182 Condition for boolean OR
183 """
184
185 __slots__ = ['left', 'right']
186 tag = None
187
188 def __init__(self, left, right):
189 self.left, self.right = left, right
190
191 def match(self, srtrack):
192 return self.left.match(srtrack) or self.right.match(srtrack)
193
194
195 class _MultiMetaMatcher:
196 """
197 Condition for boolean AND
198 """
199
200 __slots__ = ['matchers']
201 tag = None
202
203 def __init__(self, matchers):
204 self.matchers = matchers
205
206 def match(self, srtrack):
207 for ma in self.matchers:
208 if not ma.match(srtrack):
209 return False
210 return True
211
212
213 class _ManyMultiMetaMatcher:
214 """
215 TODO: think of a proper docstring for this
216
217 This handles the case where we want to match in an OR-like
218 fashion, but also know which tags were matched. Useful for
219 the collection panel expansion.
220 """
221
222 __slots__ = ['matchers', 'tags']
223 tag = None
224
225 def __init__(self, matchers):
226 self.matchers = matchers
227 self.tags = set()
228
229 def match(self, srtrack):
230 self.tags = set()
231 matched = False
232 for ma in self.matchers:
233 if ma.match(srtrack):
234 if ma.tag:
235 matched = True
236 self.tags.add(ma.tag)
237 elif hasattr(ma, 'tags') and ma.tags:
238 matched = True
239 self.tags.update(ma.tags)
240 return matched
241
242
243 class TracksMatcher:
244 """
245 Holds criteria and determines whether
246 a given track matches those criteria.
247 """
248
249 __slots__ = ['matchers', 'case_sensitive', 'keyword_tags']
250
251 def __init__(self, search_string, case_sensitive=True, keyword_tags=None):
252 """
253 :param search_string: a string describing the match conditions
254 :param case_sensitive: whether to search in a case-sensitive
255 manner.
256 :param keyword_tags: a list of tags to match search keywords
257 in.
258 """
259 self.case_sensitive = case_sensitive
260 self.keyword_tags = keyword_tags or []
261 search_string = shave_marks(search_string)
262 tokens = self.__tokenize_query(search_string)
263 tokens = self.__red(tokens)
264 tokens = self.__optimize_tokens(tokens)
265 self.matchers = self.__tokens_to_matchers(tokens)
266
267 def append_matcher(self, matcher, or_match=False):
268 '''Here so you can use playlist matchers. Probably needs better impl'''
269 if not or_match or len(self.matchers) == 0:
270 self.matchers.append(matcher)
271 else:
272 self.matchers[-1] = _OrMetaMatcher(self.matchers[-1], matcher)
273
274 def prepend_matcher(self, matcher, or_match=False):
275 '''Here so you can use playlist matchers. Probably needs better impl'''
276 if not or_match or len(self.matchers) == 0:
277 self.matchers.insert(0, matcher)
278 else:
279 self.matchers[0] = _OrMetaMatcher(matcher, self.matchers[0])
280
281 def match(self, srtrack):
282 """
283 Determine whether a given SearchResultTrack's internal
284 Track object matches this search condition.
285 """
286 for ma in self.matchers:
287 if not ma.match(srtrack):
288 break
289 if ma.tag is not None:
290 if ma.tag not in srtrack.on_tags:
291 srtrack.on_tags.append(ma.tag)
292 elif hasattr(ma, 'tags'):
293 for t in ma.tags:
294 if t not in srtrack.on_tags:
295 srtrack.on_tags.append(t)
296 else:
297 return True
298 return False
299
300 def __tokens_to_matchers(self, tokens, matchers=None):
301 """
302 Converts a token hierarchy to a list of matchers
303 """
304 if not matchers:
305 matchers = []
306
307 # if there's no more tokens, we're done
308 try:
309 token = tokens[0]
310 except IndexError:
311 return matchers
312
313 # is it a special operator?
314 if isinstance(token, list):
315 if len(token) == 1:
316 token = token[0]
317 subtoken = token[0]
318 # NOT
319 if subtoken == "!":
320 nots = self.__tokens_to_matchers(token[1])
321 matchers.append(_NotMetaMatcher(_MultiMetaMatcher(nots)))
322 # OR
323 elif subtoken == "|":
324 left = self.__tokens_to_matchers([token[1][0]])
325 right = self.__tokens_to_matchers([token[1][1]])
326 matchers.append(
327 _OrMetaMatcher(_MultiMetaMatcher(left), _MultiMetaMatcher(right))
328 )
329 # ()
330 elif subtoken == "(":
331 inner = self.__tokens_to_matchers([token[1]])
332 matchers.append(_MultiMetaMatcher(inner))
333 else:
334 return matchers
335
336 elif token == '':
337 pass
338
339 # normal token
340 else:
341 if not self.case_sensitive:
342 lower = lambda x: x.lower()
343 else:
344 lower = lambda x: x
345
346 # TODO: this stuff is kinda repetitive, can we consolidate
347 # it? Maybe move some of this into the matcher classes?
348
349 # exact match in tag
350 if "==" in token:
351 tag, content = token.split("==", 1)
352 if content == "__null__":
353 content = None
354 matcher = _ExactMatcher(tag, content, lower)
355 matchers.append(matcher)
356
357 # keyword in tag
358 elif "=" in token:
359 tag, content = token.split("=", 1)
360 content = content.strip().strip('"')
361 matcher = _InMatcher(tag, content, lower)
362 matchers.append(matcher)
363
364 elif ">" in token:
365 tag, content = token.split(">", 1)
366 content = content.strip().strip('"')
367 matcher = _GtMatcher(tag, content, lower)
368 matchers.append(matcher)
369
370 elif "<" in token:
371 tag, content = token.split("<", 1)
372 content = content.strip().strip('"')
373 matcher = _LtMatcher(tag, content, lower)
374 matchers.append(matcher)
375
376 elif "~" in token:
377 tag, content = token.split("~", 1)
378 content = content.strip().strip('"')
379 matcher = _RegexMatcher(tag, content, lower)
380 matchers.append(matcher)
381
382 # plain keyword
383 else:
384 content = token.strip().strip('"')
385 mmm = []
386 for tag in self.keyword_tags:
387 matcher = _InMatcher(tag, content, lower)
388 mmm.append(matcher)
389 matchers.append(_ManyMultiMetaMatcher(mmm))
390
391 return self.__tokens_to_matchers(tokens[1:], matchers)
392
393 def __tokenize_query(self, search):
394 """
395 Turns a search string into a list of tokens.
396 """
397 search = " " + search + " "
398
399 tokens = []
400 newsearch = ""
401 in_quotes = False
402 in_regex = False
403 n = 0
404 while n < len(search):
405 c = search[n]
406 if c == "\\":
407 if not in_regex:
408 n += 1
409 try:
410 newsearch += search[n]
411 except IndexError:
412 pass
413 elif in_quotes and c != "\"":
414 newsearch += c
415 elif c == "~":
416 in_regex = True
417 newsearch += c
418 elif c == "\"":
419 in_quotes = not in_quotes # toggle
420 # newsearch += c
421 elif c in ["|", "!", "(", ")"]:
422 newsearch += c
423 elif c == " ":
424 in_regex = False
425 tokens.append(newsearch)
426 newsearch = ""
427 else:
428 newsearch += c
429 n += 1
430 return tokens
431
432 def __red(self, tokens):
433 """
434 Turn the token list into a token list hierarchy that is
435 easier to parse.
436 """
437 # base case since we use recursion
438 if tokens == []:
439 return []
440
441 # handle parentheses
442 elif "(" in tokens:
443 num_found = 0
444 start = None
445 end = None
446 count = 0
447 for t in tokens:
448 if t == "(":
449 if start is None:
450 start = count
451 else:
452 num_found += 1
453 elif t == ")":
454 if end is None and num_found == 0:
455 end = count
456 else:
457 num_found -= 1
458 if start and end:
459 break
460 count += 1
461 before = tokens[:start]
462 inside = self.__red(tokens[start + 1 : end])
463 after = tokens[end + 1 :]
464 tokens = before + [["(", inside]] + after
465
466 # handle NOT
467 elif "!" in tokens:
468 start = tokens.index("!")
469 end = start + 2
470 before = tokens[:start]
471 inside = tokens[start + 1 : end]
472 after = tokens[end:]
473 tokens = before + [["!", inside]] + after
474
475 # handle OR
476 elif "|" in tokens:
477 start = tokens.index("|")
478 inside = [tokens[start - 1], tokens[start + 1]]
479 before = tokens[: start - 1]
480 after = tokens[start + 2 :]
481 tokens = before + [["|", inside]] + after
482
483 # nothing special, so just return it
484 else:
485 return tokens
486
487 return self.__red(tokens)
488
489 def __optimize_tokens(self, tokens):
490 """
491 Attempt to optimize tokens, to speed up matching.
492 """
493 # longer queries tend to reject more tracks, which speeds up
494 # processing, so we put them first.
495 tokens.sort(key=len)
496 return tokens
497
498
499 class TracksInList:
500 """
501 Matches tracks contained in a list/dict/set. Copies the list.
502 """
503
504 __slots__ = ['_tracks']
505 tag = None
506
507 def __init__(self, tracks):
508 if isinstance(tracks, dict):
509 self._tracks = set(tracks.keys())
510 else:
511 self._tracks = {t for t in tracks}
512
513 def match(self, track):
514 return track.track in self._tracks
515
516
517 class TracksNotInList(TracksInList):
518 """
519 Matches tracks not in a list/dict/set
520 """
521
522 def match(self, track):
523 return track.track not in self._tracks
524
525
526 def search_tracks(trackiter, trackmatchers: Collection[TracksMatcher]):
527 """
528 Search a set of tracks for those that match specified conditions.
529
530 :param trackiter: An iterable object returning Track objects
531 :param trackmatchers: A list of TrackMatcher objects
532 """
533 for srtr in trackiter:
534 if not isinstance(srtr, SearchResultTrack):
535 srtr = SearchResultTrack(srtr)
536 if all(tma.match(srtr) for tma in trackmatchers):
537 yield srtr
538
539
540 def search_tracks_from_string(
541 trackiter, search_string, case_sensitive=True, keyword_tags=None
542 ):
543 """
544 Convenience wrapper around search_tracks that builds matchers
545 automatically from the search string.
546
547 Arguments have the same meaning as the corresponding arguments on
548 on :class:`search_tracks` and :class:`TracksMatcher`.
549 """
550 matchers = [
551 TracksMatcher(
552 search_string, case_sensitive=case_sensitive, keyword_tags=keyword_tags
553 )
554 ]
555 return search_tracks(trackiter, matchers)
556
557
558 def match_track_from_string(
559 track, search_string, case_sensitive=True, keyword_tags=None
560 ):
561 matcher = TracksMatcher(
562 search_string, case_sensitive=case_sensitive, keyword_tags=keyword_tags
563 )
564 return matcher.match(SearchResultTrack(track))