【サイト内の関連ページ】
【関連する外部ページ】
Python の公式ページ: https://www.python.org/
コマンドプロンプトを管理者として実行: 別ページ »で説明
python -m pip install -U --ignore-installed pip python -m pip install -U flask flask_cors waitress
次の 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>
コマンドプロンプトを管理者として実行: 別ページ »で説明
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
このとき,次のような警告が出る場合がある.そのときには「アクセスを許可する」をクリック.