チャットボットのための Web アプリケーションのひな形の Python と HTML プログラム(投稿された文章をそのまま返す)(Python を使用)(Windows 上)
前準備
Python のインストール(Windows上)
注:既にPython(バージョン3.12を推奨)がインストール済みの場合は,この手順は不要である.
winget(Windowsパッケージマネージャー)を使用してインストールを行う
- Windowsで,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
- winget(Windowsパッケージマネージャー)が利用可能か確認する:
winget --version
- Pythonのインストール(下のコマンドにより Python 3.12 がインストールされる).
- Python詳細ガイド:Pythonまとめ »
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
- 次のコマンドを実行
コマンドプロンプトを管理者として実行: 別ページ »で説明
python -m pip install -U --ignore-installed pip python -m pip install -U flask flask_cors waitress
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
- 上に示している Python プログラムとHTMLファイルをダウンロードする.
mkdir c:\htdocs cd c:\htdocs del chat.html del chat.py curl -O https://www.kkaneko.jp/ai/win/chat.html curl -O https://www.kkaneko.jp/ai/win/chat.py
- チャットボットのプログラムを起動
新しく Windows のコマンドプロンプトを開き,次のコマンドを実行する.
cd c:\htdocs waitress-serve --listen=0.0.0.0:1000 chat:app
このとき,次のような警告が出る場合がある.そのときには「アクセスを許可する」をクリック.
- Web ブラウザで「http://localhost:1000/chat.html」を開く
- メッセージを入れ「送信」をクリックすることで動作確認.
- ログは,c:\htdocs\chatlog.txt に残る
【関連する外部サイト】
【サイト内の関連ページ】
チャットボットのための Web アプリケーションのひな形の Python と HTML プログラム(投稿された文章をそのまま返す)
flask, flask_cors, waitress のインストール
チャットボットのための Web アプリケーションのひな形の Python と HTML プログラム(投稿された文章をそのまま返す)を動かす
次の Python プログラムとHTMLファイルを使用する.
Python プログラム
# 準備
# python -m pip install -U flask flask_cors waitress
# 実行
# python chat.py ... development server
# waitress-serve --listen=0.0.0.0:1000 chat:app
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import os
app = Flask(__name__)
CORS(app)
def append_to_chatlog(text):
file_path = 'chatlog.txt'
with open(file_path, 'a', encoding='utf-8') as file:
file.write(text + '\n')
@app.route('/response', methods=['POST'])
def respond():
# POST リクエストからメッセージを取得
message = request.get_json().get('message', '')
append_to_chatlog('Q: ' + message)
# レスポンスメッセージは受け取ったメッセージをそのまま返します
response_message = "Received: " + message
append_to_chatlog('A: ' + response_message)
return jsonify({'message': response_message})
@app.route('/chat.html')
def send_chat_html():
return send_from_directory('.', 'chat.html')
if __name__ == '__main__':
app.run(host='localhost', port=1000, debug=True)
HTML ファイル
<!DOCTYPE html>
<HTML LANG="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<meta http-equiv="Content-Style-Type" content="text/css">
</head>
<body>
<h2>チャットボット</h2>
<div id="chatLog" style="height: 200px; border: 1px solid #000; padding: 10px; overflow: auto;"></div>
<input id="userInput" type="text" placeholder="メッセージを入力してください..." style="width: 80%;" />
<button onclick="sendMessage()">送信</button>
<script>
async function sendMessage() {
var input = document.getElementById('userInput');
var chatLog = document.getElementById('chatLog');
// ユーザーのメッセージを表示
chatLog.innerHTML += 'Q: ' + input.value + '<br />';
// ボットからの応答を生成
var botResponse = await generateBotResponse(input.value);
chatLog.innerHTML += 'A: ' + botResponse + '<br />';
// チャットログを一番下にスクロール
chatLog.scrollTop = chatLog.scrollHeight;
// 入力フィールドをクリア
input.value = '';
}
async function generateBotResponse(userMessage) {
try {
// ボットにメッセージを送信して応答を取得
const response = await fetch('http://localhost:1000/response', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ message: userMessage })
});
if (!response.ok) {
throw new Error('サーバからの応答が正しく行われませんでした');
}
const data = await response.json();
return data.message;
} catch (error) {
console.error('サーバとの通信に問題が発生しました', error);
return 'サーバとの通信に問題が発生しました.もう一度メッセージを送信してみてください';
}
}
</script>
</body>
</html>