VoicePromptController.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import time
  4. import oss2
  5. from django.db.models import Q
  6. from django.views import View
  7. from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET
  8. from Model.models import VoicePromptModel, UidChannelSetModel, Device_Info
  9. from Object.ResponseObject import ResponseObject
  10. from Object.TokenObject import TokenObject
  11. from Service.CommonService import CommonService
  12. from Service.ModelService import ModelService
  13. class VoicePromptView(View):
  14. def get(self, request, *args, **kwargs):
  15. request.encoding = 'utf-8'
  16. request_dict = request.GET
  17. operation = kwargs.get('operation', None)
  18. return self.validate(request, request_dict, operation)
  19. def post(self, request, *args, **kwargs):
  20. request.encoding = 'utf-8'
  21. request_dict = request.POST
  22. operation = kwargs.get('operation', None)
  23. return self.validate(request, request_dict, operation)
  24. def validate(self, request, request_dict, operation):
  25. token = request_dict.get('token', None)
  26. print(token)
  27. lang = request_dict.get('lang', None)
  28. response = ResponseObject(lang=lang)
  29. token = TokenObject(token)
  30. if token.code != 0:
  31. return response.json(token.code)
  32. if operation == 'getUploadUrl':
  33. return self.get_upload_url(request_dict, response)
  34. elif operation == 'add':
  35. return self.do_add(request_dict, response)
  36. elif operation == 'delete':
  37. return self.do_delete(token.userID, request_dict, response)
  38. elif operation == 'query':
  39. return self.do_query(request_dict, response)
  40. elif operation == 'update':
  41. return self.do_update(token.userID, request_dict, response)
  42. elif operation == 'adminGetUploadUrl':
  43. return self.admin_get_upload_url(token.userID, request_dict, response)
  44. elif operation == 'adminAdd':
  45. return self.do_admin_add(token.userID, request_dict, response)
  46. elif operation == 'adminQuery':
  47. return self.do_admin_query(token.userID, request_dict, response)
  48. elif operation == 'adminUpdate':
  49. return self.do_admin_update(token.userID, request_dict, response)
  50. elif operation == 'adminDelete':
  51. return self.do_admin_delete(token.userID, request_dict, response)
  52. elif operation == 'uploadSystemVoice':
  53. return self.upload_system_voice(request, request_dict, response)
  54. else:
  55. return response.json(404)
  56. def get_upload_url(self, request_dict, response):
  57. upload_type = request_dict.get('upload_type', None)
  58. uid = request_dict.get('uid', None)
  59. channel = request_dict.get('channel', None)
  60. type = request_dict.get('type', None)
  61. algorithm_type = int(request_dict.get('algorithmType', 99))
  62. if upload_type and uid and channel:
  63. vp_qs = VoicePromptModel.objects.filter(uid=uid, channel=channel, type=type)
  64. vp_qs = vp_qs.filter(algorithm_type=algorithm_type)
  65. count = vp_qs.count()
  66. if count >= 3:
  67. return response.json(201)
  68. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  69. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'ansjer-static-resources')
  70. name = CommonService.createOrderID()
  71. filename = str(name) + '.' + upload_type
  72. obj = 'voice_prompt/{uid}/{channel}/'.format(uid=uid, channel=channel) + filename
  73. url = bucket.sign_url('PUT', obj, 7200)
  74. return response.json(0, {'put_url': url, 'filename': filename})
  75. else:
  76. return response.json(444)
  77. def do_add(self, request_dict, response):
  78. filename = request_dict.get('filename', None)
  79. title = request_dict.get('title', None)
  80. type = request_dict.get('type', None)
  81. lang = request_dict.get('lang', '')
  82. uid = request_dict.get('uid', None)
  83. channel = request_dict.get('channel', None)
  84. algorithm_type = request_dict.get('algorithmType', None)
  85. if filename and title and type and uid and channel:
  86. voice_prompt = VoicePromptModel()
  87. voice_prompt.filename = filename
  88. voice_prompt.title = title
  89. voice_prompt.type = type
  90. voice_prompt.language = lang
  91. voice_prompt.classification = 1
  92. voice_prompt.uid = uid
  93. voice_prompt.channel = channel
  94. voice_prompt.add_time = int(time.time())
  95. if algorithm_type:
  96. voice_prompt.algorithm_type = int(algorithm_type)
  97. voice_prompt.save()
  98. res = {
  99. 'id': voice_prompt.id,
  100. 'filename': filename,
  101. 'title': title,
  102. 'type': type,
  103. }
  104. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  105. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'ansjer-static-resources')
  106. filename = res['filename']
  107. obj = 'voice_prompt/{uid}/{channel}/'.format(uid=uid, channel=channel) + filename
  108. url = bucket.sign_url('GET', obj, 3600)
  109. res['url'] = url
  110. del res['filename']
  111. return response.json(0, res)
  112. else:
  113. return response.json(444)
  114. def do_update(self, userID, request_dict, response):
  115. id = request_dict.get('id', None)
  116. title = request_dict.get('title', None)
  117. if id and title:
  118. voice_qs = VoicePromptModel.objects.filter(id=id)
  119. if voice_qs.exists():
  120. uid = voice_qs[0].uid
  121. device_qs = Device_Info.objects.filter(UID=uid, userID=userID)
  122. if device_qs.exists():
  123. voice_qs.update(title=title)
  124. return response.json(0)
  125. else:
  126. return response.json(404)
  127. else:
  128. return response.json(173)
  129. else:
  130. return response.json(444)
  131. def do_delete(self, userID, request_dict, response):
  132. id = request_dict.get('id', None)
  133. ids = request_dict.get('ids', None)
  134. if id:
  135. voice_qs = VoicePromptModel.objects.filter(id=id)
  136. elif ids:
  137. voice_qs = VoicePromptModel.objects.filter(id__in=ids.split(','))
  138. if not voice_qs.exists():
  139. return response.json(14)
  140. for voice in voice_qs:
  141. uid = voice.uid
  142. device_qs = Device_Info.objects.filter(UID=uid, userID=userID)
  143. if device_qs.exists():
  144. channel = voice.channel
  145. filename = voice.filename
  146. voice_qs.delete()
  147. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  148. bucket = oss2.Bucket(auth, 'http://oss-cn-shenzhen.aliyuncs.com', 'ansjer-static-resources')
  149. obj = 'voice_prompt/{uid}/{channel}/'.format(uid=uid, channel=channel) + filename
  150. bucket.delete_object(obj)
  151. return response.json(0)
  152. else:
  153. return response.json(404)
  154. else:
  155. return response.json(444)
  156. def do_query(self, request_dict, response):
  157. lang = request_dict.get('lang', 'en')
  158. uid = request_dict.get('uid', None)
  159. channel = request_dict.get('channel', None)
  160. # 个性语音增加算法类型区分默认0兼容老版本
  161. algorithm_type = int(request_dict.get('algorithmType', 99))
  162. if uid and channel and lang:
  163. voice_qs = VoicePromptModel.objects.filter(uid=uid, channel=channel, classification=1,
  164. algorithm_type=algorithm_type)
  165. system_qs = VoicePromptModel.objects.filter(classification=0, language=lang, status=1,
  166. algorithm_type=algorithm_type)
  167. if not system_qs.exists() and lang != 'en':
  168. system_qs = VoicePromptModel.objects.filter(classification=0, language='en', status=1,
  169. algorithm_type=algorithm_type)
  170. if lang == 'cn' and algorithm_type == 10:
  171. device_type = Device_Info.objects.filter(UID=uid).values('Type').first()['Type']
  172. system_new_qs = system_qs.filter(Q(device_types__contains=[device_type]))
  173. if system_new_qs.exists():
  174. system_qs = system_new_qs
  175. else:
  176. system_qs = system_qs.filter(Q(device_types=[]))
  177. channel_qs = UidChannelSetModel.objects.filter(uid__uid=uid, channel=channel,
  178. algorithm_type=algorithm_type)
  179. res = {
  180. 'enter_voice': {},
  181. 'leave_voice': {},
  182. 'voice_status': 0,
  183. 'voice_mute': 0
  184. }
  185. enter_voice_id = 0
  186. leave_voice_id = 0
  187. if channel_qs.exists():
  188. channel_qs = channel_qs.values('voice_prompt_enter', 'voice_prompt_leave', 'voice_prompt_status',
  189. 'voice_prompt_intelligent_mute', 'voice_start_x', 'voice_start_y',
  190. 'voice_end_x', 'voice_end_y', 'voice_start_time', 'voice_end_time',
  191. 'voice_repeat_day', 'voice_direction')
  192. print(channel_qs)
  193. enter_voice_id = int(channel_qs[0]['voice_prompt_enter'])
  194. leave_voice_id = int(channel_qs[0]['voice_prompt_leave'])
  195. res['voice_status'] = channel_qs[0]['voice_prompt_status']
  196. res['voice_mute'] = channel_qs[0]['voice_prompt_intelligent_mute']
  197. res['start_x'] = channel_qs[0]['voice_start_x']
  198. res['start_y'] = channel_qs[0]['voice_start_y']
  199. res['end_x'] = channel_qs[0]['voice_end_x']
  200. res['end_y'] = channel_qs[0]['voice_end_y']
  201. res['start_time'] = channel_qs[0]['voice_start_time']
  202. res['end_time'] = channel_qs[0]['voice_end_time']
  203. res['repeat_day'] = channel_qs[0]['voice_repeat_day']
  204. res['direction'] = channel_qs[0]['voice_direction']
  205. enter_systems = []
  206. leave_systems = []
  207. enter_customs = []
  208. leave_customs = []
  209. res['system'] = {}
  210. res['custom'] = {}
  211. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  212. bucket = oss2.Bucket(auth, 'https://oss-cn-shenzhen.aliyuncs.com', 'ansjer-static-resources')
  213. if system_qs.exists():
  214. system_qs = system_qs.values('id', 'title', 'filename', 'type')
  215. for system in system_qs:
  216. filename = system['filename']
  217. obj = 'voice_prompt/system/' + filename
  218. url = bucket.sign_url('GET', obj, 3600)
  219. system['url'] = url
  220. del system['filename']
  221. if system['type'] == 0:
  222. enter_systems.append(system)
  223. if enter_voice_id == system['id']:
  224. res['enter_voice'] = system
  225. elif system['type'] == 1:
  226. leave_systems.append(system)
  227. if leave_voice_id == system['id']:
  228. res['leave_voice'] = system
  229. if voice_qs.exists():
  230. voice_qs = voice_qs.values('id', 'title', 'filename', 'type')
  231. for voice in voice_qs:
  232. filename = voice['filename']
  233. obj = 'voice_prompt/' + uid + '/' + channel + '/' + filename
  234. url = bucket.sign_url('GET', obj, 3600)
  235. voice['url'] = url
  236. del voice['filename']
  237. if voice['type'] == 0:
  238. enter_customs.append(voice)
  239. if enter_voice_id == voice['id']:
  240. res['enter_voice'] = voice
  241. elif voice['type'] == 1:
  242. leave_customs.append(voice)
  243. if leave_voice_id == voice['id']:
  244. res['leave_voice'] = voice
  245. res['system']['enter'] = enter_systems
  246. res['system']['leave'] = leave_systems
  247. res['custom']['enter'] = enter_customs
  248. res['custom']['leave'] = leave_customs
  249. return response.json(0, res)
  250. else:
  251. return response.json(444)
  252. def admin_get_upload_url(self, userID, request_dict, response):
  253. own_perm = ModelService.check_perm(userID, 10)
  254. if not own_perm:
  255. return response.json(404)
  256. upload_type = request_dict.get('upload_type', None)
  257. if upload_type:
  258. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  259. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'ansjer-static-resources')
  260. name = CommonService.createOrderID()
  261. filename = str(name) + '.' + upload_type
  262. obj = 'voice_prompt/system/' + filename
  263. url = bucket.sign_url('PUT', obj, 7200)
  264. return response.json(0, {'put_url': url, 'filename': filename})
  265. else:
  266. return response.json(444)
  267. @classmethod
  268. def upload_system_voice(cls, request, request_dict, response):
  269. """
  270. 上传系统个性化语音(系统默认以及算法小店默认提示音)
  271. 个性化语音有两个功能涉及使用一个是设备个性化语音,一个是算法小店语音
  272. 此接口上传个性化语音文件
  273. 参数algorithmType不为空或者不等于99(默认值)则系统保存的是算法小店的个性化语音
  274. """
  275. voice_file = request.FILES.get('voiceFile', None)
  276. algorithm_type = int(request_dict.get('algorithmType', 99))
  277. voice_title = request_dict.get('voiceTitle', None)
  278. language = request_dict.get('language', None)
  279. if not all([voice_file, algorithm_type, voice_title, language]):
  280. return response.json(444)
  281. try:
  282. filename = CommonService.createOrderID() # 文件名时间+随机数生成
  283. file_ext = '.' + voice_file.name.split('.')[-1]
  284. now_time = int(time.time())
  285. key = 'voice_prompt/system/' + filename + file_ext
  286. # 上传文件到阿里云OSS
  287. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  288. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'ansjer-static-resources')
  289. bucket.put_object(key=key, data=voice_file)
  290. voice_type = 1 if algorithm_type < 99 else 0 # 算法小店提示音默认判断type=1才会显示
  291. voice_vo = {
  292. 'title': voice_title,
  293. 'filename': filename + file_ext,
  294. 'add_time': now_time,
  295. 'classification': 0,
  296. 'algorithm_type': algorithm_type,
  297. 'language': language,
  298. 'type': voice_type
  299. }
  300. VoicePromptModel.objects.create(**voice_vo)
  301. return response.json(0)
  302. except Exception as e:
  303. print(e)
  304. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  305. def do_admin_add(self, userID, request_dict, response):
  306. own_perm = ModelService.check_perm(userID, 10)
  307. if not own_perm:
  308. return response.json(404)
  309. filename = request_dict.get('filename', None)
  310. title = request_dict.get('title', None)
  311. type = request_dict.get('type', None)
  312. lang = request_dict.get('lang', '')
  313. if filename and title and type:
  314. voice_prompt = VoicePromptModel()
  315. voice_prompt.filename = filename
  316. voice_prompt.title = title
  317. voice_prompt.type = type
  318. voice_prompt.language = lang
  319. voice_prompt.classification = 0
  320. voice_prompt.add_time = int(time.time())
  321. voice_prompt.status = 0
  322. voice_prompt.save()
  323. return response.json(0)
  324. else:
  325. return response.json(444)
  326. def do_admin_query(self, userID, request_dict, response):
  327. own_perm = ModelService.check_perm(userID, 10)
  328. if not own_perm:
  329. return response.json(404)
  330. type = request_dict.get('type', 0)
  331. page = request_dict.get('page', None)
  332. line = request_dict.get('line', None)
  333. if page is None or line is None:
  334. return response.json(444)
  335. voice_qs = VoicePromptModel.objects.filter(classification=0, type=type)
  336. print(voice_qs)
  337. res = {
  338. 'count': 0
  339. }
  340. if voice_qs.exists():
  341. page = int(page)
  342. line = int(line)
  343. start = (page - 1) * line
  344. end = start + line
  345. count = voice_qs.count()
  346. res['count'] = count
  347. voice_qs = voice_qs.values('id', 'title', 'type', 'language', 'status', 'filename')[start:end]
  348. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  349. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'ansjer-static-resources')
  350. for item in voice_qs:
  351. filename = item['filename']
  352. obj = 'voice_prompt/system/' + filename
  353. url = bucket.sign_url('GET', obj, 3600)
  354. item['url'] = url
  355. del item['filename']
  356. res['data'] = list(voice_qs)
  357. return response.json(0, res)
  358. else:
  359. res['data'] = []
  360. return response.json(0, res)
  361. def do_admin_update(self, userID, request_dict, response):
  362. own_perm = ModelService.check_perm(userID, 10)
  363. if not own_perm:
  364. return response.json(404)
  365. id = request_dict.get('id', None)
  366. status = request_dict.get('status', None)
  367. title = request_dict.get('title', None)
  368. if id and status and title:
  369. VoicePromptModel.objects.filter(id=id, classification=0).update(status=status, title=title)
  370. return response.json(0)
  371. else:
  372. return response.json(444)
  373. def do_admin_delete(self, userID, request_dict, response):
  374. own_perm = ModelService.check_perm(userID, 10)
  375. if not own_perm:
  376. return response.json(404)
  377. id = request_dict.get('id', None)
  378. if id:
  379. VoicePromptModel.objects.filter(id=id, classification=0).delete()
  380. return response.json(0)
  381. else:
  382. return response.json(444)