Cache.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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=DEFAULT_CACHE_EXTENSION):
  15. self._module_name = module_name
  16. self._cache_path = cache_path
  17. self._cache_extension = cache_extension
  18. def get_audio_file_cache_path(self, words, voice, language):
  19. # fix UnicodeEncodeError: 'ascii' codec can't encode character X in position Y
  20. if isinstance(words, unicode):
  21. words = words.encode('utf-8')
  22. md5 = hashlib.md5(words).hexdigest()
  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 remove_audio_file(file_path, cache):
  31. if not cache:
  32. FileManager.remove_file(file_path)