Dhrubob's picture
Create app.py
a1edd2e verified
raw
history blame
3.74 kB
import gradio as gr
from transformers import pipeline
import pandas as pd
from datetime import datetime
import os
# -----------------------------
# Load pretrained emotion model
# -----------------------------
model_name = "superb/hubert-large-superb-er"
emotion_classifier = pipeline("audio-classification", model=model_name)
# Emotion mapping (short label β†’ full name + emoji)
EMOTION_MAP = {
"ang": ("Angry", "😑"),
"hap": ("Happy", "πŸ˜„"),
"neu": ("Neutral", "😐"),
"sad": ("Sad", "😒"),
"exc": ("Excited", "🀩"),
"fru": ("Frustrated", "😀"),
"fea": ("Fearful", "😨"),
"sur": ("Surprised", "😲"),
"dis": ("Disgusted", "🀒"),
}
# -----------------------------
# Setup data storage
# -----------------------------
os.makedirs("data", exist_ok=True)
CSV_PATH = "data/customer_complaints_emotion.csv"
# Example categories β€” these can be linked to your delivery/order system
ORDER_ISSUES = [
"Late Delivery",
"Damaged Package",
"Wrong Product Delivered",
"Missing Items",
"Rude Delivery Staff",
"Payment Issue",
"Return/Refund Request",
"Order Cancelled Automatically",
"Other Complaint"
]
# -----------------------------
# Emotion analysis function
# -----------------------------
def analyze_complaint(audio_file, complaint_type, order_id):
if audio_file is None or not complaint_type or not order_id:
return "⚠️ Please upload an audio complaint, select issue type, and enter Order ID."
# Run prediction
results = emotion_classifier(audio_file)
results = sorted(results, key=lambda x: x['score'], reverse=True)
top = results[0]
label, emoji = EMOTION_MAP.get(top['label'], (top['label'], "🎭"))
score = round(top['score'] * 100, 2)
# -----------------------------
# Build dashboard text
# -----------------------------
dashboard = f"## πŸ“ž Customer Complaint Emotion Dashboard\n"
dashboard += f"### 🎯 Detected Emotion: {emoji} **{label.upper()} ({score}%)**\n\n"
dashboard += f"### πŸ“¦ Complaint Type: **{complaint_type}**\n"
dashboard += f"### 🧾 Order ID: **{order_id}**\n\n"
dashboard += f"### πŸ“Š Emotion Breakdown\n"
for r in results:
lbl, emo = EMOTION_MAP.get(r['label'], (r['label'], "🎭"))
scr = round(r['score'] * 100, 2)
bar = "β–ˆ" * int(scr / 5)
dashboard += f"{emo} **{lbl}**: {scr}% \n{bar}\n\n"
# -----------------------------
# Save results to CSV
# -----------------------------
df = pd.DataFrame({
"datetime": [datetime.now().strftime("%Y-%m-%d %H:%M:%S")],
"order_id": [order_id],
"complaint_type": [complaint_type],
"emotion": [label],
"score": [score]
})
if os.path.exists(CSV_PATH):
df.to_csv(CSV_PATH, mode="a", header=False, index=False)
else:
df.to_csv(CSV_PATH, index=False)
return dashboard
# -----------------------------
# Gradio Interface
# -----------------------------
app = gr.Interface(
fn=analyze_complaint,
inputs=[
gr.Audio(type="filepath", label="πŸŽ™οΈ Upload Customer Complaint Voice"),
gr.Dropdown(ORDER_ISSUES, label="🚚 Select Complaint Type"),
gr.Textbox(label="πŸ“¦ Enter Order ID"),
],
outputs="markdown",
title="🎧 Customer Service Emotion Analyzer",
description=(
"Analyze voice-based customer complaints to detect emotions and "
"prioritize based on emotional intensity. Ideal for supply chain "
"and logistics feedback monitoring."
),
allow_flagging="never",
)
# -----------------------------
# Run the app
# -----------------------------
if __name__ == "__main__":
app.launch()