Skip to content

Commit

Permalink
Merge pull request #148 from home-assistant/synesthesiam-20240709-num…
Browse files Browse the repository at this point in the history
…ber-cache

Cache number words
  • Loading branch information
synesthesiam authored Jul 9, 2024
2 parents 80e418a + 543e339 commit 98cb202
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
2 changes: 1 addition & 1 deletion hassil/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.7.2
1.7.3
22 changes: 18 additions & 4 deletions hassil/recognize.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
import logging
import re
from abc import ABC
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Any, Dict, Iterable, List, Optional, Union
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union

from unicode_rbnf import RbnfEngine

Expand Down Expand Up @@ -45,6 +46,11 @@
# lang -> engine
_ENGINE_CACHE: Dict[str, RbnfEngine] = {}

# (lang, ruleset) -> number -> words
_NUMBER_WORDS_CACHE: Dict[Tuple[str, Union[str, None]], Dict[int, str]] = defaultdict(
dict
)


class HassilError(Exception):
"""Base class for hassil errors"""
Expand Down Expand Up @@ -1275,12 +1281,20 @@ def match_expression(
engine = RbnfEngine.for_language(words_language)
_ENGINE_CACHE[words_language] = engine

words_cache = _NUMBER_WORDS_CACHE[
(words_language, range_list.words_ruleset)
]

for word_number in range(
range_list.start, range_list.stop + 1, range_list.step
):
number_words = engine.format_number(
word_number, ruleset_name=range_list.words_ruleset
).translate(BREAK_WORDS_TABLE)
number_words = words_cache.get(word_number)
if number_words is None:
number_words = engine.format_number(
word_number,
ruleset_name=range_list.words_ruleset,
).translate(BREAK_WORDS_TABLE)
words_cache[word_number] = number_words

range_value = word_number
if range_list.multiplier is not None:
Expand Down

0 comments on commit 98cb202

Please sign in to comment.