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 = """ {{ bot_name }} ChatBot

{{ bot_name }} 🤖

{{ bot_name }}: Hi! I'm {{ bot_name }}. Type 'quit' to end.
""" # ---------------- 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)