bot.py 37 KB

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