Skip to content

Instantly share code, notes, and snippets.

@kujirahand
Created February 6, 2024 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kujirahand/5d365ee1f065cbee8ee833f25d196ad5 to your computer and use it in GitHub Desktop.
Save kujirahand/5d365ee1f065cbee8ee833f25d196ad5 to your computer and use it in GitHub Desktop.
Node.jsとChatGPT APIを使った翻訳ツール
// ライブラリを読み込む --- (*1)
const express = require('express');
const OpenAI = require('openai')
const path = require('path')
// APIキーを設定する(以下は書き換えが必要です★★★) --- (*2)
const API_KEY = 'xxx'
// const API_KEY = process.env['OPENAI_API_KEY']
// APIキーを設定したオブジェクトを生成
const openai = new OpenAI({ apiKey: API_KEY });
// ChatGPTに入力するプロンプトのテンプレート --- (*3)
const PROMPT_TEMPLATE = `
### 指示:
次の入力を英語、中国語、韓国語、スペイン語に翻訳してください。
### 入力:
"""__input__"""
### 出力例:
- 英語: ***
- 中国語: ***
- 韓国語: ***
- スペイン語: ***
`
// ChatGPT APIを呼び出す非同期の関数を定義 --- (*4)
async function callChatgpt(msg) {
const params = {
messages: [{ role: 'user', content: msg }],
model: 'gpt-3.5-turbo',
};
const chatCompletion = await openai.chat.completions.create(params);
return chatCompletion.choices[0].message.content;
}
// Webサーバーを起動 --- (*5)
const app = express();
const port = 3001;
const server = app.listen(port, () => {
console.log('[URL] http://localhost:' + port);
});
// サーバーの応答を設定 --- (*6)
app.get('/', (_req, res) => { //index.htmlを返す
res.sendFile(path.join(__dirname, 'index.html'));
});
// 翻訳の応答を設定 --- (*7)
app.get('/translate', async (req, res) => {
let q = '' + req.query.q;
q = q.replace(/"/g, '')
// テンプレートを置換してChatGPTに問い合わせる --- (*8)
const prompt = PROMPT_TEMPLATE.replace('__input__', q);
const result = await callChatgpt(prompt);
const toHtml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
// 結果を戻す --- (*9)
res.send(toHtml(result));
});
@kujirahand
Copy link
Author

kujirahand commented Feb 6, 2024

そして、以下が上記のプログラムで使うindex.htmlです。同じディレクトリに配置して使います。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8"><title>翻訳ツール</title>
  <style>
    textarea { width: 99%; background-color: bisque;}
  </style>
</head>
<body>
  <h1>翻訳ツール</h1>
  <div>
    翻訳したい内容を下記に入力:<br>
    <textarea id="q" rows="4"></textarea><br>
    <button onclick="getResult()">翻訳</button>
    </form>
  </div>
  <div>
    <h3>翻訳結果:</h3>
    <div>
        <textarea id="result" rows="8"></textarea>
    </div>
  </div>
  <script type="text/javascript">
    // 翻訳ボタンが押された時の処理 --- (*1)
    function getResult() {
      // 入力されたテキストを取得 --- (*2)
      const text = document.getElementById('q').value;
      const result = document.getElementById('result');
      result.value = '翻訳しています。少々お待ちください...';
      // サーバーに翻訳をリクエスト --- (*3)
      const query = `q=${encodeURIComponent(text)}`;
      fetch(`/translate?${query}`)
      .then(response => response.text())
      .then(resultText => result.value = resultText);
    }
  </script>
</body>
</html>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment