Chatbot / app.py
priyanshuarya1221's picture
Upload 4 files
270b017 verified
Raw
History Blame Contribute Delete
3.06 kB
import gradio as gr
import pandas as pd
import re
import os
# Load dataset from local CSV
df = pd.read_csv("Bitext_Sample_CustomerSupport_Training_Dataset.csv")
# Placeholder values
placeholders = {
"{{Order Number}}": "ORD12345",
"{{Currency Symbol}}": "$",
"{{Refund Amount}}": "100",
"{{Online Company Portal Info}}": "www.company.com",
"{{Online Order Interaction}}": "My Orders",
"{{Customer Support Hours}}": "9 AM - 5 PM",
"{{Customer Support Phone Number}}": os.getenv("SUPPORT_PHONE", "1-800-123-4567"),
"{{Website URL}}": "www.company.com/support"
}
def preprocess_text(text):
text = text.lower().strip()
text = re.sub(r'[^\w\s]', '', text)
return text
def extract_order_number(user_input):
match = re.search(r'\b(ord\d+)\b', user_input, re.IGNORECASE)
return match.group(1) if match else placeholders["{{Order Number}}"]
def extract_refund_amount(user_input):
match = re.search(r'\b(\d+)(?:\s*dollars?)?\b', user_input, re.IGNORECASE)
return match.group(1) if match else placeholders["{{Refund Amount}}"]
def match_intent(user_input):
user_input_cleaned = preprocess_text(user_input)
best_match = None
highest_score = 0
for index, row in df.iterrows():
instruction_cleaned = preprocess_text(row['instruction'])
user_words = set(user_input_cleaned.split())
instruction_words = set(instruction_cleaned.split())
common_words = user_words.intersection(instruction_words)
score = len(common_words) / max(len(instruction_words), 1)
if score > highest_score and score > 0.3:
highest_score = score
best_match = row
return best_match
def generate_response(user_input):
matched_row = match_intent(user_input)
if not matched_row:
return "I'm sorry, I didn't understand your request. Could you please clarify or provide more details? For example, mention your order number or refund amount."
response = matched_row['response']
local_placeholders = placeholders.copy()
if matched_row['intent'] == 'cancel_order':
local_placeholders["{{Order Number}}"] = extract_order_number(user_input)
elif matched_row['intent'] == 'track_refund':
local_placeholders["{{Refund Amount}}"] = extract_refund_amount(user_input)
for placeholder, value in local_placeholders.items():
response = response.replace(placeholder, value)
return response
# Gradio chat function
def chatbot(message, history):
return generate_response(message)
# Create Gradio interface
interface = gr.ChatInterface(
fn=chatbot,
title="Customer Support Chatbot",
description="Ask about order cancellations or refund tracking (e.g., 'cancel order ORD12345' or 'refund status for $50').",
theme="soft",
submit_btn="Send",
retry_btn=None,
undo_btn=None,
clear_btn="Clear"
)
# Launch (handled by Hugging Face Spaces)
if __name__ == "__main__":
interface.launch()