阿里云语音合成,录音文件识别,自然语言分析,rest 调用 python实现

本文涉及的产品
NLP自然语言处理_基础版,每接口每天50万次
NLP 自学习平台,3个模型定制额度 1个月
NLP自然语言处理_高级版,每接口累计50万次
简介: 阿里云语音合成,录音文件识别,自然语言分析,rest 调用 python实现

最近研究阿里云语音合成,录音文件识别,自然语言分析。

image.png

自然语言分析官网文档:

https://help.aliyun.com/document_detail/61378.html?spm=a2c4g.11186623.6.547.9q3U1C

智能语音官网文档:

https://help.aliyun.com/product/30413.html?spm=a2c4g.11186623.3.1.yS0DIK


决定采用阿里云提供的restful api接口,主要利用python urllib库来实现调用,整合里官方给出的demo,总结出调用代码。话不多说,贴出代码:


python环境

python3.5.1


http请求代理工具类

在工程目录中建立utils目录,在目录中建立init.py文件代码如下

import hashlib
import urllib.request
import hmac
import base64
import datetime
import ssl
import uuid
from urllib.error import HTTPError
class http_proxy:
    """
    Http工具类,封装了鉴权
    """
    def __init__(self, ak_id, ak_secret):
        self.__ak_id = ak_id
        self.__ak_secret = ak_secret
    def __current_gmt_time(self):
        date = datetime.datetime.strftime(datetime.datetime.utcnow(), "%a, %d %b %Y %H:%M:%S GMT")
        return date
    def __md5_base64(self, strbody):
        hash = hashlib.md5()
        hash.update(strbody.encode('utf-8'))
        print(hash.digest())
        return base64.b64encode(hash.digest()).decode('utf-8')
    def __sha1_base64(self, str_to_sign, secret):
        hmacsha1 = hmac.new(secret.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha1)
        return base64.b64encode(hmacsha1.digest()).decode('utf-8')
    def send_request(self, url, body):
        gmtnow = self.__current_gmt_time()
        print(gmtnow)
        body_md5 = self.__md5_base64(body)
        print(body_md5)
        str_to_sign = "POST\napplication/json\n" + body_md5 + "\napplication/json\n" + gmtnow
        print(str_to_sign)
        signature = self.__sha1_base64(str_to_sign, self.__ak_secret)
        print(signature)
        auth_header = "Dataplus " + self.__ak_id + ":" + signature
        print(auth_header)
        ssl._create_default_https_context = ssl._create_unverified_context
        req = urllib.request.Request(url)
        req.add_header("Accept", "application/json")
        req.add_header("Content-Type", "application/json")
        req.add_header("Date", gmtnow)
        req.add_header("Authorization", auth_header)
        data = body.encode('utf-8')
        f = urllib.request.urlopen(req, data)
        return f.read().decode('utf-8')
    def send_get(self, url, task_id):
        gmtnow = self.__current_gmt_time()
        print(gmtnow)
        accept = "application/json"
        content_type = "application/json"
        str_to_sign = "GET\n" + accept + "\n" + "" + "\n" + content_type + "\n" + gmtnow
        print(str_to_sign)
        signature = self.__sha1_base64(str_to_sign, self.__ak_secret)
        print(signature)
        auth_header = "Dataplus " + self.__ak_id + ":" + signature
        print(auth_header)
        ssl._create_default_https_context = ssl._create_unverified_context
        url += "/" + task_id
        req = urllib.request.Request(url)
        req.add_header("Accept", "application/json")
        req.add_header("Content-Type", "application/json")
        req.add_header("Date", gmtnow)
        req.add_header("Authorization", auth_header)
        f = urllib.request.urlopen(req)
        return f.read().decode('utf-8')
        # try:
        #     f = urllib.request.urlopen(req)
        # except HTTPError as e:
        #     print(e)
        #     return None
        # else:
        #     return f.read().decode('utf-8')
    def send_requestForNlp(self, path, content):
        method = "POST"
        content_type = "application/json;chrset=utf-8"
        accept = "application/json"
        host = "nlp.cn-shanghai.aliyuncs.com"
        gmtnow = self.__current_gmt_time()
        print(gmtnow)
        body_md5 = self.__md5_base64(content)
        print(body_md5)
        uuidstr =  uuid.uuid4().hex
        str_to_sign = method+"\n"+accept+"\n" + body_md5 + "\n"+content_type+"\n" + gmtnow+ "\nx-acs-signature-method:HMAC-SHA1\n" + "x-acs-signature-nonce:" + uuidstr + "\n" + path;
        print(str_to_sign)
        signature = self.__sha1_base64(str_to_sign, self.__ak_secret)
        print(signature)
        auth_header = "acs " + self.__ak_id + ":" + signature
        print(auth_header)
        ssl._create_default_https_context = ssl._create_unverified_context
        req = urllib.request.Request("http://"+host+path)
        req.add_header("Accept",accept)
        req.add_header("Content-Type", content_type)
        req.add_header("Content-MD5", body_md5)
        req.add_header("Date", gmtnow)
        req.add_header("Host", host)
        req.add_header("x-acs-signature-nonce", uuidstr)
        req.add_header("x-acs-signature-method", "HMAC-SHA1")
        req.add_header("Authorization", auth_header)
        data = content.encode('utf-8')
        f = urllib.request.urlopen(req, data)
        return f.read().decode('utf-8')
    def sendTtsPost(self, textData, ttsRequestParam,fileRootPath):
        url = 'http://nlsapi.aliyun.com/speak?'#语音合成接口
        #拼接
        paramArray = []
        for key in ttsRequestParam:
            paramArray.append(key+"="+ttsRequestParam[key])
        url+=url+'&'.join(paramArray)
        method = "POST"
        content_type = "text/plain"
        accept = "audio/" + ttsRequestParam['encode_type'] + ",application/json"
        gmtnow = self.__current_gmt_time()
        body_md5 = self.__md5_base64(textData)
        print(body_md5)
        str_to_sign = method + "\n" + accept + "\n" + body_md5 + "\n" + content_type + "\n" + gmtnow
        print(str_to_sign)
        signature = self.__sha1_base64(str_to_sign, self.__ak_secret)
        print(signature)
        auth_header = "Dataplus " + self.__ak_id + ":" + signature
        print(auth_header)
        ssl._create_default_https_context = ssl._create_unverified_context
        req = urllib.request.Request(url)
        req.add_header("accept", accept)
        req.add_header("content-Type", content_type)
        req.add_header("date", gmtnow)
        req.add_header("Authorization", auth_header)
        req.add_header("Content-Length", len(textData))
        data = textData.encode('utf-8')
        f = urllib.request.urlopen(req, data)
        if f.status ==200:
            file = 'g:audio/' + uuid.uuid4().hex + ".wav"
            content = f.read()
            with open(file, 'wb') as f:
                f.write(content)
            print("success"+file)
        else:
            print('失败!')

调用demo

在目录中建立demo.py ,注意和上面的utils目录同级

import sys
import utils
import json
# app_key   语音数据格式  领域
# nls-service-realtime-8k   8kHz采样率 智能客服服务领域,比如电话客服等
# nls-service-multi-domain  16kHz采样率    汉语通用识别
# nls-service   16kHz采样率    输入法,社交聊天
# nls-service-tv    16kHz采样率    家庭娱乐
# nls-service-shopping  16kHz采样率    电商购物
# nls-realtime-fangyan  16kHz采样率    支持东北、河南、四川等方言
# nls-service-yue-streaming 16kHz采样率    粤语
# nls-service-en    16kHz采样率    英语
ak_id = "";  ##数加管控台获得的accessId
ak_secret = ""  ## 数加管控台获得的accessSecret
url = "https://nlsapi.aliyun.com/transcriptions"
# 录音文件提交
def request():
    body = {
        'app_key': 'nls-service-multi-domain',
        'oss_link': 'http://网址/audio/zl4.mp3',
    }
    bodyStr = json.dumps(body)
    httpProxy = utils.http_proxy(ak_id, ak_secret)
    result = httpProxy.send_request(url, bodyStr)
    return result
# 录音文件识别结果查询
def query(id):
    httpProxy = utils.http_proxy(ak_id, ak_secret)
    result = httpProxy.send_get(url, id)
    return result
# 自然语音分析 分词
def nlpTest():
    path = '/nlp/api/wordpos/general'
    postBody = {
        'text': '为什么世界是这个样子,人们都不诚实,我要努力,获得成功,让别人尊敬',
        'lang': 'ZH',
    }
    bodyStr = json.dumps(postBody)
    httpProxy = utils.http_proxy(ak_id, ak_secret)
    result = httpProxy.send_requestForNlp(path,bodyStr)
    return result
#语音合成
def ttsTest():
    text = '在打招呼的时候直视对方的人在交往中往往具有攻击性,'
    fileRootPath='g:audio/'
    ttsRequestParam ={
        'encode_type':'wav',#合成语音的编码格式,支持pcm/wav/mp3/alaw
        'voice_name':'xiaogang',#xiaogang - 男,xiaoyun - 女
        'volume':'50',#0~100
        'sample_rate':'16000',#抽样频率率 8000/16000
        'speech_rate':'0',#语速 -500~500
        'pitch_rate':'0',#语调 -500~500
        'tts_nus':'1',#0 - 通过参数合成语音,1 - 拼接原始录音
        'background_music_id':'1',#播放语音时可选背景音乐,0,1
        'background_music_offset':'0',#背景音乐播放偏移时长,毫秒。当启用背景音乐时生效
        'background_music_volume':'100'#背景音乐音量,当启用背景音乐时生效,0~100
    }
    httpProxy = utils.http_proxy(ak_id, ak_secret)
    filepath = httpProxy.sendTtsPost(text,ttsRequestParam,fileRootPath)
    print(filepath)
if __name__ == '__main__':
    # print(request())
    # print(query('2324ec1ed63549318b9477f1bf3eaf8a'))
    print( nlpTest())
    # print(ttsTest())
相关文章
|
13天前
|
机器学习/深度学习 算法 搜索推荐
从理论到实践,Python算法复杂度分析一站式教程,助你轻松驾驭大数据挑战!
【10月更文挑战第4天】在大数据时代,算法效率至关重要。本文从理论入手,介绍时间复杂度和空间复杂度两个核心概念,并通过冒泡排序和快速排序的Python实现详细分析其复杂度。冒泡排序的时间复杂度为O(n^2),空间复杂度为O(1);快速排序平均时间复杂度为O(n log n),空间复杂度为O(log n)。文章还介绍了算法选择、分而治之及空间换时间等优化策略,帮助你在大数据挑战中游刃有余。
41 4
|
10天前
|
数据可视化 算法 Python
基于OpenFOAM和Python的流场动态模态分解:从数据提取到POD-DMD分析
本文介绍了如何利用Python脚本结合动态模态分解(DMD)技术,分析从OpenFOAM模拟中提取的二维切片数据,以深入理解流体动力学现象。通过PyVista库处理VTK格式的模拟数据,进行POD和DMD分析,揭示流场中的主要能量结构及动态特征。此方法为研究复杂流动系统提供了有力工具。
22 2
基于OpenFOAM和Python的流场动态模态分解:从数据提取到POD-DMD分析
|
6天前
|
自然语言处理 算法 数据挖掘
探讨如何利用Python中的NLP工具,从被动收集到主动分析文本数据的过程
【10月更文挑战第11天】本文介绍了自然语言处理(NLP)在文本分析中的应用,从被动收集到主动分析的过程。通过Python代码示例,详细展示了文本预处理、特征提取、情感分析和主题建模等关键技术,帮助读者理解如何有效利用NLP工具进行文本数据分析。
25 2
|
16天前
|
JSON 数据可视化 API
玩转数据科学:Python实战分析天气预报变动趋势
【10月更文挑战第1天】随着气候变化对日常生活的影响日益显著,理解和预测天气模式变得越来越重要。本文将引导您如何使用Python来抓取和分析天气预报数据,从而揭示天气变化的趋势。我们将介绍从获取公开气象API的数据到清洗、处理以及可视化整个过程的技术方法。
37 2
|
16天前
|
数据可视化 IDE 数据挖掘
Python助您洞察先机:2024年A股市场数据抓取与分析实战
【10月更文挑战第1天】随着2024年中国股市的强劲表现,投资者们对于如何高效获取并分析相关金融数据的需求日益增长。本文旨在介绍如何利用Python这一强大的编程语言来抓取最新的A股交易数据,并通过数据分析技术为个人投资决策提供支持。
122 1
|
19天前
|
机器学习/深度学习 数据采集 算法
【Python篇】从零到精通:全面分析Scikit-Learn在机器学习中的绝妙应用
【Python篇】从零到精通:全面分析Scikit-Learn在机器学习中的绝妙应用
30 2
|
27天前
|
Python
Python sorted() 函数和sort()函数对比分析
Python sorted() 函数和sort()函数对比分析
|
29天前
|
数据采集 网络协议 调度
Python爬虫策略分析4
Python爬虫策略分析4
40 1
|
29天前
|
数据采集 前端开发 Python
Python爬虫策略分析3
Python爬虫策略分析3
17 1
|
29天前
|
数据采集 Python
Python爬虫策略分析1
Python爬虫策略分析1
14 1