Dhrubob commited on
Commit
a2e6bf6
Β·
verified Β·
1 Parent(s): ad4bdc9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -51
app.py CHANGED
@@ -4,13 +4,13 @@ import pandas as pd
4
  from datetime import datetime
5
  import os
6
 
7
- # -----------------------------
8
- # Load pretrained emotion model
9
- # -----------------------------
10
  model_name = "superb/hubert-large-superb-er"
11
  emotion_classifier = pipeline("audio-classification", model=model_name)
12
 
13
- # Emotion mapping (short label β†’ full name + emoji)
14
  EMOTION_MAP = {
15
  "ang": ("Angry", "😑"),
16
  "hap": ("Happy", "πŸ˜„"),
@@ -23,13 +23,12 @@ EMOTION_MAP = {
23
  "dis": ("Disgusted", "🀒"),
24
  }
25
 
26
- # -----------------------------
27
  # Setup data storage
28
- # -----------------------------
29
  os.makedirs("data", exist_ok=True)
30
  CSV_PATH = "data/customer_complaints_emotion.csv"
31
 
32
- # Example categories β€” these can be linked to your delivery/order system
33
  ORDER_ISSUES = [
34
  "Late Delivery",
35
  "Damaged Package",
@@ -42,75 +41,115 @@ ORDER_ISSUES = [
42
  "Other Complaint"
43
  ]
44
 
45
- # -----------------------------
46
- # Emotion analysis function
47
- # -----------------------------
 
 
 
 
 
 
 
 
 
 
 
48
  def analyze_complaint(audio_file, complaint_type, order_id):
49
  if audio_file is None or not complaint_type or not order_id:
50
- return "⚠️ Please upload an audio complaint, select issue type, and enter Order ID."
 
 
 
 
51
 
52
- # Run prediction
53
  results = emotion_classifier(audio_file)
54
  results = sorted(results, key=lambda x: x['score'], reverse=True)
55
  top = results[0]
56
  label, emoji = EMOTION_MAP.get(top['label'], (top['label'], "🎭"))
57
  score = round(top['score'] * 100, 2)
 
58
 
59
- # -----------------------------
60
- # Build dashboard text
61
- # -----------------------------
62
- dashboard = f"## πŸ“ž Customer Complaint Emotion Dashboard\n"
63
- dashboard += f"### 🎯 Detected Emotion: {emoji} **{label.upper()} ({score}%)**\n\n"
64
- dashboard += f"### πŸ“¦ Complaint Type: **{complaint_type}**\n"
65
- dashboard += f"### 🧾 Order ID: **{order_id}**\n\n"
66
- dashboard += f"### πŸ“Š Emotion Breakdown\n"
 
67
 
 
 
68
  for r in results:
69
  lbl, emo = EMOTION_MAP.get(r['label'], (r['label'], "🎭"))
70
  scr = round(r['score'] * 100, 2)
71
  bar = "β–ˆ" * int(scr / 5)
72
- dashboard += f"{emo} **{lbl}**: {scr}% \n{bar}\n\n"
73
 
74
- # -----------------------------
75
- # Save results to CSV
76
- # -----------------------------
77
  df = pd.DataFrame({
78
  "datetime": [datetime.now().strftime("%Y-%m-%d %H:%M:%S")],
79
  "order_id": [order_id],
80
  "complaint_type": [complaint_type],
81
  "emotion": [label],
82
- "score": [score]
 
83
  })
84
  if os.path.exists(CSV_PATH):
85
  df.to_csv(CSV_PATH, mode="a", header=False, index=False)
86
  else:
87
  df.to_csv(CSV_PATH, index=False)
88
 
89
- return dashboard
90
-
91
-
92
- # -----------------------------
93
- # Gradio Interface
94
- # -----------------------------
95
- app = gr.Interface(
96
- fn=analyze_complaint,
97
- inputs=[
98
- gr.Audio(type="filepath", label="πŸŽ™οΈ Upload Customer Complaint Voice"),
99
- gr.Dropdown(ORDER_ISSUES, label="🚚 Select Complaint Type"),
100
- gr.Textbox(label="πŸ“¦ Enter Order ID"),
101
- ],
102
- outputs="markdown",
103
- title="🎧 Customer Service Emotion Analyzer",
104
- description=(
105
- "Analyze voice-based customer complaints to detect emotions and "
106
- "prioritize based on emotional intensity. Ideal for supply chain "
107
- "and logistics feedback monitoring."
108
- ),
109
- allow_flagging="never",
110
- )
111
-
112
- # -----------------------------
113
- # Run the app
114
- # -----------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  if __name__ == "__main__":
116
  app.launch()
 
4
  from datetime import datetime
5
  import os
6
 
7
+ # ----------------------------------------------------
8
+ # Load pretrained Hugging Face emotion model
9
+ # ----------------------------------------------------
10
  model_name = "superb/hubert-large-superb-er"
11
  emotion_classifier = pipeline("audio-classification", model=model_name)
12
 
13
+ # Emotion mapping
14
  EMOTION_MAP = {
15
  "ang": ("Angry", "😑"),
16
  "hap": ("Happy", "πŸ˜„"),
 
23
  "dis": ("Disgusted", "🀒"),
24
  }
25
 
26
+ # ----------------------------------------------------
27
  # Setup data storage
28
+ # ----------------------------------------------------
29
  os.makedirs("data", exist_ok=True)
30
  CSV_PATH = "data/customer_complaints_emotion.csv"
31
 
 
32
  ORDER_ISSUES = [
33
  "Late Delivery",
34
  "Damaged Package",
 
41
  "Other Complaint"
42
  ]
43
 
44
+ # ----------------------------------------------------
45
+ # Priority estimation
46
+ # ----------------------------------------------------
47
+ def get_priority(label, score):
48
+ if label in ["Angry", "Frustrated", "Fearful", "Disgusted"] and score >= 60:
49
+ return "πŸ”΄ High Priority"
50
+ elif label in ["Sad", "Surprised", "Excited"] and score >= 50:
51
+ return "🟠 Medium Priority"
52
+ else:
53
+ return "🟒 Low Priority"
54
+
55
+ # ----------------------------------------------------
56
+ # Main analysis function
57
+ # ----------------------------------------------------
58
  def analyze_complaint(audio_file, complaint_type, order_id):
59
  if audio_file is None or not complaint_type or not order_id:
60
+ return (
61
+ "⚠️ Please upload an audio complaint, select issue type, and enter Order ID.",
62
+ "",
63
+ None
64
+ )
65
 
66
+ # Run model
67
  results = emotion_classifier(audio_file)
68
  results = sorted(results, key=lambda x: x['score'], reverse=True)
69
  top = results[0]
70
  label, emoji = EMOTION_MAP.get(top['label'], (top['label'], "🎭"))
71
  score = round(top['score'] * 100, 2)
72
+ priority = get_priority(label, score)
73
 
74
+ # Dashboard summary (markdown)
75
+ summary = f"""
76
+ ### 🎯 Detected Emotion: {emoji} **{label.upper()} ({score}%)**
77
+ ### ⚑ Priority Level: {priority}
78
+ ---
79
+ **Complaint Type:** {complaint_type}
80
+ **Order ID:** {order_id}
81
+ **Timestamp:** {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
82
+ """
83
 
84
+ # Detailed emotion breakdown
85
+ breakdown = "### πŸ“Š Emotion Breakdown\n"
86
  for r in results:
87
  lbl, emo = EMOTION_MAP.get(r['label'], (r['label'], "🎭"))
88
  scr = round(r['score'] * 100, 2)
89
  bar = "β–ˆ" * int(scr / 5)
90
+ breakdown += f"{emo} **{lbl}**: {scr}% \n{bar}\n\n"
91
 
92
+ # Save log to CSV
 
 
93
  df = pd.DataFrame({
94
  "datetime": [datetime.now().strftime("%Y-%m-%d %H:%M:%S")],
95
  "order_id": [order_id],
96
  "complaint_type": [complaint_type],
97
  "emotion": [label],
98
+ "score": [score],
99
+ "priority": [priority]
100
  })
101
  if os.path.exists(CSV_PATH):
102
  df.to_csv(CSV_PATH, mode="a", header=False, index=False)
103
  else:
104
  df.to_csv(CSV_PATH, index=False)
105
 
106
+ # Display updated log
107
+ try:
108
+ log_df = pd.read_csv(CSV_PATH).tail(10)
109
+ except:
110
+ log_df = pd.DataFrame()
111
+
112
+ return summary, breakdown, log_df
113
+
114
+
115
+ # ----------------------------------------------------
116
+ # Gradio Interface with Blocks
117
+ # ----------------------------------------------------
118
+ with gr.Blocks(theme=gr.themes.Soft(), title="Customer Complaint Emotion Analyzer") as app:
119
+ gr.Markdown(
120
+ """
121
+ # 🎧 Customer Complaint Emotion Analyzer
122
+ Analyze customer **voice complaints** to detect emotional tone and **auto-prioritize** based on urgency.
123
+ Ideal for logistics, delivery, and supply chain customer service operations.
124
+ ---
125
+ """
126
+ )
127
+
128
+ with gr.Row():
129
+ audio_input = gr.Audio(type="filepath", label="πŸŽ™οΈ Upload Complaint Audio")
130
+ complaint_type = gr.Dropdown(ORDER_ISSUES, label="🚚 Complaint Type", interactive=True)
131
+ order_id = gr.Textbox(label="πŸ“¦ Order ID / Reference Number", placeholder="e.g., ORD123456")
132
+
133
+ analyze_btn = gr.Button("πŸ” Analyze Complaint", variant="primary")
134
+
135
+ with gr.Row():
136
+ summary_output = gr.Markdown(label="Summary")
137
+ breakdown_output = gr.Markdown(label="Detailed Breakdown")
138
+
139
+ with gr.Accordion("πŸ“ Recent Complaint Logs (Last 10 Entries)", open=False):
140
+ log_table = gr.Dataframe(headers=["datetime", "order_id", "complaint_type", "emotion", "score", "priority"], interactive=False)
141
+
142
+ analyze_btn.click(
143
+ fn=analyze_complaint,
144
+ inputs=[audio_input, complaint_type, order_id],
145
+ outputs=[summary_output, breakdown_output, log_table],
146
+ )
147
+
148
+ gr.Markdown("---")
149
+ gr.Markdown("πŸ‘¨β€πŸ’Ό **Developed for Supply Chain Customer Service Emotion Monitoring.**")
150
+
151
+ # ----------------------------------------------------
152
+ # Run app
153
+ # ----------------------------------------------------
154
  if __name__ == "__main__":
155
  app.launch()