1# -*- coding: utf-8 -*- 2# This file is part of beets. 3# Copyright 2016, Philippe Mongeau. 4# 5# Permission is hereby granted, free of charge, to any person obtaining 6# a copy of this software and associated documentation files (the 7# "Software"), to deal in the Software without restriction, including 8# without limitation the rights to use, copy, modify, merge, publish, 9# distribute, sublicense, and/or sell copies of the Software, and to 10# permit persons to whom the Software is furnished to do so, subject to 11# the following conditions: 12# 13# The above copyright notice and this permission notice shall be 14# included in all copies or substantial portions of the Software. 15 16"""Provides a fuzzy matching query. 17""" 18 19from __future__ import division, absolute_import, print_function 20 21from beets.plugins import BeetsPlugin 22from beets.dbcore.query import StringFieldQuery 23from beets import config 24import difflib 25 26 27class FuzzyQuery(StringFieldQuery): 28 @classmethod 29 def string_match(cls, pattern, val): 30 # smartcase 31 if pattern.islower(): 32 val = val.lower() 33 query_matcher = difflib.SequenceMatcher(None, pattern, val) 34 threshold = config['fuzzy']['threshold'].as_number() 35 return query_matcher.quick_ratio() >= threshold 36 37 38class FuzzyPlugin(BeetsPlugin): 39 def __init__(self): 40 super(FuzzyPlugin, self).__init__() 41 self.config.add({ 42 'prefix': '~', 43 'threshold': 0.7, 44 }) 45 46 def queries(self): 47 prefix = self.config['prefix'].as_str() 48 return {prefix: FuzzyQuery} 49