Cache.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import hashlib
  2. import os
  3. import logging
  4. from core.FileManager import FileManager
  5. DEFAULT_MODULE_NAME = "default"
  6. DEFAULT_CACHE_PATH = "/tmp/kalliope/tts"
  7. DEFAULT_CACHE_EXTENSION = "tts"
  8. DEFAULT_LANGUAGE = "default"
  9. DEFAULT_VOICE = "default"
  10. logging.basicConfig()
  11. logger = logging.getLogger("kalliope")
  12. class Cache:
  13. def __init__(self, module_name=DEFAULT_MODULE_NAME, cache_path=DEFAULT_CACHE_PATH,
  14. cache_extension=None):
  15. if cache_extension is None:
  16. cache_extension = DEFAULT_CACHE_EXTENSION
  17. self._module_name = module_name
  18. self._cache_path = cache_path
  19. self._cache_extension = cache_extension
  20. def get_audio_file_cache_path(self, words, language=DEFAULT_LANGUAGE, voice=DEFAULT_VOICE):
  21. # fix UnicodeEncodeError: 'ascii' codec can't encode character X in position Y
  22. if voice is None:
  23. voice = DEFAULT_VOICE
  24. md5 = self.generate_md5_from_words(words)
  25. filename = voice + "." + md5 + "." + self._cache_extension
  26. cache_directory = os.path.join(self._cache_path, self._module_name, language)
  27. file_path = os.path.join(cache_directory, filename)
  28. FileManager.create_directory(cache_directory)
  29. logger.debug("Cache directory %s exists and File path for audio is: %s", cache_directory, file_path)
  30. return file_path
  31. @staticmethod
  32. def generate_md5_from_words(words):
  33. if isinstance(words, unicode):
  34. words = words.encode('utf-8')
  35. return hashlib.md5(words).hexdigest()
  36. @staticmethod
  37. def remove_audio_file(file_path, cache):
  38. if not cache:
  39. FileManager.remove_file(file_path)