语音识别应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

187 lines
8.1 KiB

  1. # coding:utf8
  2. import os, sys
  3. import io
  4. from jsonpath_ng import jsonpath, parse
  5. import uuid
  6. sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8')
  7. cur_dir = os.path.dirname(os.path.abspath(__file__)) or os.getcwd()
  8. par_dir = os.path.abspath(os.path.join(cur_dir, os.path.pardir))
  9. sys.path.append(cur_dir)
  10. sys.path.append(par_dir)
  11. import json
  12. from django.http import HttpResponse
  13. from text_analysis.tools import to_kafka
  14. from django.views.decorators.csrf import csrf_exempt
  15. from log_util.set_logger import set_logger
  16. logging = set_logger('logs/results.log')
  17. import traceback
  18. import queue
  19. import requests
  20. from text_analysis.tools.tool import parse_data
  21. import time
  22. from datetime import datetime
  23. import os
  24. # 任务队列
  25. global task_queue
  26. task_queue = queue.Queue()
  27. # 数据队列
  28. global data_queue
  29. data_queue = queue.Queue()
  30. @csrf_exempt
  31. def ASRNew(request):
  32. if request.method == 'POST':
  33. try:
  34. raw_data = json.loads(request.body)
  35. task_queue.put(raw_data)
  36. return HttpResponse(json.dumps({"code": 1, "msg": "请求正常!"}, ensure_ascii=False))
  37. except:
  38. logging.error(traceback.format_exc())
  39. return HttpResponse(json.dumps({"code": 0, "msg": "请求json格式不正确!"}, ensure_ascii=False))
  40. else:
  41. return HttpResponse(json.dumps({"code": 0, "msg": "请求方式错误,改为post请求"}, ensure_ascii=False))
  42. def upload():
  43. while True:
  44. try:
  45. if task_queue.qsize() > 0:
  46. logging.info("取任务队列长度{}".format(task_queue.qsize()))
  47. raw_data = task_queue.get()
  48. # index = raw_data["metadata"]["index"]
  49. # datasource = raw_data["metadata"]["admin"]["datasource"]
  50. # if datasource not in raw_data["data"].keys():
  51. # logging.info("找不到相关数据源!—{}".format(raw_data))
  52. # continue
  53. # allFile = raw_data["data"][datasource]
  54. # currentFile = eval(allFile)[index]
  55. url=raw_data["input"]["fileUrl"]
  56. if "json" in url:
  57. parm = url.split("#")
  58. data1 = parse_data(raw_data, parm[0])
  59. data1_json = json.loads(data1)
  60. expr = parse(parm[2])
  61. match = [match.value for match in expr.find(data1_json)]
  62. video_url = match[0]
  63. else:
  64. video_url = parse_data(raw_data, url)
  65. fileName=video_url.rsplit('/')[-1]
  66. if "http" not in video_url:
  67. file = "https://caiji.percent.cn/" + video_url.lstrip("/")
  68. else:
  69. file=video_url
  70. # name=raw_data["metadata"]["admin"]["fileName"]
  71. # if '$.' in name:
  72. # # json.path表达式动态获取value
  73. # datasources = str(name).split(':')
  74. # # 0是数据源,1是JsonPath 表达式
  75. # datasourcestr = raw_data["data"][datasources[0]]
  76. # datasource = json.loads(datasourcestr)
  77. # # 创建 JsonPath 表达式对象
  78. # expr = parse(datasources[1])
  79. # # 使用表达式来选择 JSON 元素
  80. # match = [match.value for match in expr.find(datasource)]
  81. # fileName = match[0]
  82. currentFile={"fileName":fileName,"fileUrl":file}
  83. language = raw_data["input"]["fromLanguage"]
  84. # 从gofast获取视频
  85. myfile = requests.get(file)
  86. starttime = datetime.now().strftime('%Y-%m-%d')
  87. path = 'inputdata/' + starttime
  88. if not os.path.exists(path):
  89. os.makedirs(path)
  90. with open(path + '/' + fileName, 'wb') as f:
  91. f.write(myfile.content)
  92. logging.info("视频从gofast下载完毕,开始上传-{}".format(fileName))
  93. # 访问视频上传接口
  94. url = "https://realtime.pdeepmatrix.com/apis/media/analysis/upload"
  95. data = {'fromLanguage': language}
  96. f = open(path + '/' + fileName, 'rb')
  97. files = {'file': f}
  98. response = requests.post(url, data=data, files=files)
  99. d = json.loads(response.text)
  100. if "code" in d.keys() and d["code"] == 200:
  101. # 接口返回值data中存放视频获取结果的key
  102. result = d["data"]
  103. raw_data["result"] = {"successCode": "1", "errorLog": "", "results": "", "dataKey": result,"file":currentFile}
  104. data_queue.put(raw_data)
  105. logging.info("视频上传成功{}".format(raw_data))
  106. # to_kafka.send_kafka(raw_data,logging)
  107. else:
  108. logging.info("视频上传失败{}-{}".format(raw_data, d))
  109. f.close()
  110. # Todo删除视频文件
  111. else:
  112. # 暂无任务,进入休眠
  113. time.sleep(10)
  114. except:
  115. logging.error(traceback.format_exc())
  116. def getResult():
  117. while True:
  118. # 3秒钟结果获取一次
  119. time.sleep(3)
  120. try:
  121. if data_queue.qsize() > 0:
  122. logging.info("取数据队列长度{}".format(data_queue.qsize()))
  123. raw_data = data_queue.get()
  124. # print(raw_data)
  125. output=raw_data["output"]
  126. res_tmp={key: "" for key in output}
  127. if "id" in res_tmp.keys():
  128. res_tmp["id"]=str(uuid.uuid4())
  129. # 根据视频key访问获取结果接口
  130. dataKey = raw_data["result"]["dataKey"]
  131. url = "https://realtime.pdeepmatrix.com/apis/media/analysis/getResult"
  132. params = {'taskId': dataKey}
  133. response = requests.get(url, params=params)
  134. # print(response.text)
  135. d = json.loads(response.text)
  136. if "code" in d.keys() and d["code"] == 200:
  137. results = ""
  138. if d["data"]["code"] == "1":
  139. for sentence in d["data"]["sentences"]:
  140. results += sentence["text"]
  141. if "content" in res_tmp.keys():
  142. res_tmp["content"]=results
  143. raw_data["result"]["results"] = json.dumps(res_tmp, ensure_ascii=False)
  144. logging.info("视频解析获取结果成功{}".format(raw_data))
  145. to_kafka.send_kafka(raw_data, logging)
  146. elif d["data"]["code"] == "0":
  147. # 正在解析中,将任务再次放回数据队列
  148. data_queue.put(raw_data)
  149. logging.info("视频未解析完毕,放回队列等待{}-{}".format(raw_data, d))
  150. else:
  151. # 解析失败
  152. raw_data["result"]["successCode"] = "0"
  153. raw_data["result"]["errorLog"] = response.text
  154. raw_data["result"]["results"] = json.dumps(res_tmp, ensure_ascii=False)
  155. logging.info("视频解析获取结果失败,数据{},接口返回值{}".format(raw_data, d))
  156. to_kafka.send_kafka(raw_data, logging)
  157. else:
  158. raw_data["result"]["successCode"] = "0"
  159. raw_data["result"]["errorLog"] = response.text
  160. raw_data["result"]["results"] = json.dumps(res_tmp, ensure_ascii=False)
  161. logging.info("视频解析获取结果失败,数据{},接口返回值{}".format(raw_data, d))
  162. to_kafka.send_kafka(raw_data, logging)
  163. else:
  164. # 暂无任务,进入休眠
  165. time.sleep(10)
  166. except:
  167. raw_data["result"]["successCode"] = "0"
  168. raw_data["result"]["errorLog"] = traceback.format_exc()
  169. raw_data["result"]["results"] = ""
  170. logging.error(traceback.format_exc())
  171. to_kafka.send_kafka(raw_data, logging)