Dhrubob commited on
Commit
9a52092
Β·
verified Β·
1 Parent(s): aba2248

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -116
app.py CHANGED
@@ -1,38 +1,20 @@
1
  import gradio as gr
2
  from transformers import pipeline
3
- import pandas as pd
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
 
 
15
  os.makedirs("data", exist_ok=True)
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("""
22
- CREATE TABLE IF NOT EXISTS emotion_logs (
23
- id INTEGER PRIMARY KEY AUTOINCREMENT,
24
- datetime TEXT,
25
- team TEXT,
26
- purpose TEXT,
27
- emotion TEXT,
28
- score REAL
29
- )
30
- """)
31
- conn.commit()
32
- conn.close()
33
-
34
- init_db()
35
-
36
  # -------------------------------------------------
37
  # πŸ˜„ EMOTION MAP + COLORS
38
  # -------------------------------------------------
@@ -48,65 +30,37 @@ EMOTION_MAP = {
48
  "dis": ("Disgusted", "🀒", "#8bc34a"),
49
  }
50
 
51
- # -------------------------------------------------
52
- # πŸ’Ύ LOGGING
53
- # -------------------------------------------------
54
- def log_to_db(datetime_str, team, purpose, emotion, score):
55
- conn = sqlite3.connect(DB_PATH)
56
- cursor = conn.cursor()
57
- cursor.execute(
58
- "INSERT INTO emotion_logs (datetime, team, purpose, emotion, score) VALUES (?, ?, ?, ?, ?)",
59
- (datetime_str, team, purpose, emotion, score),
60
- )
61
- conn.commit()
62
- conn.close()
63
-
64
  # -------------------------------------------------
65
  # 🧠 EMOTION ANALYSIS
66
  # -------------------------------------------------
67
- def analyze_emotion(audio, team, custom_team, purpose, custom_purpose):
68
  if audio is None:
69
- return "⚠️ Please record or upload audio first.", None
70
 
71
- # Determine final values
72
- team_name = custom_team if team == "Other" else team
73
- purpose_name = custom_purpose if purpose == "Other" else purpose
 
 
74
 
75
- if not team_name:
76
- team_name = "Unspecified Team"
77
- if not purpose_name:
78
- purpose_name = "Unspecified Purpose"
79
-
80
- # Handle file input
81
- if isinstance(audio, tuple):
82
- audio_file = audio[0]
83
- else:
84
- audio_file = audio
85
-
86
- # Predict emotion
87
- results = emotion_classifier(audio_file)
88
  results = sorted(results, key=lambda x: x['score'], reverse=True)
89
  top = results[0]
90
  label, emoji, color = EMOTION_MAP.get(top['label'], (top['label'], "🎭", "#607d8b"))
91
  score = round(top['score'] * 100, 2)
92
 
93
- # Log data
94
- log_to_db(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), team_name, purpose_name, label, score)
95
-
96
- # Dashboard UI
97
  dashboard_html = f"""
98
- <div style="text-align:center; padding:15px;">
99
- <h2>🏒 <b>{team_name}</b></h2>
100
- <h4>🎯 Purpose: <b>{purpose_name}</b></h4>
101
  <h3 style="color:{color}; font-size:26px;">{emoji} {label.upper()} β€” {score}%</h3>
102
  <p style="color:#666;">Detected Emotion Intensity (Confidence)</p>
103
- <div style="width:80%; margin:auto; background:#eee; border-radius:20px;">
104
  <div style="width:{score}%; background:{color}; height:20px; border-radius:20px;"></div>
105
  </div>
106
- </div>
107
- <br>
108
- <h4>πŸ“Š Full Emotion Breakdown</h4>
109
- <ul>
110
  """
111
  for r in results:
112
  lbl, emo, clr = EMOTION_MAP.get(r['label'], (r['label'], "🎭", "#777"))
@@ -114,98 +68,96 @@ def analyze_emotion(audio, team, custom_team, purpose, custom_purpose):
114
  dashboard_html += f"<li>{emo} <b>{lbl}</b>: {scr}%</li>"
115
  dashboard_html += "</ul><hr>"
116
 
117
- # AI Insight
118
  insights = random.choice([
119
- "🧩 The conversation tone was balanced β€” good team stability.",
120
- "⚑ Slight emotional tension detected β€” consider a quick check-in.",
121
- "πŸ’¬ Positive tone overall β€” keep up the good engagement.",
122
- "🚨 Possible stress indicators β€” leadership follow-up advised.",
123
- "πŸ“ˆ Emotional fluctuation noted β€” monitor workload or dynamics."
124
  ])
125
 
126
  insight_html = f"""
127
- <div style="background:#f5f5f5; padding:15px; border-radius:12px; margin-top:15px; border-left:6px solid #4a90e2;">
 
 
128
  <h4 style="color:#222; margin-bottom:6px;">🧠 AI Insight</h4>
129
  <p style="color:#333; font-size:16px; font-weight:500;">{insights}</p>
130
- <p style="font-size:13px; color:#777;">Logged for Power BI visualization.</p>
131
  </div>
132
  """
133
 
134
  return dashboard_html, insight_html
135
 
136
-
137
  # -------------------------------------------------
138
- # 🎨 GRADIO APP DESIGN
139
  # -------------------------------------------------
140
- TEAM_OPTIONS = ["Test","SAP","Analytics","AI","Procurement", "Logistics", "Planning", "HR", "Operations", "IT", "Other"]
141
- PURPOSE_OPTIONS = ["Test","HR Meeting", "Team Stand-up", "One-on-One", "Customer Call", "Interview", "Project Review", "Other"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
  with gr.Blocks(theme=gr.themes.Soft()) as app:
144
- # Header
145
  gr.HTML("""
146
  <div style="text-align:center; padding:20px;">
147
- <h1>🎧 Emotion Intelligence for Teams</h1>
148
  <p style="font-size:16px; color:#555;">
149
- Detect and visualize emotional tone from team meetings or recorded conversations.<br>
150
- Designed for managers and HR to track emotional health and engagement trends.
151
  </p>
152
  </div>
153
  """)
154
 
155
- # Inputs
156
  with gr.Row():
157
- with gr.Column(scale=1):
158
- team_dropdown = gr.Dropdown(TEAM_OPTIONS, label="🏒 Select Team / Department")
159
- custom_team = gr.Textbox(label="✏️ Enter Team (if 'Other')", placeholder="Enter custom team name here")
160
-
161
- purpose_dropdown = gr.Dropdown(PURPOSE_OPTIONS, label="🎯 Purpose of the Recording")
162
- custom_purpose = gr.Textbox(label="✏️ Enter Purpose (if 'Other')", placeholder="Enter custom meeting purpose here")
163
-
164
  audio_input = gr.Audio(
165
  sources=["microphone", "upload"],
166
  type="filepath",
167
- label="πŸŽ™οΈ Record or Upload Team Meeting Audio",
168
  )
 
 
169
  analyze_btn = gr.Button("πŸš€ Analyze Emotion", variant="primary")
 
170
 
171
- with gr.Column(scale=2):
 
172
  output_html = gr.HTML()
173
  insight_html = gr.HTML()
174
 
175
- # Disclaimer
176
- gr.HTML("""
177
- <div style="background:linear-gradient(135deg, #fff8e1, #fff3cd);
178
- padding:15px;
179
- border-radius:12px;
180
- margin-top:20px;
181
- border-left:8px solid #ff9800;
182
- box-shadow:0 2px 6px rgba(0,0,0,0.1);">
183
- <h3 style="color:#d35400; margin-bottom:8px;">⚠️ Demo Disclaimer</h3>
184
- <p style="color:#333; font-size:15px; line-height:1.6;">
185
- This is a <b style="color:#e65100;">demonstration version</b> created for concept showcasing.<br>
186
- Your voice data is
187
- <b style="background-color:#fffbe6; color:#c0392b; padding:2px 6px; border-radius:4px;">
188
- NOT being saved or shared
189
- </b> anywhere.<br><br>
190
- All recordings are processed only in-memory and database logging is
191
- <b style="color:#e65100;">simulated</b> for visualization purposes.<br>
192
- βœ… Feel free to explore, record, and test the system freely.
193
- </p>
194
- </div>
195
- """)
196
-
197
-
198
- # Button Action
199
  analyze_btn.click(
200
  fn=analyze_emotion,
201
- inputs=[audio_input, team_dropdown, custom_team, purpose_dropdown, custom_purpose],
202
  outputs=[output_html, insight_html],
203
  )
204
 
205
  gr.HTML("""
206
  <hr>
207
- <p style="text-align:center; color:#999;">
208
- πŸ’Ύ Results are locally logged in <code>scm_emotion.db</code> (for Power BI integration demo).
209
  </p>
210
  """)
211
 
 
1
  import gradio as gr
2
  from transformers import pipeline
 
3
  from datetime import datetime
4
  import sqlite3
5
  import os
6
  import random
7
 
8
  # -------------------------------------------------
9
+ # 🎯 MODEL INITIALIZATION
10
  # -------------------------------------------------
11
  MODEL_NAME = "superb/hubert-large-superb-er"
12
  emotion_classifier = pipeline("audio-classification", model=MODEL_NAME)
13
 
14
+ # (Optional) Simulated DB path
15
  os.makedirs("data", exist_ok=True)
16
  DB_PATH = "data/scm_emotion.db"
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  # -------------------------------------------------
19
  # πŸ˜„ EMOTION MAP + COLORS
20
  # -------------------------------------------------
 
30
  "dis": ("Disgusted", "🀒", "#8bc34a"),
31
  }
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  # -------------------------------------------------
34
  # 🧠 EMOTION ANALYSIS
35
  # -------------------------------------------------
36
+ def analyze_emotion(audio, team, purpose):
37
  if audio is None:
38
+ return "<p style='color:red;'>⚠️ Please record or upload audio.</p>", None
39
 
40
+ # If team/purpose not filled
41
+ if team == "Other":
42
+ team = "Custom/Unspecified"
43
+ if purpose == "Other":
44
+ purpose = "Custom/Unspecified"
45
 
46
+ results = emotion_classifier(audio)
 
 
 
 
 
 
 
 
 
 
 
 
47
  results = sorted(results, key=lambda x: x['score'], reverse=True)
48
  top = results[0]
49
  label, emoji, color = EMOTION_MAP.get(top['label'], (top['label'], "🎭", "#607d8b"))
50
  score = round(top['score'] * 100, 2)
51
 
52
+ # Dashboard HTML
 
 
 
53
  dashboard_html = f"""
54
+ <div style="text-align:center; padding:15px; position:sticky; top:10px;">
55
+ <h2>🏒 <b>{team}</b> | 🎯 <b>{purpose}</b></h2>
 
56
  <h3 style="color:{color}; font-size:26px;">{emoji} {label.upper()} β€” {score}%</h3>
57
  <p style="color:#666;">Detected Emotion Intensity (Confidence)</p>
58
+ <div style="width:85%; margin:auto; background:#eee; border-radius:20px;">
59
  <div style="width:{score}%; background:{color}; height:20px; border-radius:20px;"></div>
60
  </div>
61
+ <br>
62
+ <h4>πŸ“Š Full Emotion Breakdown</h4>
63
+ <ul style="list-style:none; padding:0;">
 
64
  """
65
  for r in results:
66
  lbl, emo, clr = EMOTION_MAP.get(r['label'], (r['label'], "🎭", "#777"))
 
68
  dashboard_html += f"<li>{emo} <b>{lbl}</b>: {scr}%</li>"
69
  dashboard_html += "</ul><hr>"
70
 
71
+ # Insight
72
  insights = random.choice([
73
+ "🧩 Team seems calm and balanced today. Great stability!",
74
+ "⚑ Slight emotional tension detected. Consider quick sync-up meetings.",
75
+ "πŸ’¬ High positive tone β€” keep up the good energy!",
76
+ "🚨 Stress indicators detected. HR may follow up proactively.",
77
+ "πŸ“ˆ Emotion variation is rising β€” review workloads or deadlines."
78
  ])
79
 
80
  insight_html = f"""
81
+ <div style="background:#f5f5f5; padding:15px; border-radius:12px;
82
+ margin-top:15px; border-left:6px solid #4a90e2;
83
+ box-shadow:0 2px 6px rgba(0,0,0,0.05);">
84
  <h4 style="color:#222; margin-bottom:6px;">🧠 AI Insight</h4>
85
  <p style="color:#333; font-size:16px; font-weight:500;">{insights}</p>
86
+ <p style="font-size:13px; color:#777;">(Demo mode β€” not stored to any database)</p>
87
  </div>
88
  """
89
 
90
  return dashboard_html, insight_html
91
 
 
92
  # -------------------------------------------------
93
+ # 🎨 GRADIO INTERFACE
94
  # -------------------------------------------------
95
+ DEPARTMENTS = [
96
+ "Procurement", "Logistics", "Planning", "Inventory", "Distribution", "HR", "Other"
97
+ ]
98
+ PURPOSES = [
99
+ "HR Meeting", "Team Stand-up", "One-on-One", "Customer Call", "Interview", "Other"
100
+ ]
101
+
102
+ disclaimer_html = """
103
+ <div style="display:flex; align-items:center; background:linear-gradient(135deg, #fff8e1, #fff3cd);
104
+ padding:15px; border-radius:12px; margin-top:20px; border-left:8px solid #ff9800;
105
+ box-shadow:0 2px 6px rgba(0,0,0,0.1);">
106
+ <div style="font-size:28px; margin-right:12px; color:#ff9800;">πŸ’‘</div>
107
+ <div>
108
+ <h3 style="color:#d35400; margin:0 0 5px 0;">Demo Disclaimer</h3>
109
+ <p style="color:#333; font-size:15px; line-height:1.6; margin:0;">
110
+ This is a <b style="color:#e65100;">demonstration version</b> created for HR and leadership showcases.<br>
111
+ Your voice data is
112
+ <b style="background-color:#fffbe6; color:#c0392b; padding:2px 6px; border-radius:4px;">
113
+ NOT being saved or shared
114
+ </b> anywhere.<br>
115
+ Database logging is <b style="color:#e65100;">simulated</b> β€” you can record or upload audio freely.<br>
116
+ βœ… Safe to explore and test in this environment.
117
+ </p>
118
+ </div>
119
+ </div>
120
+ """
121
 
122
  with gr.Blocks(theme=gr.themes.Soft()) as app:
 
123
  gr.HTML("""
124
  <div style="text-align:center; padding:20px;">
125
+ <h1>🎧 SCM Emotion Intelligence Dashboard</h1>
126
  <p style="font-size:16px; color:#555;">
127
+ Analyze live or uploaded audio from meetings to understand emotional tone within teams.<br>
128
+ Built for HR & Managers to assess engagement and team well-being.
129
  </p>
130
  </div>
131
  """)
132
 
 
133
  with gr.Row():
134
+ # Left Panel: Inputs
135
+ with gr.Column(scale=1, min_width=350):
 
 
 
 
 
136
  audio_input = gr.Audio(
137
  sources=["microphone", "upload"],
138
  type="filepath",
139
+ label="πŸŽ™οΈ Record or Upload Audio",
140
  )
141
+ team_input = gr.Dropdown(DEPARTMENTS, label="🏒 Select Team / Department")
142
+ purpose_input = gr.Dropdown(PURPOSES, label="🎯 Purpose of Audio")
143
  analyze_btn = gr.Button("πŸš€ Analyze Emotion", variant="primary")
144
+ gr.HTML(disclaimer_html)
145
 
146
+ # Right Panel: Sticky Output
147
+ with gr.Column(scale=2, min_width=500):
148
  output_html = gr.HTML()
149
  insight_html = gr.HTML()
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  analyze_btn.click(
152
  fn=analyze_emotion,
153
+ inputs=[audio_input, team_input, purpose_input],
154
  outputs=[output_html, insight_html],
155
  )
156
 
157
  gr.HTML("""
158
  <hr>
159
+ <p style="text-align:center; color:#999; font-size:14px;">
160
+ πŸ’Ύ (Demo Mode) Database integration coming soon for Power BI visualization.
161
  </p>
162
  """)
163