Spaces:
Sleeping
Sleeping
Upload deepl.py
Browse files- src/deepl.py +55 -0
src/deepl.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
import os
|
| 3 |
+
import unicodedata
|
| 4 |
+
from langdetect import detect
|
| 5 |
+
import deepl
|
| 6 |
+
from dotenv import load_dotenv, find_dotenv
|
| 7 |
+
_ = load_dotenv(find_dotenv())
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
DEBUG=os.getenv("DEBUG")
|
| 12 |
+
DEEPL_URL="https://api-free.deepl.com/v2/translate"
|
| 13 |
+
|
| 14 |
+
def DeepL(text,source_lang="JA",target_lang="EN",API_KEY=os.getenv("DEEPL")):
|
| 15 |
+
#paraters パラメータの指定
|
| 16 |
+
params = {
|
| 17 |
+
'auth_key' : API_KEY,
|
| 18 |
+
'text' : text,
|
| 19 |
+
'source_lang' : source_lang, # 翻訳対象の言語
|
| 20 |
+
"target_lang": target_lang # 翻訳後の言語
|
| 21 |
+
}
|
| 22 |
+
# リクエストを投げる
|
| 23 |
+
request = requests.post(DEEPL_URL, data=params) # URIは有償版, 無償版で異なるため要注意
|
| 24 |
+
result = request.json()
|
| 25 |
+
if DEBUG:
|
| 26 |
+
print("DeepL Request print")
|
| 27 |
+
print(result)
|
| 28 |
+
if "translations" not in result:
|
| 29 |
+
print("DEEPL ERROR")
|
| 30 |
+
print(result)
|
| 31 |
+
return "404"
|
| 32 |
+
return result["translations"][0]["text"]
|
| 33 |
+
|
| 34 |
+
def detect_and_translate(text):
|
| 35 |
+
# Detect language
|
| 36 |
+
try:
|
| 37 |
+
lang = detect(text)
|
| 38 |
+
print(lang)
|
| 39 |
+
except:
|
| 40 |
+
return "Error detecting language"
|
| 41 |
+
|
| 42 |
+
# If language is not English, translate it
|
| 43 |
+
if lang != "en":
|
| 44 |
+
|
| 45 |
+
text=DeepL(text,source_lang=lang,target_lang="EN",API_KEY=os.getenv("DEEPL"))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
return text
|
| 49 |
+
|
| 50 |
+
def main():
|
| 51 |
+
test_test="DEEPLのテストの翻訳です"
|
| 52 |
+
print(detect_and_translate(test_test))
|
| 53 |
+
|
| 54 |
+
if __name__=="__main__":
|
| 55 |
+
main()
|