1
This commit is contained in:
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+18
-2
@@ -1,3 +1,19 @@
|
||||
from django.test import TestCase
|
||||
# -*- coding=utf-8
|
||||
from qcloud_cos import CosConfig
|
||||
from qcloud_cos import CosS3Client
|
||||
import sys
|
||||
import logging
|
||||
|
||||
# Create your tests here.
|
||||
# 正常情况日志级别使用 INFO,需要定位时可以修改为 DEBUG,此时 SDK 会打印和服务端的通信信息
|
||||
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
|
||||
|
||||
# 1. 设置用户属性, 包括 secret_id, secret_key, region 等。Appid 已在 CosConfig 中移除,请在参数 Bucket 中带上 Appid。Bucket 由 BucketName-Appid 组成
|
||||
secret_id = 'SecretId' # 替换为用户的 SecretId,请登录访问管理控制台进行查看和管理,https://console.cloud.tencent.com/cam/capi
|
||||
secret_key = 'SecretKey' # 替换为用户的 SecretKey,请登录访问管理控制台进行查看和管理,https://console.cloud.tencent.com/cam/capi
|
||||
region = 'ap-beijing' # 替换为用户的 region,已创建桶归属的 region 可以在控制台查看,https://console.cloud.tencent.com/cos5/bucket
|
||||
# COS支持的所有 region 列表参见 https://cloud.tencent.com/document/product/436/6224
|
||||
token = None # 如果使用永久密钥不需要填入token,如果使用临时密钥需要填入,临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048
|
||||
scheme = 'https' # 指定使用 http/https 协议来访问 COS,默认为 https,可不填
|
||||
|
||||
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)
|
||||
client = CosS3Client(config)
|
||||
+21
-1
@@ -1,8 +1,28 @@
|
||||
|
||||
from django.contrib import admin
|
||||
|
||||
from django.urls import path, include
|
||||
|
||||
from .views.GetIPDataView import GetIPDataView
|
||||
from .views.BaiduFanyiView import BaiduFanyiView
|
||||
|
||||
from .views.BaiduFanyiView import BaiduFanyiView, AllLangTypeViews, AutoLangTypeViews, RecognizeLangTypeViews, PictureRecognizeViews, SpeechRecognitionView
|
||||
|
||||
urlpatterns = [
|
||||
|
||||
path("getIpData/", GetIPDataView.as_view()),
|
||||
|
||||
path("baiduFanyi/", BaiduFanyiView.as_view()),
|
||||
|
||||
path("getAllLangType/", AllLangTypeViews.as_view()),
|
||||
|
||||
path("getAutoLangType/", AutoLangTypeViews.as_view()),
|
||||
|
||||
path("recognizeLangType/", RecognizeLangTypeViews.as_view()),
|
||||
|
||||
path("pictureRecognize/", PictureRecognizeViews.as_view()),
|
||||
|
||||
path("speechRecognition/", SpeechRecognitionView.as_view()),
|
||||
|
||||
|
||||
|
||||
]
|
||||
+206
-5
@@ -1,4 +1,8 @@
|
||||
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
|
||||
|
||||
@@ -13,6 +17,12 @@ 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()
|
||||
@@ -20,21 +30,48 @@ def make_md5(s, encoding='utf-8'):
|
||||
@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.
|
||||
appid = '20220718001275847'
|
||||
appkey = 'CJHmvf7qGs3szQy32cMg'
|
||||
|
||||
from_lang = 'en'
|
||||
to_lang = 'zh'
|
||||
|
||||
endpoint = 'http://api.fanyi.baidu.com'
|
||||
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)
|
||||
|
||||
@@ -44,5 +81,169 @@ class BaiduFanyiView(APIView):
|
||||
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)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,4 @@
|
||||
appid = '20220718001275847'
|
||||
appkey = 'CJHmvf7qGs3szQy32cMg'
|
||||
|
||||
endpoint = 'http://api.fanyi.baidu.com'
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user