bot.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  1. #!/usr/bin/env python3
  2. # encoding:utf-8
  3. import ctypes
  4. import os
  5. import time
  6. import json
  7. import wave
  8. import queue
  9. import threading
  10. import traceback
  11. import sys
  12. import pjsua2 as pj
  13. from enum import Enum
  14. from datetime import datetime
  15. from multiprocessing import Process
  16. from apscheduler.schedulers.background import BackgroundScheduler
  17. from src.core.callcenter import registry
  18. from src.core.callcenter.cache import Cache
  19. from src.core.callcenter.enumeration import HangupDir
  20. from src.core.datasource import SIP_SERVER, SERVE_HOST
  21. from src.core.voip.constant import *
  22. import requests
  23. from src.core.callcenter.api import BotChatRequest,ChatMessage
  24. from src.core import singleton_keys
  25. from src.core.callcenter.snowflake import Snowflake
  26. from src.core.callcenter.data_handler import *
  27. calls = {}
  28. # recording_file = '/code/src/core/voip/incoming_call.wav'
  29. # player_file1 = '/code/src/core/voip/test111.wav'
  30. # player_file2 = '/code/src/core/voip/test222.wav'
  31. from src.core.voip.asr import TestSt, XfAsr
  32. class BotStatus(Enum):
  33. # 等待用户讲话,未超时
  34. wait_speaking_not_timeout = 1
  35. # 等待用户讲话,已超时但用户仍在持续讲话
  36. wait_speaking_timeout_user_speaking = 2
  37. # 机器人讲话过程中
  38. speaking = 3
  39. # 等待用户讲话结束
  40. wait_user_speaking_end = 4
  41. # 等待大模型输出
  42. wait_gpt_return = 5
  43. class UserStatus(Enum):
  44. # ASR返回值为sentenceBegin后将状态置为Speaking
  45. speaking = 1
  46. # ASR返回值为sentenceEnd后,将状态置为Silence
  47. silence = 2
  48. class MyAudioMediaPort(pj.AudioMediaPort):
  49. def __init__(self, call, audio_media=None, asr=None):
  50. pj.AudioMediaPort.__init__(self)
  51. # # 打开一个 .pcm 文件来保存音频流(可选:保存为 .wav)
  52. # self.wav = wave.open(f"{recording_file}", "wb")
  53. # self.wav.setnchannels(1)
  54. # self.wav.setsampwidth(2) # 假设每个样本是 16 位(2 字节)
  55. # self.wav.setframerate(16000)
  56. print("MyAudioMediaPort::come in, debugger")
  57. self.call = call
  58. self.audio_media = audio_media
  59. self.asr = asr
  60. self.first = True
  61. self.counter = 0
  62. self.user_asr_texts = []
  63. def onFrameRequested(self, frame):
  64. print("Request audio frame:", frame)
  65. def onFrameReceived(self, frame):
  66. # self.wav.writeframes(bytes(frame.buf))
  67. if self.asr: # 如果ASR实例存在,则发送音频数据
  68. if self.first:
  69. self.first = False
  70. self.call.logger.warn("Received audio frame: %s, %s, %s", self.call.session_id,frame.buf,frame.size)
  71. if self.counter % 200 ==0:
  72. self.call.logger.warn("Received audio frame: %s, %s, %s", self.call.session_id, frame.buf, frame.size)
  73. self.counter += 1
  74. self.asr.send_audio(frame.buf)
  75. try:
  76. asr_text = self.get_asr_text()
  77. play_complete = self.call.is_play_complete()
  78. current_time = time.time() # 实时当前时间
  79. if self.call.inputType == '1.0':
  80. time_difference = int(current_time - self.call.inputLongStart)
  81. # print('current_time - self.call.inputLongStart:',time_difference > 35, self.call.txtLock , play_complete)
  82. if time_difference > 35 and play_complete:
  83. self.user_asr_texts.append(f"DTMF({self.call.digit})DTMF")
  84. user_asr_text = self.user_asr_texts[0] if len(self.user_asr_texts) == 1 else '###'.join(self.user_asr_texts)
  85. self.user_asr_texts.clear()
  86. self.call.chat(user_asr_text)
  87. # print("测试超长", user_asr_text)
  88. elif asr_text:
  89. self.user_asr_texts.append(asr_text)
  90. user_asr_text = self.user_asr_texts[0] if len(self.user_asr_texts) == 1 else '###'.join(self.user_asr_texts)
  91. self.user_asr_texts.clear()
  92. self.call.chat(user_asr_text)
  93. if time_difference > int(self.call.wait_time):
  94. self.call.reset_wait_time()
  95. else:
  96. if asr_text and not play_complete:
  97. self.user_asr_texts.append(asr_text)
  98. if (asr_text and play_complete) or (play_complete and self.user_asr_texts):
  99. if asr_text:
  100. self.user_asr_texts.append(asr_text)
  101. user_asr_text = self.user_asr_texts[0] if len(self.user_asr_texts) == 1 else '###'.join(self.user_asr_texts)
  102. self.user_asr_texts.clear()
  103. self.call.chat(user_asr_text)
  104. if self.call.wait_time and self.call.wait_time != "0" and play_complete and not asr_text:
  105. self.call.wait_time_check(current_time, self.call.wait_time)
  106. message_queue_size = self.call.message_queue.qsize()
  107. if (message_queue_size > 0 and not self.call.cur_player_file) or (message_queue_size > 0 and play_complete):
  108. # self.call.logger.info('onFrameReceived:message_queue_size=', message_queue_size, 'play_complete=', play_complete, asr_text)
  109. self.call.cur_player_file, self.call.wait_time, self.call.inputType,self.call.action, self.call.node_id = self.get_player_file()
  110. # 重置播放完成标志和超时计时器,确保新的播放从头开始计时
  111. self.call.reset_wait_time()
  112. self.call.send_bot_speaker(self.call.cur_player_file)
  113. except:
  114. pass
  115. def get_asr_text(self):
  116. try:
  117. asr_text = self.call.user_asr_text_queue.get(block=False)
  118. self.call.logger.info('get_asr_text: %s', asr_text)
  119. return asr_text
  120. except:
  121. pass
  122. def get_player_file(self):
  123. try:
  124. message = self.call.message_queue.get(block=False)
  125. player_file = [item.voice_url for item in message.contents if item.content_type == 'voice']
  126. return player_file, message.wait_time, message.inputType, message.action, message.node_id
  127. except Exception as e:
  128. traceback.print_exc()
  129. class MyAudioMediaPlayer(pj.AudioMediaPlayer):
  130. def __init__(self, player_id, sink, on_complete=None):
  131. pj.AudioMediaPlayer.__init__(self)
  132. self.player_id = player_id
  133. self.sink = sink
  134. self.on_complete = on_complete
  135. def onEof2(self):
  136. # self.stopTransmit(self.sink)
  137. if self.on_complete:
  138. self.on_complete(self.player_id)
  139. # Subclass to extend the Account and get notifications etc.
  140. class Account(pj.Account):
  141. def __init__(self, agent, user_part, **kwargs):
  142. pj.Account.__init__(self)
  143. self.agent = agent
  144. self.user_part = user_part
  145. self.calls = {}
  146. self.kwargs = kwargs
  147. def onRegState(self, prm):
  148. ai = self.getInfo()
  149. print("***OnRegState: " + prm.reason, ai.id,ai.isDefault,ai.uri,ai.regIsConfigured,ai.regIsActive,ai.regExpiresSec,ai.regStatus,ai.regStatusText,ai.regLastErr,ai.onlineStatus,ai.onlineStatusText)
  150. def onIncomingCall(self, prm):
  151. # self.agent.logger.info("daviddebugger::onIncomingCall::%s ", prm.callId)
  152. ai = self.getInfo()
  153. print("***onIncomingCall: ", prm.callId, ai.id,ai.isDefault,ai.uri,ai.regIsConfigured,ai.regIsActive,ai.regExpiresSec,ai.regStatus,ai.regStatusText,ai.regLastErr,ai.onlineStatus,ai.onlineStatusText)
  154. call = MyCall(self.agent, self, self.user_part, prm.callId, **self.kwargs)
  155. call_op_param = pj.CallOpParam(True)
  156. call_op_param.statusCode = pj.PJSIP_SC_OK
  157. call.answer(call_op_param)
  158. self.calls[prm.callId] = call
  159. class MyCall(pj.Call):
  160. def __init__(self, agent, acc, user_part, call_id, **kwargs):
  161. pj.Call.__init__(self, acc, call_id)
  162. self.agent = agent
  163. self.logger = agent.logger
  164. self.user_part = user_part
  165. self.call_id = call_id
  166. self.kwargs = kwargs
  167. self.audio_media = None
  168. self.audio_port = None
  169. self.audio_player = None
  170. self.asr = None
  171. self.session_id = kwargs.get('variable_sip_h_P-LIBRA-CallId')
  172. self.device_id = kwargs.get('variable_sip_h_P-LIBRA-DeviceId')
  173. self.call_phone = kwargs.get("Caller-Caller-ID-Number")
  174. self.logger.info("daviddebugger::self.session_id:%s, self.call_phone:%s", self.session_id,self.call_phone)
  175. self.taskId = "10001"
  176. # self.scripts = build_demo_script()
  177. self.user_asr_text_queue = queue.Queue(maxsize=100)
  178. self.message_queue = queue.Queue(maxsize=3)
  179. self.player_complete_dict = {}
  180. self.wait_time = None
  181. self.inputType = None #记录按键类型 1为长按键类型
  182. self.digit = '' # 存储长按键内容
  183. self.action = None
  184. self.node_id= 'start'
  185. self.cur_player_file = None #当前播放的文件
  186. # self.asr = TestSt(self.session_id, logger=self.logger, message_receiver=self.on_receiver_asr_result) # 创建ASR实例
  187. self.asr = XfAsr(self.session_id, logger=self.logger, message_receiver=self.on_receiver_asr_result) # 创建ASR实例
  188. self.asr.start() # 启动ASR线程
  189. self.start_time = time.time() # 当前机器人对话开始时间
  190. # 超时设置
  191. self.play_start_time = time.time() # 倒计时开始时间
  192. self.play_complete_flag = False # 倒计时开始标志
  193. self.txtLock = False
  194. self.inputLongStart = time.time() #长按键开始时间
  195. self.inter_action_total = 0
  196. self.statistics_lock = False
  197. def wait_time_check(self, current_time, wait_time):
  198. try:
  199. # 确保 wait_time 是整数类型
  200. wait_time = int(wait_time)
  201. # 如果播放尚未完成,重置标志并返回
  202. if not self.play_complete_flag:
  203. self.play_complete_flag = True
  204. self.play_start_time = current_time
  205. # print(f"开始计时: {self.play_start_time}")
  206. elapsed_time = int(current_time - self.play_start_time)
  207. # print(f"当前时间: {current_time}, 已过时间: {elapsed_time}, 最大等待时间: {wait_time}")
  208. if elapsed_time > wait_time:
  209. # self.user_asr_text_queue.put("ASR408error")
  210. self.chat('ASR408error')
  211. registry.BOT_ASR_408.labels(self.taskId).inc()
  212. self.reset_wait_time()
  213. except ValueError as e:
  214. self.logger.info(f"无效的等待时间参数: {wait_time}, 错误: {e}")
  215. self.reset_wait_time()
  216. def reset_wait_time(self):
  217. self.play_complete_flag = False # 重置播放完成标志
  218. self.play_start_time = None # 重置开始计时时间
  219. def is_play_complete(self): #语音机器人是否播放结束
  220. if self.cur_player_file:
  221. player_id = murmur3_32(self.cur_player_file)
  222. return self.player_complete_dict.get(player_id)
  223. def onDtmfDigit(self, prm):
  224. # 判断是否播放完成 否则不记录用户说的内容
  225. if not self.is_play_complete():
  226. return
  227. digit = prm.digit
  228. self.reset_wait_time()
  229. # 假设为超长类型按键 把用户输入的按键进行拼接 如果为# 则把用户输入所有按键放入队列并发送文本机器人
  230. # 如果为非正常按键服务 输入以后直接发送文本机器人
  231. if self.inputType == '1.0':
  232. if digit != '#':
  233. self.digit += digit
  234. elif digit == '#':
  235. # self.user_asr_text_queue.put(f"DTMF({self.digit})DTMF")
  236. self.chat(f"DTMF({self.digit})DTMF")
  237. else:
  238. self.user_asr_text_queue.put(f"DTMF({digit})DTMF")
  239. def onCallState(self, prm):
  240. call_info = self.getInfo()
  241. # pj.PJSIP_INV_STATE_NULL
  242. # pj.PJSIP_INV_STATE_CALLING
  243. # pj.PJSIP_INV_STATE_INCOMING
  244. # pj.PJSIP_INV_STATE_EARLY
  245. # pj.PJSIP_INV_STATE_CONNECTING
  246. # pj.PJSIP_INV_STATE_CONFIRMED
  247. # pj.PJSIP_INV_STATE_DISCONNECTED
  248. self.logger.info("daviddebugger::onCallState::[%s,%s] %s", pj.PJSIP_INV_STATE_CONFIRMED, pj.PJSIP_INV_STATE_DISCONNECTED, call_info.state)
  249. if call_info.state == pj.PJSIP_INV_STATE_CONFIRMED:
  250. # 当呼叫状态为已确认(即接通)
  251. self.bot_say_hello()
  252. if call_info.state == pj.PJSIP_INV_STATE_DISCONNECTED:
  253. self.logger.info("通话结束:%s", self.user_part)
  254. self.release()
  255. def onCallMediaState(self, prm):
  256. call_info = self.getInfo()
  257. # print("Call Media state: ", call_info.stateText)
  258. for media in call_info.media:
  259. if media.type == pj.PJMEDIA_TYPE_AUDIO and \
  260. (media.status == pj.PJSUA_CALL_MEDIA_ACTIVE):
  261. self.logger.info("Call Media state 111: %s", call_info.stateText)
  262. self.audio_media = self.getAudioMedia(media.index)
  263. try:
  264. # 建立双向通道
  265. self.receive_user_speaker()
  266. # self.bot_say_hello()
  267. except Exception as e:
  268. traceback.print_exc()
  269. def receive_user_speaker(self):
  270. self.audio_port = MyAudioMediaPort(self, self.audio_media, self.asr)
  271. self.audio_port.createPort("Incoming Call Port", build_audio_format())
  272. self.audio_media.startTransmit(self.audio_port)
  273. def send_bot_speaker(self, player_file):
  274. if not player_file :
  275. return
  276. if not self.isActive():
  277. return
  278. player_id = murmur3_32(player_file)
  279. self.player_complete_dict[player_id] = False
  280. for f in player_file:
  281. if not os.path.isfile(f):
  282. self.logger.info(f"Sending bot speaker, not exists, player_file: {player_file}, player_id: {player_id}, isActive: {self.isActive()}")
  283. return
  284. key = murmur3_32(str(datetime.now().timestamp()))
  285. self.agent.call_players[key] = [datetime.now().timestamp()]
  286. # print('self.player_complete_dict[player_id]D:', player_id, player_file, self.player_complete_dict[player_id])
  287. self.logger.info(f"Sending bot speaker, 111, player_file: {player_file}, player_id: {player_id}, isActive: {self.isActive()}")
  288. self.audio_player = MyAudioMediaPlayer(player_id, self.audio_media, on_complete=self.on_media_player_complete)
  289. if len(player_file) == 1:
  290. self.logger.info(f"Sending bot speaker, 222, player_file: {player_file}, player_id: {player_id}, isActive: {self.isActive()}")
  291. self.audio_player.createPlayer(player_file[0], pj.PJMEDIA_FILE_NO_LOOP)
  292. else:
  293. self.logger.info(f"Sending bot speaker, 333, player_file: {player_file}, player_id: {player_id}, isActive: {self.isActive()}")
  294. self.audio_player.createPlaylist(player_file, f'my_hello_playlist{player_id}', pj.PJMEDIA_FILE_NO_LOOP)
  295. self.logger.info(f"Sending bot speaker, 444, player_file: {player_file}, player_id: {player_id}, isActive: {self.isActive()}")
  296. self.audio_player.startTransmit(self.audio_media)
  297. self.agent.call_players[key].append(datetime.now().timestamp())
  298. def on_receiver_asr_result(self, message, *args):
  299. # 判断是否播放完成 否则不记录用户说的内容
  300. if not self.is_play_complete():
  301. return
  302. # self.logger.info("on_receiver_asr_result:message: %s", message)
  303. if message["name"] == "SentenceEnd":
  304. self.user_asr_text_queue.put(message["result"])
  305. elif message["name"] == "TranscriptionResultChanged":
  306. self.reset_wait_time()
  307. elif message["name"] == "TranscriptionResultError":
  308. pass
  309. # message = json.loads(message)
  310. # if message["header"]["status"] == 20000000:
  311. # if message["header"]["name"] == "SentenceEnd":
  312. # result = message["payload"]["result"]
  313. # # self.logger.info("asr返回内容Result:%s", result)
  314. # self.user_asr_text_queue.put(result)
  315. # elif message["header"]["name"] == "TranscriptionResultChanged":
  316. # self.reset_wait_time()
  317. # else:
  318. # self.logger.info(f"Status is not {message['header']['status']}")
  319. # registry.ASR_ERRORS.labels(message['header']['status']).inc()
  320. def on_media_player_complete(self, player_id):
  321. self.logger.info('player complete')
  322. self.player_complete_dict[player_id] = True
  323. self.digit = ''
  324. self.inputLongStart = time.time()
  325. #播放完毕执行的动作
  326. self.say_end_action(self.action)
  327. def bot_say_hello(self):
  328. self.chat(user_asr_text="start")
  329. def chat(self, user_asr_text=None):
  330. # 调用文本机器人接口
  331. ToTextBotAgent(user_asr_text,self)
  332. def say_end_action(self, action):
  333. self.logger.info('handling_release %s', action.action_code)
  334. action_code = action.action_code
  335. if action_code == 'hang': # 挂断
  336. self.agent.hangup(self.user_part)
  337. self.end_statistics()
  338. # 更新通话记录
  339. self.agent.dataHandleServer.update_record(self.session_id, hangup_dir=HangupDir.ROBOT_HANGUP.code)
  340. elif action_code == 'transfer': # 转人工
  341. self.agent.transfer(user_part=self.user_part, call_id=self.session_id, device_id=self.device_id)
  342. self.end_statistics()
  343. #更新通话记录
  344. self.agent.dataHandleServer.update_record(self.session_id, service_category=2)
  345. def end_statistics(self):
  346. if not self.statistics_lock:
  347. self.statistics_lock = True
  348. self.logger.info(f"self.inter_action_total:{self.inter_action_total}")
  349. latency = (time.time() - self.start_time)
  350. registry.BOT_CALL_DURATION.labels(self.taskId).observe(latency)
  351. registry.BOT_INTERACTION_ROUNDS.labels(self.taskId).observe(self.inter_action_total)
  352. def release(self):
  353. self.logger.info('liuwei::debugger::release:: come in ')
  354. if self.audio_player:
  355. try:
  356. self.audio_player.stopTransmit(self.audio_media)
  357. print("Success to stopTransmit:")
  358. except pj.Error as e:
  359. print("Failed to stopTransmit:", e)
  360. self.audio_player = None # 或调用播放器停止方法
  361. if self.audio_port:
  362. try:
  363. self.audio_media.stopTransmit(self.audio_port)
  364. print("Success to stopTransmit:")
  365. except pj.Error as e:
  366. print("Failed to stopTransmit:", e)
  367. self.audio_port = None # 或调用相关销毁方法
  368. if self.audio_media:
  369. # self.audio_media.stopTransmit()
  370. self.audio_media = None
  371. self.asr.close()
  372. # 远程挂机之后要将分机号回收
  373. self.agent.hangup(self.user_part)
  374. # self.agent.release(self.user_part)
  375. self.end_statistics()
  376. class ToTextBotAgent:
  377. def __init__(self, user_asr_text, call_agent):
  378. if not user_asr_text or (call_agent.action and call_agent.action.action_code != 'normal'):
  379. # print("ASR文本为空,终止执行。")
  380. return
  381. self.call_agent = call_agent
  382. self.request_data = BotChatRequest(
  383. nodeId=self.call_agent.node_id,
  384. userId=self.call_agent.call_phone,
  385. sessionId= self.call_agent.session_id,
  386. recordId="",
  387. taskId=self.call_agent.taskId,
  388. asrText=user_asr_text,
  389. ext= None
  390. )
  391. self.call_agent.logger.info("user_asr_text发送结果: %s", user_asr_text)
  392. if user_asr_text != 'ASR408error':
  393. self.call_agent.inter_action_total += 1
  394. # 发送请求并处理响应
  395. self.to_request(self.request_data)
  396. # self.to_quest(self.request_data)
  397. def to_request(self, request: BotChatRequest, try_count = 3):
  398. start_time = time.time()
  399. request_data = request.to_json_string()
  400. response_data = None
  401. try:
  402. message = None
  403. url = f"http://{SERVE_HOST}:40072/botservice"
  404. headers = {"Content-Type": "application/json"}
  405. while try_count > 0:
  406. once_start = time.time()
  407. try:
  408. response = requests.post(url, data=request_data, headers=headers, timeout=3)
  409. if response and response.ok:
  410. response_data = response.json()
  411. if "data" in response_data and response_data["code"] == 0:
  412. data = response_data["data"]
  413. message = ChatMessage.from_json(data)
  414. self.call_agent.message_queue.put(message)
  415. break
  416. else:
  417. self.call_agent.logger.info(f"to_request::failed, sessionId={request.sessionId}, response_data:{response_data}")
  418. else:
  419. self.call_agent.logger.info(f"to_request::请求失败,sessionId:{request.sessionId}, 状态码: {response.status_code if response else None}, 响应内容: {response.text if response else None}")
  420. except Exception as e:
  421. traceback.print_exc()
  422. self.call_agent.logger.error(f"to_request::exception, TaskId={request.taskId}, sessionId={request.sessionId}, 请求发生异常: {e}")
  423. finally:
  424. try_count = try_count - 1
  425. latency = (time.time() - once_start)
  426. registry.BOT_REQUEST_ONCE_LATENCY.labels(request.taskId).observe(latency)
  427. if not message:
  428. massage = self.get_default_response()
  429. self.call_agent.message_queue.put(massage)
  430. finally:
  431. latency = (time.time() - start_time)
  432. registry.BOT_REQUEST_COUNT.inc()
  433. registry.BOT_REQUEST_LATENCY.labels(request.taskId).observe(latency)
  434. self.call_agent.logger.info(f"to_request sessionId={self.call_agent.session_id}, timeCost={latency}, request:{request_data}, response:{response_data if response_data else None}")
  435. # def to_quest(self, request: BotChatRequest, try_count = 3):
  436. # start_time = time.time()
  437. # request_data = request.to_json_string()
  438. # response = None
  439. # try:
  440. # url = f"http://{SERVE_HOST}:40072/botservice"
  441. # # payload = request.to_json_string()
  442. # # self.call_agent.logger.info(f"请求数据:{request_data},url:{url}")
  443. # with requests.Session() as session:
  444. # message = None
  445. # # try:
  446. # session.headers.update({'Content-Type': 'application/json'})
  447. # while try_count > 0:
  448. # once_start = time.time()
  449. # try:
  450. # response = session.post(url=url, json=request_data, timeout=3)
  451. # # response = requests.post(url=url, json=json.loads(request_data), headers=headers, timeout=10) # 使用占位URL
  452. # # self.call_agent.logger.info("to_request come in , try_count=%s", try_count)
  453. # if response.status_code == 200:
  454. # response_data = response.json()
  455. # if "data" in response_data and response_data["code"]==0:
  456. # data = response_data["data"]
  457. # message = ChatMessage.from_json(data)
  458. # self.call_agent.message_queue.put(message)
  459. # break
  460. # else:
  461. # self.call_agent.logger.info(f"to_request::sessionId:{request.sessionId}, 响应中没有 'data' 字段")
  462. # else:
  463. # self.call_agent.logger.info(f"to_request::请求失败,sessionId:{request.sessionId}, 状态码: {response.status_code}, 响应内容: {response.text}")
  464. # except Exception as e:
  465. # traceback.print_exc()
  466. # self.call_agent.logger.error(f"to_request::TaskId={request.taskId}, sessionId={request.sessionId}, 请求发生异常: {e}, URL: {url}")
  467. # finally:
  468. # try_count = try_count - 1
  469. # latency = (time.time() - once_start)
  470. # registry.BOT_REQUEST_ONCE_LATENCY.labels(request.taskId).observe(latency)
  471. #
  472. # self.call_agent.logger.info(f"to_request::sessionId:{request.sessionId}, message:{message.to_json_string() if message else None}")
  473. # if not message:
  474. # message = self.get_default_response()
  475. # self.call_agent.message_queue.put(message)
  476. # # finally:
  477. # # session.close()
  478. # finally:
  479. # latency = (time.time() - start_time)
  480. # registry.BOT_REQUEST_COUNT.inc()
  481. # registry.BOT_REQUEST_LATENCY.labels(request.taskId).observe(latency)
  482. # self.call_agent.logger.info(f"to_request::sessionId={ self.call_agent.session_id}, timeCost={latency}, request:{request_data}, response:{response.text if response else None}")
  483. def get_default_response(self):
  484. response= {
  485. "node_id": "99.00",
  486. "contents": [
  487. {
  488. "content_type": "voice",
  489. "content": "正在为您转接人工服务,请稍后",
  490. "voice_url": "/root/aibot/dm/voice/transfer.wav",
  491. "voice_content": ""
  492. }
  493. ],
  494. "wait_time": 1,
  495. "action": {
  496. "action_code": "transfer",
  497. "action_content": "转人工"
  498. },
  499. "inputType": "0"
  500. }
  501. parsed_response = ChatMessage.from_json(response)
  502. return parsed_response
  503. @singleton_keys
  504. class BotAgent:
  505. def __init__(self, app, user_part_range=range(1001, 1011), host=SIP_SERVER, port="5060", password="slibra@#123456"):
  506. self.app = app
  507. self.logger = app.logger
  508. self.user_part_range, self.host, self.port, self.password = user_part_range, host, port, password
  509. self.user_part_pool = queue.Queue(maxsize=len(user_part_range))
  510. self.accounts = {}
  511. self.calls = {}
  512. self.call_players={}
  513. self.ep = pj.Endpoint()
  514. self.daemon_stopping = False
  515. self.is_stopping = False
  516. self.counter = 0
  517. self.acd_service = None
  518. self.cache = Cache(app)
  519. self.dataHandleServer = DataHandleServer(app)
  520. self.pjsua_thread = None
  521. self._start()
  522. # threading.Thread(target=self.main_thread_daemon).start()
  523. self.daemon_job_scheduler = BackgroundScheduler()
  524. self.daemon_job_scheduler.add_job(self._main_thread_daemon, 'interval', seconds=1, max_instances=1, name='bot_agent_daemon')
  525. self.daemon_job_scheduler.start()
  526. def _create_pjsua2(self, timeout_sec=86400):
  527. start_time = time.time()
  528. try:
  529. self.cache.set_register_per_hours(expire=timeout_sec - (60*3))
  530. # Create and initialize the library
  531. ep_cfg = pj.EpConfig()
  532. ep_cfg.uaConfig.threadCnt = 4
  533. ep_cfg.uaConfig.mainThreadOnly = False
  534. ep_cfg.uaConfig.maxCalls = 12
  535. ep_cfg.uaConfig.maxAccounts = 12
  536. ep_cfg.medConfig.noVad = True
  537. ep_cfg.logConfig.level = 3
  538. ep_cfg.logConfig.consoleLevel = 3
  539. self.ep.libCreate()
  540. self.ep.libInit(ep_cfg)
  541. aud_dev_mgr = self.ep.audDevManager()
  542. aud_dev_mgr.setNullDev() # 使用虚拟音频设备(如果没有实际设备)
  543. # Set up media configuration, particularly jitter buffer
  544. media_cfg = pj.MediaConfig()
  545. media_cfg.jbMinPre = 4 # Minimum pre-fetch frames
  546. media_cfg.jbMaxPre = 16 # Maximum pre-fetch frames
  547. media_cfg.noVad = True # Disable Voice Activity Detection if needed
  548. media_cfg.clockRate = 16000
  549. media_cfg.channelCount = 1
  550. media_cfg.audioFramePtime = 40
  551. # media_cfg.ptime = 40
  552. # media_cfg.clockRate = 8000
  553. self.ep.medConfig = media_cfg # Apply media config to endpoint
  554. # Create SIP transport. Error handling sample is shown
  555. sipTpConfig = pj.TransportConfig()
  556. sipTpConfig.port = 30506
  557. self.ep.transportCreate(pj.PJSIP_TRANSPORT_UDP, sipTpConfig)
  558. # Start the library
  559. self.ep.libStart()
  560. for user_part in self.user_part_range:
  561. acfg = pj.AccountConfig()
  562. acfg.idUri = f"sip:{user_part}@{self.host}:{self.port}"
  563. acfg.regConfig.registrarUri = f"sip:{self.host}:{self.port}"
  564. cred = pj.AuthCredInfo("digest", "*", f"{user_part}", 0, self.password)
  565. acfg.sipConfig.authCreds.append(cred)
  566. acfg.regConfig.timeoutSec = timeout_sec # 注册超时时间(秒)
  567. acfg.regConfig.retryIntervalSec = 10 # 重试间隔时间(秒)
  568. acfg.regConfig.firstRetryIntervalSec = 10 # 首次重试间隔时间(秒)
  569. acfg.natConfig.iceEnabled = True
  570. acfg.natConfig.turnEnabled = True
  571. acfg.natConfig.turnServer = f"stun:{self.host}:3478"
  572. # acfg.natConfig.turnUsername = "username"
  573. # acfg.natConfig.turnPassword = "password"
  574. acfg.natConfig.udpKaIntervalSec = 30
  575. acfg.natConfig.contactRewriteUse = 2
  576. acfg.natConfig.sdpNatRewriteUse = 2
  577. # Create the account
  578. acc = Account(self, user_part=user_part)
  579. acc.create(acfg)
  580. self.user_part_pool.put(user_part)
  581. self.accounts[user_part] = acc
  582. except:
  583. traceback.print_exc()
  584. finally:
  585. latency = time.time() - start_time
  586. registry.BOT_CREATE_ACCOUNT_LATENCY.observe(latency)
  587. self.logger.info("create pjsua latency: %.3fs", latency)
  588. while not self.is_stopping:
  589. registry.BOT_AGENT_LIVES.set(self.user_part_pool.qsize())
  590. self.ep.libHandleEvents(200)
  591. self.call_players.clear()
  592. self.accounts.clear()
  593. self.calls.clear()
  594. # Destroy the library
  595. self.ep.libDestroy()
  596. self.logger.info("create pjsua already shutdown")
  597. def _main_thread_daemon(self):
  598. # while not self.daemon_stopping:
  599. _lock = self._play_complete_degree_check()
  600. if _lock:
  601. self.logger.error("daviddebugger::play time greater than 60s, will restart")
  602. self.restart()
  603. return
  604. _lock = self.cache.get_pjsua_thread_lock()
  605. if _lock:
  606. self.cache.del_pjsua_thread_lock()
  607. self.logger.error("daviddebugger::thread is lock, will restart")
  608. self.restart()
  609. return
  610. _lock = self.cache.lock_register_per_hours()
  611. if not _lock and len(self.accounts) == len(self.user_part_range):
  612. self.logger.error("daviddebugger::register expire, will restart")
  613. self.restart()
  614. return
  615. # time.sleep(0.1)
  616. def _play_complete_degree_check(self):
  617. for k, v in list(self.call_players.items()):
  618. if len(v) == 2:
  619. self.call_players.pop(k)
  620. continue
  621. if len(v) == 1:
  622. sec = datetime.now().timestamp() - v[0]
  623. self.logger.info("daviddebugger::play_complete_degree_check, sec=%s", sec)
  624. if sec > 10:
  625. return True
  626. return False
  627. def transfer(self, user_part, call_id, device_id, service_id='00000000000000000'):
  628. if self.acd_service:
  629. self.acd_service.transfer_to_agent(call_id, device_id, service_id, hold=True)
  630. # sip_headers = {'P-LIBRA-HangUpReason': 'transferToAgent', 'P-LIBRA-ServiceId': service_id}
  631. try_count = 30
  632. while try_count >0:
  633. if self.cache.get_after_play_hold_music(call_id):
  634. self.hangup(user_part)
  635. break
  636. try_count = try_count - 1
  637. time.sleep(0.1)
  638. def hangup(self, user_part, reason="NORMAL_CLEARING", **sip_headers):
  639. call_op_param = pj.CallOpParam(True)
  640. call_op_param.statusCode = pj.PJSIP_SC_OK
  641. call_op_param.reason = reason
  642. call_op_param.txOption = pj.SipTxOption()
  643. sip_header_vector = pj.SipHeaderVector()
  644. for k, v in sip_headers.items():
  645. _sip_header = pj.SipHeader()
  646. _sip_header.hName = str(k)
  647. _sip_header.hValue = str(v)
  648. self.logger.info('hangup, header_name=%s, header_value=%s'%(k, v))
  649. sip_header_vector.push_back(_sip_header)
  650. call_op_param.txOption.headers = sip_header_vector
  651. try:
  652. acc = self.accounts.get(user_part)
  653. if acc:
  654. for k, v in list(acc.calls.items()):
  655. self.logger.info('hangup, call_idx=%s, call_active=%s'%(k, v.isActive()))
  656. if v.isActive():
  657. v.hangup(call_op_param)
  658. acc.calls.clear()
  659. except:
  660. traceback.print_exc()
  661. finally:
  662. # 机器人主动挂机回收分机号
  663. self.release(user_part)
  664. def register(self, **kwargs):
  665. self.logger.info('register,come in, pool.size :%d', self.user_part_pool.qsize())
  666. user_part = self.user_part_pool.get()
  667. acc = self.accounts.get(user_part)
  668. self.logger.info('register, user_part :%d, pool.size :%d', user_part, self.user_part_pool.qsize())
  669. if acc:
  670. self.logger.info('register==========> %s', acc.getId())
  671. # ps = pj.PresenceStatus()
  672. # ps.status = pj.PJSUA_BUDDY_STATUS_ONLINE
  673. # ps.activity = pj.PJRPID_ACTIVITY_AWAY
  674. # ps.note = "Away"
  675. # acc.setOnlineStatus(ps)
  676. # acc.setRegistration(renew=True)
  677. acc.kwargs = kwargs
  678. return user_part
  679. def unregister(self, user_part):
  680. acc = self.accounts.get(user_part)
  681. if acc:
  682. acc.setRegistration(renew=False)
  683. # 用户远程挂机回收分机号
  684. self.release(user_part)
  685. def release(self, user_part):
  686. if not user_part:
  687. self.logger.info("release, user_part is None")
  688. return
  689. def element_in_queue(q, element):
  690. with q.mutex: # 确保线程安全
  691. for item in list(q.queue): # 将队列转换为列表进行遍历
  692. if item == element:
  693. return True
  694. return False
  695. if element_in_queue(self.user_part_pool, user_part):
  696. self.logger.info("release, already exists, user_part :%d, pool.size :%d", user_part, self.user_part_pool.qsize())
  697. return
  698. self.user_part_pool.put(user_part)
  699. self.logger.info("release, user_part :%d, pool.size :%d", user_part, self.user_part_pool.qsize())
  700. def _start(self):
  701. self.is_stopping = False
  702. self.counter += 1
  703. self.pjsua_thread = threading.Thread(name=f"PJSUA-THREAD-{self.counter}", target=self._create_pjsua2, daemon=True)
  704. self.pjsua_thread.start()
  705. self.logger.info("bot agent starting ...")
  706. def restart(self):
  707. self.destroy()
  708. self.logger.info('restart, 22222')
  709. self._start()
  710. # threading.Thread(target=self.create_pjsua2, daemon=True).start()
  711. def destroy(self):
  712. self.is_stopping = True
  713. self.logger.info("destroy, come in 11111")
  714. try:
  715. while not self.user_part_pool.empty():
  716. self.user_part_pool.get_nowait()
  717. except:
  718. pass
  719. self.logger.info("destroy, come in 22222")
  720. # self.call_players.clear()
  721. # self.accounts.clear()
  722. # self.calls.clear()
  723. # # Destroy the library
  724. # self.ep.libDestroy()
  725. time.sleep(1)
  726. self.logger.info("destroy, come in 33333")
  727. if not self.pjsua_thread.is_alive():
  728. self.logger.info("destroy, pre thread already stopped")
  729. return
  730. ident = self.pjsua_thread.ident
  731. thread_id = ctypes.pythonapi.PyThreadState_SetAsyncExc
  732. res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
  733. ctypes.c_long(ident), ctypes.py_object(SystemExit)
  734. )
  735. self.logger.info("destroy, ident=%s, thread_id=%s, res=%s", ident, thread_id, res)
  736. # if res == 0:
  737. # raise ValueError("Invalid thread ID")
  738. # elif res > 1:
  739. # # 如果多次调用,需要复位
  740. # ctypes.pythonapi.PyThreadState_SetAsyncExc(ident, 0)
  741. # raise SystemError("PyThreadState_SetAsyncExc failed")
  742. def __del__(self):
  743. self.destroy()
  744. self.daemon_stopping = True
  745. # if __name__ == '__main__':
  746. # import logging
  747. # logger = logging.getLogger('voip')
  748. # bot = BotAgent(logger)