-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
58 lines (42 loc) · 1.66 KB
/
app.py
File metadata and controls
58 lines (42 loc) · 1.66 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
from flask import Flask, render_template, request, jsonify
import json
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from utils.text_preprocessing import clean_text
app = Flask(__name__)
# ------------------ Load FAQ Data ------------------
with open("data/faqs.json", "r", encoding="utf-8") as file:
faq_data = json.load(file)
questions = [clean_text(faq["question"]) for faq in faq_data]
answers = [faq["answer"] for faq in faq_data]
# ------------------ Vectorization ------------------
vectorizer = TfidfVectorizer(
ngram_range=(1, 2),
stop_words="english"
)
question_vectors = vectorizer.fit_transform(questions)
# ------------------ Routes ------------------
@app.route("/")
def home():
return render_template("index.html")
@app.route("/get", methods=["POST"])
def chatbot_response():
user_message = request.form.get("msg", "")
if not user_message:
return jsonify({"reply": "Please enter a question."})
user_input = clean_text(user_message)
user_vector = vectorizer.transform([user_input])
similarity_scores = cosine_similarity(user_vector, question_vectors)
best_match_index = similarity_scores.argmax()
confidence_score = similarity_scores[0][best_match_index]
if confidence_score >= 0.35:
response = answers[best_match_index]
else:
response = "Sorry, I couldn't understand that. Please try asking differently."
return jsonify({
"reply": response,
"confidence": round(float(confidence_score), 2)
})
# ------------------ Main ------------------
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)