Skip to content

Commit

Permalink
Support unambiguous detection of language if only prefixes are supplied
Browse files Browse the repository at this point in the history
o ceases search as soon as ambiguity is resolved
  • Loading branch information
pjkundert committed Nov 29, 2022
1 parent e3b8830 commit 3f2067d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/mnemonic/mnemonic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
4 changes: 4 additions & 0 deletions tests/test_mnemonic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down

0 comments on commit 3f2067d

Please sign in to comment.