菜鸡源码,专注精品下载!
当前位置:首页 > 建站教程 > 建站知识

将讯飞听见语音转文字功能用Python实现的源码

发布时间:2024-01-05  栏目:建站知识   浏览:   分类:python教程 Python源码

讯飞听见语音转文字的Python源码主要使用了百度的语音识别API和科大讯飞的语音识别API。首先,需要安装百度的语音识别库和科大讯飞的语音识别库。然后,通过录音设备获取音频文件,将音频文件上传到百度和科大讯飞的服务器进行语音识别。最后,将两个平台的识别结果进行比较,选择准确率较高的结果作为最终的识别结果。需要注意的是,使用这两个平台的API需要注册账号并获取相应的API Key。

讯飞听见语音转文字Python源码,这个只能 转中文和英文,免费的转换不能超过3分钟。

#-*-coding:utf-8-*-#☯Author:******#☯Email:******@****.***#☯Date:2021/06/2420:13importosimportreimporttimeimportrandomimportloggingimportdatetimeimportrequestsfromloggingimporthandlersfromcollectionsimportOrderedDictfromurllib3importencode_multipart_formdata#日志模块classLogGer(object):def__init__(self,name):os.makedirs("./log")ifnotos.path.exists("./log")elseNone#创建日志文件文件夹get_logger_a=logging.getLogger()get_logger_a.setLevel(logging.INFO)#设置默认级别formatter=logging.Formatter('%(levelname)s%(asctime)s%(filename)s[line:%(lineno)d]:%(message)s')log_file_path='./log/{}_{}.log'.format(name,time.strftime('%Y%m%d'))rotating_handler=handlers.RotatingFileHandler(log_file_path,maxBytes=20*1024*1024,backupCount=10,encoding='utf-8')rotating_handler.setFormatter(formatter)get_logger_a.addHandler(rotating_handler)stream_handler=logging.StreamHandler()stream_handler.setFormatter(formatter)get_logger_a.addHandler(stream_handler)#过滤级别:控制台输出INFO和WARNING级别,文件只记录WARNING级别info_filter=logging.Filter()info_filter.filter=lambdarecord:record.levelno<logging.WARNING#设置过滤等级warn_filter=logging.Filter()warn_filter.filter=lambdarecord:record.levelno>=logging.WARNING#stream_handler.addFilter(info_filter)rotating_handler.addFilter(warn_filter)#爬虫主程序classTestSpider:LogGer(str(os.path.basename(__file__))[:-3])logging.info('systemisworkingnow.')def__init__(self):pass#随机头@staticmethoddefrandom_ua():return"Mozilla/5.0(WindowsNT{})AppleWebKit/537.36(KHTML,likeGecko)Chrome/{}Safari/537.36".format(random.choice(['10.0;Win64;x64','10.0;WOW64','10.0','6.2;WOW64','6.2;Win64;x64','6.2','6.1','6.1;Win64;x64','6.1;WOW64']),random.choice(['70.0.3538.16','70.0.3538.67','70.0.3538.97','71.0.3578.137','71.0.3578.30','71.0.3578.33','71.0.3578.80','72.0.3626.69','72.0.3626.7','73.0.3683.20','73.0.3683.68','74.0.3729.6','75.0.3770.140','75.0.3770.8','75.0.3770.90','76.0.3809.12','76.0.3809.126','76.0.3809.25','76.0.3809.68','77.0.3865.10','77.0.3865.40','78.0.3904.105','78.0.3904.11','78.0.3904.70','79.0.3945.16','79.0.3945.36','80.0.3987.106','80.0.3987.16','81.0.4044.138','81.0.4044.20','81.0.4044.69','83.0.4103.14','83.0.4103.39','84.0.4147.30','85.0.4183.38','85.0.4183.83','85.0.4183.87','86.0.4240.22','87.0.4280.20','87.0.4280.88','88.0.4324.27']))#下载器defrequester(self,url,retry=3,**kwargs):""":paramurl:必须传入的url:paramretry:不需要自己传,自动忽视:paramkwargs:传递需要的参数,必须“参数名=参数”:return:返回正常访问的内容或者返回None"""try:returnrequests.request(url=url,method=kwargs.get('method')ifkwargs.get('method')else'get',timeout=kwargs.get('timeout')ifkwargs.get('timeout')else30,params=kwargs.get('params'),data=kwargs.get('data'),files=kwargs.get('files'),json=kwargs.get('json'),cookies=kwargs.get('cookies'),allow_redirects=Trueifkwargs.get('allow_redirects')in[None,True]elseFalse,proxies={'http':'http://{}'.format(kwargs.get('proxies')),'https':'http://{}'.format(kwargs.get('proxies'))}ifkwargs.get('proxies')elseNone,headers=kwargs.get('headers')ifkwargs.get('headers')else{'Accept':'*/*','Connection':'close','Accept-Encoding':'gzip,deflate,br','User-Agent':self.random_ua()},verify=False)exceptExceptionase:returnlogging.warning('requesterror:%s'%e)ifretry<1elseself.requester(url,retry-1,**kwargs)defupload(self,file_path:str,**kwargs:any)->Noneordict:c=str(kwargs.get("code"))ifkwargs.get("code")andlen(str(kwargs.get("code")))==16else"s4Qyl0knnW8pjpDK"response=self.requester(method="post",url="https://www.iflyrec.com/AudioStreamService/v1/audios",params={"type":"whole","folder":f"{random.randint(10000000000000000,99999999999999999)}"},headers={'Host':'www.iflyrec.com','Connection':'close','User-Agent':self.random_ua(),'X-Biz-Id':'xftj','Content-Type':f'multipart/form-data;boundary=----WebKitFormBoundary{c}','Accept':'*/*','Origin':'https://www.iflyrec.com','Referer':'https://www.iflyrec.com/html/addMachineOrder.html','Accept-Encoding':'gzip,deflate','Accept-Language':'zh-CN,zh;q=0.9'},data=encode_multipart_formdata(OrderedDict([("language",(None,1,'multipart/form-data')),("id",(None,'WU_FILE_0','multipart/form-data')),('name',(None,os.path.basename(file_path),'multipart/form-data')),('type',(None,'audio/wav','multipart/form-data')),('lastModifiedDate',(None,datetime.datetime.utcnow().strftime('%a%b%d%Y%H:%M:%SGMT+0800')+"(中国标准时间)",'multipart/form-data')),('size',(None,os.path.getsize(file_path),'multipart/form-data')),('file',(os.path.basename(file_path),open(file_path,"rb").read(),'audio/wav')),]),boundary=f'----WebKitFormBoundary{c}')[0],proxies=kwargs.get('proxies'))#requesterrorifresponseisNone:returnlogging.warning(f"上传失败了,请测试网络连接情况,file:{file_path}")#responseerrorif"uploadedSize"notinresponse.text:returnlogging.warning(f"上传响应结果中不不包含关键字,file:{file_path}")elifresponse.json().get('biz').get('uploadedSize')isNone:returnlogging.warning(f"上传响应中关键值缺失,file:{file_path}")returnresponse.json()defcrc32check(self,fileid:str,crc32:str)->Noneorbool:response=self.requester(url=f"https://www.iflyrec.com/TranscriptOrderService/v1/tempAudios/{fileid}/initAudioInfo?crc32={crc32}",method="post",headers={'Host':'www.iflyrec.com','Connection':'close','Accept':'application/json,text/javascript,*/*;q=0.01','X-Requested-With':'XMLHttpRequest','User-Agent':self.random_ua(),'X-Biz-Id':'xftj','Origin':'https://www.iflyrec.com','Referer':'https://www.iflyrec.com/html/addMachineOrder.html','Accept-Encoding':'gzip,deflate','Accept-Language':'zh-CN,zh;q=0.9',})ifresponseisNone:returnlogging.warning("校验失败:网络不通...")returnTrueif"000000"inresponse.textelseFalsedefdistinguish(self,path,mode=False):response=self.requester(method="get"ifmodeelse"post",url="https://www.iflyrec.com/TranscriptPreviewService/v1/aiTranscriptPreviews",headers={'Host':'www.iflyrec.com','Connection':'close','Accept':'application/json','X-Requested-With':'XMLHttpRequest','User-Agent':"Mozilla/5.0(WindowsNT6.2;Win64;x64)AppleWebKit/537.36",'X-Biz-Id':'xftj','Content-Type':'application/json;charset=UTF-8','Origin':'https://www.iflyrec.com','Referer':'https://www.iflyrec.com/html/addMachineOrder.html','Accept-Encoding':'gzip,deflate','Accept-Language':'zh-CN,zh;q=0.9'},params={"filePath":path,"transcriptLanguage":1},json={"filePath":path,"transcriptLanguage":1}ifmodeisFalseelseNone,)ifresponseisNone:returnlogging.warning("识别失败:网络故障")ifmodeisFalseand"true"inresponse.text:returnself.distinguish(path,True)ifmodeisTrueand"speaker"inresponse.text:info=response.json()['biz']['transcriptResult']return"".join([i.strip()foriinre.findall(r'''"content":"([\S\s]*?)"''',info)])else:returnlogging.warning("识别失败:未知错误")@staticmethoddefwrite2txt(path,content):withopen(path,"a+",encoding="utf-8")asf:f.write(content+"\n")#运行入口defrun(self):#提交数据res=self.upload(r"C:\Users\Administrator\Desktop\英语\4.wav")ifresisNone:return#crc32验证msg=self.crc32check(**{"fileid":res['biz']['fileId'],"crc32":res['biz']['crc32']})ifmsgisnotTrue:return#开始识别text=self.distinguish(res['biz']['transPreviewPath'])print(f"获取响应结果:{text}")if__name__=='__main__':start=TestSpider()start.run()


相关文章

    无相关信息
评论
建站知识
建站知识
使用技巧
调试安装
运营推广