Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Python script to calculate time needed for google tts
- #Need to install "gTTS" and "mutagen" from pip
- #Maintained by Append ([email protected])
- import time
- import shelve
- import ssl
- from gtts import gTTS
- from mutagen.mp3 import MP3
- FILE_SHELVE='result.shelve'
- def calc_ttstime(speak,repeat):
- """
- For the string "speak"*repeat, measured its length after it is pronounced by Google TTS.
- This function utilize gTTS package to generate mp3 file,
- then measure the file length with mutagen package.
- speak: the text you want Google TTS to pronounce.
- Can be integer(unicode) or string.
- """
- if type(speak) == int:
- # 0x4E00 -> chr(0x4E00) -> chr(0x4E00)+chr(0x4E00)+chr(0x4E00)+...
- # store the files using individual name
- speakstr = chr(speak)*repeat
- mp3_file=str('0x%4X'%speak)+".mp3"
- elif type(speak) == str:
- # speak+speak+speak+speak+speak+speak+...
- # store in a specific file
- speakstr = speak*repeat
- mp3_file="tmp.mp3"
- # Generate the mp3 file using gTTS package
- tts = gTTS(text=speakstr, lang='zh-TW', slow=False)
- tts.save(mp3_file)
- # Measure the length
- audio = MP3(mp3_file)
- return audio.info.length
- def sort_shelve():
- """
- return the sorted data from current shelve.
- """
- tmp_shelve=shelve.open(FILE_SHELVE)
- tmp_lst = sorted(tmp_shelve.values(),key=lambda x:x[1])
- tmp_shelve.close()
- return tmp_lst
- def build_shelve():
- """
- generate calc_ttstime(x) for all characters in unicode CJK block.
- """
- #unicode CJK block: 0x4E00 ~ 0x9FFFF
- for i in range(0x4E00,0x9FFF):
- str_i = str('0x%4X'%i)
- res_shelve = shelve.open(FILE_SHELVE,flag='c')
- if str_i not in res_shelve:
- try:
- tic=time.time()
- res=(chr(i),calc_ttstime(i,10))
- toc=time.time()-tic
- print("%s, %s, %10.6f, %10.6f"%(str_i,res[0],res[1],toc))
- res_shelve[str_i]=res
- except KeyboardInterrupt:
- break
- except ssl.SSLError:
- print("%s, SSL Error, leave Blank"%str_i)
- except:
- pass
- res_shelve.close()
- if __name__ == "__main__":
- build_shelve()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement