249 lines
7.6 KiB
Python
249 lines
7.6 KiB
Python
from symtable import Class
|
|
|
|
from django.core.signing import base64_hmac
|
|
from rest_framework.decorators import permission_classes
|
|
from rest_framework.parsers import MultiPartParser, FormParser
|
|
from rest_framework.permissions import AllowAny
|
|
from rest_framework.views import APIView
|
|
|
|
from rest_framework.response import Response
|
|
from rest_framework import status
|
|
|
|
import requests
|
|
import json
|
|
|
|
import requests
|
|
import random
|
|
import json
|
|
from hashlib import md5
|
|
|
|
from twisted.scripts.htmlizer import header
|
|
|
|
from .info.baidu_lang_info import languages, auto_lang
|
|
|
|
from .info.baidu_fanyi_appid import appid, appkey, endpoint
|
|
|
|
|
|
def make_md5(s, encoding='utf-8'):
|
|
return md5(s.encode(encoding)).hexdigest()
|
|
|
|
@permission_classes([AllowAny])
|
|
class BaiduFanyiView(APIView):
|
|
def post(self, request):
|
|
"""
|
|
|
|
请求参数为 q 翻译内容 文本长度限制3000字以下
|
|
from_lang 原语言
|
|
to_lang 翻译语言 (支持 auto 为自动识别)
|
|
|
|
|
|
:param request:
|
|
:return:
|
|
"""
|
|
print(request.data)
|
|
|
|
# Set your own appid/appkey.
|
|
|
|
|
|
from_lang = request.data.get('from_lang')
|
|
to_lang = request.data.get('to_lang')
|
|
|
|
if (from_lang not in languages) or (to_lang not in languages) or (to_lang == "auto"):
|
|
return Response(
|
|
{
|
|
"message": "翻译语种异常"
|
|
},
|
|
status=status.HTTP_400_BAD_REQUEST
|
|
)
|
|
|
|
if from_lang == to_lang:
|
|
return Response(
|
|
{
|
|
"message": "翻译数据异常"
|
|
}
|
|
)
|
|
|
|
path = '/api/trans/vip/translate'
|
|
url = endpoint + path
|
|
|
|
query = request.data['q']
|
|
|
|
if len(query) > 3000:
|
|
return Response({"请求数据长度过长已经超过3000."}, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
salt = random.randint(32768, 65536)
|
|
sign = make_md5(appid + query + str(salt) + appkey)
|
|
|
|
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
|
|
payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}
|
|
|
|
r = requests.post(url, params=payload, headers=headers)
|
|
result = r.json()
|
|
|
|
return Response(result, status=status.HTTP_200_OK)
|
|
|
|
@permission_classes([AllowAny])
|
|
class AutoLangTypeViews(APIView): # 获取可用自动识别的所有语言类型
|
|
def get(self, request):
|
|
return Response(auto_lang, status=status.HTTP_200_OK)
|
|
|
|
@permission_classes([AllowAny])
|
|
class AllLangTypeViews(APIView): # 获取可用自动识别的所有语言类型
|
|
def get(self, request):
|
|
return Response(languages, status=status.HTTP_200_OK)
|
|
|
|
|
|
@permission_classes([AllowAny])
|
|
class RecognizeLangTypeViews(APIView): # 文本语种识别
|
|
"""
|
|
|
|
请求参数为 q 翻译内容 文本长度限制3000字以下
|
|
|
|
:param request:
|
|
:return:
|
|
"""
|
|
def post(self, request):
|
|
|
|
path = '/api/trans/vip/language'
|
|
url = endpoint + path
|
|
|
|
query = request.data.get("q")
|
|
|
|
if len(query) > 3000:
|
|
return Response({"请求数据长度过长已经超过3000."}, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
salt = random.randint(32768, 65536)
|
|
sign = make_md5(appid + query + str(salt) + appkey)
|
|
|
|
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
|
|
payload = {'appid': appid, 'q': query, 'salt': salt, 'sign': sign}
|
|
|
|
r = requests.post(url, params=payload, headers=headers)
|
|
result = r.json()
|
|
|
|
code = result.get('error_code')
|
|
|
|
if code == 0:
|
|
return Response(result, status=status.HTTP_200_OK)
|
|
elif code == 54009:
|
|
return Response({
|
|
"message": "不在课识别语种范围."
|
|
}, status=status.HTTP_400_BAD_REQUEST)
|
|
else :
|
|
return Response({
|
|
"message": "其他问题请联系管理员."
|
|
}, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
import requests
|
|
import random
|
|
from hashlib import md5
|
|
|
|
from .info.baidu_fanyi_appid import appid as app_id, appkey as app_key
|
|
|
|
from .info.baidu_lang_info import cuid, mac, p_code, p_lang_type
|
|
|
|
@permission_classes([AllowAny])
|
|
class PictureRecognizeViews(APIView): # 图片翻译
|
|
|
|
parser_classes = [MultiPartParser, FormParser]
|
|
|
|
def post(self, request):
|
|
|
|
file_data = request.FILES['file'].read()
|
|
|
|
path = '/api/trans/sdk/picture'
|
|
url = endpoint + path
|
|
|
|
from_lang = request.GET.get("from_lang")
|
|
to_lang = request.GET.get("to_lang")
|
|
picture_type = request.GET.get("picture")
|
|
|
|
if (from_lang == to_lang) or (to_lang == "auto"):
|
|
return Response({"message": "翻译数据错误."}, status=status.HTTP_400_BAD_REQUEST)
|
|
if (from_lang not in p_lang_type.keys()) or (to_lang not in p_lang_type.keys()) :
|
|
return Response({"message": "翻译语种异常."}, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
def get_md5(string, encoding='utf-8'):
|
|
return md5(string.encode(encoding)).hexdigest()
|
|
|
|
salt = random.randint(32768, 65536)
|
|
sign = get_md5(app_id + md5(file_data).hexdigest() + str(salt) + cuid + mac + app_key)
|
|
|
|
payload = {'from': from_lang, 'to': to_lang, 'appid': app_id, 'salt': salt, 'sign': sign, 'cuid': cuid,
|
|
'mac': mac}
|
|
image = {'image': (f"p_image.{ picture_type }", file_data, "multipart/form-data")}
|
|
|
|
response = requests.post(url, params=payload, files=image)
|
|
result = response.json()
|
|
|
|
if result['error_code'] == 0:
|
|
return Response(result, status=status.HTTP_200_OK)
|
|
else:
|
|
result = p_code[result['error_code']]
|
|
return Response(result, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
from .info.baidu_lang_info import y_speech_type, pcm_y_lang_type, y_lang_type
|
|
|
|
import time
|
|
|
|
import hmac
|
|
import hashlib
|
|
import base64
|
|
|
|
|
|
@permission_classes([AllowAny])
|
|
class SpeechRecognitionView(APIView):
|
|
|
|
parser_classes = [MultiPartParser, FormParser]
|
|
|
|
def post(self, request):
|
|
speech_type = request.GET.get("speech_type")
|
|
|
|
if speech_type not in y_speech_type:
|
|
return Response({"message": "不支持的语音类型."}, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
from_lang = request.GET.get('from_lang')
|
|
to_lang = request.GET.get('to_lang')
|
|
|
|
if (from_lang == to_lang) or (to_lang == "auto"):
|
|
return Response({"message": "翻译数据错误."}, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
if (from_lang not in (pcm_y_lang_type.keys() if speech_type == "pcm" else y_lang_type.keys())) or (to_lang not in (pcm_y_lang_type.keys() if speech_type == "pcm" else y_lang_type.keys())):
|
|
return Response({"message": "翻译语种异常."}, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
voice = request.FILES.get("voice").read()
|
|
|
|
base64_hmac_voice = base64.b64encode(voice).decode('utf-8')
|
|
|
|
timestamp = str(int(time.time()))
|
|
|
|
path = "/api/trans/v2/voicetrans"
|
|
|
|
url = endpoint + path
|
|
|
|
msg = appid + timestamp + base64_hmac_voice
|
|
sign = base64.b64encode(hmac.new(app_key.encode("utf-8"), msg.encode("utf-8"), digestmod=hashlib.sha256).digest())
|
|
|
|
print(sign)
|
|
|
|
headers = {
|
|
"Content-Type": "application/json",
|
|
"X-Appid": app_id,
|
|
"X-Timestamp": timestamp,
|
|
"X-Sign": sign,
|
|
"X-EncryptType": "hmac256"
|
|
}
|
|
|
|
data = {
|
|
"format": speech_type,
|
|
"voice": base64_hmac_voice,
|
|
"to": to_lang,
|
|
"from": from_lang,
|
|
}
|
|
|
|
response = requests.post(url, headers = headers,data = data)
|
|
|
|
result = response.json()
|
|
return Response(result, status=status.HTTP_200_OK) |