1 from aip import AipSpeech,AipNlp # 导入nlp自然语言处理
 2 import time,os
 3 
 4 """ 你的 APPID AK SK """
 5 APP_ID = '15421138'
 6 API_KEY = 'eI4GfKPgA7EWgyZ0v09whgSA'
 7 SECRET_KEY = 'zmGBwnlAnHuTsWDHiHbzGgGS4ooBM7dn'
 8 
 9 nlp =  AipNlp(APP_ID, API_KEY, SECRET_KEY)
10 client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
11 
12 
13 # 读取文件
14 def get_file_content(filePath):
15     os.system(f"ffmpeg -y  -i {filePath} -acodec pcm_s16le -f s16le -ac 1 -ar 16000 {filePath}.pcm")
16     with open(f"{filePath}.pcm", 'rb') as fp:
17         return fp.read()
18 
19 
20 def audio2text(filepath):
21     # 识别本地文件,返回文字
22     res = client.asr(get_file_content(filepath), 'pcm', 16000, {
23         'dev_pid': 1536,
24     })
25 
26     print(res.get("result")[0])
27 
28     return res.get("result")[0]
29 
30 
31 def text2audio(text):
32     # 识别文字内容,转换为音频文件
33     filename = f"{time.time()}.mp3"
34     result = client.synthesis(text, 'zh', 1, {
35         'vol': 5,
36         "spd": 3,
37         "pit": 7,
38         "per": 4
39     })
40 
41     # 识别正确返回语音二进制 错误则返回dict 参照下面错误码
42     if not isinstance(result, dict):
43         with open(filename, 'wb') as f:
44             f.write(result)
45 
46     return filename
47 
48 
49 def to_tuling(text):
50     # 调用图灵机器人接口,对于提问做出回答
51     import requests
52 
53     args = {
54         "reqType": 0,
55         "perception": {
56             "inputText": {
57                 "text": text
58             }
59         },
60         "userInfo": {
61             "apiKey": "9a9a026e2eb64ed6b006ad99d27f6b9e",
62             "userId": "1111"
63         }
64     }
65 
66     url = "http://openapi.tuling123.com/openapi/api/v2"
67 
68     res = requests.post(url, json=args)
69 
70     text = res.json().get("results")[0].get("values").get("text")
71     return text
72 
73 # res = nlp.simnet("你叫什么名字","你的名字是什么")
74 # print(res)
75 
76 
77 text = audio2text("bjtq.wma")
78 # nlp自然语言处理,识别相似度
79 if nlp.simnet("你叫什么名字",text).get("score") >= 0.68 :
80     text = "我的名字叫梁慧"
81 else:
82     text = to_tuling(text)
83 
84 filename = text2audio(text)
85 
86 os.system(filename)