def __init__(self, text, lang, segment_num, segment_count=None): self.text = text self.lang = lang self.segment_num = segment_num self.segment_count = segment_count self.preload_mutex = threading.Lock() if not hasattr(__class__, "cache"): db_filepath = os.path.join( appdirs.user_cache_dir(appname="google_speech", appauthor=False), "google_speech-cache.sqlite") os.makedirs(os.path.dirname(db_filepath), exist_ok=True) cache_name = "sound_data" __class__.cache = web_cache.ThreadedWebCache( db_filepath, cache_name, expiration=60 * 60 * 24 * 365, # 1 year caching_strategy=web_cache.CachingStrategy.LRU) logging.getLogger().debug( "Total size of file '%s': %s" % (db_filepath, __class__.cache.getDatabaseFileSize())) purged_count = __class__.cache.purge() logging.getLogger().debug( "%u obsolete entries have been removed from cache '%s'" % (purged_count, cache_name)) row_count = len(__class__.cache) logging.getLogger().debug("Cache '%s' contains %u entries" % (cache_name, row_count))
import os, web_cache, base64 from google_speech import Speech, SpeechSegment cachepath = os.path.join('cache') db_filepath = os.path.join(cachepath, "google_speech-cache.sqlite") os.makedirs(os.path.dirname(db_filepath), exist_ok=True) cache_name = "sound_data" SpeechSegment.BASE_URL = 'https://translate.google.{}/translate_tts'.format( os.environ.get('TLD') or 'com') SpeechSegment.cache = web_cache.ThreadedWebCache( db_filepath, cache_name, expiration=60 * 60 * 24 * 365, # 1 year caching_strategy=web_cache.CachingStrategy.LRU) def get_gspeech(text: str): if not text: return speech = Speech(text, 'en') filename = os.path.join(cachepath, "cache.mp3") speech.save(filename) with open(filename, 'rb') as f: base64_audio = base64.b64encode(f.read()) return base64_audio