金子邦彦研究室人工知能Windows で動く人工知能関係 Pythonアプリケーション,オープンソースソフトウエア)チャットボットのための Web アプリケーションのひな形の Python と HTML プログラム(投稿された文章をそのまま返す)(Python を使用)(Windows 上)

チャットボットのための Web アプリケーションのひな形の Python と HTML プログラム(投稿された文章をそのまま返す)(Python を使用)(Windows 上)

目次

  1. 前準備
  2. チャットボットのための Web アプリケーションのひな形の Python と HTML プログラム(投稿された文章をそのまま返す)

前準備

Python のインストール(Windows 上)

サイト内の関連ページ

関連する外部ページ

Python の公式ページ: https://www.python.org/

チャットボットのための Web アプリケーションのひな形の Python と HTML プログラム(投稿された文章をそのまま返す)

flask, flask_cors, waitress のインストール

  1. Windows で,コマンドプロンプト管理者として実行
  2. 次のコマンドを実行

    コマンドプロンプトを管理者として実行: 別ページ »で説明

    python -m pip install -U --ignore-installed pip
    python -m pip install -U 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>
  1. Windows で,コマンドプロンプト管理者として実行

    コマンドプロンプトを管理者として実行: 別ページ »で説明

  2. 上に示している 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
    
  3. チャットボットのプログラムを起動

    新しく Windowsコマンドプロンプトを開き、次のコマンドを実行する.

    cd c:\htdocs
    waitress-serve --listen=0.0.0.0:1000 chat:app
    

    [image]

    このとき,次のような警告が出る場合がある.そのときには「アクセスを許可する」をクリック.

    [image]
  4. Web ブラウザで「http://localhost:1000/chat.html」を開く

    [image]
  5. メッセージを入れ「送信」をクリックすることで動作確認.

    [image]
  6. ログは,c:\htdocs\chatlog.txt に残る

    [image]