File size: 3,735 Bytes
a1edd2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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()