当前位置:   article > 正文

AI 文本语音互转的Python例子 (仅后台代码)_ai text voice

ai text voice

AI.py

  1. # -*- coding: utf-8 -*-
  2. # ################## 入口类 ##################
  3. import os
  4. from flask import Flask,render_template,request
  5. from LogX import Log1
  6. from AI_TTS_Azure import Azure
  7. from AI_VoiceToText_Baidu import BaiduAi
  8. log1 = Log1.log(None)
  9. # static_url_path='' 指明静态资源在 /static/ 下,URL 路径则可以直接省略 static 路径
  10. App3 = Flask(__name__, static_url_path='')
  11. App3.secret_key = os.urandom(32) #'U2FsdGVkX19B/bZVZXszkfQOBEseDukn' # AES,jiami,Hsbc123#
  12. ########## 首页
  13. @App3.route('/', methods=['GET', 'POST'])
  14. @App3.route('/home', methods=['GET', 'POST'])
  15. @App3.route('/index', methods=['GET', 'POST'])
  16. def home():
  17. return render_template('home.html')
  18. ########## 文本转语音
  19. @App3.route('/index1', methods=['GET'])
  20. def index1():
  21. return render_template('index1.html')
  22. ########## 文本转语音
  23. @App3.route('/index1', methods=['POST'])
  24. def index1_tts():
  25. result = Azure.ttsMain(None,request0=request)
  26. return render_template('index1.html', msg=result['msg'], filepath=result['filepath'])
  27. ########## 文本转语音
  28. @App3.route('/index2', methods=['GET'])
  29. def index2():
  30. return render_template('index2.html')
  31. ########## 文本转语音
  32. @App3.route('/index2', methods=['POST'])
  33. def index2_stt():
  34. result = BaiduAi.sttMain(None,request0=request)
  35. return render_template('index2.html', msg=result['msg'], filepath=result['filepath'])
  36. if __name__=='__main__':
  37. App3.run(host='0.0.0.0', port=6789)

AI_TTS_Azure.py

  1. # -*- coding: utf-8 -*-
  2. ### 文本转语音 Azure ###
  3. import os
  4. import requests
  5. import time
  6. from xml.etree import ElementTree
  7. from LogX import Log1
  8. from ConfigFile import Config
  9. log1 = Log1.log(None)
  10. msg1 = '处理失败.'
  11. filepath1 = ''
  12. '''
  13. 快速入门:https://docs.microsoft.com/zh-cn/azure/cognitive-services/speech-service/quickstart-python-text-to-speech
  14. 官方源码:https://github.com/Azure-Samples/Cognitive-Speech-TTS/blob/master/Samples-Http/Python/TTSSample.py
  15. 获取密钥:https://azure.microsoft.com/zh-cn/try/cognitive-services/my-apis/?apiSlug=speech-services&country=China&allowContact=true&fromLogin=True
  16. 终结点: https://westus.api.cognitive.microsoft.com/sts/v1.0
  17. 获取Token接口:https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken
  18. 文本转语音接口:https://westus.tts.speech.microsoft.com/cognitiveservices/v1
  19. 密钥 1: 8c0779e6846c43478f83fb2bd2fdd610
  20. 密钥 2: c7fa26e8ea4c46368ddafbe76fdf0827
  21. '''
  22. proxyHttp = Config.getBasic(None, 'http-proxy','http')
  23. proxyHttps = Config.getBasic(None, 'http-proxy','https')
  24. azureKey1 = Config.getBasic(None, 'Azure-Key','key1')
  25. azureKey2 = Config.getBasic(None, 'Azure-Key','key2')
  26. azureKey = azureKey1 if azureKey1=='' else azureKey2
  27. class Azure(object):
  28. def ttsMain(self,request0):
  29. log1.warn(' >>> 进入 ttsMain ')
  30. global msg1
  31. global filepath1
  32. nowtime1 = time.strftime('%Y%m%d%H%M%S')
  33. texttype = request0.form['texttype']
  34. caiyanglv = request0.form['caiyanglv']
  35. yinse = request0.form['yinse']
  36. voicefilename1 = 'voice_' + nowtime1 + '_[' + caiyanglv + ']_[' + yinse + '].wav'
  37. voice_key = ''
  38. if texttype != '': # 文本类型<表单输入文本,上传文件文本,指定网页文本>
  39. textcontent = ''
  40. uploadPath = os.getcwd() + '/upload/'
  41. if not os.path.exists(uploadPath):
  42. os.makedirs(uploadPath)
  43. #####[1] 表单文本
  44. if texttype == 'formtext':
  45. textcontent = request0.form['text1']
  46. if textcontent != '':
  47. # log1.info(' 待转换的文本内容:\n' + textcontent)
  48. log1.warn(' 开始转换语音-表单文本 ...')
  49. filepath1 = Azure.textToVoice(None, text0=textcontent, voicefilename=voicefilename1,
  50. voice_encode_type=caiyanglv, voice_speeker_type=yinse,
  51. subscription_key=voice_key)
  52. if filepath1 != '':
  53. msg1 = '处理成功!'
  54. else:
  55. error = '处理失败!'
  56. else:
  57. msg1 = '处理失败!请输入文本内容'
  58. log1.error(' ' + msg1)
  59. #####[2] 文件文本
  60. elif texttype == 'filetext':
  61. fileObj1 = request0.files['file1']
  62. if fileObj1 != '':
  63. filename0 = fileObj1.filename
  64. filename0_ext = filename0.split('.')[-1]
  65. filename0_ext_accept = ['txt', 'log', 'ini', 'conf']
  66. if filename0_ext not in filename0_ext_accept:
  67. msg1 = '处理失败!请上传纯文本格式的文件,支持的后缀:txt,log,ini,conf'
  68. log1.error(' ' + msg1)
  69. else:
  70. filenamenew = nowtime1 + '.' + filename0_ext
  71. abPath = uploadPath + '/text_' + filenamenew
  72. log1.info(' 开始上传文件 ...')
  73. fileObj1.save(abPath)
  74. log1.info(' 文件上传成功:' + abPath)
  75. fileUpload = open(abPath, 'r', encoding='utf-8').read()
  76. for textline in fileUpload:
  77. textcontent = textcontent + textline
  78. log1.info(' 开始转换语音-上传文件 ...')
  79. filepath1 = Azure.fileToVoice(None, filePath0=abPath, voicefilename=voicefilename1,
  80. voice_encode_type=caiyanglv, voice_speeker_type=yinse,
  81. subscription_key=voice_key)
  82. if filepath1 != '':
  83. msg1 = '处理成功!'
  84. else:
  85. msg1 = '处理失败!'
  86. else:
  87. msg1 = '处理失败!请选择文件'
  88. log1.error('>>> ' + msg1)
  89. #####[3] 网页文本
  90. elif texttype == 'webpagetext':
  91. msg1 = '您好,暂不支持网页方式.'
  92. log1.info(' ' + msg1)
  93. '''
  94. weburl1 = request.form['weburl1']
  95. if textcontent != '':
  96. textcontent = weburl1 # 通过URL获取网页文本,应该加点过滤参数,获取指定DOM元素内的文本
  97. log1.info('>>> 开始转换语音-网页地址 ...')
  98. filepath1 = Azure.tts_text(None, text0=textcontent, voicefilename=voicefilename1,
  99. voice_encode_type=caiyanglv, voice_speeker_type=yinse, subscription_key=voice_key)
  100. msg1 = '处理成功'
  101. else:
  102. msg1 = '处理失败!请输入网页地址(URL)'
  103. log1.info('>>> ' + msg1)
  104. '''
  105. #####[0] 参数错误
  106. else:
  107. msg1 = '处理失败!文本类型参数错误:texttype=' + texttype
  108. log1.error('>>> ' + msg1)
  109. else:
  110. msg1 = '处理失败!文本类型参数不能为空.'
  111. log1.error('>>> ' + msg1)
  112. if filepath1!='' :
  113. filepath1 = request0.url_root + filepath1.replace('static/', '')
  114. result = {'msg': msg1, 'filepath': filepath1} # 返回结果,键值对,字典
  115. log1.warn('>>> 全部操作已经完成')
  116. log1.warn('>>> 返回结果:\nresult=' + str(result))
  117. return result
  118. ### 文件转语音
  119. def fileToVoice(self, filePath0, voicefilename, voice_encode_type, voice_speeker_type, subscription_key):
  120. filepath = ''
  121. log1.debug('传入的参数值:'
  122. + '\nfilePath0=' + filePath0
  123. + '\nvoicefilename=' + voicefilename
  124. + '\nvoice_encode_type=' + voice_encode_type
  125. + '\nvoice_speeker_type=' + voice_speeker_type)
  126. if subscription_key == '':
  127. subscription_key = 'c7fa26e8ea4c46368ddafbe76fdf0827'
  128. # tts = input('Input some text to convert to speech: ') # 控制台输入
  129. # tts = 'Hello everyone, I am 18 years old and have a deposit of 1.23 million. I want to get a wife.'
  130. file_obj = open(filePath0, 'rb') # 英文内容:'rU',中文内容:,'rb'
  131. # tts = ''
  132. # for eachline in file_obj: # 一行一行读取
  133. # if eachline != '':
  134. # tts += eachline
  135. # tts = file_obj.read() # 英文内容
  136. tts = str(file_obj.read(), encoding='utf-8') # 中文内容
  137. #log1.debug(' 待转换文本:' + tts )
  138. timestr = time.strftime('%Y%m%d%H%M')
  139. proxies = {
  140. 'http': proxyHttp,
  141. 'https': proxyHttps,
  142. }
  143. fetch_token_url = 'https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken'
  144. headers = {
  145. 'Ocp-Apim-Subscription-Key': subscription_key
  146. }
  147. response = requests.post(fetch_token_url, headers=headers, proxies=proxies, verify=False)
  148. access_token = str(response.text)
  149. #log1.debug(' 获取到Token:' + access_token)
  150. constructed_url = 'https://westus.tts.speech.microsoft.com/cognitiveservices/v1'
  151. headers = {
  152. # 前面带有单词 Bearer 的授权令牌
  153. 'Authorization': 'Bearer ' + access_token,
  154. # 指定所提供的文本的内容类型。 接受的值:application/ssml+xml。
  155. 'Content-Type': 'application/ssml+xml',
  156. # 指定音频输出格式,取值如下:
  157. # raw-16khz-16bit-mono-pcm (百度AI的语音转文本时,需要采用这个格式,但Windows自带的播放器是无法播放的)
  158. # raw-8khz-8bit-mono-mulaw
  159. # riff-8khz-8bit-mono-alaw
  160. # riff-8khz-8bit-mono-mulaw
  161. # riff-16khz-16bit-mono-pcm
  162. # audio-16khz-128kbitrate-mono-mp3
  163. # audio-16khz-64kbitrate-mono-mp3
  164. # audio-16khz-32kbitrate-mono-mp3
  165. # raw-24khz-16bit-mono-pcm
  166. # riff-24khz-16bit-mono-pcm (这个格式 可以播放)
  167. # audio-24khz-160kbitrate-mono-mp3
  168. # audio-24khz-96kbitrate-mono-mp3
  169. # audio-24khz-48kbitrate-mono-mp3
  170. 'X-Microsoft-OutputFormat': voice_encode_type,
  171. # 应用程序名称,少于 255 个字符。
  172. # Chrome的 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36
  173. 'User-Agent': 'Chrome/73.0.3683.86'
  174. }
  175. xml_body = ElementTree.Element('speak', version='1.0')
  176. xml_body.set('{http://www.w3.org/XML/1998/namespace}lang', 'en-us')
  177. voice = ElementTree.SubElement(xml_body, 'voice')
  178. voice.set('{http://www.w3.org/XML/1998/namespace}lang', 'en-US')
  179. # 标准语音列表:https://docs.microsoft.com/zh-cn/azure/cognitive-services/speech-service/language-support#standard-voices
  180. # 【下面5行:英语(美国)】 【语音性别,语音全称,语音简称】
  181. # 女 'Microsoft Server Speech Text to Speech Voice (en-US, ZiraRUS)' 'en-US-ZiraRUS'
  182. # 女 'Microsoft Server Speech Text to Speech Voice (en-US, JessaRUS)' 'en-US-JessaRUS'
  183. # 男 'Microsoft Server Speech Text to Speech Voice (en-US, BenjaminRUS)' 'en-US-BenjaminRUS'
  184. # 女 'Microsoft Server Speech Text to Speech Voice (en-US, Jessa24kRUS)' 'en-US-Jessa24kRUS'
  185. # 男 'Microsoft Server Speech Text to Speech Voice (en-US, Guy24kRUS)' 'en-US-Guy24kRUS'
  186. # 【下面3行:中文(中国)】
  187. # 女 'Microsoft Server Speech Text to Speech Voice (zh-CN, HuihuiRUS)' 'zh-CN-HuihuiRUS'
  188. # 女 'Microsoft Server Speech Text to Speech Voice (zh-CN, Yaoyao, Apollo)' 'zh-CN-Yaoyao-Apollo'
  189. # 男 'Microsoft Server Speech Text to Speech Voice (zh-CN, Kangkang, Apollo)' 'zh-CN-Kangkang-Apollo'
  190. voice.set('name',voice_speeker_type)
  191. voice.text = tts
  192. body = ElementTree.tostring(xml_body)
  193. log1.debug(' 调用接口转换语音中......')
  194. response = requests.post(constructed_url, headers=headers, data=body, proxies=proxies, verify=False)
  195. if response.status_code == 200:
  196. filepath = 'static/voice/' + voicefilename
  197. with open(filepath, 'wb') as audio:
  198. audio.write(response.content)
  199. log1.warn(' 文本转语音已完成,生成的音频文件:' + filepath)
  200. else:
  201. print('[失败] response code: ' + str(response.status_code)
  202. + '\nresponse headers: ' + str(response.headers) )
  203. return filepath
  204. ### 文本转语音
  205. def textToVoice(self, text0, voicefilename, voice_encode_type, voice_speeker_type, subscription_key):
  206. filepath = ''
  207. log1.debug('传入的参数值:'
  208. #+ '\ntext0=' + text0
  209. + '\nvoicefilename=' + voicefilename
  210. + '\nvoice_encode_type=' + voice_encode_type
  211. + '\nvoice_speeker_type=' + voice_speeker_type )
  212. if subscription_key=='':
  213. subscription_key = 'c7fa26e8ea4c46368ddafbe76fdf0827'
  214. # tts = input('Input some text to convert to speech: ') # 控制台输入
  215. tts = text0
  216. timestr = time.strftime('%Y%m%d%H%M')
  217. proxies = {
  218. 'http': proxyHttp,
  219. 'https': proxyHttps,
  220. }
  221. fetch_token_url = 'https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken'
  222. headers = {
  223. 'Ocp-Apim-Subscription-Key': subscription_key
  224. }
  225. response = requests.post(fetch_token_url, headers=headers, proxies=proxies, verify=False)
  226. access_token = str(response.text)
  227. #log1.debug(' 获取到Token:' + access_token)
  228. constructed_url = 'https://westus.tts.speech.microsoft.com/cognitiveservices/v1'
  229. headers = {
  230. # 前面带有单词 Bearer 的授权令牌
  231. 'Authorization': 'Bearer ' + access_token,
  232. # 指定所提供的文本的内容类型
  233. 'Content-Type': 'application/ssml+xml',
  234. # 指定音频输出格式
  235. 'X-Microsoft-OutputFormat': voice_encode_type,
  236. # 应用程序名称,少于 255 个字符。
  237. 'User-Agent': 'Chrome/73.0.3683.86'
  238. }
  239. xml_body = ElementTree.Element('speak', version='1.0')
  240. xml_body.set('{http://www.w3.org/XML/1998/namespace}lang', 'en-us')
  241. voice = ElementTree.SubElement(xml_body, 'voice')
  242. voice.set('{http://www.w3.org/XML/1998/namespace}lang', 'en-US')
  243. # 'en-US-Guy24kRUS',全称:'Microsoft Server Speech Text to Speech Voice (en-US, Guy24KRUS)'
  244. voice.set('name',voice_speeker_type)
  245. voice.text = tts
  246. body = ElementTree.tostring(xml_body)
  247. log1.debug(' 调用接口转换语音中......')
  248. response = requests.post(constructed_url, headers=headers, data=body, proxies=proxies, verify=False)
  249. if response.status_code == 200:
  250. filepath = 'static/voice/' + voicefilename
  251. with open(filepath, 'wb') as audio:
  252. audio.write(response.content)
  253. log1.warn(' 文本转语音已完成,生成的音频文件:' + filepath)
  254. else:
  255. print('[失败] response code: ' + str(response.status_code)
  256. + '\nresponse : ' + str(response.content) )
  257. return filepath
  258. ### 函数入口
  259. if __name__ == '__main__':
  260. test = Azure()
  261. abPath = 'static/backup/text/tts_txt_zhcn.txt'
  262. caiyanglv = 'riff-24khz-16bit-mono-pcm'
  263. yinse = 'zh-CN-HuihuiRUS'
  264. voicefilename1 = 'voice_1001_[' + caiyanglv + ']_['+yinse+'].wav'
  265. test.fileToVoice( filePath0 = abPath, voicefilename = voicefilename1, voice_encode_type = caiyanglv,
  266. voice_speeker_type = yinse, subscription_key = '')

AI_VoiceToText_Baidu.py

  1. # -*- coding: utf-8 -*-
  2. ### 语音识别 百度API ###
  3. # Home:https://ai.baidu.com/tech/speech/asr
  4. # API: https://ai.baidu.com/docs#/ASR-Online-Python-SDK/top
  5. # Q&A: https://ai.baidu.com/docs#/FAQ/a53b4698
  6. # 在线文本转语音(汇丰无法试听和下载):https://developer.baidu.com/vcast
  7. from aip import AipSpeech
  8. from ConfigFile import Config
  9. from LogX import Log1
  10. import time
  11. import os
  12. log1 = Log1.log(None)
  13. msg1 = '处理失败.'
  14. filepath1 = ''
  15. class BaiduAi(object):
  16. """ 你的 APPID AK SK """
  17. proxyHttp = Config.getBasic(None, group0='http-proxy', key0='http')
  18. proxyHttps = Config.getBasic(None, group0='http-proxy', key0='https')
  19. APP_ID = Config.getBasic(None, group0='Baidu-Ai', key0='appid')
  20. API_KEY = Config.getBasic(None, group0='Baidu-Ai', key0='appkey')
  21. SECRET_KEY = Config.getBasic(None, group0='Baidu-Ai', key0='secretkey')
  22. # ### 语音转文本,表单入口
  23. def sttMain(self, request0):
  24. global msg1
  25. global filepath1
  26. nowtime1 = time.strftime('%Y%m%d%H%M%S')
  27. fromLanguage = request0.form['fromLanguage'] # 来源语言
  28. toLanguage = request0.form['toLanguage'] # 目标语言
  29. textfilename1 = 'text_' + nowtime1 + '_[' + fromLanguage + ']_[' + toLanguage + '].txt'
  30. uploadPath = os.getcwd() + '/upload/'
  31. fileObj1 = request0.files['file1']
  32. if fileObj1 != '':
  33. filename0 = fileObj1.filename
  34. filename0_ext = filename0.split('.')[-1]
  35. filename0_ext_accept = ['wav']
  36. if filename0_ext not in filename0_ext_accept:
  37. msg1 = '处理失败!请上传wav格式的音频文件。'
  38. log1.error('>>> ' + msg1)
  39. else:
  40. filenamenew = nowtime1 + '.' + filename0_ext
  41. abPath = uploadPath + '/voice_' + filenamenew
  42. log1.info('>>> 开始上传文件 ...')
  43. fileObj1.save(abPath)
  44. log1.info('>>> 文件上传成功:' + abPath)
  45. # 开始转换语音
  46. textDict = BaiduAi.aiMain(None, filePath0=abPath, toLanguage0=toLanguage)
  47. if textDict != '':
  48. err_no = textDict['err_no']
  49. err_msg = textDict['err_msg']
  50. result = textDict['result'][0]
  51. log1.debug('>>> 状态码:' + str(err_no))
  52. log1.debug('>>> 状态:' + err_msg)
  53. log1.debug('>>> 结果:' + result)
  54. # TODO 将文本写入文件
  55. filepath1 = 'static/textfile/'+textfilename1
  56. open(filepath1, "w", encoding='UTF-8').write(result)
  57. log1.debug('>>> 写入文件完成:' + filepath1)
  58. filepath1 = request0.url_root + 'textfile/' + textfilename1
  59. if filepath1 != '':
  60. msg1 = '处理成功!'
  61. else:
  62. msg1 = '处理失败!'
  63. else:
  64. msg1 = '处理失败!请选择文件'
  65. log1.error('>>> ' + msg1)
  66. result = {'msg': msg1, 'filepath': filepath1} # 返回结果,键值对,字典
  67. log1.warn('>>> 全部操作已经完成')
  68. log1.warn('>>> 返回结果:\nresult=' + str(result))
  69. return result
  70. # ### 语音转文本,转换函数,返回字典类型
  71. def aiMain(self, filePath0, toLanguage0):
  72. # AipSpeech是语音识别的Python SDK客户端
  73. client = AipSpeech(BaiduAi.APP_ID, BaiduAi.API_KEY, BaiduAi.SECRET_KEY) # 访问百度API,内置访问http的函数,并写死了URL路径
  74. proxies = {
  75. "http": BaiduAi.proxyHttp,
  76. "https": BaiduAi.proxyHttps,
  77. }
  78. client.setProxies(proxies)
  79. # client.setConnectionTimeoutInMillis( 10000 ) # 建立连接的超时时间(毫秒),默认不需要设置
  80. # client.setSocketTimeoutInMillis(300000) # 通过打开的连接传输数据的超时时间(毫秒)
  81. # 上传 本地音频文件(SpeechToText.wav)
  82. # 支持的格式:原始 PCM 的录音参数必须符合 16k 采样率、16bit 位深、单声道,支持的格式有:pcm(不压缩)、wav(不压缩,pcm编码)、amr(压缩格式)。
  83. # 有长度限制(测试时尽量短一点)
  84. # 返回结果为字典类型(Dict / json)
  85. response = client.asr(BaiduAi.get_file_content(None,filePath=filePath0), 'wav', 16000, {
  86. # 1536:普通话(支持简单的英文识别)
  87. # 默认1537:普通话(纯中文识别)
  88. # 1737:英语
  89. # 1637:粤语
  90. 'dev_pid': int(toLanguage0),
  91. })
  92. return response
  93. # {'corpus_no': '6714166347641437907', 'err_msg': 'success.', 'err_no': 0, 'result': ['识别后的内容'], 'sn': '602626830571563263672'}
  94. # ### 语音转文本,读取本地文件
  95. def get_file_content(self,filePath):
  96. with open(filePath, 'rb') as fp:
  97. return fp.read()
  98. ### 函数入口
  99. if __name__ == "__main__":
  100. baidu = BaiduAi()
  101. filepath9 = 'static/backup/sound/voice_20190916142927_[raw-16khz-16bit-mono-pcm]_[en-US-ZiraRUS].wav'
  102. languageNum = 1737
  103. textDict = baidu.aiMain( filePath0=filepath9, toLanguage0=languageNum)
  104. print (str(textDict))
  105. if textDict!='':
  106. err_no = textDict['err_no']
  107. err_msg = textDict['err_msg']
  108. result = textDict['result'][0]
  109. print ('状态码:' + err_no)
  110. print ('状态:' + err_msg)
  111. print ('结果:' + result)

ConfigFile

  1. # -*- coding: utf-8 -*-
  2. import os
  3. from configparser import ConfigParser
  4. class Config(object):
  5. def __init__(self):
  6. super(Config, self).__init__()
  7. self.config = ConfigParser()
  8. #print('配置文件路径:'+os.getcwd()+'/configs/basic.ini')
  9. self.config.read(os.getcwd()+'/configs/basic.ini',encoding='utf-8')
  10. # ### 代理配置
  11. # user
  12. # pass
  13. def getBasic (self,group0, key0):
  14. cfg0 = Config().config
  15. value0 = cfg0.get(group0, key0)
  16. return value0
  17. if __name__ == "__main__":
  18. cc = Config()
  19. # print (cc.getBasic( group0='http-proxy', key0='http' ))
'
运行

LogX.py

  1. # -*- coding: utf-8 -*-
  2. import logging
  3. import logging.handlers
  4. class Log1(object):
  5. def log(self):
  6. # 日志对象
  7. logger1 = logging.getLogger('AIFuture')
  8. if not logger1.handlers:
  9. # 日志级别-会覆盖 Handler的子级别
  10. logfilePath = 'logs/AI.log'
  11. logger1.setLevel(logging.DEBUG)
  12. # 用于输出到文件
  13. #logfile1 = logging.FileHandler(logfilePath)
  14. logfile1 = logging.handlers.RotatingFileHandler(logfilePath, maxBytes=10 * 1024 * 1024, backupCount=5, encoding='utf-8')
  15. #logfile1.setLevel(logging.DEBUG)
  16. # 用于输出到控制台
  17. logcmd1 = logging.StreamHandler()
  18. #logcmd1.setLevel(logging.INFO)
  19. # 格式化日志
  20. logformatter = logging.Formatter('[%(asctime)s] [%(levelname)s] [%(filename)s(line:%(lineno)d)] %(message)s')
  21. # 应用格式
  22. logfile1.setFormatter(logformatter)
  23. logcmd1.setFormatter(logformatter)
  24. # 注入对象
  25. logger1.addHandler(logcmd1)
  26. logger1.addHandler(logfile1)
  27. return logger1
'
运行

start_AI.sh

  1. #! /bin/bash
  2. . ~/.bash_profile
  3. mypython -u AI.py
  4. '''
  5. 进入目录: cd /home/pyai/tts
  6. 启动命令: nohup sh start_AI.sh > start_AI.sh.out &
  7. 停止命令:
  8. 查看进程: ps -ef|grep AI
  9. 显示 端口占用:netstat -lnt|grep 6789
  10. sudo netstat -antup
  11. sudo netstat -antup|grep PID号
  12. sudo ps -ef|grep 进程名
  13. '''
  14. '''
  15. 依赖插件:mypip install configparser --user
  16. flask
  17. jinja2
  18. requests
  19. logger1
  20. baidu-aip
  21. configparser
  22. '''

configs/basic.ini

  1. # http 代理配置
  2. [http-proxy]
  3. http = http://***
  4. https = http://***
  5. # 微软 Azure 语音密钥
  6. [Azure-Key]
  7. key1 = 8c0779e6846c43478f83fb2bd2fdd610
  8. key2 = c7fa26e8ea4c46368ddafbe76fdf0827
  9. [Baidu-Ai]
  10. appid = 16735297
  11. appkey = P7IGlBm443VcSaCWCQT6WrXh
  12. secretkey = pdlslL0ysPFUU8yF6dQtoN5yxrfdSupD

相关目录结构:

  1. 项目根目录/configs/basic.ini
  2. 项目根目录/logs
  3. 项目根目录/static/backup/sound
  4. 项目根目录/static/backup/text
  5. 项目根目录/static/history
  6. 项目根目录/static/textfile
  7. 项目根目录/static/voice
  8. 项目根目录/templates/***.html
  9. 项目根目录/upload
  10. 项目根目录/AI.py
  11. 项目根目录/AI_TTS_Azure.py
  12. 项目根目录/AI_VoiceToText_Baidu.py
  13. 项目根目录/ConfigFile.py
  14. 项目根目录/LogX.py
  15. 项目根目录/start_AI.py

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/821058
推荐阅读
相关标签
  

闽ICP备14008679号