voxprep 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- voxprep/__init__.py +42 -0
- voxprep/_skill/SKILL.md +49 -0
- voxprep/agents.py +64 -0
- voxprep/backends/__init__.py +91 -0
- voxprep/backends/funasr.py +78 -0
- voxprep/backends/openai.py +135 -0
- voxprep/backends/parakeet.py +303 -0
- voxprep/backends/sensevoice.py +286 -0
- voxprep/chunker.py +421 -0
- voxprep/cli.py +469 -0
- voxprep/diagnose.py +130 -0
- voxprep/downloads.py +105 -0
- voxprep/fbank.py +155 -0
- voxprep/io.py +245 -0
- voxprep/mcp_server.py +214 -0
- voxprep/models/SILERO_VAD_LICENSE +21 -0
- voxprep/models/__init__.py +0 -0
- voxprep/models/silero_vad_16k_op15.onnx +0 -0
- voxprep/presets.py +208 -0
- voxprep/py.typed +0 -0
- voxprep/reference.py +220 -0
- voxprep/stitch.py +392 -0
- voxprep/transcript.py +408 -0
- voxprep/vad.py +190 -0
- voxprep-0.1.0.dist-info/METADATA +267 -0
- voxprep-0.1.0.dist-info/RECORD +29 -0
- voxprep-0.1.0.dist-info/WHEEL +4 -0
- voxprep-0.1.0.dist-info/entry_points.txt +2 -0
- voxprep-0.1.0.dist-info/licenses/LICENSE +21 -0
voxprep/__init__.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""voxprep: turn any audio/video into model-ready input for any AI, then stitch results back.
|
|
2
|
+
|
|
3
|
+
import voxprep as vp
|
|
4
|
+
|
|
5
|
+
vp.inspect("meeting.mp4") # what is it, which models take it
|
|
6
|
+
result = vp.prepare("meeting.mp4", target="openai") # compress, split at pauses if needed
|
|
7
|
+
texts = [my_model(c.to_bytes()) for c in result.chunks]
|
|
8
|
+
vp.stitch(result, texts).refine().to_srt("meeting.srt")
|
|
9
|
+
|
|
10
|
+
vp.transcribe("meeting.mp4", via="groq") # all of the above in one call
|
|
11
|
+
vp.extract_reference("podcast.mp4", "cosyvoice")[0].save("ref.wav")
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from . import presets, vad
|
|
15
|
+
from .chunker import Chunk, PreparedResult, prepare
|
|
16
|
+
from .diagnose import Report, inspect
|
|
17
|
+
from .io import Audio, load, probe
|
|
18
|
+
from .reference import Candidate, extract_reference
|
|
19
|
+
from .stitch import stitch, transcribe
|
|
20
|
+
from .transcript import Segment, Transcript
|
|
21
|
+
|
|
22
|
+
__version__ = "0.1.0"
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"Audio",
|
|
26
|
+
"Candidate",
|
|
27
|
+
"Chunk",
|
|
28
|
+
"PreparedResult",
|
|
29
|
+
"Report",
|
|
30
|
+
"Segment",
|
|
31
|
+
"Transcript",
|
|
32
|
+
"__version__",
|
|
33
|
+
"extract_reference",
|
|
34
|
+
"inspect",
|
|
35
|
+
"load",
|
|
36
|
+
"prepare",
|
|
37
|
+
"presets",
|
|
38
|
+
"probe",
|
|
39
|
+
"stitch",
|
|
40
|
+
"transcribe",
|
|
41
|
+
"vad",
|
|
42
|
+
]
|
voxprep/_skill/SKILL.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: voxprep
|
|
3
|
+
description: Work with audio and video files - transcribe, subtitle, summarize or answer questions about a recording (meeting, call, podcast, lecture, video), fit a file to a speech API's size or length limit, merge per-chunk transcripts into one SRT/VTT on the original timeline, or pick a clean voice-clone reference clip. Use it whenever you need to know what is said in a recording; you can't listen to audio yourself.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# voxprep
|
|
7
|
+
|
|
8
|
+
You can't hear audio. To work with a recording, turn it into a timestamped transcript with
|
|
9
|
+
voxprep, then read that.
|
|
10
|
+
|
|
11
|
+
If you have voxprep's MCP tools (`transcribe`, `inspect_media`, `prepare_media`,
|
|
12
|
+
`stitch_results`, `ref_clip`), use them: they take the same options as the commands below and
|
|
13
|
+
return the transcript text directly. The first call can take a minute or two while voxprep
|
|
14
|
+
installs. Otherwise use the `voxprep` command; if it isn't installed: `pip install voxprep`.
|
|
15
|
+
|
|
16
|
+
## Getting a transcript
|
|
17
|
+
|
|
18
|
+
1. `voxprep inspect FILE --json` shows the length and whether there's much speech.
|
|
19
|
+
2. `voxprep transcribe FILE -f md -o FILE.md --json`. It uses Groq if `GROQ_API_KEY` is set,
|
|
20
|
+
OpenAI if `OPENAI_API_KEY` is set, and otherwise a built-in local English model that needs
|
|
21
|
+
no key (downloaded once, about 660 MB). For Mandarin, Cantonese, Japanese or Korean
|
|
22
|
+
recordings add `--language zh` (or `yue`, `ja`, `ko`). Don't go looking for keys.
|
|
23
|
+
3. Read `FILE.md`. Each line starts with `[HH:MM:SS]`, so you can quote times back to the user.
|
|
24
|
+
- If the JSON output has a `hint`, tell the user: it says when another model would do better.
|
|
25
|
+
- If it lists `possible_gaps`, part of the recording may be missing from the transcript;
|
|
26
|
+
say so instead of filling it in.
|
|
27
|
+
|
|
28
|
+
Groq and OpenAI cost the user money or free quota, and the local model can take a while on long
|
|
29
|
+
files. For anything longer than a few minutes, say how long the file is and check before
|
|
30
|
+
running it.
|
|
31
|
+
|
|
32
|
+
## Other jobs
|
|
33
|
+
|
|
34
|
+
| Job | Command |
|
|
35
|
+
| --- | --- |
|
|
36
|
+
| Subtitles | `voxprep subtitle FILE -o FILE.srt --json` |
|
|
37
|
+
| Chunks for some other model | `voxprep prepare FILE --for custom --max-mb N --max-sec N --format wav -o DIR --json` |
|
|
38
|
+
| Merge that model's answers | save them as `DIR/chunk_000.txt` etc., then `voxprep stitch DIR -o out.srt --json` |
|
|
39
|
+
| Voice-clone reference | `voxprep ref-clip FILE --for f5\|cosyvoice\|qwen3-tts -o ref.wav --json` |
|
|
40
|
+
| List presets and limits | `voxprep presets --json` |
|
|
41
|
+
|
|
42
|
+
Output formats for `-f`: `srt vtt md txt json claude`.
|
|
43
|
+
|
|
44
|
+
`--json` prints one JSON object on stdout; progress goes to stderr. Exit code 0 means success,
|
|
45
|
+
2 bad input, 1 anything else (the error is one line on stderr).
|
|
46
|
+
|
|
47
|
+
Before cloning someone's voice with `ref-clip`, make sure the user has the right to.
|
|
48
|
+
`ref-clip` can't tell speakers apart: with several people in the recording, use `--save-all` and
|
|
49
|
+
have the user pick (add `--via` to see what each candidate says).
|
voxprep/agents.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Tell coding agents about voxprep: install the Claude Code skill, or print a rules snippet.
|
|
2
|
+
|
|
3
|
+
``voxprep install-skill`` copies ``SKILL.md`` to ``~/.claude/skills/voxprep/`` (or a project's
|
|
4
|
+
``.claude/skills/``). Agents that read ``AGENTS.md`` or a rules file get :data:`SNIPPET`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
SKILL_NAME = "voxprep"
|
|
13
|
+
|
|
14
|
+
SNIPPET = """\
|
|
15
|
+
## Audio and video
|
|
16
|
+
|
|
17
|
+
You can't listen to audio. For recordings, use voxprep (`pip install voxprep`):
|
|
18
|
+
|
|
19
|
+
- Transcript: `voxprep transcribe FILE -f md -o FILE.md --json`. Lines start with [HH:MM:SS].
|
|
20
|
+
It uses Groq or OpenAI if their key is set, else a built-in local English model (no key);
|
|
21
|
+
add `--language zh` (or yue, ja, ko) for those languages.
|
|
22
|
+
Tell me any `hint` in the output. Check with me before long files.
|
|
23
|
+
- Subtitles: `voxprep subtitle FILE -o FILE.srt --json`
|
|
24
|
+
- File too big for a model:
|
|
25
|
+
`voxprep prepare FILE --for openai|groq|gemini|sensevoice -o DIR --json`,
|
|
26
|
+
or `--for custom --max-mb N --max-sec N`. Save each chunk's answer as DIR/chunk_000.txt etc.,
|
|
27
|
+
then `voxprep stitch DIR -o out.srt --json`.
|
|
28
|
+
- Voice-clone reference: `voxprep ref-clip FILE --for f5|cosyvoice|qwen3-tts -o ref.wav --json`
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def skill_source() -> Path:
|
|
33
|
+
"""``SKILL.md`` shipped in the wheel, or the repository copy when running from source."""
|
|
34
|
+
here = Path(__file__).resolve().parent
|
|
35
|
+
for p in (here / "_skill" / "SKILL.md", here.parents[1] / "skills" / SKILL_NAME / "SKILL.md"):
|
|
36
|
+
if p.is_file():
|
|
37
|
+
return p
|
|
38
|
+
raise FileNotFoundError("SKILL.md is missing from this voxprep install")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def claude_skills_dir(project: str | Path | None = None) -> Path:
|
|
42
|
+
"""Where Claude Code looks for skills: ``<project>/.claude/skills`` or the user's own."""
|
|
43
|
+
if project is not None:
|
|
44
|
+
return Path(project) / ".claude" / "skills"
|
|
45
|
+
config = os.environ.get("CLAUDE_CONFIG_DIR")
|
|
46
|
+
return (Path(config) if config else Path.home() / ".claude") / "skills"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def install_skill(skills_dir: str | Path | None = None) -> tuple[Path, str]:
|
|
50
|
+
"""Copy the skill into ``skills_dir`` (default: the user's Claude Code skills).
|
|
51
|
+
|
|
52
|
+
Returns the installed file and what happened: ``installed``, ``updated`` or ``unchanged``.
|
|
53
|
+
"""
|
|
54
|
+
text = skill_source().read_text(encoding="utf-8")
|
|
55
|
+
target = Path(skills_dir or claude_skills_dir()) / SKILL_NAME / "SKILL.md"
|
|
56
|
+
if target.is_file():
|
|
57
|
+
if target.read_text(encoding="utf-8") == text:
|
|
58
|
+
return target, "unchanged"
|
|
59
|
+
status = "updated"
|
|
60
|
+
else:
|
|
61
|
+
status = "installed"
|
|
62
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
63
|
+
target.write_text(text, encoding="utf-8", newline="\n")
|
|
64
|
+
return target, status
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Built-in backends that call a speech model for each chunk.
|
|
2
|
+
|
|
3
|
+
A backend is any object with:
|
|
4
|
+
|
|
5
|
+
* ``name``: str
|
|
6
|
+
* ``preset``: name of the preset its chunks must follow
|
|
7
|
+
* ``transcribe(chunk, prompt=None)``: returns something :func:`voxprep.stitch` can read
|
|
8
|
+
(an API response, a dict, a :class:`~voxprep.transcript.Transcript`, SRT or plain text).
|
|
9
|
+
|
|
10
|
+
Model SDKs are optional extras, imported only when a backend is created.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import importlib.util
|
|
16
|
+
import os
|
|
17
|
+
from typing import Protocol
|
|
18
|
+
|
|
19
|
+
from ..chunker import Chunk
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Backend(Protocol):
|
|
23
|
+
name: str
|
|
24
|
+
preset: str
|
|
25
|
+
|
|
26
|
+
def transcribe(self, chunk: Chunk, prompt: str | None = None): ...
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def choose_backend() -> str:
|
|
30
|
+
"""Name of the backend ``auto`` resolves to: ``VOXPREP_VIA`` if that is set (e.g. ``local``
|
|
31
|
+
to keep every recording on this computer), else Groq if ``GROQ_API_KEY`` is set, else
|
|
32
|
+
OpenAI if ``OPENAI_API_KEY`` is set (either needs the ``openai`` package), else the
|
|
33
|
+
built-in local model (downloaded on first use)."""
|
|
34
|
+
pinned = os.environ.get("VOXPREP_VIA", "").strip().lower()
|
|
35
|
+
if pinned and pinned != "auto":
|
|
36
|
+
if pinned not in NAMES:
|
|
37
|
+
raise ValueError(f"VOXPREP_VIA={pinned!r}: choose {', '.join(NAMES[1:])}")
|
|
38
|
+
return pinned
|
|
39
|
+
sdk = importlib.util.find_spec("openai") is not None
|
|
40
|
+
if os.environ.get("GROQ_API_KEY"):
|
|
41
|
+
if sdk:
|
|
42
|
+
return "groq"
|
|
43
|
+
raise ImportError('GROQ_API_KEY is set; to use Groq: pip install "voxprep[groq]"')
|
|
44
|
+
if os.environ.get("OPENAI_API_KEY") and sdk:
|
|
45
|
+
return "openai"
|
|
46
|
+
return "local"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def get_backend(name: str = "auto", **options) -> Backend:
|
|
50
|
+
if name == "auto":
|
|
51
|
+
name = choose_backend()
|
|
52
|
+
if name == "openai":
|
|
53
|
+
from .openai import OpenAIBackend
|
|
54
|
+
|
|
55
|
+
return OpenAIBackend(**options)
|
|
56
|
+
if name == "groq":
|
|
57
|
+
from .openai import GroqBackend
|
|
58
|
+
|
|
59
|
+
return GroqBackend(**options)
|
|
60
|
+
if name == "local":
|
|
61
|
+
# English (the default): Parakeet. Mandarin, Cantonese, Japanese, Korean: SenseVoice.
|
|
62
|
+
if options.get("language") in ("zh", "yue", "ja", "ko"):
|
|
63
|
+
from .sensevoice import SenseVoiceBackend
|
|
64
|
+
|
|
65
|
+
return SenseVoiceBackend(**options)
|
|
66
|
+
from .parakeet import ParakeetBackend
|
|
67
|
+
|
|
68
|
+
return ParakeetBackend(**options)
|
|
69
|
+
if name in ("funasr", "sensevoice"):
|
|
70
|
+
from .funasr import FunASRBackend
|
|
71
|
+
|
|
72
|
+
return FunASRBackend(**options)
|
|
73
|
+
raise KeyError(f"unknown backend {name!r}; choose auto, groq, openai, local or funasr")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
NAMES = ["auto", "groq", "openai", "local", "funasr"]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def hint_for(backend, transcript) -> str | None:
|
|
80
|
+
"""Advice worth passing on to the user after a run, or None.
|
|
81
|
+
|
|
82
|
+
Only the built-in local model gives any: on first use (it was just downloaded), when it
|
|
83
|
+
seems not to know the language, when it was slow, or when speech may be missing.
|
|
84
|
+
"""
|
|
85
|
+
tip = getattr(backend, "hint", None)
|
|
86
|
+
if getattr(backend, "name", "") == "local" and transcript.gaps and not tip:
|
|
87
|
+
tip = (
|
|
88
|
+
"Some speech may be missing from this transcript; Groq or OpenAI may do better: "
|
|
89
|
+
"set GROQ_API_KEY (free key: https://console.groq.com/keys) and use --via groq."
|
|
90
|
+
)
|
|
91
|
+
return tip
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Local SenseVoice / FunASR models (free, offline, strong on Chinese).
|
|
2
|
+
|
|
3
|
+
Needs ``pip install "voxprep[funasr]"``, which brings PyTorch; the core package does not.
|
|
4
|
+
voxprep cuts the audio into <=28 s pieces at pauses, so the model's own VAD is not needed.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from collections import Counter
|
|
11
|
+
|
|
12
|
+
from ..chunker import Chunk
|
|
13
|
+
|
|
14
|
+
_TAGS = re.compile(r"<\|[^|]*\|>")
|
|
15
|
+
_LANG = re.compile(r"^<\|([a-z]{2,3})\|>")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class FunASRBackend:
|
|
19
|
+
name = "funasr"
|
|
20
|
+
preset = "sensevoice"
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
model: str = "iic/SenseVoiceSmall",
|
|
25
|
+
device: str = "cpu",
|
|
26
|
+
language: str = "auto",
|
|
27
|
+
model_obj=None,
|
|
28
|
+
**model_kwargs,
|
|
29
|
+
):
|
|
30
|
+
self.language = language
|
|
31
|
+
self.detected: Counter[str] = Counter() # language SenseVoice heard in each chunk
|
|
32
|
+
if model_obj is None:
|
|
33
|
+
try:
|
|
34
|
+
from funasr import AutoModel
|
|
35
|
+
except ImportError as e: # pragma: no cover - depends on extras
|
|
36
|
+
raise ImportError(
|
|
37
|
+
'the funasr backend needs FunASR: pip install "voxprep[funasr]"'
|
|
38
|
+
) from e
|
|
39
|
+
model_obj = AutoModel(model=model, device=device, disable_update=True, **model_kwargs)
|
|
40
|
+
self.model = model_obj
|
|
41
|
+
|
|
42
|
+
def transcribe(self, chunk: Chunk, prompt: str | None = None) -> dict:
|
|
43
|
+
source = chunk.audio.resample(16000).samples if chunk.audio is not None else str(chunk.path)
|
|
44
|
+
results = self._run(source, self.language)
|
|
45
|
+
if self.language == "auto":
|
|
46
|
+
# SenseVoice guesses the language per 28 s piece and sometimes guesses wrong,
|
|
47
|
+
# which garbles that piece. Once one language clearly dominates, a piece heard as
|
|
48
|
+
# something else is done again in the dominant language.
|
|
49
|
+
heard = _language(results)
|
|
50
|
+
main, n = self.detected.most_common(1)[0] if self.detected else (None, 0)
|
|
51
|
+
if heard and main and heard != main and n >= 2 and n >= 0.6 * self.detected.total():
|
|
52
|
+
results = self._run(source, main)
|
|
53
|
+
heard = main
|
|
54
|
+
if heard:
|
|
55
|
+
self.detected[heard] += 1
|
|
56
|
+
text = "".join(clean(r.get("text", "")) for r in results)
|
|
57
|
+
return {"text": text}
|
|
58
|
+
|
|
59
|
+
def _run(self, source, language: str) -> list[dict]:
|
|
60
|
+
return self.model.generate(input=source, cache={}, language=language, use_itn=True)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _language(results: list[dict]) -> str | None:
|
|
64
|
+
for r in results:
|
|
65
|
+
m = _LANG.match(r.get("text", ""))
|
|
66
|
+
if m and m.group(1) not in ("nospeech", "unk"):
|
|
67
|
+
return m.group(1)
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def clean(text: str) -> str:
|
|
72
|
+
"""Drop SenseVoice's language / emotion / event tags such as ``<|zh|><|NEUTRAL|>``."""
|
|
73
|
+
try:
|
|
74
|
+
from funasr.utils.postprocess_utils import rich_transcription_postprocess
|
|
75
|
+
|
|
76
|
+
return rich_transcription_postprocess(text)
|
|
77
|
+
except ImportError:
|
|
78
|
+
return _TAGS.sub("", text).strip()
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""OpenAI transcription API, and Groq through its OpenAI-compatible endpoint.
|
|
2
|
+
|
|
3
|
+
Needs ``pip install "voxprep[openai]"`` (Groq uses the same package).
|
|
4
|
+
|
|
5
|
+
Each chunk is sent on its own, without the previous chunk's text as ``prompt``. Prompting
|
|
6
|
+
made Whisper skip sentences and invent "Thank you for watching" in our tests (7.5% vs 5.5%
|
|
7
|
+
word errors on a 20-minute recording, 2 sentences lost vs none). ``context=True`` turns it
|
|
8
|
+
back on, e.g. to carry spellings of names from one chunk to the next.
|
|
9
|
+
|
|
10
|
+
Some models (gpt-4o-transcribe and its relatives) return text without segment times.
|
|
11
|
+
``gives_timestamps()`` says which kind a model is, and ``transcribe`` sends text-only models
|
|
12
|
+
shorter chunks so the times voxprep fills in from detected speech stay close.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
|
|
20
|
+
from ..chunker import Chunk
|
|
21
|
+
|
|
22
|
+
_TIMED = re.compile(r"whisper") # return segment times
|
|
23
|
+
_TEXT_ONLY = re.compile(r"gpt-4o.*transcribe") # documented to return text only
|
|
24
|
+
|
|
25
|
+
PROMPT_CHARS = 200 # previous text passed as context; Whisper reads ~224 prompt tokens
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class OpenAIBackend:
|
|
29
|
+
name = "openai"
|
|
30
|
+
preset = "openai"
|
|
31
|
+
remote = "OpenAI" # the service the audio is uploaded to
|
|
32
|
+
default_model = "gpt-transcribe"
|
|
33
|
+
api_key_env = "OPENAI_API_KEY"
|
|
34
|
+
base_url: str | None = None
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
model: str | None = None,
|
|
39
|
+
language: str | None = None,
|
|
40
|
+
context: bool = False,
|
|
41
|
+
client=None,
|
|
42
|
+
api_key: str | None = None,
|
|
43
|
+
base_url: str | None = None,
|
|
44
|
+
):
|
|
45
|
+
self.model = model or self.default_model
|
|
46
|
+
self.language = language
|
|
47
|
+
self.context = context
|
|
48
|
+
self._verbose = True # ask for segment timestamps until the model says no
|
|
49
|
+
self._timed: bool | None = None # known after gives_timestamps()
|
|
50
|
+
if client is None:
|
|
51
|
+
try:
|
|
52
|
+
from openai import OpenAI
|
|
53
|
+
except ImportError as e: # pragma: no cover - depends on extras
|
|
54
|
+
raise ImportError(
|
|
55
|
+
f"the {self.name} backend needs the openai package: "
|
|
56
|
+
f'pip install "voxprep[{self.name}]"'
|
|
57
|
+
) from e
|
|
58
|
+
api_key = api_key or os.environ.get(self.api_key_env)
|
|
59
|
+
if not api_key:
|
|
60
|
+
raise ValueError(f"no API key: set {self.api_key_env} or pass api_key=")
|
|
61
|
+
client = OpenAI(api_key=api_key, base_url=base_url or self.base_url)
|
|
62
|
+
self.client = client
|
|
63
|
+
|
|
64
|
+
def gives_timestamps(self) -> bool:
|
|
65
|
+
"""Whether the model returns segment times. Models we don't know are asked once,
|
|
66
|
+
with one second of silence."""
|
|
67
|
+
if self._timed is None:
|
|
68
|
+
if _TIMED.search(self.model):
|
|
69
|
+
self._timed = True
|
|
70
|
+
elif _TEXT_ONLY.search(self.model):
|
|
71
|
+
self._timed = False
|
|
72
|
+
else:
|
|
73
|
+
self._timed = self._probe()
|
|
74
|
+
self._verbose = self._timed
|
|
75
|
+
return self._timed
|
|
76
|
+
|
|
77
|
+
def _probe(self) -> bool:
|
|
78
|
+
import numpy as np
|
|
79
|
+
|
|
80
|
+
from ..io import Audio, encode
|
|
81
|
+
|
|
82
|
+
clip = encode(Audio(np.zeros(16000, np.float32), 16000), "wav")
|
|
83
|
+
try:
|
|
84
|
+
self.client.audio.transcriptions.create(
|
|
85
|
+
model=self.model,
|
|
86
|
+
file=("probe.wav", clip, "audio/wav"),
|
|
87
|
+
response_format="verbose_json",
|
|
88
|
+
timestamp_granularities=["segment"],
|
|
89
|
+
)
|
|
90
|
+
except Exception as e:
|
|
91
|
+
if _format_unsupported(e):
|
|
92
|
+
return False
|
|
93
|
+
raise
|
|
94
|
+
return True
|
|
95
|
+
|
|
96
|
+
def transcribe(self, chunk: Chunk, prompt: str | None = None):
|
|
97
|
+
kwargs = {
|
|
98
|
+
"model": self.model,
|
|
99
|
+
"file": (chunk.filename, chunk.to_bytes(), chunk.mime_type),
|
|
100
|
+
}
|
|
101
|
+
if self.language:
|
|
102
|
+
kwargs["language"] = self.language
|
|
103
|
+
if prompt and self.context:
|
|
104
|
+
kwargs["prompt"] = prompt[-PROMPT_CHARS:]
|
|
105
|
+
create = self.client.audio.transcriptions.create
|
|
106
|
+
if self._verbose:
|
|
107
|
+
try:
|
|
108
|
+
return create(
|
|
109
|
+
**kwargs, response_format="verbose_json", timestamp_granularities=["segment"]
|
|
110
|
+
)
|
|
111
|
+
except Exception as e:
|
|
112
|
+
if not _format_unsupported(e):
|
|
113
|
+
raise
|
|
114
|
+
# e.g. gpt-4o-*-transcribe only return json; times then come from VAD
|
|
115
|
+
self._verbose = self._timed = False
|
|
116
|
+
out = create(**kwargs, response_format="json")
|
|
117
|
+
if self.language and hasattr(out, "model_dump"): # plain json names no language
|
|
118
|
+
out = {**out.model_dump(), "language": self.language}
|
|
119
|
+
return out
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class GroqBackend(OpenAIBackend):
|
|
123
|
+
name = "groq"
|
|
124
|
+
preset = "groq"
|
|
125
|
+
remote = "Groq"
|
|
126
|
+
default_model = "whisper-large-v3-turbo"
|
|
127
|
+
api_key_env = "GROQ_API_KEY"
|
|
128
|
+
base_url = "https://api.groq.com/openai/v1"
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _format_unsupported(e: Exception) -> bool:
|
|
132
|
+
msg = str(e).lower()
|
|
133
|
+
return type(e).__name__ == "BadRequestError" and (
|
|
134
|
+
"response_format" in msg or "timestamp" in msg or "verbose_json" in msg
|
|
135
|
+
)
|