Cache.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import shutil
  2. import hashlib
  3. import os
  4. import logging
  5. class Cache:
  6. DEFAULT_MODULE_NAME = "default"
  7. DEFAULT_CACHE_PATH = "/tmp/jarvis/tts"
  8. DEFAULT_CACHE_EXTENSION = ".tts"
  9. def __init__(self, module_name=DEFAULT_MODULE_NAME, cache_path=DEFAULT_CACHE_PATH, cache_extension=DEFAULT_CACHE_EXTENSION):
  10. self._module_name = module_name
  11. self._cache_path = cache_path
  12. self._cache_extension = cache_extension
  13. def get_audio_file_cache_path(self, words, voice, language):
  14. md5 = hashlib.md5(words).hexdigest()
  15. filename = voice + "." + md5 + self._cache_extension
  16. cache_directory = os.path.join(self._cache_path, self._module_name, language)
  17. file_path = os.path.join(cache_directory, filename)
  18. self.create_directory(cache_directory)
  19. logging.debug("Cache directory %s exists and File path for audio is: %s", cache_directory, file_path)
  20. return file_path
  21. @staticmethod
  22. def create_directory(cache_path):
  23. if not os.path.exists(cache_path):
  24. os.makedirs(cache_path)
  25. def write_in_file(self, file_path, content):
  26. with open(file_path, "wb") as file_open:
  27. file_open.write(content)
  28. file_open.close()
  29. return not self.file_is_empty(file_path)
  30. def wipe_cache(self):
  31. shutil.rmtree(self._cache_path)
  32. @staticmethod
  33. def file_is_empty(file_path):
  34. return os.path.getsize(file_path) == 0