File size: 8,880 Bytes
767a4c5
 
 
 
 
 
 
 
 
 
39a4dc6
3938252
d7ba4a9
 
 
 
 
e17c67c
 
d7ba4a9
 
 
 
 
 
 
 
 
 
 
e17c67c
 
d7ba4a9
e17c67c
3938252
d7ba4a9
 
 
92972fa
d7ba4a9
 
92972fa
d7ba4a9
 
 
d63a76c
92972fa
 
 
 
 
 
 
 
 
 
 
d7ba4a9
 
 
3938252
 
 
d7ba4a9
 
92972fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7ba4a9
92972fa
 
 
 
 
 
 
d7ba4a9
 
 
92972fa
051a33d
c30e743
3938252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c30e743
d7ba4a9
c30e743
3938252
d7ba4a9
 
c30e743
d7ba4a9
 
3938252
d7ba4a9
3938252
d7ba4a9
c30e743
3938252
 
 
 
92972fa
d7ba4a9
3938252
c30e743
3938252
 
 
 
 
7d7870d
d7ba4a9
92972fa
cb2c0d1
92972fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7ba4a9
 
 
 
 
051a33d
 
d7ba4a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92972fa
d7ba4a9
 
 
 
 
 
 
 
 
 
 
 
 
3938252
d7ba4a9
 
 
 
 
e17c67c
 
 
 
 
c5e938a
e17c67c
d7ba4a9
 
 
 
 
 
 
 
 
 
3938252
 
 
 
 
d7ba4a9
 
 
 
 
 
 
 
 
 
 
 
 
3938252
d7ba4a9
 
 
 
 
 
3938252
d7ba4a9
 
 
 
 
 
 
cb2c0d1
d7ba4a9
92972fa
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# Patch missing HfFolder before gradio imports it
import sys
from unittest.mock import MagicMock
try:
    from huggingface_hub import HfFolder
except ImportError:
    import huggingface_hub
    huggingface_hub.HfFolder = MagicMock()
    sys.modules["huggingface_hub"].HfFolder = MagicMock()

import gradio as gr
import assemblyai as aai
import librosa
import soundfile as sf
import torch
import json
import csv
import os
import tempfile
import warnings
from datetime import datetime
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch.nn.functional as F
from docx import Document
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet

warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore", category=RuntimeWarning)

# =========================
# CONFIG
# =========================
aai.settings.api_key = os.getenv("ASSEMBLYAI_API_KEY")
device = "cuda" if torch.cuda.is_available() else "cpu"

tokenizer = AutoTokenizer.from_pretrained(
    "j-hartmann/emotion-english-distilroberta-base"
)
sentiment_model = AutoModelForSequenceClassification.from_pretrained(
    "j-hartmann/emotion-english-distilroberta-base"
)
sentiment_model.to(device)
sentiment_model.eval()

# Maps model's 7 emotion classes to business-friendly labels
EMOTION_LABELS = {
    0: ("πŸ”΄", "Negative"),   # Anger
    1: ("πŸ”΄", "Negative"),   # Disgust
    2: ("πŸ”΄", "Negative"),   # Fear
    3: ("🟒", "Positive"),   # Joy
    4: ("🟑", "Neutral"),    # Neutral
    5: ("πŸ”΄", "Negative"),   # Sadness
    6: ("🟒", "Positive"),   # Surprise
}

# =========================
# HELPERS
# =========================
def format_time(ms):
    s = ms / 1000
    return f"{int(s // 60):02d}:{int(s % 60):02d}"


def split_into_chunks(text, chunk_size=200):
    """
    Split text into equal fixed-character chunks.
    Breaks at the nearest space to avoid cutting mid-word.
    """
    text = text.strip()
    if len(text) <= chunk_size:
        return [text]

    chunks = []
    while len(text) > chunk_size:
        split_at = text.rfind(" ", 0, chunk_size)
        if split_at == -1:
            split_at = chunk_size
        chunks.append(text[:split_at].strip())
        text = text[split_at:].strip()

    if text:
        chunks.append(text)

    return chunks


def analyze_sentiment(text):
    inputs = tokenizer(
        text,
        return_tensors="pt",
        truncation=True,
        max_length=512,
        padding=True
    ).to(device)
    with torch.no_grad():
        logits = sentiment_model(**inputs).logits
    probs = F.softmax(logits, dim=-1)[0]
    return torch.argmax(probs).item()


def build_segments(transcript):
    speaker_map = {}
    counter = 1
    segments = []
    for u in transcript.utterances:
        raw = str(u.speaker)
        if raw not in speaker_map:
            speaker_map[raw] = counter
            counter += 1
        segments.append({
            "speaker": speaker_map[raw],
            "start": format_time(u.start or 0),
            "end": format_time(u.end or 0),
            "text": u.text,
        })
    return segments


# =========================
# MAIN PROCESS
# =========================
def process_audio(file, speakers, language, state):
    if file is None:
        return "❌ No audio provided", "", "", state

    temp_wav = None
    try:
        audio, sr = librosa.load(file, sr=None, mono=True)
        with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
            sf.write(tmp.name, audio, sr)
            temp_wav = tmp.name

        config = aai.TranscriptionConfig(
            speaker_labels=True,
            speakers_expected=int(speakers) if speakers > 0 else None,
            language_code=None if language == "auto" else language,
            speech_model=aai.SpeechModel.best
        )
        transcript = aai.Transcriber().transcribe(temp_wav, config)

        if transcript.error:
            return f"❌ {transcript.error}", "", "", state

        segments = build_segments(transcript)
        speaker_count = len(set(s["speaker"] for s in segments))

        conversation = ""
        export_segments = []

        for i, seg in enumerate(segments, start=1):
            chunks = split_into_chunks(seg["text"])

            for c_idx, chunk in enumerate(chunks, start=1):
                emotion_idx = analyze_sentiment(chunk)
                emoji, label = EMOTION_LABELS.get(emotion_idx, ("βšͺ", "Unknown"))

                chunk_label = f" | Chunk {c_idx}" if len(chunks) > 1 else ""

                conversation += (
                    f"Speaker {seg['speaker']} | Utterance {i}{chunk_label}\n"
                    f"({seg['start']} - {seg['end']})\n"
                    f"{emoji} {label}: {chunk}\n\n"
                )

                export_segments.append({
                    "speaker": seg["speaker"],
                    "start": seg["start"],
                    "end": seg["end"],
                    "chunk": c_idx,
                    "text": chunk,
                    "sentiment": label,
                })

        new_state = {"segments": export_segments, "conversation": conversation}
        return (
            "βœ… Done",
            conversation,
            f"Speakers: {speaker_count} | Utterances: {len(segments)}",
            new_state,
        )

    except Exception as e:
        return f"❌ Error: {str(e)}", "", "", state

    finally:
        if temp_wav and os.path.exists(temp_wav):
            os.remove(temp_wav)


# =========================
# EXPORT
# =========================
def export_file(format_type, state):
    segments = state.get("segments", [])
    conversation = state.get("conversation", "")
    if not conversation and not segments:
        return None

    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

    if format_type == "TXT":
        path = f"/tmp/conversation_{timestamp}.txt"
        with open(path, "w", encoding="utf-8") as f:
            f.write(conversation)
    elif format_type == "JSON":
        path = f"/tmp/conversation_{timestamp}.json"
        with open(path, "w", encoding="utf-8") as f:
            json.dump(segments, f, indent=4)
    elif format_type == "CSV":
        path = f"/tmp/conversation_{timestamp}.csv"
        with open(path, "w", newline="", encoding="utf-8") as f:
            writer = csv.DictWriter(
                f, fieldnames=["speaker", "start", "end", "chunk", "text", "sentiment"]
            )
            writer.writeheader()
            writer.writerows(segments)
    elif format_type == "WORD":
        path = f"/tmp/conversation_{timestamp}.docx"
        doc = Document()
        doc.add_heading("Conversation Transcript", 0)
        doc.add_paragraph(conversation)
        doc.save(path)
    elif format_type == "PDF":
        path = f"/tmp/conversation_{timestamp}.pdf"
        doc = SimpleDocTemplate(path)
        styles = getSampleStyleSheet()
        content = [Paragraph(conversation.replace("\n", "<br/>"), styles["Normal"])]
        doc.build(content)
    else:
        return None

    return path


# =========================
# UI
# =========================
with gr.Blocks(title="AI Conversation Sentiment Analyzer", theme=gr.themes.Soft()) as app:

    gr.Markdown("# πŸŽ™ AI Conversation Sentiment Analyzer")

    state = gr.State({"segments": [], "conversation": ""})

    with gr.Group():
        gr.Markdown("### πŸŽ™ Input Audio")
        audio = gr.Audio(sources=["upload", "microphone"], type="filepath")

    with gr.Group():
        gr.Markdown("### βš™ Settings")
        with gr.Row():
            speakers = gr.Number(value=0, label="Speakers (0 = auto-detect)")
            language = gr.Dropdown(
                ["auto", "en", "fr", "es", "de"], value="auto", label="Language"
            )

    analyze_btn = gr.Button("πŸš€ Analyze", variant="primary")

    with gr.Group():
        gr.Markdown("### πŸ’¬ Conversation Output")
        status = gr.Textbox(label="Status")
        conversation_box = gr.Textbox(lines=18, label="Conversation + Sentiment")
        info = gr.Textbox(label="Info")

    with gr.Group():
        gr.Markdown("### πŸ“ Export")
        with gr.Row():
            export_format = gr.Dropdown(
                ["TXT", "JSON", "CSV", "WORD", "PDF"], value="TXT", label="Format"
            )
            export_btn = gr.Button("⬇ Export")
        download = gr.File()

    analyze_btn.click(
        process_audio,
        inputs=[audio, speakers, language, state],
        outputs=[status, conversation_box, info, state],
    )
    export_btn.click(
        export_file,
        inputs=[export_format, state],
        outputs=[download],
    )

if __name__ == "__main__":
    app.launch(server_name="0.0.0.0", server_port=7860)