LoginSignup
0
1

DeepL APIを利用して英語を日本語に翻訳

Last updated at Posted at 2023-12-06

はじめに

自分は英語がとても苦手で日常生活中で頻繁に翻訳サイトを利用しています。
その為、いつもお世話になっているDeepLの翻訳機能を自分のサイトなどで起動できるようにしてみました。

今回使用したDeepL APIの説明

Freeプラン(無料)
・すべての機能をご利用可能
・DeepL REST APIへのアクセス
・1か月に500,000文字まで翻訳
・1,000個の用語集(一部言語のみ)

Proプラン(月/650円)
・万全のセキュリティ対策
・DeepL REST APIへのアクセス
・翻訳できるテキスト量に制限なし
・1,000個の用語集(一部言語のみ)
・ご利用分だけお支払い(1,000,000文字あたり¥2,500)
・リクエストを優先的に処理

今回は、Freeプランで作成しました。(金がないため)

Pythonで実行

main.py
import requests


def translate_text(text, target_lang='EN'):
  api_url = 'https://api-free.deepl.com/v2/translate'
  api_key = 'APIの認証キー'

  data = {'text': text, 'target_lang': target_lang, 'auth_key': api_key}

  response = requests.post(api_url, data=data)

  if response.status_code == 200:
    result = response.json()
    translations = result.get('translations', [])
    if translations:
      return translations[0].get('text', '')
    else:
      return 'Translation not available.'
  else:
    return f'Error: {response.status_code}, {response.text}'


user_input = input('日本語の文を入力して: ')

english_translation = translate_text(user_input)

print(f'日本語: {user_input}')
print(f'英語: {english_translation}')

結果
スクリーンショット 2023-12-06 16.54.44.png

『api_key = 'APIの認証キー'』のAPI認証キー部分に、各自自分で取得したキーを入れてください。

htmlとJavaScriptを利用して実行

index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>翻訳</title>
  <style>
    #inputText {
      width: 50%;
      height: 80px;
    }

    #outputText {
      width: 50%;
      height: 80px;
      margin-top: 10px;
    }

    #translateBtn {
      margin-top: 50px;
    }
  </style>
</head>
<body>
  <h1>英語→日本語翻訳</h1>
  <label for="inputText">日本語を入力:</label>
  <textarea id="inputText" placeholder="Enter text to translate"></textarea>
  <button id="translateBtn">翻訳</button>
  <textarea id="outputText" readonly></textarea>
  <label for="outputText">結果:</label>

  <script src="app.js"></script>
</body>
</html>
app.js
document.addEventListener('DOMContentLoaded', function () {
    const apiKey = '認証キー'; 
    const translateBtn = document.getElementById('translateBtn');
    const inputText = document.getElementById('inputText');
    const outputText = document.getElementById('outputText');
  
    translateBtn.addEventListener('click', function () {
      const textToTranslate = inputText.value;
  
      fetch('https://api-free.deepl.com/v2/translate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `auth_key=${apiKey}&text=${encodeURIComponent(textToTranslate)}&target_lang=EN-US`,
      })
        .then(response => response.json())
        .then(data => {
          if (data.translations && data.translations.length > 0) {
            outputText.value = data.translations[0].text;
          } else {
            outputText.value = 'Translation failed.';
          }
        })
        .catch(error => {
          console.error('Error translating text:', error);
          outputText.value = 'Translation failed.';
        });
    });
  });

結果
スクリーンショット 2023-12-06 17.51.58.png

Pythonの時と同じで、『const apiKey = '認証キー';』の認証キーのところに各自のキーを入力してください。

まとめ

今回行ってみて、結構簡単に翻訳機能をつけることができたため他のシステムやサイトと連携や、UIを凝ったものにするなどもしてみたいなと思います。
また、今回利用したDeepL APIのFreeプランでは翻訳する文字数に制限があるため利用する際は注意して利用しましょう。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1