VoicePromptController.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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_qs = system_qs.filter(Q(device_types=[]) | Q(device_types__contains=[device_type]))
  173. channel_qs = UidChannelSetModel.objects.filter(uid__uid=uid, channel=channel,
  174. algorithm_type=algorithm_type)
  175. res = {
  176. 'enter_voice': {},
  177. 'leave_voice': {},
  178. 'voice_status': 0,
  179. 'voice_mute': 0
  180. }
  181. enter_voice_id = 0
  182. leave_voice_id = 0
  183. if channel_qs.exists():
  184. channel_qs = channel_qs.values('voice_prompt_enter', 'voice_prompt_leave', 'voice_prompt_status',
  185. 'voice_prompt_intelligent_mute', 'voice_start_x', 'voice_start_y',
  186. 'voice_end_x', 'voice_end_y', 'voice_start_time', 'voice_end_time',
  187. 'voice_repeat_day', 'voice_direction')
  188. print(channel_qs)
  189. enter_voice_id = int(channel_qs[0]['voice_prompt_enter'])
  190. leave_voice_id = int(channel_qs[0]['voice_prompt_leave'])
  191. res['voice_status'] = channel_qs[0]['voice_prompt_status']
  192. res['voice_mute'] = channel_qs[0]['voice_prompt_intelligent_mute']
  193. res['start_x'] = channel_qs[0]['voice_start_x']
  194. res['start_y'] = channel_qs[0]['voice_start_y']
  195. res['end_x'] = channel_qs[0]['voice_end_x']
  196. res['end_y'] = channel_qs[0]['voice_end_y']
  197. res['start_time'] = channel_qs[0]['voice_start_time']
  198. res['end_time'] = channel_qs[0]['voice_end_time']
  199. res['repeat_day'] = channel_qs[0]['voice_repeat_day']
  200. res['direction'] = channel_qs[0]['voice_direction']
  201. enter_systems = []
  202. leave_systems = []
  203. enter_customs = []
  204. leave_customs = []
  205. res['system'] = {}
  206. res['custom'] = {}
  207. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  208. bucket = oss2.Bucket(auth, 'https://oss-cn-shenzhen.aliyuncs.com', 'ansjer-static-resources')
  209. if system_qs.exists():
  210. system_qs = system_qs.values('id', 'title', 'filename', 'type')
  211. for system in system_qs:
  212. filename = system['filename']
  213. obj = 'voice_prompt/system/' + filename
  214. url = bucket.sign_url('GET', obj, 3600)
  215. system['url'] = url
  216. del system['filename']
  217. if system['type'] == 0:
  218. enter_systems.append(system)
  219. if enter_voice_id == system['id']:
  220. res['enter_voice'] = system
  221. elif system['type'] == 1:
  222. leave_systems.append(system)
  223. if leave_voice_id == system['id']:
  224. res['leave_voice'] = system
  225. if voice_qs.exists():
  226. voice_qs = voice_qs.values('id', 'title', 'filename', 'type')
  227. for voice in voice_qs:
  228. filename = voice['filename']
  229. obj = 'voice_prompt/' + uid + '/' + channel + '/' + filename
  230. url = bucket.sign_url('GET', obj, 3600)
  231. voice['url'] = url
  232. del voice['filename']
  233. if voice['type'] == 0:
  234. enter_customs.append(voice)
  235. if enter_voice_id == voice['id']:
  236. res['enter_voice'] = voice
  237. elif voice['type'] == 1:
  238. leave_customs.append(voice)
  239. if leave_voice_id == voice['id']:
  240. res['leave_voice'] = voice
  241. res['system']['enter'] = enter_systems
  242. res['system']['leave'] = leave_systems
  243. res['custom']['enter'] = enter_customs
  244. res['custom']['leave'] = leave_customs
  245. return response.json(0, res)
  246. else:
  247. return response.json(444)
  248. def admin_get_upload_url(self, userID, request_dict, response):
  249. own_perm = ModelService.check_perm(userID, 10)
  250. if not own_perm:
  251. return response.json(404)
  252. upload_type = request_dict.get('upload_type', None)
  253. if upload_type:
  254. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  255. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'ansjer-static-resources')
  256. name = CommonService.createOrderID()
  257. filename = str(name) + '.' + upload_type
  258. obj = 'voice_prompt/system/' + filename
  259. url = bucket.sign_url('PUT', obj, 7200)
  260. return response.json(0, {'put_url': url, 'filename': filename})
  261. else:
  262. return response.json(444)
  263. @classmethod
  264. def upload_system_voice(cls, request, request_dict, response):
  265. """
  266. 上传系统个性化语音(系统默认以及算法小店默认提示音)
  267. 个性化语音有两个功能涉及使用一个是设备个性化语音,一个是算法小店语音
  268. 此接口上传个性化语音文件
  269. 参数algorithmType不为空或者不等于99(默认值)则系统保存的是算法小店的个性化语音
  270. """
  271. voice_file = request.FILES.get('voiceFile', None)
  272. algorithm_type = int(request_dict.get('algorithmType', 99))
  273. voice_title = request_dict.get('voiceTitle', None)
  274. language = request_dict.get('language', None)
  275. if not all([voice_file, algorithm_type, voice_title, language]):
  276. return response.json(444)
  277. try:
  278. filename = CommonService.createOrderID() # 文件名时间+随机数生成
  279. file_ext = '.' + voice_file.name.split('.')[-1]
  280. now_time = int(time.time())
  281. key = 'voice_prompt/system/' + filename + file_ext
  282. # 上传文件到阿里云OSS
  283. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  284. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'ansjer-static-resources')
  285. bucket.put_object(key=key, data=voice_file)
  286. voice_type = 1 if algorithm_type < 99 else 0 # 算法小店提示音默认判断type=1才会显示
  287. voice_vo = {
  288. 'title': voice_title,
  289. 'filename': filename + file_ext,
  290. 'add_time': now_time,
  291. 'classification': 0,
  292. 'algorithm_type': algorithm_type,
  293. 'language': language,
  294. 'type': voice_type
  295. }
  296. VoicePromptModel.objects.create(**voice_vo)
  297. return response.json(0)
  298. except Exception as e:
  299. print(e)
  300. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  301. def do_admin_add(self, userID, request_dict, response):
  302. own_perm = ModelService.check_perm(userID, 10)
  303. if not own_perm:
  304. return response.json(404)
  305. filename = request_dict.get('filename', None)
  306. title = request_dict.get('title', None)
  307. type = request_dict.get('type', None)
  308. lang = request_dict.get('lang', '')
  309. if filename and title and type:
  310. voice_prompt = VoicePromptModel()
  311. voice_prompt.filename = filename
  312. voice_prompt.title = title
  313. voice_prompt.type = type
  314. voice_prompt.language = lang
  315. voice_prompt.classification = 0
  316. voice_prompt.add_time = int(time.time())
  317. voice_prompt.status = 0
  318. voice_prompt.save()
  319. return response.json(0)
  320. else:
  321. return response.json(444)
  322. def do_admin_query(self, userID, request_dict, response):
  323. own_perm = ModelService.check_perm(userID, 10)
  324. if not own_perm:
  325. return response.json(404)
  326. type = request_dict.get('type', 0)
  327. page = request_dict.get('page', None)
  328. line = request_dict.get('line', None)
  329. if page is None or line is None:
  330. return response.json(444)
  331. voice_qs = VoicePromptModel.objects.filter(classification=0, type=type)
  332. print(voice_qs)
  333. res = {
  334. 'count': 0
  335. }
  336. if voice_qs.exists():
  337. page = int(page)
  338. line = int(line)
  339. start = (page - 1) * line
  340. end = start + line
  341. count = voice_qs.count()
  342. res['count'] = count
  343. voice_qs = voice_qs.values('id', 'title', 'type', 'language', 'status', 'filename')[start:end]
  344. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  345. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'ansjer-static-resources')
  346. for item in voice_qs:
  347. filename = item['filename']
  348. obj = 'voice_prompt/system/' + filename
  349. url = bucket.sign_url('GET', obj, 3600)
  350. item['url'] = url
  351. del item['filename']
  352. res['data'] = list(voice_qs)
  353. return response.json(0, res)
  354. else:
  355. res['data'] = []
  356. return response.json(0, res)
  357. def do_admin_update(self, userID, request_dict, response):
  358. own_perm = ModelService.check_perm(userID, 10)
  359. if not own_perm:
  360. return response.json(404)
  361. id = request_dict.get('id', None)
  362. status = request_dict.get('status', None)
  363. title = request_dict.get('title', None)
  364. if id and status and title:
  365. VoicePromptModel.objects.filter(id=id, classification=0).update(status=status, title=title)
  366. return response.json(0)
  367. else:
  368. return response.json(444)
  369. def do_admin_delete(self, userID, request_dict, response):
  370. own_perm = ModelService.check_perm(userID, 10)
  371. if not own_perm:
  372. return response.json(404)
  373. id = request_dict.get('id', None)
  374. if id:
  375. VoicePromptModel.objects.filter(id=id, classification=0).delete()
  376. return response.json(0)
  377. else:
  378. return response.json(444)