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

AI.py

# -*- coding: utf-8 -*-

# ################## 入口类 ##################
import os
from flask import Flask,render_template,request
from LogX import Log1
from AI_TTS_Azure import Azure
from AI_VoiceToText_Baidu import BaiduAi

log1 = Log1.log(None)
# static_url_path='' 指明静态资源在 /static/ 下,URL 路径则可以直接省略 static 路径
App3 = Flask(__name__, static_url_path='')
App3.secret_key = os.urandom(32) #'U2FsdGVkX19B/bZVZXszkfQOBEseDukn' # AES,jiami,Hsbc123#

########## 首页
@App3.route('/', methods=['GET', 'POST'])
@App3.route('/home', methods=['GET', 'POST'])
@App3.route('/index', methods=['GET', 'POST'])
def home():
    return render_template('home.html')

########## 文本转语音
@App3.route('/index1', methods=['GET'])
def index1():
    return render_template('index1.html')

########## 文本转语音
@App3.route('/index1', methods=['POST'])
def index1_tts():
    result = Azure.ttsMain(None,request0=request)
    return render_template('index1.html', msg=result['msg'], filepath=result['filepath'])

########## 文本转语音
@App3.route('/index2', methods=['GET'])
def index2():
    return render_template('index2.html')

########## 文本转语音
@App3.route('/index2', methods=['POST'])
def index2_stt():
    result = BaiduAi.sttMain(None,request0=request)
    return render_template('index2.html', msg=result['msg'], filepath=result['filepath'])


if __name__=='__main__':
    App3.run(host='0.0.0.0', port=6789)




AI_TTS_Azure.py

# -*- coding: utf-8 -*-


### 文本转语音 Azure ###
import os
import requests
import time
from xml.etree import ElementTree
from LogX import Log1
from ConfigFile import Config

log1 = Log1.log(None)
msg1 = '处理失败.'
filepath1 = ''

'''
快速入门:https://docs.microsoft.com/zh-cn/azure/cognitive-services/speech-service/quickstart-python-text-to-speech
官方源码:https://github.com/Azure-Samples/Cognitive-Speech-TTS/blob/master/Samples-Http/Python/TTSSample.py
获取密钥:https://azure.microsoft.com/zh-cn/try/cognitive-services/my-apis/?apiSlug=speech-services&country=China&allowContact=true&fromLogin=True
终结点: https://westus.api.cognitive.microsoft.com/sts/v1.0
获取Token接口:https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken
文本转语音接口:https://westus.tts.speech.microsoft.com/cognitiveservices/v1
密钥 1: 8c0779e6846c43478f83fb2bd2fdd610
密钥 2: c7fa26e8ea4c46368ddafbe76fdf0827
'''

proxyHttp   = Config.getBasic(None, 'http-proxy','http')
proxyHttps  = Config.getBasic(None, 'http-proxy','https')
azureKey1   = Config.getBasic(None, 'Azure-Key','key1')
azureKey2   = Config.getBasic(None, 'Azure-Key','key2')
azureKey    = azureKey1 if azureKey1=='' else azureKey2


class Azure(object):

    def ttsMain(self,request0):
        log1.warn(' >>> 进入 ttsMain ')
        global msg1
        global filepath1
        nowtime1 = time.strftime('%Y%m%d%H%M%S')
        texttype = request0.form['texttype']
        caiyanglv = request0.form['caiyanglv']
        yinse = request0.form['yinse']
        voicefilename1 = 'voice_' + nowtime1 + '_[' + caiyanglv + ']_[' + yinse + '].wav'

        voice_key = ''

        if texttype != '':  # 文本类型<表单输入文本,上传文件文本,指定网页文本>
            textcontent = ''
            uploadPath = os.getcwd() + '/upload/'
            if not os.path.exists(uploadPath):
                os.makedirs(uploadPath)

            #####[1] 表单文本
            if texttype == 'formtext':
                textcontent = request0.form['text1']
                if textcontent != '':
                    # log1.info(' 待转换的文本内容:\n' + textcontent)
                    log1.warn(' 开始转换语音-表单文本 ...')
                    filepath1 = Azure.textToVoice(None, text0=textcontent, voicefilename=voicefilename1,
                                                  voice_encode_type=caiyanglv, voice_speeker_type=yinse,
                                                  subscription_key=voice_key)
                    if filepath1 != '':
                        msg1 = '处理成功!'
                    else:
                        error = '处理失败!'
                else:
                    msg1 = '处理失败!请输入文本内容'
                    log1.error(' ' + msg1)

            #####[2] 文件文本
            elif texttype == 'filetext':
                fileObj1 = request0.files['file1']
                if fileObj1 != '':
                    filename0 = fileObj1.filename
                    filename0_ext = filename0.split('.')[-1]
                    filename0_ext_accept = ['txt', 'log', 'ini', 'conf']
                    if filename0_ext not in filename0_ext_accept:
                        msg1 = '处理失败!请上
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值