使用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 网络编程起步(Socket发送消息)
Sep 06 Python
Python中的二叉树查找算法模块使用指南
Jul 04 Python
老生常谈Python序列化和反序列化
Jun 28 Python
对python内置map和six.moves.map的区别详解
Dec 19 Python
django富文本编辑器的实现示例
Apr 10 Python
python获取点击的坐标画图形的方法
Jul 09 Python
Python Tkinter Entry和Text的添加与使用详解
Mar 04 Python
Python基于QQ邮箱实现SSL发送
Apr 26 Python
给ubuntu18安装python3.7的详细教程
Jun 08 Python
python上selenium的弹框操作实现
Jul 13 Python
Python 日期与时间转换的方法
Aug 01 Python
基于Pygame实现简单的贪吃蛇游戏
Dec 06 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 保留字列表
2012/10/04 PHP
php防止伪造的数据从URL提交方法
2014/06/27 PHP
php获取英文姓名首字母的方法
2015/07/13 PHP
制作个性化的WordPress登陆界面的实例教程
2016/05/21 PHP
PHP APP微信提现接口代码
2018/09/30 PHP
php实现文章评论系统
2019/02/18 PHP
php使用lua+redis实现限流,计数器模式,令牌桶模式
2019/04/04 PHP
jquery 学习之一 对象访问
2010/11/23 Javascript
CSS鼠标响应事件经过、移动、点击示例介绍
2013/09/04 Javascript
js如何判断访问是来自搜索引擎(蜘蛛人)还是直接访问
2015/09/14 Javascript
Javascript的表单验证-提交表单
2016/03/18 Javascript
javascript中不易分清的slice,splice和split三个函数
2016/03/29 Javascript
使用jquery给新生的th绑定hover事件的实例
2017/02/10 Javascript
Vue中的slot使用插槽分发内容的方法
2018/03/01 Javascript
Vuejs在v-for中,利用index来对第一项添加class的方法
2018/03/03 Javascript
javascript数组去重方法总结(推荐)
2019/03/20 Javascript
JavaScript实现京东快递单号查询
2020/11/30 Javascript
浅析python 中__name__ = '__main__' 的作用
2014/07/05 Python
Python中用Spark模块的使用教程
2015/04/13 Python
Python实现根据IP地址和子网掩码算出网段的方法
2015/07/30 Python
Python数据结构之图的应用示例
2018/05/11 Python
Linux下python与C++使用dlib实现人脸检测
2018/06/29 Python
Python3.5实现的三级菜单功能示例
2019/03/25 Python
python3 小数位的四舍五入(用两种方法解决round 遇5不进)
2019/04/11 Python
Python使用mongodb保存爬取豆瓣电影的数据过程解析
2019/08/14 Python
pd.DataFrame统计各列数值多少的实例
2019/12/05 Python
TripAdvisor斯洛伐克:阅读评论、比较价格和酒店预订
2018/04/25 全球购物
上海雨人软件技术开发有限公司测试题
2015/07/14 面试题
Shell如何接收变量输入
2016/08/06 面试题
大学本科毕业生求职简历的自我评价
2013/10/09 职场文书
入党积极分子思想汇报范文
2014/01/05 职场文书
大学生活动策划方案
2014/02/10 职场文书
司机职责范本
2014/03/08 职场文书
烟台的海导游词
2015/02/02 职场文书
OpenCV中resize函数插值算法的实现过程(五种)
2021/06/05 Python
我的收音机情缘
2022/04/05 无线电