Cache.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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. class Cache:
  11. def __init__(self, module_name=DEFAULT_MODULE_NAME, cache_path=DEFAULT_CACHE_PATH, cache_extension=DEFAULT_CACHE_EXTENSION):
  12. self._module_name = module_name
  13. self._cache_path = cache_path
  14. self._cache_extension = cache_extension
  15. if self._cache_extension is None:
  16. self._cache_extension = DEFAULT_CACHE_EXTENSION
  17. def get_audio_file_cache_path(self, words, voice, language):
  18. # fix UnicodeEncodeError: 'ascii' codec can't encode character X in position Y
  19. words = words.encode('utf-8')
  20. md5 = hashlib.md5(words).hexdigest()
  21. filename = voice + "." + md5 + self._cache_extension
  22. cache_directory = os.path.join(self._cache_path, self._module_name, language)
  23. file_path = os.path.join(cache_directory, filename)
  24. FileManager.create_directory(cache_directory)
  25. logging.debug("Cache directory %s exists and File path for audio is: %s", cache_directory, file_path)
  26. return file_path
  27. @staticmethod
  28. def remove_audio_file(file_path, cache):
  29. if not cache:
  30. FileManager.remove_file(file_path)