Spaces:
Runtime error
Runtime error
| 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__) | |
| def index(): | |
| return render_template("chat.html") # Make sure chat.html exists | |
| def chat(): | |
| msg = request.form["msg"] | |
| response = chatbot_response(msg) | |
| return response | |
| if __name__ == "__main__": | |
| app.run(debug=False) |