File size: 7,407 Bytes
eb2cf07 |
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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 |
#!/usr/bin/env python3
"""
Gradio Interface for Voice Sentiment Analysis
Wav2Vec 2.0 + BERT Pipeline
"""
import gradio as gr
import pandas as pd
import os
from utils import custom_css
from voice_sentiment import VoiceSentimentAnalyzer
# Initialize model (once)
print("Loading models...")
analyzer = VoiceSentimentAnalyzer()
print("Models ready!")
def analyze_audio_file(audio_file):
"""Analyze an uploaded audio file"""
if audio_file is None:
return "No audio file provided", "", "", ""
try:
# Analyze the call
result = analyzer.analyze_call(audio_file)
# Format results
transcription = result['transcription']
sentiment = result['sentiment']
score = f"{result['score']:.2f}"
satisfaction = result['satisfaction']
# Emoji based on sentiment
emoji_map = {
"POSITIVE": "π",
"NEGATIVE": "π ",
"NEUTRAL": "π"
}
emoji = emoji_map.get(sentiment, "β")
status = f"Analysis completed {emoji}"
return status, transcription, sentiment, score, satisfaction
except Exception as e:
error_msg = f"Analysis error: {str(e)}"
return error_msg, "", "", "", ""
def analyze_batch_files(files):
"""Analyze multiple audio files"""
if not files:
return "No files provided", None
try:
results = []
for file in files:
result = analyzer.analyze_call(file.name)
results.append({
"File": os.path.basename(file.name),
"Transcription": result['transcription'][:100] + "..." if len(result['transcription']) > 100 else result['transcription'],
"Sentiment": result['sentiment'],
"Score": round(result['score'], 2),
"Satisfaction": result['satisfaction']
})
# Create DataFrame for display
df = pd.DataFrame(results)
csv_filename = "analysis_results.csv"
print(f"Saving {len(df)} rows to CSV...")
df.to_csv(csv_filename, index=False)
print(f"CSV saved successfully") #
# Verify CSV was created and has content
if os.path.exists(csv_filename): # β NEW DEBUG BLOCK
file_size = os.path.getsize(csv_filename)
print(f"CSV file exists, size: {file_size} bytes")
else:
print("CSV file was not created!")
# Statistics
total = len(results)
positive = len([r for r in results if r['Sentiment'] == 'POSITIVE'])
negative = len([r for r in results if r['Sentiment'] == 'NEGATIVE'])
neutral = len([r for r in results if r['Sentiment'] == 'NEUTRAL'])
stats = f"""π Statistics:
β’ Total: {total} calls
β’ Positive: {positive} ({positive/total*100:.1f}%)
β’ Negative: {negative} ({negative/total*100:.1f}%)
β’ Neutral: {neutral} ({neutral/total*100:.1f}%)"""
return stats, df
except Exception as e:
error_msg = f"Analysis error: {str(e)}"
return error_msg, None
# Gradio Interface
with gr.Blocks(title="Voice Sentiment Analysis", theme=gr.themes.Soft(), css=custom_css) as app:
gr.Markdown("""
# Voice Sentiment Analysis System
### Wav2Vec 2.0 + BERT Pipeline
Automatically analyze customer call sentiment and classify satisfaction.
""")
with gr.Tabs():
# Tab 1: Single file analysis
with gr.Tab("Single File"):
gr.Markdown("### Analyze one voice call")
with gr.Row():
with gr.Column():
audio_input = gr.Audio(
type="filepath",
label="Upload your audio file"
)
analyze_btn = gr.Button(
"Analyze",
variant="primary",
size="lg"
)
with gr.Column():
status_output = gr.Textbox(
label="π Status",
interactive=False
)
transcription_output = gr.Textbox(
label="π Transcription",
lines=3,
interactive=False
)
with gr.Row():
sentiment_output = gr.Textbox(
label="π Sentiment",
interactive=False
)
score_output = gr.Textbox(
label="π― Confidence Score",
interactive=False
)
satisfaction_output = gr.Textbox(
label="π Customer Satisfaction",
interactive=False
)
# Tab 2: Multiple files analysis
with gr.Tab("Multiple Files"):
gr.Markdown("### Analyze multiple calls in batch")
files_input = gr.File(
file_count="multiple",
file_types=[".wav", ".mp3", ".m4a"],
label="Upload your audio files"
)
batch_analyze_btn = gr.Button(
"Analyze All",
variant="primary",
size="lg"
)
batch_status = gr.Textbox(
label="Statistics",
lines=6,
interactive=False
)
results_table = gr.Dataframe(
label="Detailed Results",
interactive=False
)
# Tab 3: Information
with gr.Tab("Information"):
gr.Markdown("""
### How it works?
**3-step pipeline:**
1. **Audio β Text**: Transcription with Wav2Vec 2.0
2. **Text β Sentiment**: Analysis with multilingual BERT
3. **Classification**: Customer satisfaction (Satisfied/Dissatisfied/Neutral)
### Supported formats
- WAV (recommended)
- MP3
- M4A
### Classifications
- **π Satisfied**: Positive sentiment with high confidence
- **π Dissatisfied**: Negative sentiment with high confidence
- **π Neutral**: Neutral sentiment or low confidence
### Tips
- Clear audio quality recommended
- Optimal duration: 10 seconds to 2 minutes
- Avoid excessive background noise
""")
# Event connections
analyze_btn.click(
fn=analyze_audio_file,
inputs=[audio_input],
outputs=[status_output, transcription_output, sentiment_output, score_output, satisfaction_output]
)
batch_analyze_btn.click(
fn=analyze_batch_files,
inputs=[files_input],
outputs=[batch_status, results_table]
)
# Launch the application
if __name__ == "__main__":
app.launch(
share=True, # Creates a public link
server_name="0.0.0.0", # Accessible from other machines
server_port=7860
) |