プロジェクトのファイル構成
chatbot_project/
│
├── app.py
├── chatbot.db (自動生成されます)
├── requirements.txt
├── templates/
│ └── index.html
└── static/
└── css/
└── style.css
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AIチャットボット</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<style>
.chat-container {
max-width: 700px;
margin: 50px auto;
background: #fff;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
overflow: hidden;
}
.messages {
height: 500px;
overflow-y: auto;
border-bottom: 1px solid #ddd;
padding: 20px;
}
.message {
margin: 10px 0;
}
.user .message-content {
background: #007bff;
color: #fff;
border-radius: 15px 15px 0 15px;
padding: 10px 15px;
display: inline-block;
}
.bot .message-content {
background: #f1f1f1;
border-radius: 15px 15px 15px 0;
padding: 10px 15px;
display: inline-block;
}
.input-group {
padding: 20px;
}
</style>
</head>
<body>
<div class="chat-container">
<div class="messages" id="messages"></div>
<div class="input-group">
<input type="text" id="userInput" class="form-control" placeholder="メッセージを入力">
<div class="input-group-append">
<button class="btn btn-primary" onclick="sendMessage()">送信</button>
</div>
</div>
</div>
<script>
async function sendMessage() {
const userInput = document.getElementById('userInput').value;
if (userInput.trim() === "") return;
displayMessage(userInput, 'user');
document.getElementById('userInput').value = "";
try {
const response = await fetch('/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: userInput })
});
const data = await response.json();
displayMessage(data.reply, 'bot');
} catch (error) {
displayMessage('エラーが発生しました。', 'bot');
}
}
function displayMessage(message, sender) {
const messagesDiv = document.getElementById('messages');
const messageDiv = document.createElement('div');
messageDiv.className = `message ${sender}`;
const messageContent = document.createElement('div');
messageContent.className = 'message-content';
messageContent.textContent = message;
messageDiv.appendChild(messageContent);
messagesDiv.appendChild(messageDiv);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
</script>
</body>
</html>
style.css
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
app.py
from flask import Flask, request, jsonify, render_template
import nltk
from nltk.chat.util import Chat, reflections
import spacy
import sqlite3
import os
app = Flask(__name__)
nlp = spacy.load('en_core_web_sm')
pairs = [
[
r"こんにちは|やあ|おはよう",
["こんにちは!", "やあ!", "おはようございます!"]
],
[
r"あなたの名前は何ですか?",
["私はAIチャットボットです。", "私の名前はまだありません。"]
],
[
r"さようなら|バイバイ",
["さようなら!", "またね!"]
]
]
chat = Chat(pairs, reflections)
# SQLiteデータベース接続
def get_db_connection():
conn = sqlite3.connect('chatbot.db')
conn.row_factory = sqlite3.Row
return conn
with get_db_connection() as conn:
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_message TEXT,
bot_response TEXT
)
''')
conn.commit()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/chat', methods=['POST'])
def chat_response():
user_message = request.json.get('message')
response = chat.respond(user_message)
if response is None:
response = advanced_nlp_response(user_message)
with get_db_connection() as conn:
c = conn.cursor()
c.execute('INSERT INTO messages (user_message, bot_response) VALUES (?, ?)', (user_message, response))
conn.commit()
return jsonify({'reply': response})
def advanced_nlp_response(user_message):
doc = nlp(user_message)
if doc.ents:
entities = [ent.text for ent in doc.ents]
return f"あなたのメッセージには次のエンティティが含まれています: {', '.join(entities)}"
else:
return "ごめんなさい、理解できませんでした。"
@app.route('/history', methods=['GET'])
def chat_history():
with get_db_connection() as conn:
c = conn.cursor()
c.execute('SELECT * FROM messages')
rows = c.fetchall()
history = [{"user_message": row["user_message"], "bot_response": row["bot_response"]} for row in rows]
return jsonify(history)
if __name__ == '__main__':
nltk.download('punkt')
app.run(debug=True)