Spaces:
Sleeping
Sleeping
File size: 14,148 Bytes
857b1b2 f14c6b9 857b1b2 f14c6b9 857b1b2 f14c6b9 857b1b2 f14c6b9 857b1b2 f14c6b9 857b1b2 f14c6b9 857b1b2 f14c6b9 857b1b2 f14c6b9 857b1b2 f14c6b9 f2fe172 f14c6b9 857b1b2 f14c6b9 857b1b2 f14c6b9 857b1b2 f14c6b9 857b1b2 f14c6b9 857b1b2 f14c6b9 857b1b2 f14c6b9 857b1b2 f14c6b9 857b1b2 f14c6b9 857b1b2 f14c6b9 857b1b2 f14c6b9 857b1b2 | 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 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 | import logging
import subprocess
import time
from pathlib import Path
from typing import List, Dict, Optional, Tuple
from dataclasses import dataclass
from collections import defaultdict, Counter
import numpy as np
import librosa
from app.core.config import get_settings
from app.services.transcription import TranscriptionService
from app.services.alignment import AlignmentService
from app.services.transcription import WordTimestamp
from app.services.emo import EmotionService
from app.services.diarization import (
DiarizationService,
SpeakerSegment,
DiarizationResult,
)
logger = logging.getLogger(__name__)
settings = get_settings()
@dataclass
class TranscriptSegment:
"""A transcribed segment with speaker info."""
start: float
end: float
speaker: str
role: Optional[str]
text: str
emotion: Optional[str] = None
icon: Optional[str] = None
@dataclass
class EmotionPoint:
time: float
emotion: str
icon: Optional[str]
@dataclass
class EmotionChange:
time: float
emotion_from: str
emotion_to: str
icon_from: Optional[str] = None
icon_to: Optional[str] = None
@dataclass
class ProcessingResult:
"""Result of audio processing."""
segments: List[TranscriptSegment]
speaker_count: int
duration: float
processing_time: float
speakers: List[str]
roles: Dict[str, str]
txt_content: str = ""
csv_content: str = ""
emotion_timeline: List[EmotionPoint] = None
emotion_changes: List[EmotionChange] = None
def normalize_asr_result(result: dict):
words = []
for w in result.get("words", []):
word = (
w.get("word", "")
.strip()
)
if not word:
continue
words.append(
{
"word": word,
"start": float(w["start"]),
"end": float(w["end"]),
"speaker": w.get("speaker"),
"confidence": float(
w.get("confidence", 1.0)
),
}
)
text = result.get("text", "").strip()
return text, words
def guess_speaker_by_overlap(start, end, diar_segments):
best_spk = None
best_overlap = 0.0
for seg in diar_segments:
overlap = max(0.0, min(end, seg.end) - max(start, seg.start))
if overlap > best_overlap:
best_overlap = overlap
best_spk = seg.speaker
return best_spk or diar_segments[0].speaker
def convert_audio_to_wav(audio_path: Path) -> Path:
"""Convert any audio to WAV 16kHz Mono using ffmpeg."""
output_path = audio_path.parent / f"{audio_path.stem}_processed.wav"
if output_path.exists():
output_path.unlink()
command = [
"ffmpeg",
"-i",
str(audio_path),
"-ar",
"16000",
"-ac",
"1",
"-y",
str(output_path),
]
try:
subprocess.run(
command, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
logger.info(f"Converted audio to WAV: {output_path}")
return output_path
except subprocess.CalledProcessError as e:
logger.error(f"FFmpeg conversion failed: {e}")
return audio_path
def format_timestamp(seconds: float) -> str:
m = int(seconds // 60)
s = seconds % 60
return f"{m:02d}:{s:06.3f}"
def merge_consecutive_segments(
segments: List[SpeakerSegment],
max_gap: float = 0.80,
max_overlap: float = 0.15,
) -> List[SpeakerSegment]:
if not segments:
return []
segments = sorted(
segments,
key=lambda x: x.start
)
merged = [segments[0]]
for seg in segments[1:]:
prev = merged[-1]
gap = seg.start - prev.end
if (
seg.speaker == prev.speaker
and gap >= -max_overlap
and gap <= max_gap
):
prev.end = max(
prev.end,
seg.end
)
else:
merged.append(seg)
return merged
def overlap_prefix(a: str, b: str, n: int = 12) -> bool:
if not a or not b:
return False
a = a.strip().lower()
b = b.strip().lower()
return a[:n] in b or b[:n] in a
class Processor:
@classmethod
async def process_audio(
cls,
audio_path: Path,
model_name: str = "PhoWhisper Lora Finetuned",
language="vi",
merge_segments: bool = True
) -> ProcessingResult:
import asyncio
t0 = time.time()
EmotionService.preload_model()
# 1: Convert to WAV
logger.info("Step 1: Converting audio to WAV 16kHz...")
wav_path = await asyncio.get_event_loop().run_in_executor(
None, convert_audio_to_wav, audio_path
)
# 2: Load audio
y, sr = librosa.load(wav_path, sr=16000, mono=True)
if y.size == 0:
raise ValueError("Empty audio")
duration = len(y) / sr
# 3: Diarization
logger.info("Step 3: Running diarization...")
diarization: DiarizationResult = await DiarizationService.diarize_async(
wav_path
)
diarization_segments = diarization.segments or []
if not diarization_segments:
diarization_segments = [SpeakerSegment(0.0, duration, "SPEAKER_0")]
speakers = ["SPEAKER_0"]
roles = {"SPEAKER_0": "KH"}
diarization_segments.sort(key=lambda x: x.start)
if merge_segments and diarization_segments:
logger.info("Step 4: Merging consecutive segments...")
diarization_segments = merge_consecutive_segments(diarization_segments)
# 4. Normalize speakers
raw_speakers = sorted({seg.speaker for seg in diarization_segments})
speaker_map = {spk: f"Speaker {i+1}" for i, spk in enumerate(raw_speakers)}
speakers = list(speaker_map.values())
raw_roles = diarization.roles or {}
roles = {}
for raw_spk, label in speaker_map.items():
roles[label] = raw_roles.get(raw_spk, "KH")
logger.info(f"roles(mapped) = {roles}")
# 7: Transcribe segments after diarization
logger.info("Step 7: Running ASR with external VAD batch...")
asr_result = await TranscriptionService.transcribe_with_words_async(
audio_array=y,
model_name=model_name,
language=language,
vad_options=False
)
text, raw_words = normalize_asr_result(asr_result)
if not raw_words:
processed_segments = [
TranscriptSegment(
start=0.0,
end=duration,
speaker=speakers[0],
role=roles[speakers[0]],
text="(No speech detected)",
)
]
else:
# ===== CONVERT TO WordTimestamp =====
word_objs: List[WordTimestamp] = []
for w in raw_words:
spk = w.get("speaker")
if spk is None:
spk = guess_speaker_by_overlap(
w["start"], w["end"], diarization_segments
)
word_objs.append(
WordTimestamp(
word=w["word"],
start=w["start"],
end=w["end"],
speaker=spk,
confidence=w.get("confidence", 1.0)
)
)
word_objs.sort(key=lambda x: x.start)
# ===== ALIGNMENT =====
aligned_segments = AlignmentService.align_precision(
word_objs,
diarization_segments
)
processed_segments = []
if not aligned_segments:
vote = [w.speaker for w in word_objs if w.speaker]
if vote:
raw_spk = Counter(vote).most_common(1)[0][0]
else:
raw_spk = diarization_segments[0].speaker
label = speaker_map.get(raw_spk, "Speaker 1")
processed_segments.append(
TranscriptSegment(0, duration, label, roles[label], text)
)
else:
for seg in aligned_segments:
raw_spk = seg.speaker
label = speaker_map.get(raw_spk, "Speaker 1")
role = roles.get(label, "KH")
processed_segments.append(
TranscriptSegment(
start=seg.start,
end=seg.end,
speaker=label,
role=role,
text=seg.text,
)
)
processed_segments.sort(key=lambda x: x.start)
# 8 : Predict emotion segments
logger.info("Step 8: Predicting emo per segment ")
processed_segments = cls._predict_emotion_segments(processed_segments, y, sr)
# build emotion timeline
emotion_timeline = cls.build_emotion_timeline(processed_segments)
# detect emotion change
emotion_changes = cls.detect_emotion_changes(emotion_timeline)
processing_time = time.time() - t0
txt_content = cls._generate_txt(
processed_segments, len(speakers), processing_time, duration, roles
)
csv_content = cls._generate_csv(processed_segments)
return ProcessingResult(
segments=processed_segments,
speaker_count=len(speakers),
duration=duration,
processing_time=processing_time,
speakers=speakers,
roles=roles,
txt_content=txt_content,
csv_content=csv_content,
emotion_timeline=emotion_timeline,
emotion_changes=emotion_changes,
)
@staticmethod
def _predict_emotion_segments(
segments: List[TranscriptSegment], audio: np.ndarray, sr: int
):
for seg in segments:
# chα» predict emotion cho KH
if seg.role != "KH":
seg.emotion = None
seg.icon = None
continue
emotion = EmotionService.predict_segment(audio, sr, seg.start, seg.end)
seg.emotion = emotion
seg.icon = EmotionService.meta.get(emotion, {}).get("emoji", "π")
return segments
@staticmethod
def build_emotion_timeline(segments):
timeline = []
for seg in segments:
if seg.role != "KH":
continue
if not seg.emotion:
continue
if not seg.icon:
continue
icon = EmotionService.meta.get(seg.emotion, {}).get("emoji", "π")
timeline.append(
EmotionPoint(time=seg.start, emotion=seg.emotion, icon=icon)
)
return timeline
@staticmethod
def detect_emotion_changes(timeline):
changes = []
prev = None
for point in timeline:
if prev is not None and prev.emotion != point.emotion:
icon_from = EmotionService.meta.get(prev.emotion, {}).get("emoji", "π")
icon_to = EmotionService.meta.get(point.emotion, {}).get("emoji", "π")
changes.append(
EmotionChange(
time=point.time,
emotion_from=prev.emotion,
emotion_to=point.emotion,
icon_from=icon_from,
icon_to=icon_to,
)
)
prev = point
return changes
@classmethod
def _generate_txt(
cls,
segments: List[TranscriptSegment],
speaker_count: int,
processing_time: float,
duration: float,
roles: Dict[str, str],
) -> str:
segments = sorted(segments, key=lambda s: s.start)
speakers = []
for seg in segments:
if seg.speaker and seg.speaker not in speakers:
speakers.append(seg.speaker)
lines = [
"# Transcription Result",
f"# Duration: {format_timestamp(duration)}",
f"# Speakers: {speaker_count}",
f"# Roles: {roles}",
f"# Processing time: {processing_time:.1f}s",
"",
]
icon_pool = ["π΅", "π’", "π‘", "π ", "π΄", "π£"]
speaker_icons = {
spk: icon_pool[i % len(icon_pool)] for i, spk in enumerate(speakers)
}
for seg in segments:
ts = f"[{format_timestamp(seg.start)} β {format_timestamp(seg.end)}]"
role = seg.role or "UNKNOWN"
speaker_icon = speaker_icons.get(seg.speaker, "βͺ")
emotion = seg.emotion or ""
emotion_icon = (
EmotionService.meta.get(emotion, {}).get("emoji", "") if emotion else ""
)
lines.append(
f"{ts} {speaker_icon} [{seg.speaker}|{role}] {seg.text} {emotion_icon} {emotion}"
)
return "\n".join(lines)
@classmethod
def _generate_csv(cls, segments: List[TranscriptSegment]) -> str:
import csv
from io import StringIO
output = StringIO()
writer = csv.writer(output)
writer.writerow(["start", "end", "speaker", "text", "emotion", "icon"])
for seg in segments:
emotion = seg.emotion or ""
icon = (
EmotionService.meta.get(emotion, {}).get("emoji", "") if emotion else ""
)
writer.writerow(
[
round(seg.start, 3),
round(seg.end, 3),
seg.speaker,
seg.text,
emotion,
icon,
]
)
return output.getvalue()
|