Cache.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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/jarvis/tts"
  7. DEFAULT_CACHE_EXTENSION = "tts"
  8. DEFAULT_LANGUAGE = "default"
  9. DEFAULT_VOICE = "default"
  10. logging.basicConfig()
  11. logger = logging.getLogger("jarvis")
  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. md5 = self.generate_md5_from_words(words)
  23. filename = voice + "." + md5 + "." + self._cache_extension
  24. cache_directory = os.path.join(self._cache_path, self._module_name, language)
  25. file_path = os.path.join(cache_directory, filename)
  26. FileManager.create_directory(cache_directory)
  27. logger.debug("Cache directory %s exists and File path for audio is: %s", cache_directory, file_path)
  28. return file_path
  29. @staticmethod
  30. def generate_md5_from_words(words):
  31. if isinstance(words, unicode):
  32. words = words.encode('utf-8')
  33. return hashlib.md5(words).hexdigest()
  34. @staticmethod
  35. def remove_audio_file(file_path, cache):
  36. if not cache:
  37. FileManager.remove_file(file_path)