前言
本項(xiàng)目基于百度語(yǔ)音識(shí)別API,結(jié)合了語(yǔ)音識(shí)別、視頻轉(zhuǎn)換音頻識(shí)別以及語(yǔ)句停頓分割識(shí)別等多種技術(shù),從而實(shí)現(xiàn)了高效的視頻字幕生成。
首先,我們采用百度語(yǔ)音識(shí)別API,通過(guò)對(duì)語(yǔ)音內(nèi)容進(jìn)行分析,將音頻轉(zhuǎn)換成文本。這個(gè)步驟使得我們能夠從語(yǔ)音中提取出有意義的文本信息。
其次,我們運(yùn)用視頻轉(zhuǎn)換音頻識(shí)別技術(shù),將視頻中的音頻部分提取出來(lái),并進(jìn)行同樣的文本識(shí)別操作。這樣,我們就可以對(duì)視頻中的聲音內(nèi)容進(jìn)行準(zhǔn)確的文字化。
另外,我們還引入了語(yǔ)句停頓分割識(shí)別,用于識(shí)別語(yǔ)音中的語(yǔ)句邊界和停頓,從而更準(zhǔn)確地切分出每個(gè)語(yǔ)句的內(nèi)容。
綜合上述技術(shù),我們成功地實(shí)現(xiàn)了視頻字幕的生成。通過(guò)對(duì)視頻中的語(yǔ)音內(nèi)容進(jìn)行逐幀識(shí)別、轉(zhuǎn)換和分割,我們能夠準(zhǔn)確地將語(yǔ)音內(nèi)容轉(zhuǎn)化為文本,并在視頻上生成相應(yīng)的字幕。
本項(xiàng)目不僅能夠?yàn)橐曨l內(nèi)容提供字幕,也為內(nèi)容創(chuàng)作者提供了方便,使得他們能夠更好地將視頻內(nèi)容傳達(dá)給觀(guān)眾。同時(shí),這也為包括聽(tīng)障人士在內(nèi)的用戶(hù)提供了更友好的觀(guān)看體驗(yàn)。
總體設(shè)計(jì)
本部分包括系統(tǒng)整體結(jié)構(gòu)圖和系統(tǒng)流程圖。
系統(tǒng)整體結(jié)構(gòu)圖
系統(tǒng)整體結(jié)構(gòu)如圖所示。
系統(tǒng)流程圖
系統(tǒng)流程如圖所示。
運(yùn)行環(huán)境
在Windows環(huán)境下完成Python 3所需的配置,并運(yùn)行代碼即可。
模塊實(shí)現(xiàn)
本項(xiàng)目包括7個(gè)模塊:數(shù)據(jù)預(yù)處理、翻譯、格式轉(zhuǎn)換、音頻切割、語(yǔ)音識(shí)別、文本切割和main
函數(shù),下面分別給出各模塊的功能介紹及相關(guān)代碼。
1. 數(shù)據(jù)預(yù)處理
基于百度語(yǔ)音API得到所需要的APP_ID
、API_KEY
、SECRET_KEY
。進(jìn)入百度語(yǔ)音官網(wǎng)地址為http://yuyin.baidu.com,在右上角單擊“控制臺(tái)”按鈕,登錄百度賬號(hào),如圖所示。
在控制臺(tái)左端單擊“產(chǎn)品服務(wù)”-“語(yǔ)音技術(shù)”進(jìn)入語(yǔ)音識(shí)別界面,如圖所示。
進(jìn)入后,可能會(huì)提示需要實(shí)名認(rèn)證,填入相關(guān)信息,完成認(rèn)證即可。
單擊“創(chuàng)建應(yīng)用”,根據(jù)需求填寫(xiě)項(xiàng)目名稱(chēng)、類(lèi)型、所需接口、語(yǔ)音包名、應(yīng)用描述等信息后即可創(chuàng)建成功,如圖所示。
按下圖,查看應(yīng)用詳情即可得到APP_ID
、API_KEY
、SECRET_KEY
供后續(xù)調(diào)用,在此界面也可查看調(diào)用量限制等信息,如下兩圖所示。
注意:如果API接口狀態(tài)為待開(kāi)通付費(fèi)的話(huà),需要在左邊“概覽”頁(yè)中,選擇需要開(kāi)通的API接口,進(jìn)行開(kāi)通。如下圖所示。
本項(xiàng)目使用百度語(yǔ)音識(shí)別API接口,采用以下兩種方法調(diào)用,最終采用后者。
(1) 下載使用SDK
根據(jù)pip工具使用pip install baidu-aip
下載。
調(diào)用代碼為:
from aip import AipSpeech
APP_ID = 'XXXXXXX'
API_KEY = '****************'
SECRET_KEY = '*********************'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
#讀取文件
def get_file_content(file_path):
with open(file_path, 'rb') as fp:
return fp.read()
result=client.asr(get_file_content('test2.wav'),'wav',16000,{
'dev_pid': 1537,
})
print(type(result))
print(result)
(2)不需要下載SDK
首先,根據(jù)文檔組裝.url獲取token;其次,處理本地音頻以JSON格式POST到百度語(yǔ)音識(shí)別服務(wù)器,獲得返回結(jié)果。
#合成請(qǐng)求token的URL
url = baidu_server + "grant_type=" + grant_type + "&client_id=" + client_id + "&client_secret=" + client_secret
#獲取token
res = urllib.request.urlopen(url).read()
data = json.loads(res.decode('utf-8'))
token = data["access_token"]
print(token)
下載配置所需要的庫(kù)相關(guān)操作如下:
(1)安裝moviepy庫(kù)
moviepy用于視頻編輯Python庫(kù):切割、拼接、標(biāo)題插入、視頻合成、視頻處理。moviepy依賴(lài)庫(kù)有numpy、imageio、decorator、 tqdm。
在cmd使用命令pip install moviepy
安裝moviepy庫(kù)。
安裝時(shí)可能存在的問(wèn)題:發(fā)生報(bào)錯(cuò)導(dǎo)致下載安裝停止時(shí),查看報(bào)錯(cuò)信息可能為依賴(lài)庫(kù)的缺失。
如Anaconda中的Python未安裝tqdm發(fā)生報(bào)錯(cuò),使用conda list
查看確認(rèn)缺失該庫(kù),可通過(guò)conda install tqdm
下載安裝,其他庫(kù)缺失問(wèn)題也可依照類(lèi)似方法解決。
(2)安裝js2py庫(kù)
爬蟲(chóng)時(shí)很多網(wǎng)站使用js加密技術(shù),js2py可以在Python環(huán)境下運(yùn)行Java代碼,擺脫Java環(huán)境的瓶頸。制作中英文字幕時(shí),涉及百度語(yǔ)音識(shí)別英文輸出,需將其翻譯為中文,因此,安裝is2py庫(kù) 爬蟲(chóng)調(diào)用百度翻譯的JavaScript腳本。
(3)安裝pydub庫(kù)
根據(jù)音頻的靜默檢測(cè)語(yǔ)句停頓,進(jìn)行合理斷句識(shí)別,pydub庫(kù)使用pip工具安裝,在cmd命令行輸入pip insall pydub
。
使用pydub)庫(kù) from pydub import AudioSegment
, 驗(yàn)證安裝是否成功可通過(guò)例程檢測(cè),若報(bào)錯(cuò)沒(méi)有pydub庫(kù),則安裝失敗。
2. 翻譯
將識(shí)別的英文結(jié)果使用爬蟲(chóng)調(diào)用百度翻譯,得到對(duì)應(yīng)的中文翻譯。
class baidu_Translate():
def __init__(self):
self.js = js2py.eval_js('''
var i = null;
function n(r, o) {
for (var t = 0; t < o.length - 2; t += 3) {
var a = o.charAt(t + 2);
a = a >= "a" ? a.charCodeAt(0) - 87 : Number(a),
a = "+" === o.charAt(t + 1) ? r >>> a: r << a,
r = "+" === o.charAt(t) ? r + a & 4294967295 : r ^ a
}
return r
}
var hash = function e(r,gtk) {
var o = r.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g);
if (null === o) {
var t = r.length;
t > 30 && (r = "" + r.substr(0, 10) + r.substr(Math.floor(t / 2) - 5, 10) + r.substr( - 10, 10))
} else {
for (var e = r.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/), C = 0, h = e.length, f = []; h > C; C++)"" !== e[C] && f.push.a pply(f, a(e[C].split(""))),C !== h - 1 && f.push(o[C]);
var g = f.length;
g > 30 && (r = f.slice(0, 10).join("")+f.slice(Math.floor(g/ 2) - 5, Math.floor(g / 2) + 5).join("") + f.slice( - 10).join(""))
}
var u = void 0,
u = null !== i ? i: (i = gtk || "") || "";
for (var d = u.split("."), m = Number(d[0]) || 0, s = Number(d [1]) || 0, S = [], c = 0, v = 0; v < r.length; v++) {
var A = r.charCodeAt(v);
128 > A ? S[c++] = A: (2048 > A ? S[c++] = A >> 6 | 192 : (55296 ===(64512 & A) && v + 1 < r.length && 56320 ===(64512&r.charCodeAt(v + 1)) ? (A = 65536 + ((1023 & A) << 10) + (1023 & r.charCodeAt(++v)), S[c++] = A >> 18 | 240, S[c++] = A >> 12 &63 | 128) : S[c++] = A >> 12 | 224,S[c++] = A >> 6 & 63 | 128), S[c++] = 63 & A | 128)
}
for (
var p = m,F = "+-a^+6", D = "+-3^+b+-f", b = 0;
b < S.length; b++) p += S[b],p = n(p, F);
return p = n(p, D),
p ^= s,
0 > p && (p = (2147483647 & p) + 2147483648),
p %= 1e6,
p.toString() + "." + (p ^ m)
}
''')
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36', }
self.session = requests.Session()
self.session.get('https://fanyi.baidu.com', headers=headers)
response = self.session.get('https://fanyi.baidu.com', headers=headers)
self.token = re.findall("token: '(.*?)',", response.text)[0]
self.gtk = '320305.131321201' # re.findall("window.gtk = '(.*?)';", response.text, re.S)[0]
def translate(self, query, from_lang='en', to_lang='zh'):
#語(yǔ)言檢測(cè)
self.session.post('https://fanyi.baidu.com/langdetect', data={'query': query})
#單擊事件
self.session.get('https://click.fanyi.baidu.com/?src=1&locate=zh&actio n=query&type=1&page=1')
#翻譯
data = {
'from': from_lang,
'to': to_lang,
'query': query,
'transtype': 'realtime',
'simple_means_flag': '3',
'sign': self.js(query, self.gtk),
'token': self.token
}
response = self.session.post('https://fanyi.baidu.com/v2transapi', data=data)
json = response.json()
if 'error' in json:
pass
#return 'error: {}'.format(json['error'])
else:
return response.json()['trans_result']['data'][0]['dst']
3. 格式轉(zhuǎn)換
百度語(yǔ)音識(shí)別API有嚴(yán)格的參數(shù)要求,使用moviepy庫(kù)完成從視頻中提取音頻工作。
def separate_audio(file_path, save_path):
#視頻轉(zhuǎn)音頻,音頻編碼要求:.wav格式、采樣率 16000、16bit 位深、單聲道
audio_file = save_path + '\\tmp.wav'
audio = AudioFileClip(file_path)
audio.write_audiofile(audio_file, ffmpeg_params=['-ar', '16000', '-ac', '1'], logger=None)
return audio_file
4. 音頻切割
使用pydub庫(kù),利用停頓時(shí)的音頻分貝降低作為判定斷句標(biāo)準(zhǔn),設(shè)置停頓時(shí)的分貝閾值,拆分后的小音頻不短于0.5s,不長(zhǎng)于5s。
def cut_point(path, dbfs=1.25): #音頻切割函數(shù)
sound = AudioSegment.from_file(path, format="wav")
tstamp_list = detect_silence(sound, 600, sound.dBFS * dbfs, 1)
timelist = []
for i in range(len(tstamp_list)):
if i == 0:
back = 0
else:
back = tstamp_list[i - 1][1] / 1000
timelist.append([back, tstamp_list[i][1] / 1000])
min_len = 0.5 #切割所得音頻不短于0.5s,不長(zhǎng)于5s
max_len = 5
result = []
add = 0
total = len(timelist)
for x in range(total):
if x + add < total:
into, out = timelist[x + add]
if out-into>min_len and out-into<max_len and x + add +1 < total:
add += 1
out = timelist[x + add][1]
result.append([into, out])
elif out - into > max_len:
result.append([into, out])
else:
break
return result
5. 語(yǔ)音識(shí)別
調(diào)用百度語(yǔ)音識(shí)別API進(jìn)行操作,填寫(xiě)申請(qǐng)App所得信息,上傳待識(shí)別音頻,進(jìn)行中文或英文識(shí)別,返回所得文本。
class baidu_SpeechRecognition(): #調(diào)用百度語(yǔ)音識(shí)別API進(jìn)行操作
def __init__(self, dev_pid):
Speech_APP_ID = '19712136'
Speech_API_KEY = 'Loo4KbNtagchc2BLdCnHEnZl'
Speech_SECRET_KEY = 'DO4UlSnw7FzpodU2G3yXQSHLv6Q2inN8'
self.dev_pid = dev_pid
self.SpeechClient = AipSpeech(Speech_APP_ID, Speech_API_KEY, Speech_SECRET_KEY)
self.TranslClient = baidu_Translate()
def load_audio(self, audio_file): #讀取加載音頻文件
self.source = AudioSegment.from_wav(audio_file)
def speech_recognition(self, offset, duration, fanyi):
#語(yǔ)音識(shí)別,根據(jù)要求的參數(shù)進(jìn)行設(shè)置
data = self.source[offset * 1000:duration * 1000].raw_data
result = self.SpeechClient.asr(data, 'wav', 16000, {'dev_pid': self.dev_pid, })
fanyi_text = ''
if fanyi:
try:
fanyi_text = self.TranslClient.translate(result['result'][0])
#調(diào)用translate()函數(shù),將識(shí)別文本翻譯或直接輸出
except:
pass
try:
return [result['result'][0], fanyi_text] #返回所得文本
except:
#print('錯(cuò)誤:',result)
return ['', '']
6. 文本切割
斷句,避免同一畫(huà)面內(nèi)出現(xiàn)過(guò)多文字影響觀(guān)感,將38設(shè)為閾值,小于38時(shí)正常顯示,大于則切割,分段顯示。
def cut_text(text, length=38):
#文本切割,即斷句,一個(gè)畫(huà)面最多單語(yǔ)言字?jǐn)?shù)不超過(guò)38,否則將多出的加入下一畫(huà)面
newtext = ''
if len(text) > length:
while True:
cutA = text[:length]
cutB = text[length:]
newtext += cutA + '\n'
if len(cutB) < 4:
newtext = cutA + cutB
break
elif len(cutB) > length:
text = cutB
else:
newtext += cutB
break
return newtext
return text
7. main函數(shù)
讓模塊(函數(shù))可以自己?jiǎn)为?dú)執(zhí)行,構(gòu)造調(diào)用其他函數(shù)的入口,設(shè)置簡(jiǎn)單的交互功能,用戶(hù)根據(jù)需要選擇語(yǔ)言類(lèi)型、字幕類(lèi)型以及是否將字幕直接加入視頻中,并可觀(guān)察當(dāng)前工作進(jìn)度、推算所需時(shí)間、文件格式錯(cuò)誤時(shí)報(bào)錯(cuò)。
if __name__ == '__main__':
def StartHandle(timeList, save_path, srt_mode=2, result_print=False):
index = 0
total = len(timeList)
a_font = r'{\fn微軟雅黑\fs14}' #中、英字幕字體設(shè)置
b_font = r'{\fn微軟雅黑\fs10}'
fanyi = False if srt_mode == 1 else True
file_write = open(save_path, 'a', encoding='utf-8')
for x in range(total):
into, out = timelist[x]
timeStamp=format_time(into - 0.2) +'--> '+ format_time(out- 0.2)
result=baidufanyi.speech_recognition(into+0.1,out - 0.1, fanyi)
if result_print:
if srt_mode == 0:
print(timeStamp, result[0])
else:
print(timeStamp, result)
else:
progressbar(total, x, '識(shí)別中...&& - {0}/{1}'.format('%03d' % (total), '%03d' % (x)), 44)
#將切割后所得的識(shí)別文本結(jié)果按順序?qū)懭?,中、英、中英雙語(yǔ)不同
if len(result[0]) > 1:
index += 1
text = str(index) + '\n' + timeStamp + '\n'
if srt_mode == 0: # 僅中文
text += a_font + cut_text(result[1])
elif srt_mode == 1: # 僅英文
text += b_font + cut_text(result[0])
else: #中文+英文
text+=a_font+cut_text(result[1])+'\n'+b_font + result[0]
text = text.replace('\u200b', '') + '\n\n'
file_write.write(text)
file_write.close()
if not result_print:
progressbar(total,total,'識(shí)別中...&&-{0}/{1}'.format('%03d'% (total), '%03d' % (total)), 44)
os.system('cls')
wav_path = os.environ.get('TEMP')
#語(yǔ)音模型,1536為普通話(huà)+簡(jiǎn)單英文,1537為普通話(huà),1737為英語(yǔ),1637為粵語(yǔ),1837川話(huà),1936普通話(huà)遠(yuǎn)場(chǎng)
pid_list = 1536, 1537, 1737, 1637, 1837, 1936
#設(shè)置參數(shù)
print('[ 百度語(yǔ)音識(shí)別字幕生成器 - by Teri ]\n')
__line__print__('1 模式選擇')
input_dev_pid = input('請(qǐng)選擇識(shí)別模式:\n'
'\n (1)普通話(huà),'
'\n (2)普通話(huà)+簡(jiǎn)單英語(yǔ),'
'\n (3)英語(yǔ),'
'\n (4)粵語(yǔ),'
'\n (5)四川話(huà),'
'\n (6)普通話(huà)-遠(yuǎn)場(chǎng)'
'\n\n請(qǐng)輸入一個(gè)選項(xiàng)(默認(rèn)3):')
__line__print__('2 字幕格式')
input_srt_mode = input('請(qǐng)選擇字幕格式:\n'
'\n (1)中文,'
'\n (2)英文,'
'\n (3)中文+英文,'
'\n\n請(qǐng)輸入一個(gè)選項(xiàng)(默認(rèn)3):')
__line__print__('3 實(shí)時(shí)輸出')
input_print = input('是否實(shí)時(shí)輸出結(jié)果到屏幕? (默認(rèn):否/y:輸出):').upper()
#處理參數(shù),根據(jù)用戶(hù)輸入給出相應(yīng)參數(shù)
dev_pid = int(input_dev_pid) if input_dev_pid else 3
dev_pid -= 1
srt_mode = int(input_srt_mode) if input_srt_mode else 3
srt_mode -= 1
re_print = True if input_print == 'Y' else False
#輸入文件
__line__print__('4 打開(kāi)文件')
input_file = input('請(qǐng)拖入一個(gè)文件或文件夾并按回車(chē):').strip('"')
video_file = []
if not os.path.isdir(input_file):
video_file = [input_file]
else:
file_list = file_filter(input_file)
for a, b in file_list:
video_file.append(a + '\\' + b)
#執(zhí)行確認(rèn)
select_dev = ['普通話(huà)', '普通話(huà)+簡(jiǎn)單英語(yǔ)', '英語(yǔ)', '粵語(yǔ)', '四川話(huà)', '普通話(huà)-遠(yuǎn)場(chǎng)']
select_mode = ['中文', '英文', '中文+英文']
__line__print__('5 確認(rèn)執(zhí)行')
input('當(dāng)前的設(shè)置:\n識(shí)別模式: {0}, 字幕格式: {1}, 輸出結(jié)果: {2}\n當(dāng)前待處理文件 {3} 個(gè)\n請(qǐng)按下回車(chē)開(kāi)始處理...'.format(
select_dev[dev_pid],
select_mode[srt_mode],
'是' if re_print else '否',
len(video_file)
))
#批量處理,調(diào)用所設(shè)函數(shù)進(jìn)行處理工作
total_file = len(video_file)
total_time = time.time()
baidufanyi = baidu_SpeechRecognition(pid_list[dev_pid])
for i in range(total_file): #在所給文件范圍內(nèi)循環(huán)運(yùn)行
item_time = time.time() #項(xiàng)目時(shí)間
file_name = video_file[i].split('\\')[-1]
print('\n>>>>>>>> ...正在處理音頻... <<<<<<<<', end='')
audio_file = separate_audio(video_file[i], wav_path) #視頻轉(zhuǎn)音頻
timelist = cut_point(audio_file, dbfs=1.15) #音頻切割
if timelist:
print('\r>>>>>>>> 當(dāng)前:{} 預(yù)計(jì):{} <<<<<<<<'.format(
'%03d' % (i),
countTime(len(timelist) * 5, now=False)
))
srt_name = video_file[i][:video_file[i].rfind('.')] + '.srt'
#根據(jù)時(shí)間將輸出循環(huán)寫(xiě)入字幕文件
baidufanyi.load_audio(audio_file)
StartHandle(timelist, srt_name, srt_mode, re_print)
print('\n{} 處理完成, 本次用時(shí){}'.format(file_name, countTime(item_time)))
else:
print('音頻參數(shù)錯(cuò)誤')
#執(zhí)行完成,統(tǒng)計(jì)所用時(shí)間
input('全部完成, 處理了{(lán)}個(gè)文件, 全部用時(shí){}'.format(total_file, countTime(total_time)))
#本部分包括活動(dòng)類(lèi)、模塊的相關(guān)函數(shù)、主函數(shù)代碼
from moviepy.editor import AudioFileClip
from pydub import AudioSegment
from pydub.silence import detect_silence
from aip import AipSpeech
import os
import time
import re
import requests
import js2py
class baidu_Translate():
def __init__(self):
self.js = js2py.eval_js('''
var i = null;
function n(r, o) {
for (var t = 0; t < o.length - 2; t += 3) {
var a = o.charAt(t + 2);
a = a >= "a" ? a.charCodeAt(0) - 87 : Number(a),
a = "+" === o.charAt(t + 1) ? r >>> a: r << a,
r = "+" === o.charAt(t) ? r + a & 4294967295 : r ^ a
}
return r
}
var hash = function e(r,gtk) {
var o = r.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g);
if (null === o) {
var t = r.length;
t > 30 && (r = "" + r.substr(0, 10) + r.substr(Math.floor(t / 2) - 5, 10) + r.substr( - 10, 10))
} else {
for (var e = r.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/), C = 0, h = e.length, f = []; h > C; C++)"" !== e[C] && f.push.apply(f, a(e[C].split(""))),
C !== h - 1 && f.push(o[C]);
var g = f.length;
g > 30 && (r = f.slice(0, 10).join("") + f.slice(Math.floor(g / 2) - 5, Math.floor(g / 2) + 5).join("") + f.slice( - 10).join(""))
}
var u = void 0,
u = null !== i ? i: (i = gtk || "") || "";
for (var d = u.split("."), m = Number(d[0]) || 0, s = Number(d[1]) || 0, S = [], c = 0, v = 0; v < r.length; v++) {
var A = r.charCodeAt(v);
128 > A ? S[c++] = A: (2048 > A ? S[c++] = A >> 6 | 192 : (55296 === (64512 & A) && v + 1 < r.length && 56320 === (64512 & r.charCodeAt(v + 1)) ? (A = 65536 + ((1023 & A) << 10) + (1023 & r.charCodeAt(++v)), S[c++] = A >> 18 | 240, S[c++] = A >> 12 & 63 | 128) : S[c++] = A >> 12 | 224, S[c++] = A >> 6 & 63 | 128), S[c++] = 63 & A | 128)
}
for (
var p = m,F = "+-a^+6", D = "+-3^+b+-f", b = 0;
b < S.length; b++) p += S[b],p = n(p, F);
return p = n(p, D),
p ^= s,
0 > p && (p = (2147483647 & p) + 2147483648),
p %= 1e6,
p.toString() + "." + (p ^ m)
}
''')
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36', }
self.session = requests.Session()
self.session.get('https://fanyi.baidu.com', headers=headers)
response = self.session.get('https://fanyi.baidu.com', headers=headers)
self.token = re.findall("token: '(.*?)',", response.text)[0]
self.gtk = '320305.131321201' # re.findall("window.gtk = '(.*?)';", response.text, re.S)[0]
def translate(self, query, from_lang='en', to_lang='zh'):
#語(yǔ)言檢測(cè)
self.session.post('https://fanyi.baidu.com/langdetect', data={'query': query})
#單擊事件 self.session.get('https://click.fanyi.baidu.com/?src=1&locate=zh&action=query&type=1&page=1')
#翻譯
data = {
'from': from_lang,
'to': to_lang,
'query': query,
'transtype': 'realtime',
'simple_means_flag': '3',
'sign': self.js(query, self.gtk),
'token': self.token
}
response =self.session.post('https://fanyi.baidu.com/v2transapi', data=data)
json = response.json()
if 'error' in json:
pass
#return 'error: {}'.format(json['error'])
else:
return response.json()['trans_result']['data'][0]['dst']
class baidu_SpeechRecognition():
def __init__(self, dev_pid):
#百度語(yǔ)音識(shí)別API
Speech_APP_ID = '19712136'
Speech_API_KEY = 'Loo4KbNtagchc2BLdCnHEnZl'
Speech_SECRET_KEY = 'DO4UlSnw7FzpodU2G3yXQSHLv6Q2inN8'
self.dev_pid = dev_pid
self.SpeechClient = AipSpeech(Speech_APP_ID, Speech_API_KEY, Speech_SECRET_KEY)
self.TranslClient = baidu_Translate()
def load_audio(self, audio_file):
self.source = AudioSegment.from_wav(audio_file)
def speech_recognition(self, offset, duration, fanyi):
data = self.source[offset * 1000:duration * 1000].raw_data
result = self.SpeechClient.asr(data, 'wav', 16000, {'dev_pid': self.dev_pid, })
fanyi_text = ''
if fanyi:
try:
fanyi_text = self.TranslClient.translate(result['result'][0])
except:
pass
try:
return [result['result'][0], fanyi_text]
except:
#print('錯(cuò)誤:',result)
return ['', '']
def cut_point(path, dbfs=1.25):
sound = AudioSegment.from_file(path, format="wav")
tstamp_list = detect_silence(sound, 600, sound.dBFS * dbfs, 1)
timelist = []
for i in range(len(tstamp_list)):
if i == 0:
back = 0
else:
back = tstamp_list[i - 1][1] / 1000
timelist.append([back, tstamp_list[i][1] / 1000])
min_len = 0.5
max_len = 5
result = []
add = 0
total = len(timelist)
for x in range(total):
if x + add < total:
into, out = timelist[x + add]
if out-into>min_len and out - into < max_len and x + add + 1 < total:
add += 1
out = timelist[x + add][1]
result.append([into, out])
elif out - into > max_len:
result.append([into, out])
else:
break
return result
def cut_text(text, length=38):
newtext = ''
if len(text) > length:
while True:
cutA = text[:length]
cutB = text[length:]
newtext += cutA + '\n'
if len(cutB) < 4:
newtext = cutA + cutB
break
elif len(cutB) > length:
text = cutB
else:
newtext += cutB
break
return newtext
return text
def progressbar(total, temp, text='&&', lenght=40): #定義進(jìn)度欄
content = '\r' + text.strip().replace('&&', '[{0}{1}]{2}%')
percentage = round(temp / total * 100, 2)
a = round(temp / total * lenght)
b = lenght - a
print(content.format('■' * a, '□' * b, percentage), end='')
def format_time(seconds): #定義時(shí)間格式
sec = int(seconds)
m, s = divmod(sec, 60)
h, m = divmod(m, 60)
fm = int(str(round(seconds, 3)).split('.')[-1])
return "%02d:%02d:%02d,%03d" % (h, m, s, fm)
def separate_audio(file_path, save_path): #定義音頻間隔
audio_file = save_path + '\\tmp.wav'
audio = AudioFileClip(file_path)
audio.write_audiofile(audio_file, ffmpeg_params=['-ar', '16000', '-ac', '1'], logger=None)
return audio_file
def file_filter(path, alldir=False): #定義文件過(guò)濾
key = ['mp4', 'mov']
if alldir:
dic_list = os.walk(path)
else:
dic_list = os.listdir(path)
find_list = []
for i in dic_list:
if os.path.isdir(i[0]):
header = i[0]
file = i[2]
for f in file:
for k in key:
if f.rfind(k) != -1:
find_list.append([header, f])
else:
for k in key:
if i.rfind(k) != -1:
find_list.append([path, i])
if find_list:
find_list.sort(key=lambda txt: re.findall(r'\d+', txt[1])[0])
return find_list
def countTime(s_time, now=True): #定義累計(jì)時(shí)間
if now: s_time = (time.time() - s_time)
m, s = divmod(int(s_time), 60)
return '{}分{}秒'.format('%02d' % (m), '%02d' % (s))
def __line__print__(txt='-' * 10): #定義打印
print('\n' + '-' * 10 + ' ' + txt + ' ' + '-' * 10 + '\n')
if __name__ == '__main__': #主函數(shù)
def StartHandle(timeList, save_path, srt_mode=2, result_print=False):
index = 0
total = len(timeList)
a_font = r'{\fn微軟雅黑\fs14}'
b_font = r'{\fn微軟雅黑\fs10}'
fanyi = False if srt_mode == 1 else True
file_write = open(save_path, 'a', encoding='utf-8')
for x in range(total):
into, out = timelist[x]
timeStamp = format_time(into - 0.2) + ' --> ' + format_time(out - 0.2)
result = baidufanyi.speech_recognition(into + 0.1, out - 0.1, fanyi)
if result_print:
if srt_mode == 0:
print(timeStamp, result[0])
else:
print(timeStamp, result)
else:
progressbar(total, x, '識(shí)別中...&& - {0}/{1}'.format('%03d' % (total), '%03d' % (x)), 44)
if len(result[0]) > 1:
index += 1
text = str(index) + '\n' + timeStamp + '\n'
if srt_mode == 0: #僅中文
text += a_font + cut_text(result[1])
elif srt_mode == 1: #僅英文
text += b_font + cut_text(result[0])
else: #中文+英文
text += a_font + cut_text(result[1]) + '\n' + b_font + result[0]
text = text.replace('\u200b', '') + '\n\n'
file_write.write(text)
file_write.close()
if not result_print:
progressbar(total, total, '識(shí)別中...&& - {0}/{1}'.format('%03d' % (total), '%03d' % (total)), 44)
os.system('cls')
wav_path = os.environ.get('TEMP')
#語(yǔ)音模型
pid_list = 1536, 1537, 1737, 1637, 1837, 1936
#設(shè)置參數(shù)
print('[ 百度語(yǔ)音識(shí)別字幕生成器 - by 谷健&任家旺 ]\n')
__line__print__('1 模式選擇')
input_dev_pid = input('請(qǐng)選擇識(shí)別模式:\n'
'\n (1)普通話(huà),'
'\n (2)普通話(huà)+簡(jiǎn)單英語(yǔ),'
'\n (3)英語(yǔ),'
'\n (4)粵語(yǔ),'
'\n (5)四川話(huà),'
'\n (6)普通話(huà)-遠(yuǎn)場(chǎng)'
'\n\n請(qǐng)輸入一個(gè)選項(xiàng)(默認(rèn)3):')
__line__print__('2 字幕格式')
input_srt_mode = input('請(qǐng)選擇字幕格式:\n'
'\n (1)中文,'
'\n (2)英文,'
'\n (3)中文+英文,'
'\n\n請(qǐng)輸入一個(gè)選項(xiàng)(默認(rèn)3):')
__line__print__('3 實(shí)時(shí)輸出')
input_print = input('是否實(shí)時(shí)輸出結(jié)果到屏幕? (默認(rèn):否/y:輸出):').upper()
#處理參數(shù)
dev_pid = int(input_dev_pid) if input_dev_pid else 3
dev_pid -= 1
srt_mode = int(input_srt_mode) if input_srt_mode else 3
srt_mode -= 1
re_print = True if input_print == 'Y' else False
#輸入文件
__line__print__('4 打開(kāi)文件')
input_file = input('請(qǐng)拖入一個(gè)文件或文件夾并按回車(chē):').strip('"')
video_file = []
if not os.path.isdir(input_file):
video_file = [input_file]
else:
file_list = file_filter(input_file)
for a, b in file_list:
video_file.append(a + '\\' + b)
#執(zhí)行確認(rèn)
select_dev = ['普通話(huà)', '普通話(huà)+簡(jiǎn)單英語(yǔ)', '英語(yǔ)', '粵語(yǔ)', '四川話(huà)', '普通話(huà)-遠(yuǎn)場(chǎng)']
select_mode = ['中文', '英文', '中文+英文']
__line__print__('5 確認(rèn)執(zhí)行')
input('當(dāng)前的設(shè)置:\n識(shí)別模式: {0}, 字幕格式: {1}, 輸出結(jié)果: {2}\n當(dāng)前待處理文件 {3} 個(gè)\n請(qǐng)按下回車(chē)開(kāi)始處理...'.format(
select_dev[dev_pid],
select_mode[srt_mode],
'是' if re_print else '否',
len(video_file)
))
#批量處理
total_file = len(video_file)
total_time = time.time()
baidufanyi = baidu_SpeechRecognition(pid_list[dev_pid])
for i in range(total_file):
item_time = time.time()
file_name = video_file[i].split('\\')[-1]
print('\n>>>>>>>> ...正在處理音頻... <<<<<<<<', end='')
audio_file = separate_audio(video_file[i], wav_path)
timelist = cut_point(audio_file, dbfs=1.15)
if timelist:
print('\r>>>>>>>> 當(dāng)前:{} 預(yù)計(jì):{} <<<<<<<<'.format(
'%03d' % (i),
countTime(len(timelist) * 5, now=False)
))
srt_name = video_file[i][:video_file[i].rfind('.')] + '.srt'
baidufanyi.load_audio(audio_file)
StartHandle(timelist, srt_name, srt_mode, re_print)
print('\n{} 處理完成, 本次用時(shí){}'.format(file_name, countTime(item_time)))
else:
print('音頻參數(shù)錯(cuò)誤')
#執(zhí)行完成
input('全部完成, 處理了{(lán)}個(gè)文件, 全部用時(shí){}'.format(total_file, countTime(total_time)))
系統(tǒng)測(cè)試
運(yùn)行Python代碼,根據(jù)提示進(jìn)行交互選擇。選擇待識(shí)別視頻語(yǔ)言,如圖1所示;選擇需要的字幕語(yǔ)言,如圖2所示。
選擇是否實(shí)時(shí)輸出字幕結(jié)果,選擇文件路徑: (需要在英文輸入法下使用雙引號(hào))確認(rèn)需求,如圖所示。
本次運(yùn)行的設(shè)置:
識(shí)別模式英語(yǔ)(3),字幕格式為中文+英文(3)是否實(shí)時(shí)輸出字幕為(y) 。結(jié)果:實(shí)時(shí)查看字幕輸出,如圖所示。
生成.srt字幕文件,如圖所示。
在播放器中選擇打開(kāi)或關(guān)閉字幕,當(dāng)生成多個(gè)字幕文件(如英文/中文/英文+中文)時(shí)也可在播放器中設(shè)置更換字幕文件。
使用記事本打開(kāi)字幕文件,如圖所示。
查看字幕文件加入視頻的效果,原無(wú)字幕視頻,如圖所示。
加入生成字幕后的視頻,如圖所示。
工程源代碼下載
詳見(jiàn)本人博客資源下載頁(yè)文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-639272.html
其它資料下載
如果大家想繼續(xù)了解人工智能相關(guān)學(xué)習(xí)路線(xiàn)和知識(shí)體系,歡迎大家翻閱我的另外一篇博客《重磅 | 完備的人工智能AI 學(xué)習(xí)——基礎(chǔ)知識(shí)學(xué)習(xí)路線(xiàn),所有資料免關(guān)注免套路直接網(wǎng)盤(pán)下載》
這篇博客參考了Github知名開(kāi)源平臺(tái),AI技術(shù)平臺(tái)以及相關(guān)領(lǐng)域?qū)<遥篋atawhale,ApacheCN,AI有道和黃海廣博士等約有近100G相關(guān)資料,希望能幫助到所有小伙伴們。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-639272.html
到了這里,關(guān)于基于百度語(yǔ)音識(shí)別API智能語(yǔ)音識(shí)別和字幕推薦系統(tǒng)——深度學(xué)習(xí)算法應(yīng)用(含全部工程源碼)+測(cè)試數(shù)據(jù)集的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!