File size: 2,329 Bytes
cfe1b75
 
 
 
 
6de1ff2
 
 
39e9f62
6de1ff2
 
 
 
 
 
 
39e9f62
6de1ff2
 
cfe1b75
 
6de1ff2
 
cfe1b75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6de1ff2
cfe1b75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6de1ff2
 
cfe1b75
 
 
 
 
 
 
 
 
 
 
6de1ff2
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
import json
import random
from fuzzywuzzy import process
from flask import Flask, request, render_template
import joblib
from huggingface_hub import hf_hub_download
import os
from dotenv import load_dotenv

def config():
    load_dotenv()

API_Key = os.getenv('token')
database_ID = os.getenv('db_database_ID') 
fl_name = os.getenv('fl_name')
model_name = os.getenv('model_name')

intents_path = hf_hub_download(repo_id=database_ID, filename=fl_name, use_auth_token=API_Key)
with open(intents_path, "r") as file:
    intents = json.load(file)

model_path = hf_hub_download(repo_id=database_ID, filename=model_name, use_auth_token=API_Key)
nlp = joblib.load(model_path)

# 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 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 = Flask(__name__)

@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)