From b64acaddd53cdd8e4818ffb3a933bc36dc63f182 Mon Sep 17 00:00:00 2001 From: Perry Kundert Date: Tue, 29 Nov 2022 05:30:36 -0800 Subject: [PATCH] Support unambiguous detection of language if only prefixes are supplied o ceases search as soon as ambiguity is resolved --- src/mnemonic/mnemonic.py | 7 +++++-- tests/test_mnemonic.py | 4 ++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/mnemonic/mnemonic.py b/src/mnemonic/mnemonic.py index 9457f9d..e64921d 100644 --- a/src/mnemonic/mnemonic.py +++ b/src/mnemonic/mnemonic.py @@ -90,13 +90,16 @@ def normalize_string(txt: AnyStr) -> str: @classmethod def detect_language(cls, code: str) -> str: - """Scan the Mnemonic until the language becomes unambiguous.""" + """Scan the Mnemonic until the language becomes unambiguous, including as abbreviation prefixes.""" code = cls.normalize_string(code) possible = set(cls(lang) for lang in cls.list_languages()) for word in code.split(): - possible = set(p for p in possible if word in p.wordlist) + # possible languages have candidate(s) starting with the word/prefix + possible = set(p for p in possible if any(c.startswith( word ) for c in p.wordlist)) if not possible: raise ConfigurationError(f"Language unrecognized for {word!r}") + if len( possible ) < 2: + break if len(possible) == 1: return possible.pop().language raise ConfigurationError( diff --git a/tests/test_mnemonic.py b/tests/test_mnemonic.py index 40785ff..9cc4eb0 100755 --- a/tests/test_mnemonic.py +++ b/tests/test_mnemonic.py @@ -57,6 +57,10 @@ def test_failed_checksum(self) -> None: def test_detection(self) -> None: self.assertEqual("english", Mnemonic.detect_language("security")) + self.assertEqual( "english", Mnemonic.detect_language( "fruit wave dwarf" )) # ambiguous up to wave + self.assertEqual( "english", Mnemonic.detect_language( "fru wago dw" )) # ambiguous french/english up to dwarf prefix + self.assertEqual( "french", Mnemonic.detect_language( "fru wago dur enje" )) # ambiguous french/english up to enjeu prefix + with self.assertRaises(Exception): Mnemonic.detect_language( "jaguar xxxxxxx"