| 1 |
"""Provides a fuzzy matching query.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import difflib |
| 6 |
from typing import TYPE_CHECKING |
| 7 |
|
| 8 |
from beets import config |
| 9 |
from beets.dbcore.query import StringFieldQuery |
| 10 |
from beets.plugins import BeetsPlugin |
| 11 |
|
| 12 |
if TYPE_CHECKING: |
| 13 |
from ._typing import JSONDict |
| 14 |
|
| 15 |
|
| 16 |
class FuzzyQuery(StringFieldQuery[str]): |
| 17 |
def __init__(self, field_name: str, pattern: str, *_) -> None: |
| 18 |
# Fuzzy matching is only available via `string_match`. |
| 19 |
super().__init__(field_name, pattern, fast=False) |
| 20 |
|
| 21 |
@classmethod |
| 22 |
def string_match(cls, pattern: str, val: str) -> bool: |
| 23 |
# smartcase |
| 24 |
if pattern.islower(): |
| 25 |
val = val.lower() |
| 26 |
query_matcher = difflib.SequenceMatcher(None, pattern, val) |
| 27 |
threshold = config["fuzzy"]["threshold"].as_number() |
| 28 |
# Adjust match threshold for the case that the pattern is shorter |
| 29 |
# than the value being matched. This allows the pattern to match |
| 30 |
# substrings of the value, not just the entire value. |
| 31 |
if len(pattern) < len(val): |
| 32 |
max_possible_ratio = 2 * len(pattern) / (len(pattern) + len(val)) |
| 33 |
threshold *= max_possible_ratio |
| 34 |
|
| 35 |
# If upper bound of the ratio meets threshold, then calculate |
| 36 |
# the actual ratio. |
| 37 |
if query_matcher.quick_ratio() >= threshold: |
| 38 |
return query_matcher.ratio() >= threshold |
| 39 |
|
| 40 |
return False |
| 41 |
|
| 42 |
|
| 43 |
class FuzzyPlugin(BeetsPlugin): |
| 44 |
def __init__(self) -> None: |
| 45 |
super().__init__() |
| 46 |
self.config.add({"prefix": "~", "threshold": 0.7}) |
| 47 |
|
| 48 |
def queries(self) -> JSONDict: |
| 49 |
prefix = self.config["prefix"].as_str() |
| 50 |
return {prefix: FuzzyQuery} |