Cache.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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. words = words.encode('utf-8')
  21. md5 = hashlib.md5(words).hexdigest()
  22. filename = voice + "." + md5 + "." + self._cache_extension
  23. cache_directory = os.path.join(self._cache_path, self._module_name, language)
  24. file_path = os.path.join(cache_directory, filename)
  25. FileManager.create_directory(cache_directory)
  26. logger.debug("Cache directory %s exists and File path for audio is: %s", cache_directory, file_path)
  27. return file_path
  28. @staticmethod
  29. def remove_audio_file(file_path, cache):
  30. if not cache:
  31. FileManager.remove_file(file_path)