Add LRU caching to corpus file loaders and pronounce utilities - #1320
Conversation
…ilities Co-authored-by: bact <128572+bact@users.noreply.github.com>
|
@copilot Line 21 of pythainlp/util/pronounce.py, remove unnecessary |
…nce.py and syllable.py Co-authored-by: bact <128572+bact@users.noreply.github.com>
Fixed in 0aa4a10. Removed |
|



What do these changes do
Apply LRU caching to corpus file readers and pronounce utilities to eliminate redundant I/O and object construction on repeated calls. Also removes unnecessary
list()conversions on already-iterable objects.What was wrong
get_corpus(),get_corpus_as_is(), andget_corpus_default_db()re-read and re-parsed files on every invocation, even when called repeatedly with the same arguments (e.g.ttc.py,tnc.py, andphupha.pyeach callget_corpus()with the same filename from two separate functions).rhyme()performed an O(n) scan over all single-syllable Thai words on every call, with no per-word memoisation.spelling()rebuilt aTokenizerfrom scratch on every call.all_thai_words_dictinpronounce.pywas an inconsistent pattern compared to the rest of the codebase.list()calls wrapped already-iterable objects (frozenset,str) inpronounce.pyandsyllable.py.How this fixes it
pythainlp/corpus/core.pyget_corpus(filename, comments)—@lru_cache(maxsize=None). Measured 13,500× faster on cache hits (13.5 ms → 0.001 ms).get_corpus_as_is(filename)—@lru_cache(maxsize=None). Same benefit for the list-returning variant._load_default_db()— new private cached helper that reads and parsesdefault_db.jsononce.get_corpus_default_db()delegates to it instead of re-reading the file on every call.pythainlp/util/pronounce.py_single_syllable_thai_words()— replaces the bare module-level mutable globalall_thai_words_dictwith a@lru_cache(maxsize=None)function, consistent withtokenize/__init__.pypattern. Removes unnecessarylist()wrapping of thefrozensetreturned bythai_words().rhyme(word)—@lru_cache(maxsize=1024). Per-word memoisation of the O(n) scan._spelling_tokenizer()—@lru_cache(maxsize=None)factory; avoids rebuilding aTokenizerwith identical arguments on everyspelling()call._spelling_impl(word)—@lru_cache(maxsize=1024)private core ofspelling(). The public function keeps its non-string validation guard and delegates to the cached impl.pythainlp/util/syllable.pylist()calls wrappingthai_consonantsandthai_tonemarks(both strings) in membership tests — single-characterinchecks work directly on strings.Your checklist for this pull request
Original prompt
💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.