File size: 1,951 Bytes
cfe1b75
 
 
 
 
39e9f62
 
 
cfe1b75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import random
from fuzzywuzzy import process
from flask import Flask, request, render_template
import joblib

app = Flask(__name__)

# Load intents.json
with open("static/intents.json", "r") as file:
    intents = json.load(file)

import joblib
nlp = joblib.load("static/chatbot_model1.joblib")

# Extract all possible questions for fuzzy matching
all_questions = []
question_to_intent = {}
for intent in intents["intents"]:
    for pattern in intent["patterns"]:
        all_questions.append(pattern)
        question_to_intent[pattern] = intent["tag"]

# Function to get intent using the trained model
def get_intent(text):
    doc = nlp(text)
    intent = max(doc.cats, key=doc.cats.get)
    return intent, doc.cats[intent]

# Function for fuzzy matching
def fuzzy_match(text, questions, threshold=80):
    match, score = process.extractOne(text, questions)
    return match if score >= threshold else None

# Function to get chatbot response
def chatbot_response(user_input):
    intent, confidence = get_intent(user_input)

    if confidence > 0.75:  # If spaCy model is confident
        for intent_data in intents["intents"]:
            if intent_data["tag"] == intent:
                return random.choice(intent_data["responses"])

    # Fallback to fuzzy matching
    best_match = fuzzy_match(user_input, all_questions)
    if best_match:
        matched_intent = question_to_intent[best_match]
        for intent_data in intents["intents"]:
            if intent_data["tag"] == matched_intent:
                return random.choice(intent_data["responses"])

    return "Sorry, I didn't understand that. Can you rephrase?"

# Flask routes
@app.route("/")
def index():
    return render_template("chat.html")  # Make sure chat.html exists

@app.route("/get", methods=["POST"])
def chat():
    msg = request.form["msg"]
    response = chatbot_response(msg)
    return response

if __name__ == "__main__":
    app.run(debug=False)