Plana-Archive commited on
Commit
656b60c
·
verified ·
1 Parent(s): 53572b3

Clean up previous raw files

Browse files
Files changed (1) hide show
  1. Zero-CPU/tools/translate.py +0 -61
Zero-CPU/tools/translate.py DELETED
@@ -1,61 +0,0 @@
1
- """
2
- 翻译api
3
- """
4
- from config import config
5
-
6
- import random
7
- import hashlib
8
- import requests
9
-
10
-
11
- def translate(Sentence: str, to_Language: str = "jp", from_Language: str = ""):
12
- """
13
- :param Sentence: 待翻译语句
14
- :param from_Language: 待翻译语句语言
15
- :param to_Language: 目标语言
16
- :return: 翻译后语句 出错时返回None
17
-
18
- 常见语言代码:中文 zh 英语 en 日语 jp
19
- """
20
- appid = config.translate_config.app_key
21
- key = config.translate_config.secret_key
22
- if appid == "" or key == "":
23
- return "请开发者在config.yml中配置app_key与secret_key"
24
- url = "https://fanyi-api.baidu.com/api/trans/vip/translate"
25
- texts = Sentence.splitlines()
26
- outTexts = []
27
- for t in texts:
28
- if t != "":
29
- # 签名计算 参考文档 https://api.fanyi.baidu.com/product/113
30
- salt = str(random.randint(1, 100000))
31
- signString = appid + t + salt + key
32
- hs = hashlib.md5()
33
- hs.update(signString.encode("utf-8"))
34
- signString = hs.hexdigest()
35
- if from_Language == "":
36
- from_Language = "auto"
37
- headers = {"Content-Type": "application/x-www-form-urlencoded"}
38
- payload = {
39
- "q": t,
40
- "from": from_Language,
41
- "to": to_Language,
42
- "appid": appid,
43
- "salt": salt,
44
- "sign": signString,
45
- }
46
- # 发送请求
47
- try:
48
- response = requests.post(
49
- url=url, data=payload, headers=headers, timeout=3
50
- )
51
- response = response.json()
52
- if "trans_result" in response.keys():
53
- result = response["trans_result"][0]
54
- if "dst" in result.keys():
55
- dst = result["dst"]
56
- outTexts.append(dst)
57
- except Exception:
58
- return Sentence
59
- else:
60
- outTexts.append(t)
61
- return "\n".join(outTexts)