2021年3月1日 星期一

翻譯年糕 - 機器學習函式庫的綜合運用

 


小時候看到"小叮噹"拿出翻譯年糕的時候覺得很神奇
又是拜機器學習的進步之賜,現在手機就可以做出類似的功能了


常用這類 App 和不同語系的人們溝通的人應該會有一種體會:
想要了解一個國家的文化並做有深度的交流,還是要學習它的語言
不過透過機器確實可以讓我們在各方面得到很大的幫助,
我剛上幼兒園的女兒最近要做英文演說比賽,底下是幼兒園給的講稿

=================
Good morning,everyone.
 My name is Joan.
 My story is Hua Mulan, Hua Mulan.
Long time ago, there was a heroine, 
named Hua Mulan. 
She lived with her parents and a younger brother. 
Recently Huns had begun to invade the border.
Mulan's dad got notices of conscription for the army. 
But he is aged, the young brother was only a eight-year-old child. Mulan decided to take her dad's place in the army.
The next day, she went to the market to buy herself a horse and some gear.
 Mulan disguised herself into a handsome young man and was heading for army's camp. Mulan contributed a lot to the defeats over the enemy. Finally the Huns were totally defeated and the army returned home in triumph.
     The Emperor gave Mulan a rich reward of money and let her return immediately to her hometown.
 Back in her own room, Mulan took off her armor and put on a dress. All her fellow soldiers were stunned, "he" would turn out to be a beauty.
People admired Mulan for her self-giving love to her family and her nation.
 Thank you for your attention. Bye
=======================
在擔心我們自己教她唸會發音不標準的同時,我想到了
文字轉語音TTS 這個技術,
在 python 上導入 gTTS 這套函式就可以輕鬆寫程式把英文稿轉換成標準的英文語音了,在語言學習的道路上學會活用各種工具一定可以事半功倍的,所以別再說唸文組不需要學程式了,程式設計絕對是未來社會最重要的一種能力之一。

前置處理:安裝會用到的函式庫
pip install pyMicVoiceDetection 
pip install SpeechRecognition
pip install googletrans==3.1.0a0
pip install gtts pygame 

底下讓我們來看看 『翻譯年糕』 的程式如何撰寫吧…

#===========錄音===============
import pyMicVoiceDetection as vd
vd.recordAsyn('test.wav',dur=6,deviceIndex=1,TH=0.1)
#===語音辨識(語音轉文字)======
import speech_recognition as sr
r = sr.Recognizer()
with sr.WavFile('test.wav') as source:
    audio = r.record(source) 
Text = r.recognize_google(audio,language='zh-tw')
print(Text)
#==========翻譯===============
import googletrans
#print(googletrans.LANGUAGES)
translator = googletrans.Translator()
results = translator.translate(text = Text,src='zh-tw',dest='en')
print(results.text)
#=======文字轉語音============
from gtts import gTTS
tts = gTTS(text=results.text,lang = 'en' )
tts.save('temp.mp3')#,slow=True)
#==========播放mp3============
from pygame import mixer  # Load the popular external library
mixer.init()
mixer.music.load('temp.mp3')
mixer.music.play()