|
| 1 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 2 | +# of this software and associated documentation files (the "Software"), to deal |
| 3 | +# in the Software without restriction, including without limitation the rights |
| 4 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 5 | +# copies of the Software, and to permit persons to whom the Software is |
| 6 | +# furnished to do so, subject to the following conditions: |
| 7 | +# |
| 8 | +# The above copyright notice and this permission notice shall be included in all |
| 9 | +# copies or substantial portions of the Software. |
| 10 | +# |
| 11 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 12 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 13 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 14 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 15 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 16 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 17 | +# SOFTWARE. |
| 18 | +from .string_distance import MetricStringDistance |
| 19 | + |
| 20 | + |
| 21 | +class SIFT4Options(MetricStringDistance): |
| 22 | + def __init__(self, options=None): |
| 23 | + self.options = { |
| 24 | + 'maxdistance': 0, |
| 25 | + 'tokenizer': lambda x: [i for i in x], |
| 26 | + 'tokenmatcher': lambda t1, t2: t1 == t2, |
| 27 | + 'matchingevaluator': lambda t1, t2: 1, |
| 28 | + 'locallengthevaluator': lambda x: x, |
| 29 | + 'transpositioncostevaluator': lambda c1, c2: 1, |
| 30 | + 'transpositionsevaluator': lambda lcss, trans: lcss - trans |
| 31 | + } |
| 32 | + otheroptions = { |
| 33 | + 'tokenizer': { |
| 34 | + 'ngram': self.ngramtokenizer, |
| 35 | + 'wordsplit': self.wordsplittokenizer, |
| 36 | + 'characterfrequency': self.characterfrequencytokenizer |
| 37 | + }, |
| 38 | + 'tokematcher': {'sift4tokenmatcher': self.sift4tokenmatcher}, |
| 39 | + 'matchingevaluator': {'sift4matchingevaluator': self.sift4matchingevaluator}, |
| 40 | + 'locallengthevaluator': { |
| 41 | + 'rewardlengthevaluator': self.rewardlengthevaluator, |
| 42 | + 'rewardlengthevaluator2': self.rewardlengthevaluator2 |
| 43 | + }, |
| 44 | + 'transpositioncostevaluator': {'longertranspositionsaremorecostly':self.longertranspositionsaremorecostly}, |
| 45 | + 'transpositionsevaluator': {} |
| 46 | + } |
| 47 | + if isinstance(options, dict): |
| 48 | + for k, v in options.items(): |
| 49 | + if k in self.options.keys(): |
| 50 | + if k == 'maxdistance': |
| 51 | + if isinstance(v, int): |
| 52 | + self.options[k] = v |
| 53 | + else: |
| 54 | + raise ValueError("Option maxdistance should be int") |
| 55 | + else: |
| 56 | + if callable(v): |
| 57 | + self.options[k] = v |
| 58 | + else: |
| 59 | + if v in otheroptions[k].keys(): |
| 60 | + self.options[k] = otheroptions[k][v] |
| 61 | + else: |
| 62 | + msg = "Option {} should be callable or one of [{}]".format(k, ', '.join(otheroptions[k].keys())) |
| 63 | + raise ValueError(msg) |
| 64 | + else: |
| 65 | + raise ValueError("Option {} not recognized.".format(k)) |
| 66 | + elif options is not None: |
| 67 | + raise ValueError("options should be a dictionary") |
| 68 | + self.maxdistance = self.options['maxdistance'] |
| 69 | + self.tokenizer = self.options['tokenizer'] |
| 70 | + self.tokenmatcher = self.options['tokenmatcher'] |
| 71 | + self.matchingevaluator = self.options['matchingevaluator'] |
| 72 | + self.locallengthevaluator = self.options['locallengthevaluator'] |
| 73 | + self.transpositioncostevaluator = self.options['transpositioncostevaluator'] |
| 74 | + self.transpositionsevaluator = self.options['transpositionsevaluator'] |
| 75 | + |
| 76 | + # tokenizers: |
| 77 | + @staticmethod |
| 78 | + def ngramtokenizer(s, n): |
| 79 | + result = [] |
| 80 | + if not s: |
| 81 | + return result |
| 82 | + for i in range(len(s) - n - 1): |
| 83 | + result.append(s[i:(i + n)]) |
| 84 | + return result |
| 85 | + |
| 86 | + @staticmethod |
| 87 | + def wordsplittokenizer(s): |
| 88 | + if not s: |
| 89 | + return [] |
| 90 | + return s.split() |
| 91 | + |
| 92 | + @staticmethod |
| 93 | + def characterfrequencytokenizer(s): |
| 94 | + letters = [i for i in 'abcdefghijklmnopqrstuvwxyz'] |
| 95 | + return [s.lower().count(x) for x in letters] |
| 96 | + |
| 97 | + # tokenMatchers: |
| 98 | + @staticmethod |
| 99 | + def sift4tokenmatcher(t1, t2): |
| 100 | + similarity = 1 - SIFT4().distance(t1, t2, 5) / max(len(t1), len(t2)) |
| 101 | + return similarity > 0.7 |
| 102 | + |
| 103 | + # matchingEvaluators: |
| 104 | + @staticmethod |
| 105 | + def sift4matchingevaluator(t1, t2): |
| 106 | + similarity = 1 - SIFT4().distance(t1, t2, 5) / max(len(t1), len(t2)) |
| 107 | + return similarity |
| 108 | + |
| 109 | + # localLengthEvaluators: |
| 110 | + @staticmethod |
| 111 | + def rewardlengthevaluator(l): |
| 112 | + if l < 1: |
| 113 | + return l |
| 114 | + return l - 1 / (l + 1) |
| 115 | + |
| 116 | + @staticmethod |
| 117 | + def rewardlengthevaluator2(l): |
| 118 | + return pow(l, 1.5) |
| 119 | + |
| 120 | + # transpositionCostEvaluators: |
| 121 | + @staticmethod |
| 122 | + def longertranspositionsaremorecostly(c1, c2): |
| 123 | + return abs(c2 - c1) / 9 + 1 |
| 124 | + |
| 125 | + |
| 126 | +class SIFT4: |
| 127 | + # As described in https://siderite.dev/blog/super-fast-and-accurate-string-distance.html/ |
| 128 | + def distance(self, s1, s2, maxoffset=5, options=None): |
| 129 | + options = SIFT4Options(options) |
| 130 | + t1, t2 = options.tokenizer(s1), options.tokenizer(s2) |
| 131 | + l1, l2 = len(t1), len(t2) |
| 132 | + if l1 == 0: |
| 133 | + return l2 |
| 134 | + if l2 == 0: |
| 135 | + return l1 |
| 136 | + |
| 137 | + c1, c2, lcss, local_cs, trans, offset_arr = 0, 0, 0, 0, 0, [] |
| 138 | + while (c1 < l1) and (c2 < l2): |
| 139 | + if options.tokenmatcher(t1[c1], t2[c2]): |
| 140 | + local_cs += options.matchingevaluator(t1[c1], t2[c2]) |
| 141 | + isTrans = False |
| 142 | + i = 0 |
| 143 | + while i < len(offset_arr): |
| 144 | + ofs = offset_arr[i] |
| 145 | + if (c1 <= ofs['c1']) or (c2 <= ofs['c2']): |
| 146 | + isTrans = abs(c2 - c1) >= abs(ofs['c2'] - ofs['c1']) |
| 147 | + if isTrans: |
| 148 | + trans += options.transpositioncostevaluator(c1, c2) |
| 149 | + else: |
| 150 | + if not ofs['trans']: |
| 151 | + ofs['trans'] = True |
| 152 | + trans += options.transpositioncostevaluator(ofs['c1'], ofs['c2']) |
| 153 | + break |
| 154 | + else: |
| 155 | + if (c1 > ofs['c2']) and (c2 > ofs['c1']): |
| 156 | + offset_arr.pop(i) |
| 157 | + else: |
| 158 | + i += 1 |
| 159 | + offset_arr.append({'c1': c1, 'c2': c2, 'trans': isTrans}) |
| 160 | + else: |
| 161 | + lcss += options.locallengthevaluator(local_cs) |
| 162 | + local_cs = 0 |
| 163 | + if c1 != c2: |
| 164 | + c1 = c2 = min(c1, c2) |
| 165 | + for i in range(maxoffset): |
| 166 | + if (c1 + i < l1) or (c2 + i < l2): |
| 167 | + if (c1 + i < l1) and options.tokenmatcher(t1[c1 + i], t2[c2]): |
| 168 | + c1 += i - 1 |
| 169 | + c2 -= 1 |
| 170 | + break |
| 171 | + if (c2 + i < l2) and options.tokenmatcher(t1[c1], t2[c2 + i]): |
| 172 | + c1 -= 1 |
| 173 | + c2 += i - 1 |
| 174 | + break |
| 175 | + c1 += 1 |
| 176 | + c2 += 1 |
| 177 | + if options.maxdistance: |
| 178 | + temporarydistance = options.locallengthevaluator(max(c1, c2)) - options.transpositionsevaluator(lcss, trans) |
| 179 | + if temporarydistance >= options.maxdistance: |
| 180 | + return round(temporarydistance) |
| 181 | + if (c1 >= l1) or (c2 >= l2): |
| 182 | + lcss += options.locallengthevaluator(local_cs) |
| 183 | + local_cs = 0 |
| 184 | + c1 = c2 = min(c1, c2) |
| 185 | + lcss += options.locallengthevaluator(local_cs) |
| 186 | + return round(options.locallengthevaluator(max(l1, l2)) - options.transpositionsevaluator(lcss, trans)) |
| 187 | + |
| 188 | + |
0 commit comments