使用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访问mysql数据库的实现方法(2则示例)
Jan 06 Python
Django返回json数据用法示例
Sep 18 Python
Python列表list解析操作示例【整数操作、字符操作、矩阵操作】
Jul 25 Python
使用pip发布Python程序的方法步骤
Oct 11 Python
python多线程下信号处理程序示例
May 31 Python
详解pandas数据合并与重塑(pd.concat篇)
Jul 09 Python
对Python _取log的几种方式小结
Jul 25 Python
Django之PopUp的具体实现方法
Aug 31 Python
wxpython布局的实现方法
Nov 01 Python
python函数装饰器之带参数的函数和带参数的装饰器用法示例
Nov 06 Python
python判断两个序列的成员是否一样的实例代码
Mar 01 Python
浅析python实现动态规划背包问题
Dec 31 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最常用的ini函数分析 针对PHP.ini配置文件
2010/04/22 PHP
php学习之 循环结构实现代码
2011/06/09 PHP
php设计模式之简单工厂模式详解
2014/09/04 PHP
WordPress主题制作之模板文件的引入方法
2015/12/28 PHP
PHP的Laravel框架中使用AdminLTE模板来编写网站后台界面
2016/03/21 PHP
javascript动画效果类封装代码
2007/08/28 Javascript
JavaScript 学习小结(适合新手参考)
2009/07/30 Javascript
javascript制作幻灯片(360度全景图片)
2015/07/28 Javascript
购物车前端开发(jQuery和bootstrap3)
2016/08/27 Javascript
JavaScript利用闭包实现模块化
2017/01/13 Javascript
JavaScript之面向对象_动力节点Java学院整理
2017/06/29 Javascript
利用JS hash制作单页Web应用的方法详解
2017/10/10 Javascript
angularjs实现猜大小功能
2017/10/23 Javascript
vue项目中引入noVNC远程桌面的方法
2018/03/05 Javascript
vue2.0 资源文件assets和static的区别详解
2018/04/08 Javascript
基于脚手架创建Vue项目实现步骤详解
2020/08/03 Javascript
如何检测JavaScript中的死循环示例详解
2020/08/30 Javascript
Vue双向数据绑定(MVVM)的原理
2020/10/03 Javascript
分享8个JavaScript库可更好地处理本地存储
2020/10/12 Javascript
Python利用多进程将大量数据放入有限内存的教程
2015/04/01 Python
Python3.遍历某文件夹提取特定文件名的实例
2018/04/26 Python
Python json模块dumps、loads操作示例
2018/09/06 Python
详解用Python实现自动化监控远程服务器
2019/05/18 Python
django认证系统实现自定义权限管理的方法
2019/08/28 Python
Django返回HTML文件的实现方法
2020/09/17 Python
python 基于Apscheduler实现定时任务
2020/12/15 Python
CHARLES & KEITH英国官网:新加坡时尚品牌
2018/07/04 全球购物
加热夹克:RAVEAN
2018/10/19 全球购物
圣诞树世界:Christmas Tree World
2019/12/10 全球购物
远东集团网络工程师面试题
2014/10/20 面试题
毕业自荐信
2013/12/16 职场文书
财务会计自荐信范文
2014/02/21 职场文书
幼儿园小班家长寄语
2014/04/02 职场文书
投资协议书范本
2014/04/21 职场文书
2014年卫生工作总结
2014/11/27 职场文书
SpringBoot项目多数据源及mybatis 驼峰失效的问题解决方法
2022/07/07 Java/Android