File size: 4,128 Bytes
ebb4774
641deba
 
ebb4774
 
641deba
7d8a7af
641deba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebb4774
7d8a7af
ebb4774
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa92b28
ebb4774
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
from flask import Flask, render_template_string, request, jsonify
import random

app = Flask(__name__)

class ChatBot:
    def __init__(self, name="Sophia"):
        self.name = name
        self.responses = {
            "greeting": [
                "Hey there! 👋",
                "Hello, how’s your day going?",
                "Hi! What’s on your mind?"
            ],
            "farewell": [
                "Goodbye 👋",
                "Catch you later!",
                "See you soon!"
            ],
            "default": [
                "Interesting… tell me more.",
                "Hmm, I see. Go on.",
                "That’s something to think about."
            ]
        }

    def understand(self, user_input):
        text = user_input.lower()
        if any(word in text for word in ["hi", "hello", "hey"]):
            return "greeting"
        elif any(word in text for word in ["bye", "goodnight", "see you"]):
            return "farewell"
        else:
            return "default"

    def respond(self, user_input):
        intent = self.understand(user_input)
        return random.choice(self.responses[intent])

bot = ChatBot("Sophia")

# ---------------- HTML Template ----------------
page = """
<!DOCTYPE html>
<html>
<head>
    <title>{{ bot_name }} ChatBot</title>
    <style>
        body { font-family: Arial, sans-serif; background: #f4f4f9; }
        #chatbox { width: 100%; max-width: 600px; margin: 30px auto; padding: 20px;
                   background: white; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.2); }
        #messages { height: 400px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; border-radius: 5px; }
        .msg { margin: 5px 0; }
        .user { color: blue; }
        .bot { color: green; }
        #inputArea { margin-top: 10px; display: flex; }
        #userInput { flex: 1; padding: 10px; }
        #sendBtn { padding: 10px 20px; }
    </style>
</head>
<body>
    <div id="chatbox">
        <h2>{{ bot_name }} 🤖</h2>
        <div id="messages">
            <div class="msg bot">{{ bot_name }}: Hi! I'm {{ bot_name }}. Type 'quit' to end.</div>
        </div>
        <div id="inputArea">
            <input type="text" id="userInput" placeholder="Type your message..." autofocus>
            <button id="sendBtn">Send</button>
        </div>
    </div>

    <script>
        const sendBtn = document.getElementById("sendBtn");
        const userInput = document.getElementById("userInput");
        const messages = document.getElementById("messages");

        function addMessage(sender, text) {
            const div = document.createElement("div");
            div.classList.add("msg", sender);
            div.textContent = sender === "user" ? "You: " + text : "{{ bot_name }}: " + text;
            messages.appendChild(div);
            messages.scrollTop = messages.scrollHeight;
        }

        async function sendMessage() {
            const text = userInput.value.trim();
            if (!text) return;
            addMessage("user", text);
            userInput.value = "";
            
            const response = await fetch("/chat", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ message: text })
            });
            const data = await response.json();
            addMessage("bot", data.reply);
        }

        sendBtn.addEventListener("click", sendMessage);
        userInput.addEventListener("keypress", function(e) {
            if (e.key === "Enter") sendMessage();
        });
    </script>
</body>
</html>
"""

# ---------------- Routes ----------------
@app.route("/")
def home():
    return render_template_string(page, bot_name=bot.name)

@app.route("/chat", methods=["POST"])
def chat():
    user_msg = request.json.get("message", "")
    if user_msg.lower() in ["quit", "exit"]:
        reply = "It was nice chatting with you. Bye!"
    else:
        reply = bot.respond(user_msg)
    return jsonify({"reply": reply})


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)