【python】使用百度api进行音频文件转写
【python】使用百度api进行音频文件转写
脚本目标:
- 智能云的音频文件转写文档只给了个demo,每次只能传1分钟以内的音频啥的,不好直接用,简单打包一下,做到把音频放文件夹,直接出转写结果就行了,偶尔用一下的用户,就我这个用着应该没什么问题
环境准备:
- 百度智能云先开通音频文件转写,创建一个应用,应用名称随便写,描述随便写,接口选择选全选,语音包名不需要,应用创建完后,在应用列表里有个Api Key和Secret Key,复制下来,脚本要用
- 下载ffmpeg,把bin文件夹里的三个exe文件复制到项目文件夹下
脚本思路:
- 创建一个文件夹,让用户把音频放里面,用pydub把音频分割成每段59秒,依次调用音频文件转写的api,把返回结果保存到一起就行了
代码实现:
- 分割音频
代码
def CutAudio(self, path): format = path[-3:] filename = path.split("\\")[-1] filename = re.findall(rf"(.*?)\.{format}", filename) # 取出.mp3后缀的文件名 print(f"文件名={filename[0]}----格式={format}") mp3 = AudioSegment.from_file(f'{path}', f"{format}") # 打开mp3文件 mp3 = mp3.set_frame_rate(16000) mp3 = mp3.set_channels(1) cuts = make_chunks(mp3, self.long) for index, cut in enumerate(cuts): CutName = (f"{filename[0]}-{index}.wav") cut.export(f'{self.TempAudio}/{CutName}', format="wav") print(f"{filename[0]}分割完成")
最终代码:其实就是把分割音频部分和提供的demo结合到一起
import base64
import json
import os.path
import re
import sys
import time
from os import mkdir, listdir
from shutil import rmtree
from pydub import AudioSegment
from pydub.utils import make_chunks
IS_PY3 = sys.version_info.major == 3
from urllib.request import urlopen
from urllib.request import Request
from urllib.error import URLError
from urllib.parse import urlencode
timer = time.perf_counter
class DemoError(Exception):
pass
class AudioToText:
AudioDir = "./AudioDir"
TempAudio = "./TempAudio"
AudioPath = ""
long = 59000 # 切割的长度
API_KEY = '?????????????'
SECRET_KEY = '??????????????'
AUDIO_FILE = '.....'
FORMAT = AUDIO_FILE[-3:]
RATE = 16000 # 固定值
CUID = '123456PYTHON' # 可填可不填
DEV_PID = 1737 # 1537 表示识别普通话,1737 英文
ASR_URL = 'http://vop.baidu.com/server_api'
SCOPE = 'audio_voice_assistant_get' # 有此scope表示有asr能力,没有请在网页里勾选,非常旧的应用可能没有
TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'
def __init__(self):
if not os.path.exists(self.AudioDir):
mkdir(self.AudioDir)
mkdir(self.TempAudio)
self.AudioPath = input(f"1.单个音频文件:输入音频文件路径\n2.多个音频文件:把音频全放到{self.AudioDir}文件夹里后Enter\n")
language = int(input("普通话选择1 , 英文选择2\n"))
if language == 1:
self.DEV_PID = 1537
elif language == 2:
self.DEV_PID = 1737
def CutAudio(self, path):
format = path[-3:]
filename = path.split("\\")[-1]
filename = re.findall(rf"(.*?)\.{format}", filename) # 取出.mp3后缀的文件名
print(f"文件名={filename[0]}----格式={format}")
mp3 = AudioSegment.from_file(f'{path}', f"{format}") # 打开mp3文件
mp3 = mp3.set_frame_rate(16000)
mp3 = mp3.set_channels(1)
cuts = make_chunks(mp3, self.long)
for index, cut in enumerate(cuts):
CutName = (f"{filename[0]}-{index}.wav")
cut.export(f'{self.TempAudio}/{CutName}', format="wav")
print(f"{filename[0]}分割完成")
def OneAudioFile(self):
self.CutAudio(self.AudioPath)
def ManyAudioFile(self):
for each in listdir(self.AudioDir):
self.CutAudio(f"{self.AudioDir}\\{each}")
def fetch_token(self):
params = {'grant_type': 'client_credentials',
'client_id': self.API_KEY,
'client_secret': self.SECRET_KEY}
post_data = urlencode(params)
if (IS_PY3):
post_data = post_data.encode('utf-8')
req = Request(self.TOKEN_URL, post_data)
try:
f = urlopen(req)
result_str = f.read()
except URLError as err:
result_str = err.read()
if (IS_PY3):
result_str = result_str.decode()
result = json.loads(result_str)
if ('access_token' in result.keys() and 'scope' in result.keys()):
if self.SCOPE and (not self.SCOPE in result['scope'].split(' ')): # SCOPE = False 忽略检查
raise DemoError('scope is not correct')
return result['access_token']
else:
raise DemoError(
'MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')
def transfer(self, path):
token = self.fetch_token()
speech_data = []
with open(path, 'rb') as speech_file:
speech_data = speech_file.read()
length = len(speech_data)
if length == 0:
raise DemoError('file %s length read 0 bytes' % path)
speech = base64.b64encode(speech_data)
if (IS_PY3):
speech = str(speech, 'utf-8')
params = {'dev_pid': self.DEV_PID,
# "lm_id" : LM_ID, #测试自训练平台开启此项
'format': path[-3:],
'rate': self.RATE,
'token': token,
'cuid': self.CUID,
'channel': 1,
'speech': speech,
'len': length
}
post_data = json.dumps(params, sort_keys=False)
req = Request(self.ASR_URL, post_data.encode('utf-8'))
req.add_header('Content-Type', 'application/json')
try:
begin = timer()
f = urlopen(req)
result_str = f.read()
except URLError as err:
result_str = err.read()
if (IS_PY3):
result_str = str(result_str, 'utf-8')
result_str = re.findall(r":\[\"(.*?)\"\],", result_str)[0]
print(result_str)
with open("result.txt", "a") as of:
of.write(f"{result_str}\n")
def do_trans(self):
for each in listdir(f"./{self.TempAudio}"):
self.transfer(f"{self.TempAudio}/{each}")
def run(self):
if self.AudioPath is not "":
self.OneAudioFile()
else:
self.ManyAudioFile()
self.do_trans()
def __del__(self):
rmtree(self.TempAudio)
if __name__ == '__main__':
audio = AudioToText()
audio.run()
看到那个一堆问号的Api Key 和 Secret Key了吗,把之前复制下来的粘贴上去
把没安装的库自己安装一下,ffmpeg里的三个exe要记得复制到项目文件夹
然后直接跑就行了
后记:
其实就是方便大家,可以直接用这个功能,可以不用浪费时间再写一遍