Make TTSCahce safer

Add __contains__ method to TTSCache, The cache contains a SHA if the SHA is
known and all expected files exists on disk.

This is handles unexpected system events in a more consistent manner and
will still be fast for the case where a new sentence needs to be
synthetisized.
pull/2914/head
Åke Forslund 2021-04-28 22:45:20 +02:00
parent 0e2a78068a
commit 5d3393b935
2 changed files with 17 additions and 1 deletions

View File

@ -102,6 +102,9 @@ class AudioFile:
except Exception:
LOG.exception("Failed to write {} to cache".format(self.name))
def exists(self):
return self.path.exists()
class PhonemeFile:
def __init__(self, cache_dir: Path, sentence_hash: str):
@ -133,6 +136,9 @@ class PhonemeFile:
except Exception:
LOG.exception("Failed to write {} to cache".format(self.name))
def exists(self):
return self.path.exists()
class TextToSpeechCache:
"""Class for all persistent and temporary caching operations."""
@ -156,6 +162,16 @@ class TextToSpeechCache:
str(self.temporary_cache_dir), permissions=0o755
)
def __contains__(self, sha):
"""The cache contains a SHA if it knows of it and it exists on disk."""
if sha not in self.cached_sentences:
return False # Doesn't know of it
else:
# Audio file must exist, phonemes are optional.
audio, phonemes = self.cached_sentences[sha]
return (audio.exists() and
(phonemes is None or phonemes.exists()))
def load_persistent_cache(self):
"""Load the contents of dialog files to the persistent cache directory.

View File

@ -355,7 +355,7 @@ class TTS(metaclass=ABCMeta):
for sentence, l in chunks:
sentence_hash = hash_sentence(sentence)
if sentence_hash in self.cache.cached_sentences:
if sentence_hash in self.cache:
audio_file, phoneme_file = self._get_sentence_from_cache(
sentence_hash
)