问答系统的前后端代码

前端代码

index.tml

<!DOCTYPE html>
<html>

<head>
    <title>桥梁维养领域知识问答</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <script type="text/javascript" src="./js/index.js"></script>
    <script type="text/javascript" src="./js/test.js"></script>
    <link rel="stylesheet" type="text/css" href="./css/index.css">
 
    <link rel="stylesheet" type="text/css" href="./css/test.css">
    <style>        
    </style>
    <script>
        //以下代码是问题文本的处理
        async function sendMessage() {
            var inputElement = document.getElementById('message-input');
            var quesion_message = inputElement.value.trim();

            if (quesion_message !== '') {
                var chatMessagesElement = document.getElementById('chat-messages');
                var userMessageElement = document.createElement('div');
                userMessageElement.textContent = 'You: ' + quesion_message;
                userMessageElement.className = 'user-message';
                chatMessagesElement.appendChild(userMessageElement);

                // Send the message to a server or process it in some way
                // Here, we'll just simulate a delayed bot response
                setTimeout(async function () {
                    // 创建机器人答案消息元素
                    var botMessageElement = document.createElement('div');
                    answer_res = "正在思考答案,请稍等……"
                    //这里写一个调用后端接口的API的返回值的处理相关代码
                    try {
                        // 发送消息给后端API
                        var response = await fetch('http://127.0.0.1:5000/get_answer/', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({ message: quesion_message })
                        });

                        if (response.ok) {
                            var data = await response.json();

                            // 获取答案文本和ID,拼接处理答案
                            var answerText = data.text;
                            var answerID = data.ID;
                            answer_res = answerText

                        } else {
                            console.error('Error:', response.status);
                            answer_res = '不好意思,调用服务端接口出错了,响应状态是response.status';
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        answer_res = '不好意思,服务端接口出错了,错误消息是' + error;
                    }

                    answer_res = 'Bot: This is a response to your message.' + answer_res //要返回给用户的答案
                    botMessageElement.textContent = answer_res;
                    botMessageElement.className = 'bot-message';
                    chatMessagesElement.appendChild(botMessageElement);

                    // Scroll to the bottom of the chat messages
                    chatMessagesElement.scrollTop = chatMessagesElement.scrollHeight;
                }, 1000);

                inputElement.value = '';  // 清空用户输入框
            }
        }
        function handleKeyPress(event) {
            if (event.keyCode === 13) {
                event.preventDefault();
                sendMessage();
            }
        }
    </script>
</head>

<body>    
    <div class="chat-container">
        <div class="chat-header">
            <h1>桥梁维养领域知识问答</h1>
        </div>
        <div id="chat-messages" class="chat-messages"></div>
        <div class="chat-input">
            <button id="voice-input-button" onclick="startSpeechRecognition()">
                <i class="fas fa-microphone"></i>
            </button>
            <input type="text" id="message-input" placeholder="请输入您的问题" onkeypress="handleKeyPress(event)">
            <button onclick="sendMessage()">发送</button>
            <button onclick="showTextBubbles()">显示文本气泡</button>
            <button onclick="addBubbles()">添加文本气泡</button>                      
        </div>
    </div>
</body>

</html>

test.css

.bubble {
    display: inline-block;
    background-color: #f1f1f1;
    color: black;
    padding: 10px;
    border-radius: 10px;
    margin-right: 5px;
}

.bubble-container {
    display: flex;
    align-items: flex-start;
    margin-bottom: 5px;
}

index.css

body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 20px;
}

.chat-container {
    max-width: 800px;
    margin: 0 auto;
    border: 1px solid #ccc;
    border-radius: 5px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;

}

.chat-header {
    background-color: #f2f2f2;
    padding: 10px;
    text-align: center;
}

.chat-messages {
    height: 400px;
    overflow-y: scroll;
    padding: 10px;
    background-color: #fff;
}

.chat-input {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    background-color: #f2f2f2;
}

#voice-input-button {
padding: 5px;
border: none;
background-color: transparent;
color: #888;
cursor: pointer;
font-size: 16px;
transition: color 0.3s;
}

#voice-input-button.active {
color: #4CAF50;
}
.user-message {
    color: blue;
    white-space: pre-line;
    /* 修改为 pre-line */
    text-align: left;
    position: relative;
    background-color: #e1f0ff;
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 10px;
    max-width: 100%;
    overflow-wrap: break-word;
    word-wrap: break-word;
    /* 添加这行 */
    word-break: break-all;
    /* 添加这行 */
    white-space: normal;
    /* 添加这行 */
    width: fit-content;
    /* 根据内容自动调整宽度 */
    margin-left: auto;
    /* 用户消息推向右侧 */
}

.user-message::before {
    content: "";
    position: absolute;
    top: 0;
    right: -10px;
    width: 0;
    height: 0;
    border-top: 14px solid transparent;
    border-left: 14px solid #e1f0ff;
}

.bot-message {
    color: green;
    text-align: left;
    position: relative;
    background-color: #d5ffd5;
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 10px;
    max-width: 100%;
    overflow-wrap: break-word;
    align-self: flex-start;
    /* 机器人文本靠左显示 */
    word-wrap: break-word;
    /* 添加这行 */
    word-break: break-all;
    /* 添加这行 */
    white-space: normal;
    /* 添加这行 */
    width: fit-content;
    /* 根据内容自动调整宽度 */
}

.bot-message::before {
    content: "";
    position: absolute;
    top: 0;
    left: -14px;
    width: 0;
    height: 0;
    border-top: 14px solid transparent;
    border-right: 14px solid #d5ffd5;
}

input[type="text"] {
    flex-grow: 1;
    margin-right: 10px;
    padding: 5px;
    height: 40px;
    /* 调整输入框的高度 */
    font-size: 16px;
    /* 调整输入框的文字大小 */
}

button {
    padding: 5px 10px;
    border: none;
    background-color: #4CAF50;
    color: white;
    cursor: pointer;
    height: 40px;
    font-size: 16px;
    /* 调整按钮的文字大小 */
}

button:hover {
    background-color: #45a049;
}

index.js

// 在语音识别结束后触发的事件处理函数
recognition.onresult = function (event) {
    var result = event.results[0][0].transcript;

    // 将语音识别结果添加到输入框中
    document.getElementById('message-input').value = result;
}

// 更新语音识别按钮的状态
function updateVoiceInputButtonStatus() {
    var voiceInputButton = document.getElementById('voice-input-button');

    if (recognition && recognition.recognizing) {
        voiceInputButton.classList.add('active');
    } else {
        voiceInputButton.classList.remove('active');
    }
}

// 处理点击语音识别按钮的函数
function startSpeechRecognition() {
    // 如果正在识别,则停止识别
    if (recognition && recognition.recognizing) {
        recognition.stop();
        return;
    }

    // 创建 SpeechRecognition 对象,如果尚未创建
    if (!recognition) {
        recognition = new webkitSpeechRecognition();

        // 设置语言为中文(中国)
        recognition.lang = 'zh-CN';

        // 在开始语音识别时触发的事件处理函数
        recognition.onstart = function (event) {
            recognition.recognizing = true;
            updateVoiceInputButtonStatus();
        }

        // 在停止语音识别时触发的事件处理函数
        recognition.onend = function (event) {
            recognition.recognizing = false;
            updateVoiceInputButtonStatus();
        }
    }

    // 开始语音识别
    recognition.start();

    // 更新语音识别按钮的状态
    updateVoiceInputButtonStatus();
}

### 

test.js

function showTextBubbles() {
     // 创建文本气泡元素
     var bubble1 = document.createElement("div");
     var bubble2 = document.createElement("div");
 
     // 设置文本气泡的样式
     bubble1.className = "text-bubble";
     bubble2.className = "text-bubble";
 
     // 设置文本气泡的内容
     bubble1.innerText = "文本气泡1";
     bubble2.innerText = "文本气泡2";
 
     // 将文本气泡添加到聊天消息容器中的底部
     var chatMessages = document.getElementById("chat-messages");
     chatMessages.appendChild(bubble1);
     chatMessages.appendChild(bubble2);
}

function addBubbles() {
    var messagesContainer = document.getElementById("chat-messages");

    // 创建气泡容器
    var bubbleContainer = document.createElement("div");
    bubbleContainer.className = "bubble-container";

    // 创建左侧文本气泡
    var leftBubble = document.createElement("div");
    leftBubble.className = "bubble";
    leftBubble.innerText = "左侧文本气泡";
    bubbleContainer.appendChild(leftBubble);

    // 创建右侧文本气泡
    var rightBubble = document.createElement("div");
    rightBubble.className = "bubble";
    rightBubble.innerText = "右侧文本气泡";
    bubbleContainer.appendChild(rightBubble);

    // 将气泡容器添加到消息容器中
    messagesContainer.appendChild(bubbleContainer);
}

后端代码

# -*- coding: utf-8 -*-
# @Time : 2023-06-26 23:34 
# @Author : 山南君 
# @File : QA_for_bridge.py 
# @Function :
# @History : 
# @Reference : 
# @Software: PyCharm

from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/get_answer/', methods=['POST'])
def get_answer():
    data = request.get_json()
    message = data.get('message')
    # 在这里处理消息,生成相应的答案文本和ID
    answer_text = "这是您的消息的响应: "
    answer_id = 12345
    response = {
        'text': answer_text,
        'ID': answer_id
    }
    # print(message)
    return jsonify(response)

@app.route('/test2/')
def process_message2():
    return 'jsonify(response)'

if __name__ == '__main__':
    app.run()

python包

Flask 2.0.0
Flask-Cors 4.0.0

你可能感兴趣的:(系统研发,flask)