forked from TempeHS/TempeHS_Python-Flask_DevContainer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
114 lines (84 loc) · 2.93 KB
/
app.py
File metadata and controls
114 lines (84 loc) · 2.93 KB
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
import re
from flask import Flask, render_template, request, jsonify
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
# Create the Flask application
app = Flask(__name__)
# Initialize the chatbot
chatbot = ChatBot(
"StudentBot",
storage_adapter="chatterbot.storage.SQLStorageAdapter",
database_uri="sqlite:///chatbot_database.sqlite3",
)
# Train the chatbot with English conversations
trainer = ChatterBotCorpusTrainer(chatbot)
trainer.train("chatterbot.corpus.english")
@app.route("/")
def home():
"""Serve the main chat page."""
return render_template("index.html")
# Safety: Keywords that should trigger a mental health response
CRISIS_KEYWORDS = [
"suicide",
"kill myself",
"end my life",
"self harm",
"self-harm",
"dont want to live",
"don't want to live",
"want to die",
]
CRISIS_RESPONSE = """I'm concerned about what you've shared. Please know that you're not alone.
If you're in crisis, please reach out for support:
- Lifeline: 13 11 14 (24/7)
- Kids Helpline: 1800 55 1800
- Beyond Blue: 1300 22 4636
I'm just a chatbot and can't provide the support you need, but these services have trained counselors ready to help right now."""
def check_for_crisis(message):
"""Check if message contains crisis keywords."""
message_lower = message.lower()
for keyword in CRISIS_KEYWORDS:
if keyword in message_lower:
return True
return False
def sanitise_input(message):
"""
Clean and validate user input.
Returns cleaned message or None if invalid.
"""
if not message:
return None
# Remove leading/trailing whitespace
message = message.strip()
# Check if message is empty after stripping
if not message:
return None
# Remove HTML tags (prevents script injection)
message = re.sub(r"<[^>]+>", "", message)
# Check length after cleaning
if len(message) > 500:
return None
return message
@app.route("/chat", methods=["POST"])
@app.route("/chat", methods=["POST"])
def chat():
"""Handle chat messages and return bot responses."""
data = request.get_json()
raw_message = data.get("message", "")
# Sanitise and validate input
user_message = sanitise_input(raw_message)
if user_message is None:
if not raw_message or not raw_message.strip():
return jsonify({"response": "Please enter a message!"})
else:
return jsonify(
{"response": "Message too long! Please keep it under 500 characters."}
)
# Safety check for crisis keywords (use original for better detection)
if check_for_crisis(raw_message):
return jsonify({"response": CRISIS_RESPONSE})
# Get the chatbot's response
bot_response = chatbot.get_response(user_message)
return jsonify({"response": str(bot_response)})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)