VoicePromptController.py 18 KB

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