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)