Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions aai_cli/code_gen/transcribe.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ def render(
llm_gateway,
output,
needs_download=needs_download,
needs_stdin=source == "-",
needs_re=needs_re,
has_sections=ranges_expr is not None,
)
Expand Down Expand Up @@ -98,14 +99,16 @@ def _header_block(
output: str | None,
*,
needs_download: bool,
needs_stdin: bool,
needs_re: bool,
has_sections: bool,
) -> list[str]:
"""Imports plus the api-key (and non-default environment) settings lines."""
stdlib_imports = ["import os"]
if needs_download:
# The download path fetches audio to a temp dir before uploading.
if needs_download or needs_stdin:
stdlib_imports.append("import tempfile")
if needs_stdin:
stdlib_imports.extend(["import sys", "from pathlib import Path"])
if needs_re:
# Chapter-regex sections compile to re.compile(...) in the generated script.
stdlib_imports.append("import re")
Expand Down Expand Up @@ -161,7 +164,18 @@ def _transcribe_block(
kwargs = "\n".join(serialize.config_kwarg_lines(merged, indent=4))
parts += ["", f"config = aai.TranscriptionConfig(\n{kwargs}\n)"]
config_arg = ", config=config"
if needs_download:
if source == "-":
parts += [
"",
"_audio_bytes = sys.stdin.buffer.read()",
"if not _audio_bytes:",
' raise ValueError("No audio received on stdin.")',
"with tempfile.TemporaryDirectory() as _tmp:",
' _audio = Path(_tmp) / "audio"',
" _audio.write_bytes(_audio_bytes)",
f" transcript = transcriber.transcribe(str(_audio){config_arg})",
]
elif needs_download:
# AssemblyAI can't read a YouTube/podcast page URL itself, so download the
# audio with yt-dlp into a temp dir and upload the local file — what the CLI does.
parts += [
Expand Down
51 changes: 51 additions & 0 deletions tests/test_transcribe_show_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@
flag-to-config mapping and flag validation live in test_transcribe_flags.py.
"""

import io
import runpy
import wave
from pathlib import Path

import assemblyai as aai
import pytest
from typer.testing import CliRunner

from aai_cli.main import app
Expand Down Expand Up @@ -44,6 +51,50 @@ def _boom(*a, **k):
assert '"force_keyframes_at_cuts": True,' in result.output


def test_transcribe_show_code_reads_binary_stdin(tmp_path, monkeypatch, mocker, capsys):
contents = io.BytesIO()
with wave.open(contents, "wb") as wav:
wav.setparams((1, 2, 16000, 0, "NONE", "not compressed"))
wav.writeframes(b"\x00\xff" * 160)
audio = contents.getvalue()

def transcribe(source, *, config):
assert Path(source).read_bytes() == audio
assert config.raw.speech_models == ["universal-3-5-pro"]
return mocker.Mock(status=aai.TranscriptStatus.completed, text="Fixture transcript.")

sdk = mocker.patch.object(aai.Transcriber, "transcribe", side_effect=transcribe)
result = runner.invoke(app, ["transcribe", "-", "--show-code", "-o", "text"])
assert result.exit_code == 0
sdk.assert_not_called()

script = tmp_path / "transcribe.py"
script.write_text(result.stdout, encoding="utf-8")
monkeypatch.setattr(aai.settings, "api_key", None)
monkeypatch.setenv("ASSEMBLYAI_API_KEY", "test-key")
monkeypatch.setattr("sys.stdin", io.TextIOWrapper(io.BytesIO(audio)))
runpy.run_path(str(script))

assert capsys.readouterr().out == "Fixture transcript.\n"
sdk.assert_called_once()
assert not Path(sdk.call_args.args[0]).exists()


def test_transcribe_show_code_rejects_empty_binary_stdin(tmp_path, monkeypatch, mocker):
sdk = mocker.patch.object(aai.Transcriber, "transcribe")
result = runner.invoke(app, ["transcribe", "-", "--show-code", "-o", "text"])
assert result.exit_code == 0

script = tmp_path / "transcribe.py"
script.write_text(result.stdout, encoding="utf-8")
monkeypatch.setattr(aai.settings, "api_key", None)
monkeypatch.setenv("ASSEMBLYAI_API_KEY", "test-key")
monkeypatch.setattr("sys.stdin", io.TextIOWrapper(io.BytesIO()))
with pytest.raises(ValueError, match="No audio received on stdin"):
runpy.run_path(str(script))
sdk.assert_not_called()


def test_transcribe_show_code_without_source_uses_placeholder(monkeypatch):
# --show-code never transcribes, so it must not demand a source/--sample; it emits
# runnable code with a clearly-marked placeholder path instead of erroring.
Expand Down