This commit is contained in:
JiriUhlir
2026-07-10 10:08:51 +02:00
parent 57faf12d97
commit d55089b1c8
5 changed files with 105 additions and 37 deletions
+37 -3
View File
@@ -21,12 +21,19 @@ async def transcribe(
diarize: bool,
smart_format: bool,
) -> str:
"""Přepíše audio Deepgramem a vrátí prostý transkript (channels[0].alternatives[0].transcript)."""
"""Přepíše audio Deepgramem.
Když je zapnutá diarizace, vrátí přepis se štítky mluvčích (z `utterances`),
např. `Mluvčí 0: ...`. Bez diarizace vrátí plochý transkript.
"""
params = {
"model": model,
"language": language,
"diarize": "true" if diarize else "false",
"smart_format": "true" if smart_format else "false",
# utterances rozseká přepis na promluvy s přiřazeným mluvčím — nutné, aby
# v textu bylo vidět rozlišení mluvčích (samotný `transcript` je plochý).
"utterances": "true" if diarize else "false",
}
headers = {
"Authorization": f"Token {api_key}",
@@ -48,9 +55,36 @@ async def transcribe(
data = resp.json()
try:
channels = data["results"]["channels"]
alternative = channels[0]["alternatives"][0]
results = data["results"]
# 1) Preferuj diarizovaný výstup z utterances (se štítky mluvčích).
diarized = _format_utterances(results.get("utterances"))
if diarized:
return diarized
# 2) Fallback na plochý transkript.
alternative = results["channels"][0]["alternatives"][0]
return alternative.get("transcript", "") or ""
except (KeyError, IndexError, TypeError) as exc:
log.error("Unexpected Deepgram response shape: %s", exc)
raise UpstreamError("Neočekávaná struktura odpovědi z Deepgramu.") from exc
def _format_utterances(utterances) -> str:
"""Sloučí Deepgram utterances do přepisu se štítky mluvčích (`Mluvčí N: ...`).
Po sobě jdoucí promluvy stejného mluvčího spojí do jednoho řádku.
"""
if not utterances:
return ""
lines: list[str] = []
prev_speaker = None
for utt in utterances:
text = (utt.get("transcript") or "").strip()
if not text:
continue
speaker = utt.get("speaker")
if speaker != prev_speaker:
lines.append(f"Mluvčí {speaker}: {text}")
prev_speaker = speaker
else:
lines[-1] += " " + text
return "\n".join(lines)
+2 -1
View File
@@ -20,7 +20,8 @@ async def transcribe(
"""Přepíše audio přes OpenAI Whisper (/audio/transcriptions) a vrátí text."""
headers = {"Authorization": f"Bearer {api_key}"}
files = {"file": (filename or "audio.mp3", audio, content_type or "application/octet-stream")}
form = {"model": model}
# temperature=0 => deterministický přepis, méně halucinací na tichu/šumu.
form = {"model": model, "temperature": "0"}
if language:
form["language"] = language
url = f"{OPENAI_BASE_URL}/audio/transcriptions"