Coverage for rdgai/languages.py: 100.00%

29 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-24 23:53 +0000

1from functools import cache 

2from pathlib import Path 

3 

4@cache 

5def read_language_codes_yaml_cached() -> dict[str, str]: 

6 path = Path(__file__).parent / "data/language-subtag-registry.yaml" 

7 

8 assert path.exists(), f"File not found: {path}" 

9 

10 import yaml 

11 with open(path, encoding='utf8') as f: 

12 result = yaml.safe_load(f) 

13 return result 

14 

15 

16def convert_language_code(code:str) -> str: 

17 codes = read_language_codes_yaml_cached() 

18 if code in codes: 

19 return codes[code] 

20 

21 return code 

22 

23# --------------------------------------------------------------------------- 

24# language-specific spelling rules (used only when the file's language matches) 

25# --------------------------------------------------------------------------- 

26 

27def greek_trivially_respelled(first:str, second:str) -> bool: 

28 """ Greek: one word with a movable ν / ς or an elided final vowel (ειπεν / ειπε, αλλα / αλλ). """ 

29 short, long = sorted((first, second), key=len) 

30 return len(long) == len(short) + 1 and long.startswith(short) and long[-1] in "νσαεοι" 

31 

32 

33SPELLING_RULES = { 

34 "grc": greek_trivially_respelled, # Ancient Greek 

35 "el": greek_trivially_respelled, # Greek 

36} 

37 

38 

39def spelling_rule(language:str): 

40 """ The trivial-respelling rule for a language code (e.g. 'grc', 'grc-Grek'), or None. """ 

41 code = (language or "").split("-")[0].lower() 

42 return SPELLING_RULES.get(code) 

43 

44 

45def trivially_respelled(first:str, second:str, language:str="") -> bool: 

46 """ The same word after normalization, or a trivial respelling under the rules for the file's language (if any). """ 

47 from .search import normalize 

48 first, second = normalize(first), normalize(second) 

49 if first == second: 

50 return True 

51 rule = spelling_rule(language) 

52 return bool(rule and rule(first, second))