KrizTech100 commited on
Commit
2b7872d
·
verified ·
1 Parent(s): c30e743

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -235
app.py CHANGED
@@ -1,272 +1,93 @@
1
  import gradio as gr
2
- from dotenv import load_dotenv
3
- import assemblyai as aai
4
- import librosa
5
- import soundfile as sf
6
- import torch
7
- import json
8
- import csv
9
  import os
10
  import tempfile
11
- import time
12
- from datetime import datetime
13
- from transformers import AutoTokenizer, AutoModelForSequenceClassification
14
- import torch.nn.functional as F
15
- from docx import Document
16
- from reportlab.platypus import SimpleDocTemplate, Paragraph
17
- from reportlab.lib.styles import getSampleStyleSheet
18
 
19
  # =========================
20
- # CONFIG
21
  # =========================
22
- load_dotenv()
23
 
24
- aai.settings.api_key = os.getenv("ASSEMBLYAI_API_KEY")
25
- hf_token = os.getenv("HF_TOKEN")
26
 
27
- if not hf_token:
28
- raise ValueError("❌ HF_TOKEN is missing. Add it to your .env")
 
 
29
 
30
- device = "cuda" if torch.cuda.is_available() else "cpu"
31
 
32
- MODEL_NAME = "nlptown/bert-base-multilingual-uncased-sentiment"
 
 
 
33
 
34
  # =========================
35
- # LOAD MODEL (FIXED)
36
  # =========================
37
- def load_hf_model():
38
- for attempt in range(3):
39
- try:
40
- tokenizer = AutoTokenizer.from_pretrained(
41
- MODEL_NAME,
42
- token=hf_token,
43
- cache_dir="./models"
44
- )
45
 
46
- model = AutoModelForSequenceClassification.from_pretrained(
47
- MODEL_NAME,
48
- token=hf_token,
49
- cache_dir="./models"
50
- )
51
 
52
- return tokenizer, model
 
53
 
54
- except Exception as e:
55
- print(f"⚠️ HF load failed (attempt {attempt+1}): {e}")
56
- time.sleep(5)
57
 
58
- raise RuntimeError(" Failed to load Hugging Face model after retries")
59
 
60
- tokenizer, model = load_hf_model()
 
 
 
 
61
 
62
- model.to(device)
63
- model.eval()
 
 
64
 
65
- # =========================
66
- # GLOBAL
67
- # =========================
68
- global_segments = []
69
- global_conversation = ""
70
-
71
- # =========================
72
- # HELPERS
73
- # =========================
74
- def format_time(ms):
75
- s = ms / 1000
76
- return f"{int(s//60):02d}:{int(s%60):02d}"
77
-
78
-
79
- def build_segments(transcript):
80
  speaker_map = {}
81
- current_id = 1
82
- segments = []
83
-
84
- for u in transcript.utterances:
85
- raw = str(u.speaker)
86
-
87
- if raw not in speaker_map:
88
- speaker_map[raw] = current_id
89
- current_id += 1
90
-
91
- segments.append({
92
- "speaker": speaker_map[raw],
93
- "start": format_time(u.start or 0),
94
- "end": format_time(u.end or 0),
95
- "text": u.text
96
- })
97
-
98
- return segments
99
 
 
100
 
101
- def analyze_text(text):
102
- inputs = tokenizer(
103
- text,
104
- return_tensors="pt",
105
- truncation=True,
106
- max_length=512
107
- ).to(device)
108
 
109
- with torch.no_grad():
110
- logits = model(**inputs).logits
 
 
111
 
112
- probs = F.softmax(logits, dim=-1)[0]
113
- return torch.argmax(probs).item() + 1
114
 
 
 
115
 
116
- # =========================
117
- # MAIN PROCESS
118
- # =========================
119
- def process_audio(file, speakers=0, language="auto"):
120
- global global_segments, global_conversation
121
-
122
- if file is None:
123
- return "❌ No audio provided", "", ""
124
-
125
- path = file if isinstance(file, str) else file.name
126
- temp_path = None
127
-
128
- try:
129
- # Load audio
130
- audio, sr = librosa.load(path, sr=None, mono=True)
131
-
132
- # Create TEMP FILE
133
- with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
134
- sf.write(tmp.name, audio, sr)
135
- temp_path = tmp.name
136
 
137
- config = aai.TranscriptionConfig(
138
- speaker_labels=True,
139
- speakers_expected=speakers if speakers > 0 else None,
140
- language_code=None if language == "auto" else language
141
  )
142
 
143
- transcript = aai.Transcriber().transcribe(temp_path, config)
144
-
145
- if transcript.error:
146
- return f"❌ {transcript.error}", "", ""
147
-
148
- global_segments = build_segments(transcript)
149
- speaker_count = len(set(s["speaker"] for s in global_segments))
150
-
151
- label_map = {
152
- 1: ("🔴", "Very Negative"),
153
- 2: ("🟠", "Negative"),
154
- 3: ("🟡", "Neutral"),
155
- 4: ("🟢", "Positive"),
156
- 5: ("🟢", "Very Positive")
157
- }
158
-
159
- conversation = ""
160
-
161
- for i, seg in enumerate(global_segments, start=1):
162
- score = analyze_text(seg["text"])
163
- emoji, label = label_map.get(score, ("⚪", "Unknown"))
164
-
165
- conversation += (
166
- f"Speaker {seg['speaker']} | Utterance {i}\n"
167
- f"({seg['start']} - {seg['end']})\n"
168
- f"{emoji} {label}: {seg['text']}\n\n"
169
- )
170
-
171
- global_conversation = conversation
172
-
173
- return "✅ Done", conversation, f"Speakers: {speaker_count} | Utterances: {len(global_segments)}"
174
-
175
- except Exception as e:
176
- return f"❌ Error: {str(e)}", "", ""
177
-
178
- finally:
179
- if temp_path and os.path.exists(temp_path):
180
- os.remove(temp_path)
181
-
182
-
183
- # =========================
184
- # EXPORT
185
- # =========================
186
- def export_file(format_type):
187
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
188
-
189
- if format_type == "TXT":
190
- path = f"conversation_{timestamp}.txt"
191
- with open(path, "w", encoding="utf-8") as f:
192
- f.write(global_conversation)
193
-
194
- elif format_type == "JSON":
195
- path = f"conversation_{timestamp}.json"
196
- with open(path, "w", encoding="utf-8") as f:
197
- json.dump(global_segments, f, indent=4)
198
-
199
- elif format_type == "CSV":
200
- path = f"conversation_{timestamp}.csv"
201
- with open(path, "w", newline="", encoding="utf-8") as f:
202
- writer = csv.DictWriter(f, fieldnames=["speaker", "start", "end", "text"])
203
- writer.writeheader()
204
- writer.writerows(global_segments)
205
-
206
- elif format_type == "WORD":
207
- path = f"conversation_{timestamp}.docx"
208
- doc = Document()
209
- doc.add_heading("Conversation Transcript", 0)
210
- doc.add_paragraph(global_conversation)
211
- doc.save(path)
212
-
213
- elif format_type == "PDF":
214
- path = f"conversation_{timestamp}.pdf"
215
- doc = SimpleDocTemplate(path)
216
- styles = getSampleStyleSheet()
217
- content = [Paragraph(global_conversation.replace("\n", "<br/>"), styles["Normal"])]
218
- doc.build(content)
219
-
220
- return path
221
 
222
 
223
  # =========================
224
  # UI
225
  # =========================
226
- with gr.Blocks(title="AI Conversation Sentiment System") as app:
227
-
228
- gr.Markdown("# 🎙 AI Conversation Sentiment Analyzer")
229
-
230
- with gr.Group():
231
- gr.Markdown("### 🎙 Input Audio")
232
- audio = gr.Audio(sources=["upload", "microphone"], type="filepath")
233
-
234
- with gr.Group():
235
- gr.Markdown("### ⚙ Settings")
236
- with gr.Row():
237
- speakers = gr.Number(value=0, label="Speakers (0 = auto)")
238
- language = gr.Dropdown(["auto", "en", "fr", "es", "de"], value="auto")
239
-
240
- analyze_btn = gr.Button("🚀 Analyze")
241
-
242
- with gr.Group():
243
- gr.Markdown("### 💬 Conversation Output")
244
- status = gr.Textbox(label="Status")
245
- conversation_box = gr.Textbox(lines=18, label="Conversation + Sentiment")
246
- info = gr.Textbox(label="Info")
247
-
248
- with gr.Group():
249
- gr.Markdown("### 📁 Export")
250
- with gr.Row():
251
- export_format = gr.Dropdown(
252
- ["TXT", "JSON", "CSV", "WORD", "PDF"],
253
- value="TXT",
254
- label="Select Format"
255
- )
256
- export_btn = gr.Button("⬇ Export")
257
- download = gr.File()
258
-
259
- analyze_btn.click(
260
- process_audio,
261
- inputs=[audio, speakers, language],
262
- outputs=[status, conversation_box, info]
263
- )
264
 
265
- export_btn.click(
266
- export_file,
267
- inputs=[export_format],
268
- outputs=[download]
269
- )
 
 
270
 
271
- if __name__ == "__main__":
272
- app.launch(theme=gr.themes.Soft())
 
1
  import gradio as gr
 
 
 
 
 
 
 
2
  import os
3
  import tempfile
4
+ import whisper
5
+ from pyannote.audio import Pipeline
6
+ from transformers import pipeline as hf_pipeline
 
 
 
 
7
 
8
  # =========================
9
+ # LOAD MODELS
10
  # =========================
 
11
 
12
+ HF_TOKEN = os.getenv("HF_TOKEN")
 
13
 
14
+ diarization_pipeline = Pipeline.from_pretrained(
15
+ "pyannote/speaker-diarization",
16
+ use_auth_token=HF_TOKEN
17
+ )
18
 
19
+ whisper_model = whisper.load_model("base")
20
 
21
+ sentiment_pipeline = hf_pipeline(
22
+ "sentiment-analysis",
23
+ model="nlptown/bert-base-multilingual-uncased-sentiment"
24
+ )
25
 
26
  # =========================
27
+ # MAIN FUNCTION
28
  # =========================
 
 
 
 
 
 
 
 
29
 
30
+ def analyze_audio(audio_file):
 
 
 
 
31
 
32
+ if audio_file is None:
33
+ return "❌ No audio uploaded"
34
 
35
+ # Save temp file
36
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
37
+ temp_path = tmp.name
38
 
39
+ os.system(f"ffmpeg -i \"{audio_file}\" -ar 16000 -ac 1 \"{temp_path}\" -y")
40
 
41
+ # =========================
42
+ # TRANSCRIPTION
43
+ # =========================
44
+ result = whisper_model.transcribe(temp_path)
45
+ transcript_text = result["text"]
46
 
47
+ # =========================
48
+ # DIARIZATION
49
+ # =========================
50
+ diarization = diarization_pipeline(temp_path)
51
 
52
+ # 🔥 MAP RAW SPEAKERS → Speaker 1, 2, 3...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  speaker_map = {}
54
+ speaker_counter = 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
+ output = "🎙 TRANSCRIPT + SPEAKERS + SENTIMENT\n\n"
57
 
58
+ for turn, _, speaker in diarization.itertracks(yield_label=True):
 
 
 
 
 
 
59
 
60
+ # Assign clean speaker labels
61
+ if speaker not in speaker_map:
62
+ speaker_map[speaker] = f"Speaker {speaker_counter}"
63
+ speaker_counter += 1
64
 
65
+ clean_speaker = speaker_map[speaker]
 
66
 
67
+ # Simple text (you can upgrade alignment later)
68
+ segment_text = transcript_text
69
 
70
+ sentiment = sentiment_pipeline(segment_text[:512])[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
+ output += (
73
+ f"{clean_speaker} ({turn.start:.2f}s - {turn.end:.2f}s)\n"
74
+ f"Sentiment: {sentiment['label']} ({round(sentiment['score'],2)})\n"
75
+ f"Text: {segment_text}\n\n"
76
  )
77
 
78
+ return output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
 
81
  # =========================
82
  # UI
83
  # =========================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
+ app = gr.Interface(
86
+ fn=analyze_audio,
87
+ inputs=gr.Audio(type="filepath", label="Upload Audio"),
88
+ outputs=gr.Textbox(lines=25, label="Results"),
89
+ title="🎙 AI Conversation Analyzer",
90
+ description="Speaker Diarization + Sentiment Analysis"
91
+ )
92
 
93
+ app.launch()