使用Python和百度语音识别生成视频字幕的实现


Posted in Python onApril 09, 2020

从视频中提取音频

安装 moviepy

pip install moviepy

相关代码:

audio_file = work_path + '\\out.wav'
video = VideoFileClip(video_file)
video.audio.write_audiofile(audio_file,ffmpeg_params=['-ar','16000','-ac','1'])

根据静音对音频分段

使用音频库 pydub,安装:

pip install pydub

第一种方法:

# 这里silence_thresh是认定小于-70dBFS以下的为silence,发现小于 sound.dBFS * 1.3 部分超过 700毫秒,就进行拆分。这样子分割成一段一段的。
sounds = split_on_silence(sound, min_silence_len = 500, silence_thresh= sound.dBFS * 1.3)


sec = 0
for i in range(len(sounds)):
 s = len(sounds[i])
 sec += s
print('split duration is ', sec)
print('dBFS: {0}, max_dBFS: {1}, duration: {2}, split: {3}'.format(round(sound.dBFS,2),round(sound.max_dBFS,2),sound.duration_seconds,len(sounds)))

使用Python和百度语音识别生成视频字幕的实现

感觉分割的时间不对,不好定位,我们换一种方法:

# 通过搜索静音的方法将音频分段
# 参考:https://wqian.net/blog/2018/1128-python-pydub-split-mp3-index.html
timestamp_list = detect_nonsilent(sound,500,sound.dBFS*1.3,1)
 
for i in range(len(timestamp_list)):
 d = timestamp_list[i][1] - timestamp_list[i][0]
 print("Section is :", timestamp_list[i], "duration is:", d)
print('dBFS: {0}, max_dBFS: {1}, duration: {2}, split: {3}'.format(round(sound.dBFS,2),round(sound.max_dBFS,2),sound.duration_seconds,len(timestamp_list)))

输出结果如下:

使用Python和百度语音识别生成视频字幕的实现

感觉这样好处理一些

使用百度语音识别

现在百度智能云平台创建一个应用,获取 API Key 和 Secret Key:

使用Python和百度语音识别生成视频字幕的实现

获取 Access Token

使用百度 AI 产品需要授权,一定量是免费的,生成字幕够用了。

'''
百度智能云获取 Access Token
'''
def fetch_token():
 params = {'grant_type': 'client_credentials',
    'client_id': API_KEY,
    'client_secret': SECRET_KEY}
 post_data = urlencode(params)
 if (IS_PY3):
  post_data = post_data.encode( 'utf-8')
 req = Request(TOKEN_URL, post_data)
 try:
  f = urlopen(req)
  result_str = f.read()
 except URLError as err:
  print('token http response http code : ' + str(err.errno))
  result_str = err.reason
 if (IS_PY3):
  result_str = result_str.decode()


 print(result_str)
 result = json.loads(result_str)
 print(result)
 if ('access_token' in result.keys() and 'scope' in result.keys()):
  print(SCOPE)
  if SCOPE and (not SCOPE in result['scope'].split(' ')): # SCOPE = False 忽略检查
   raise DemoError('scope is not correct')
  print('SUCCESS WITH TOKEN: %s EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))
  return result['access_token']
 else:
  raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')

使用 Raw 数据进行合成

这里使用百度语音极速版来合成文字,因为官方介绍专有GPU服务集群,识别响应速度较标准版API提升2倍及识别准确率提升15%。适用于近场短语音交互,如手机语音搜索、聊天输入等场景。 支持上传完整的录音文件,录音文件时长不超过60秒。实时返回识别结果

def asr_raw(speech_data, token):
 length = len(speech_data)
 if length == 0:
  # raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)
  raise DemoError('file length read 0 bytes')


 params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}
 #测试自训练平台需要打开以下信息
 #params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID, 'lm_id' : LM_ID}
 params_query = urlencode(params)


 headers = {
  'Content-Type': 'audio/' + FORMAT + '; rate=' + str(RATE),
  'Content-Length': length
 }


 url = ASR_URL + "?" + params_query
 # print post_data
 req = Request(ASR_URL + "?" + params_query, speech_data, headers)
 try:
  begin = timer()
  f = urlopen(req)
  result_str = f.read()
  # print("Request time cost %f" % (timer() - begin))
 except URLError as err:
  # print('asr http response http code : ' + str(err.errno))
  result_str = err.reason


 if (IS_PY3):
  result_str = str(result_str, 'utf-8')
 return result_str

生成字幕

字幕格式: https://www.cnblogs.com/tocy/p/subtitle-format-srt.html

生成字幕其实就是语音识别的应用,将识别后的内容按照 srt 字幕格式组装起来就 OK 了。具体字幕格式的内容可以参考上面的文章,代码如下:

idx = 0
for i in range(len(timestamp_list)):
 d = timestamp_list[i][1] - timestamp_list[i][0]
 data = sound[timestamp_list[i][0]:timestamp_list[i][1]].raw_data
 str_rst = asr_raw(data, token)
 result = json.loads(str_rst)
 # print("rst is ", result)
 # print("rst is ", rst['err_no'][0])


 if result['err_no'] == 0:
  text.append('{0}\n{1} --> {2}\n'.format(idx, format_time(timestamp_list[i][0]/ 1000), format_time(timestamp_list[i][1]/ 1000)))
  text.append( result['result'][0])
  text.append('\n')
  idx = idx + 1
  print(format_time(timestamp_list[i][0]/ 1000), "txt is ", result['result'][0])
with open(srt_file,"r+") as f:
 f.writelines(text)

总结

我在视频网站下载了一个视频来作测试,极速模式从速度和识别率来说都是最好的,感觉比网易见外平台还好用。

到此这篇关于使用Python和百度语音识别生成视频字幕的文章就介绍到这了,更多相关Python 百度语音识别生成视频字幕内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python基于pygame实现响应游戏中事件的方法(附源码)
Nov 11 Python
Python实现类的创建与使用方法示例
Jul 25 Python
python 3.6 tkinter+urllib+json实现火车车次信息查询功能
Dec 20 Python
Python解决N阶台阶走法问题的方法分析
Dec 28 Python
利用Python将数值型特征进行离散化操作的方法
Nov 06 Python
pandas 层次化索引的实现方法
Jul 06 Python
Python实现栈和队列的简单操作方法示例
Nov 29 Python
Python实现计算长方形面积(带参数函数demo)
Jan 18 Python
python logging模块的使用
Sep 07 Python
python中实现栈的三种方法
Dec 19 Python
AI:如何训练机器学习的模型
Apr 16 Python
浅谈Python数学建模之固定费用问题
Jun 23 Python
利用Python制作动态排名图的实现代码
Apr 09 #Python
使用python接受tgam的脑波数据实例
Apr 09 #Python
解决使用python print打印函数返回值多一个None的问题
Apr 09 #Python
Python 实现自动完成A4标签排版打印功能
Apr 09 #Python
python网络编程:socketserver的基本使用方法实例分析
Apr 09 #Python
Python使用扩展库pywin32实现批量文档打印实例
Apr 09 #Python
python3 自动打印出最新版本执行的mysql2redis实例
Apr 09 #Python
You might like
php格式化工具Beautify PHP小小BUG
2008/04/24 PHP
php堆排序(heapsort)练习
2013/11/13 PHP
浅析Laravel5中队列的配置及使用
2016/08/04 PHP
PHP中的函数声明与使用详解
2017/05/27 PHP
php格式文件打开的四种方法
2018/02/24 PHP
TP5(thinkPHP5)框架基于ajax与后台数据交互操作简单示例
2018/09/03 PHP
JavaScript获得选中文本内容的方法
2008/12/02 Javascript
关于捕获用户何时点击window.onbeforeunload的取消事件
2011/03/06 Javascript
计算世界完全对称日的js代码,粗糙版
2011/11/04 Javascript
JS Loading功能的简单实现
2013/11/29 Javascript
jquery validate添加自定义验证规则(验证邮箱 邮政编码)
2013/12/04 Javascript
js实现一个链接打开两个链接地址的方法
2015/05/12 Javascript
Bootstrap~多级导航(级联导航)的实现效果【附代码】
2016/03/08 Javascript
vue.js 使用v-if v-else发现没有执行解决办法
2017/05/15 Javascript
详解如何在vue中使用sass
2017/06/21 Javascript
JS div匀速移动动画与变速移动动画代码实例
2019/03/26 Javascript
JS实现的检验身份证格式并输出出生日期,年龄,性别,出生地示例
2019/05/17 Javascript
nodejs中使用worker_threads来创建新的线程的方法
2021/01/22 NodeJs
vue 根据选择的月份动态展示日期对应的星期几
2021/02/06 Vue.js
[39:11]DOTA2上海特级锦标赛C组资格赛#2 LGD VS Newbee第二局
2016/02/28 DOTA
Python简单生成随机姓名的方法示例
2017/12/27 Python
Python socket套接字实现C/S模式远程命令执行功能案例
2018/07/06 Python
Python中@property的理解和使用示例
2019/06/11 Python
python图片剪裁代码(图片按四个点坐标剪裁)
2020/03/10 Python
python要安装在哪个盘
2020/06/15 Python
prAna官网:瑜伽、旅行和冒险服装
2019/03/10 全球购物
极简鞋类,赤脚的感觉:Lems Shoes
2019/08/06 全球购物
德国消费电子产品购物网站:Guter Kauf
2020/09/15 全球购物
香奈儿美国官网:CHANEL美国
2020/05/20 全球购物
创业计划书如何编写
2014/02/06 职场文书
党员岗位承诺口号大全
2014/03/28 职场文书
《四季》教学反思
2014/04/08 职场文书
团支部建设方案
2014/05/02 职场文书
技术经济专业求职信
2014/09/03 职场文书
HashMap实现保存两个key相同的数据
2021/06/30 Java/Android
基于angular实现树形二级表格
2021/10/16 Javascript