Przeglądaj źródła

讯飞智能回复

linhaohong 1 rok temu
rodzic
commit
e1750ee38f

+ 2 - 1
Ansjer/urls.py

@@ -25,7 +25,7 @@ from Controller import FeedBack, EquipmentOTA, EquipmentInfo, AdminManage, AppIn
     RegionController, VPGController, LanguageController, TestController, DeviceConfirmRegion, S3GetStsController, \
     DetectControllerV2, PcInfo, PctestController, DeviceDebug, PaymentCycle, \
     DeviceLogController, CouponController, AiController, ShadowController, AppAccountManagement, InitController, \
-    WeatherControl
+    WeatherControl, SmartReplyController
 from Controller.Cron import CronTaskController
 from Controller.MessagePush import EquipmentMessagePush
 from Controller.SensorGateway import SensorGatewayController, EquipmentFamilyController
@@ -272,6 +272,7 @@ urlpatterns = [
     re_path(r'^weather/(?P<operation>.*)$', WeatherControl.WeatherView.as_view()),
     re_path(r'^alexaApi/', include("Ansjer.server_urls.alexa_url")),
     re_path('appCampaign/(?P<operation>.*)', AppCampaignController.AppCampaignView.as_view()),
+    re_path('wsParam/(?P<operation>.*)', SmartReplyController.WsParamService.as_view()),
 
     # 后台界面接口 -------------------------------------------------------------------------------------------------------
     # 登录,用户信息,权限

+ 24 - 6
Object/WsParam/AIChatObject.py

@@ -70,10 +70,10 @@ class ChatClient:
             if choices["status"] == 2:
                 ws.close()
 
-    def on_error(self, error):
+    def on_error(self, ws, error):
         print(f"WebSocket error: {error}")
 
-    def on_close(self):
+    def on_close(self, ws):
         print("WebSocket connection closed")
 
     def on_open(self, ws):
@@ -114,11 +114,29 @@ class ChatClient:
         }
 
     def start(self):
-        websocket.enableTrace(False)
+        websocket.enableTrace(True)
         self.ws = websocket.WebSocketApp(self.create_url(),
                                          on_message=lambda ws, msg: self.on_message(ws, msg),
-                                         on_error=lambda msg: self.on_error(msg),
-                                         on_close=self.on_close,
-                                         on_open=lambda ws: self.on_open(ws))  # 使用 lambda 来确保 ws 参数传递
+                                         on_error=lambda ws, error: self.on_error(ws, error),
+                                         on_close=lambda ws: self.on_close(ws),
+                                         on_open=lambda ws: self.on_open(ws))
         self.ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
         return self.response
+
+
+if __name__ == "__main__":
+    appid = "fcff8f4b"
+    api_secret = "ZTU3NWMyNTI1MTI4NTU5ZGUxMDZhNmQ5"
+    api_key = "037571e7285e64e8dc321fa5b937fea2"
+    gpt_url = "wss://spark-api.xf-yun.com/v3.5/chat"
+    domain = "generalv3.5"
+    system = "现在扮演李白,你豪情万丈,狂放不羁;接下来请用李白的口吻和用户对话。"
+    query = "不好意思,你超过7步了,拖下去砍了。"
+    history = [
+        {"role": "user", "content": "你给我写一首诗,以兄弟为题不包含兄弟2字,七步内成诗,不行杀了你"},
+        {"role": "assistant",
+         "content": "君若问兄弟,我以诗代言。江山共长天,一脉同根源。风雨共行路,携手笑苍天。豪情万丈志,生死共肩连。肝胆相照映,此心永不偏。纵有千般难,并肩共前缘。人生如梦幻,唯愿共度年。此诗赠君子,兄弟情谊传。"},
+    ]
+    chat = ChatClient(appid, api_key, api_secret, gpt_url, domain, query, history, system)
+    response = chat.start()
+    print(response)

+ 2 - 1
Object/WsParam/WsParamRecognizeObject.py

@@ -16,6 +16,7 @@ import _thread as thread
 调用讯飞模型 语音转文字
 """
 
+
 class WsParamRecognize:
     STATUS_FIRST_FRAME = 0
     STATUS_CONTINUE_FRAME = 1
@@ -109,4 +110,4 @@ class WsParamRecognize:
                                          on_close=self.on_close,
                                          on_open=lambda ws: self.on_open(ws))
         self.ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
-        return self.all_sentences
+        return self.all_sentences

+ 9 - 9
Object/WsParam/WsParamSynthesizeObject.py

@@ -9,15 +9,15 @@ import ssl
 from wsgiref.handlers import format_date_time
 from datetime import datetime
 from time import mktime
-import _thread as thread
-
+import threading  # 使用更现代的threading代替_thread
 
 """
 调用讯飞模型 文字转语音 
 """
 
+
 class WsParamSynthesize:
-    def __init__(self, APPID, APIKey, APISecret, Text):
+    def __init__(self, APPID, APIKey, APISecret, Text, AudioType="pcm"):
         self.APPID = APPID
         self.APIKey = APIKey
         self.APISecret = APISecret
@@ -26,7 +26,11 @@ class WsParamSynthesize:
 
         # 初始化其他需要的属性
         self.CommonArgs = {"app_id": self.APPID}
-        self.BusinessArgs = {"aue": "lame", "auf": "audio/L16;rate=16000", "vcn": "xiaoyan", "tte": "utf8", "sfl": 1}
+        if AudioType == "mp3":
+            self.BusinessArgs = {"aue": "lame", "auf": "audio/L16;rate=16000", "vcn": "xiaoyan", "tte": "utf8",
+                                 "sfl": 1}
+        else:
+            self.BusinessArgs = {"aue": "raw", "auf": "audio/L16;rate=16000", "vcn": "xiaoyan", "tte": "utf8"}
         self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode('utf-8')), "UTF8")}
 
     def create_url(self):
@@ -55,10 +59,6 @@ class WsParamSynthesize:
         }
         # 拼接鉴权参数,生成url
         url = url + '?' + urlencode(v)
-        # print("date: ",date)
-        # print("v: ",v)
-        # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
-        # print('websocket url :', url)
         return url
 
     def on_message(self, ws, message):
@@ -95,7 +95,7 @@ class WsParamSynthesize:
             d = json.dumps(d)
             ws.send(d)
 
-        thread.start_new_thread(run, ())
+        threading.Thread(target=run).start()  # 使用threading.Thread以提供更好的线程管理
 
     def start(self):
         websocket.enableTrace(False)