Dhrubob commited on
Commit
2f6d242
Β·
verified Β·
1 Parent(s): 1189f71

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -57
app.py CHANGED
@@ -4,10 +4,11 @@ import pandas as pd
4
  from datetime import datetime
5
  import sqlite3
6
  import os
 
7
 
8
- # -------------------------------
9
- # 🎯 Initialize Model and Database
10
- # -------------------------------
11
  MODEL_NAME = "superb/hubert-large-superb-er"
12
  emotion_classifier = pipeline("audio-classification", model=MODEL_NAME)
13
 
@@ -15,7 +16,6 @@ os.makedirs("data", exist_ok=True)
15
  DB_PATH = "data/scm_emotion.db"
16
 
17
  def init_db():
18
- """Create SQLite database table if it doesn't exist."""
19
  conn = sqlite3.connect(DB_PATH)
20
  cursor = conn.cursor()
21
  cursor.execute("""
@@ -32,26 +32,25 @@ def init_db():
32
 
33
  init_db()
34
 
35
- # -------------------------------
36
- # πŸ˜„ Emotion Mapping
37
- # -------------------------------
38
  EMOTION_MAP = {
39
- "ang": ("Angry", "😑"),
40
- "hap": ("Happy", "πŸ˜„"),
41
- "neu": ("Neutral", "😐"),
42
- "sad": ("Sad", "😒"),
43
- "exc": ("Excited", "🀩"),
44
- "fru": ("Frustrated", "😀"),
45
- "fea": ("Fearful", "😨"),
46
- "sur": ("Surprised", "😲"),
47
- "dis": ("Disgusted", "🀒"),
48
  }
49
 
50
- # -------------------------------
51
- # πŸ’Ύ Logging Function
52
- # -------------------------------
53
  def log_to_db(datetime_str, department, emotion, score):
54
- """Insert analyzed record into SQLite database."""
55
  conn = sqlite3.connect(DB_PATH)
56
  cursor = conn.cursor()
57
  cursor.execute(
@@ -61,58 +60,83 @@ def log_to_db(datetime_str, department, emotion, score):
61
  conn.commit()
62
  conn.close()
63
 
64
- # -------------------------------
65
- # 🎧 Core Emotion Analysis
66
- # -------------------------------
67
  def analyze_emotion(audio, department):
68
  if audio is None or not department:
69
- return "⚠️ Please record/upload audio and select a department."
70
 
71
- # Handle both live mic input (tuple) and uploaded file (path)
72
  if isinstance(audio, tuple):
73
  audio_file = audio[0]
74
  else:
75
  audio_file = audio
76
 
77
- # Run model prediction
78
  results = emotion_classifier(audio_file)
79
  results = sorted(results, key=lambda x: x['score'], reverse=True)
80
  top = results[0]
81
- label, emoji = EMOTION_MAP.get(top['label'], (top['label'], "🎭"))
82
  score = round(top['score'] * 100, 2)
83
 
84
- # Log to database
85
  log_to_db(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), department, label, score)
86
 
87
- # Build dashboard
88
- dashboard = f"## 🏒 SCM Emotion Monitoring Dashboard\n"
89
- dashboard += f"### 🧭 Department: **{department}**\n"
90
- dashboard += f"### 🎯 Detected Emotion: {emoji} **{label.upper()} ({score}%)**\n\n"
91
- dashboard += "### πŸ“Š Emotion Breakdown\n"
92
-
 
 
 
 
 
 
 
 
93
  for r in results:
94
- lbl, emo = EMOTION_MAP.get(r['label'], (r['label'], "🎭"))
95
  scr = round(r['score'] * 100, 2)
96
- bar = "β–ˆ" * int(scr / 5)
97
- dashboard += f"{emo} **{lbl}**: {scr}% \n{bar}\n\n"
98
-
99
- dashboard += "---\nπŸ’Ύ Emotion data saved to database for Power BI visualization."
100
- return dashboard
101
-
102
- # -------------------------------
103
- # 🎨 Gradio UI
104
- # -------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  DEPARTMENTS = ["Procurement", "Logistics", "Planning", "Inventory", "Distribution", "HR"]
106
 
107
- with gr.Blocks(theme="soft") as app:
108
- gr.Markdown("## 🎧 SCM Internal Communication Emotion Analyzer")
109
- gr.Markdown(
110
- "Analyze team meeting recordings or live speech to detect emotional tone "
111
- "across departments. Useful for HR & leadership to track team sentiment and stress trends."
112
- )
 
 
 
 
113
 
114
  with gr.Row():
115
- with gr.Column():
116
  audio_input = gr.Audio(
117
  sources=["microphone", "upload"],
118
  type="filepath",
@@ -121,16 +145,23 @@ with gr.Blocks(theme="soft") as app:
121
  department_input = gr.Dropdown(
122
  DEPARTMENTS, label="🏒 Select Department/Team"
123
  )
124
- analyze_btn = gr.Button("πŸ” Analyze Emotion", variant="primary")
125
-
126
- with gr.Column():
127
- output_display = gr.Markdown(label="Results Dashboard")
128
 
129
  analyze_btn.click(
130
  fn=analyze_emotion,
131
  inputs=[audio_input, department_input],
132
- outputs=output_display,
133
  )
134
 
 
 
 
 
 
 
 
135
  if __name__ == "__main__":
136
- app.launch()
 
4
  from datetime import datetime
5
  import sqlite3
6
  import os
7
+ import random
8
 
9
+ # -------------------------------------------------
10
+ # 🎯 MODEL & DATABASE INITIALIZATION
11
+ # -------------------------------------------------
12
  MODEL_NAME = "superb/hubert-large-superb-er"
13
  emotion_classifier = pipeline("audio-classification", model=MODEL_NAME)
14
 
 
16
  DB_PATH = "data/scm_emotion.db"
17
 
18
  def init_db():
 
19
  conn = sqlite3.connect(DB_PATH)
20
  cursor = conn.cursor()
21
  cursor.execute("""
 
32
 
33
  init_db()
34
 
35
+ # -------------------------------------------------
36
+ # πŸ˜„ EMOTION MAP + COLORS
37
+ # -------------------------------------------------
38
  EMOTION_MAP = {
39
+ "ang": ("Angry", "😑", "#ff4d4d"),
40
+ "hap": ("Happy", "πŸ˜„", "#4caf50"),
41
+ "neu": ("Neutral", "😐", "#9e9e9e"),
42
+ "sad": ("Sad", "😒", "#2196f3"),
43
+ "exc": ("Excited", "🀩", "#ff9800"),
44
+ "fru": ("Frustrated", "😀", "#f44336"),
45
+ "fea": ("Fearful", "😨", "#673ab7"),
46
+ "sur": ("Surprised", "😲", "#00bcd4"),
47
+ "dis": ("Disgusted", "🀒", "#8bc34a"),
48
  }
49
 
50
+ # -------------------------------------------------
51
+ # πŸ’Ύ LOGGING
52
+ # -------------------------------------------------
53
  def log_to_db(datetime_str, department, emotion, score):
 
54
  conn = sqlite3.connect(DB_PATH)
55
  cursor = conn.cursor()
56
  cursor.execute(
 
60
  conn.commit()
61
  conn.close()
62
 
63
+ # -------------------------------------------------
64
+ # 🧠 EMOTION ANALYSIS
65
+ # -------------------------------------------------
66
  def analyze_emotion(audio, department):
67
  if audio is None or not department:
68
+ return "⚠️ Please record/upload audio and select a department.", None
69
 
 
70
  if isinstance(audio, tuple):
71
  audio_file = audio[0]
72
  else:
73
  audio_file = audio
74
 
 
75
  results = emotion_classifier(audio_file)
76
  results = sorted(results, key=lambda x: x['score'], reverse=True)
77
  top = results[0]
78
+ label, emoji, color = EMOTION_MAP.get(top['label'], (top['label'], "🎭", "#607d8b"))
79
  score = round(top['score'] * 100, 2)
80
 
 
81
  log_to_db(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), department, label, score)
82
 
83
+ # Dashboard HTML
84
+ dashboard_html = f"""
85
+ <div style="text-align:center; padding:15px;">
86
+ <h2>🏒 <b>{department}</b> Department</h2>
87
+ <h3 style="color:{color}; font-size:26px;">{emoji} {label.upper()} β€” {score}%</h3>
88
+ <p style="color:#666;">Detected Emotion Intensity (Confidence)</p>
89
+ <div style="width:80%; margin:auto; background:#eee; border-radius:20px;">
90
+ <div style="width:{score}%; background:{color}; height:20px; border-radius:20px;"></div>
91
+ </div>
92
+ </div>
93
+ <br>
94
+ <h4>πŸ“Š Full Emotion Breakdown</h4>
95
+ <ul>
96
+ """
97
  for r in results:
98
+ lbl, emo, clr = EMOTION_MAP.get(r['label'], (r['label'], "🎭", "#777"))
99
  scr = round(r['score'] * 100, 2)
100
+ dashboard_html += f"<li>{emo} <b>{lbl}</b>: {scr}%</li>"
101
+ dashboard_html += "</ul><hr>"
102
+
103
+ # Generate insights
104
+ insights = random.choice([
105
+ "🧩 Team seems calm and balanced today. Great stability!",
106
+ "⚑ Slight emotional tension detected. Consider quick sync-up meetings.",
107
+ "πŸ’¬ High positive tone β€” keep up the good team energy!",
108
+ "🚨 Signs of stress in communication. HR may follow up proactively.",
109
+ "πŸ“ˆ Emotion variation is increasing β€” check workload or deadlines."
110
+ ])
111
+
112
+ insight_html = f"""
113
+ <div style="background:#f5f5f5; padding:10px; border-radius:10px; margin-top:15px;">
114
+ <h4>🧠 AI Insight</h4>
115
+ <p>{insights}</p>
116
+ <p style='font-size:13px; color:#999;'>Logged for Power BI visualization.</p>
117
+ </div>
118
+ """
119
+
120
+ return dashboard_html, insight_html
121
+
122
+ # -------------------------------------------------
123
+ # 🎨 GRADIO APP DESIGN
124
+ # -------------------------------------------------
125
  DEPARTMENTS = ["Procurement", "Logistics", "Planning", "Inventory", "Distribution", "HR"]
126
 
127
+ with gr.Blocks(theme=gr.themes.Soft()) as app:
128
+ gr.HTML("""
129
+ <div style="text-align:center; padding:20px;">
130
+ <h1>🎧 SCM Emotion Intelligence Dashboard</h1>
131
+ <p style="font-size:16px; color:#555;">
132
+ Analyze live team communication and detect emotional tone across Supply Chain departments.<br>
133
+ Ideal for HR and leadership to monitor sentiment, engagement, and burnout patterns.
134
+ </p>
135
+ </div>
136
+ """)
137
 
138
  with gr.Row():
139
+ with gr.Column(scale=1):
140
  audio_input = gr.Audio(
141
  sources=["microphone", "upload"],
142
  type="filepath",
 
145
  department_input = gr.Dropdown(
146
  DEPARTMENTS, label="🏒 Select Department/Team"
147
  )
148
+ analyze_btn = gr.Button("πŸš€ Analyze Emotion", variant="primary")
149
+ with gr.Column(scale=2):
150
+ output_html = gr.HTML()
151
+ insight_html = gr.HTML()
152
 
153
  analyze_btn.click(
154
  fn=analyze_emotion,
155
  inputs=[audio_input, department_input],
156
+ outputs=[output_html, insight_html],
157
  )
158
 
159
+ gr.HTML("""
160
+ <hr>
161
+ <p style="text-align:center; color:#999;">
162
+ πŸ’Ύ All results stored in <code>scm_emotion.db</code> for Power BI visualization.
163
+ </p>
164
+ """)
165
+
166
  if __name__ == "__main__":
167
+ app.launch(server_name="0.0.0.0", server_port=7860)