使用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中用Spark模块的使用教程
Apr 13 Python
Python3中条件控制、循环与函数的简易教程
Nov 21 Python
快速查询Python文档方法分享
Dec 27 Python
Python实现KNN邻近算法
Jan 28 Python
python-itchat 统计微信群、好友数量,及原始消息数据的实例
Feb 21 Python
python调用并链接MATLAB脚本详解
Jul 05 Python
如何用Python来搭建一个简单的推荐系统
Aug 07 Python
Python 取numpy数组的某几行某几列方法
Oct 24 Python
Python中Selenium模块的使用详解
Oct 09 Python
Django解决frame拒绝问题的方法
Dec 18 Python
python基础之模块的导入
Oct 24 Python
聊聊基于pytorch实现Resnet对本地数据集的训练问题
Mar 25 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阻止页面后退的方法分享
2014/02/17 PHP
PHP异常处理浅析
2015/05/12 PHP
PHP模拟asp.net的StringBuilder类实现方法
2015/08/08 PHP
jQuery EasyUI 中文API Button使用实例
2010/04/14 Javascript
ModelDialog JavaScript模态对话框类代码
2011/04/17 Javascript
node.js中的socket.io入门实例
2014/04/26 Javascript
JS及PHP代码编写八大排序算法
2016/07/12 Javascript
JavaScript禁止用户多次提交的两种方法
2016/07/24 Javascript
Web安全测试之XSS实例讲解
2016/08/15 Javascript
Javascript中apply、call、bind的巧妙使用
2016/08/18 Javascript
BootStrap 超链接变按钮的实现方法
2016/09/25 Javascript
Bootstrap的Carousel配合dropload.js实现移动端滑动切换图片
2017/03/10 Javascript
理解Angular的providers给Http添加默认headers
2017/07/04 Javascript
jQuery插件Validation表单验证详解
2018/05/26 jQuery
vue element-ul实现展开和收起功能的实例代码
2020/11/25 Vue.js
Python中的日期时间处理详解
2016/11/17 Python
详解Python 实现元胞自动机中的生命游戏(Game of life)
2018/01/27 Python
python3学习之Splash的安装与实例教程
2018/07/09 Python
python使用time、datetime返回工作日列表实例代码
2019/05/09 Python
对Python 简单串口收发GUI界面的实例详解
2019/06/12 Python
python3 map函数和filter函数详解
2019/08/26 Python
python/Matplotlib绘制复变函数图像教程
2019/11/21 Python
用Python实现童年贪吃蛇小游戏功能的实例代码
2020/12/07 Python
CSS Grid布局教程之浏览器开启CSS Grid Layout汇总
2014/12/30 HTML / CSS
不可轻视HTML5!App三年内将被html5顶替彻底消失
2015/11/18 HTML / CSS
HTML5中的强制下载属性download使用实例解析
2016/05/12 HTML / CSS
施华洛世奇英国官网:SWAROVSKI英国
2017/03/13 全球购物
歌唱比赛策划方案
2014/06/06 职场文书
男性健康日的活动方案
2014/08/18 职场文书
销售人才自我评价范文
2014/09/27 职场文书
2015纪念九一八事变84周年演讲稿
2015/03/19 职场文书
2015年九一八事变纪念活动实施方案
2015/05/06 职场文书
十大最帅动漫男主 碓冰拓海上榜,第一是《灌篮高手》男主角
2022/03/18 日漫
Python+OpenCV实现在图像上绘制矩形
2022/03/21 Python
Redis中key的过期删除策略和内存淘汰机制
2022/04/12 Redis
JS前端使用Canvas快速实现手势解锁特效
2022/09/23 Javascript