Spaces:
Sleeping
Sleeping
| import requests | |
| import os | |
| import unicodedata | |
| from langdetect import detect | |
| import deepl | |
| from dotenv import load_dotenv, find_dotenv | |
| _ = load_dotenv(find_dotenv()) | |
| DEBUG=os.getenv("DEBUG") | |
| DEEPL_URL="https://api-free.deepl.com/v2/translate" | |
| def DeepL(text,source_lang="JA",target_lang="EN",API_KEY=os.getenv("DEEPL")): | |
| #paraters パラメータの指定 | |
| params = { | |
| 'auth_key' : API_KEY, | |
| 'text' : text, | |
| 'source_lang' : source_lang, # 翻訳対象の言語 | |
| "target_lang": target_lang # 翻訳後の言語 | |
| } | |
| # リクエストを投げる | |
| request = requests.post(DEEPL_URL, data=params) # URIは有償版, 無償版で異なるため要注意 | |
| result = request.json() | |
| if DEBUG: | |
| print("DeepL Request print") | |
| print(result) | |
| if "translations" not in result: | |
| print("DEEPL ERROR") | |
| print(result) | |
| return "404" | |
| return result["translations"][0]["text"] | |
| def detect_and_translate(text): | |
| # Detect language | |
| try: | |
| lang = detect(text) | |
| print(lang) | |
| except: | |
| return "Error detecting language" | |
| # If language is not English, translate it | |
| if lang != "en": | |
| text=DeepL(text,source_lang=lang,target_lang="EN",API_KEY=os.getenv("DEEPL")) | |
| return text | |
| def main(): | |
| test_test="DEEPLのテストの翻訳です" | |
| print(detect_and_translate(test_test)) | |
| if __name__=="__main__": | |
| main() |