rawi-speech 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.
Files changed (93) hide show
  1. rawi/__init__.py +7 -0
  2. rawi/__main__.py +8 -0
  3. rawi/audio/__init__.py +0 -0
  4. rawi/audio/io.py +217 -0
  5. rawi/audio/vad.py +48 -0
  6. rawi/cli.py +487 -0
  7. rawi/client.py +74 -0
  8. rawi/config.py +96 -0
  9. rawi/engines/__init__.py +0 -0
  10. rawi/engines/base.py +175 -0
  11. rawi/engines/factory.py +50 -0
  12. rawi/engines/stt/__init__.py +0 -0
  13. rawi/engines/stt/cohere.py +148 -0
  14. rawi/engines/stt/faster_whisper.py +77 -0
  15. rawi/engines/stt/qwen3.py +221 -0
  16. rawi/engines/stt/sirocco.py +147 -0
  17. rawi/engines/tts/__init__.py +0 -0
  18. rawi/engines/tts/chatterbox.py +100 -0
  19. rawi/engines/tts/f5.py +321 -0
  20. rawi/engines/tts/kokoro_engine.py +196 -0
  21. rawi/engines/tts/mlx_audio_engine.py +131 -0
  22. rawi/engines/tts/omnivoice_engine.py +88 -0
  23. rawi/engines/tts/speecht5.py +121 -0
  24. rawi/engines/tts/supertonic.py +288 -0
  25. rawi/engines/tts/tiny_voca.py +271 -0
  26. rawi/engines/tts/tiny_voca_cs.py +70 -0
  27. rawi/engines/tts/torch_base.py +290 -0
  28. rawi/engines/tts/voxcpm.py +86 -0
  29. rawi/engines/tts/xtts.py +151 -0
  30. rawi/errors.py +164 -0
  31. rawi/log.py +23 -0
  32. rawi/manager.py +215 -0
  33. rawi/registry/__init__.py +0 -0
  34. rawi/registry/manifest.py +154 -0
  35. rawi/registry/models.yaml +977 -0
  36. rawi/registry/store.py +230 -0
  37. rawi/server/__init__.py +0 -0
  38. rawi/server/app.py +127 -0
  39. rawi/server/routes/__init__.py +0 -0
  40. rawi/server/routes/health.py +18 -0
  41. rawi/server/routes/native.py +112 -0
  42. rawi/server/routes/openai_audio.py +281 -0
  43. rawi/server/schemas.py +34 -0
  44. rawi/server/state.py +23 -0
  45. rawi/text/__init__.py +0 -0
  46. rawi/text/arabic.py +117 -0
  47. rawi/text/metrics.py +38 -0
  48. rawi/vendor/README.md +78 -0
  49. rawi/vendor/catt_tashkeel/LICENSE +201 -0
  50. rawi/vendor/catt_tashkeel/__init__.py +14 -0
  51. rawi/vendor/catt_tashkeel/bw2ar.py +129 -0
  52. rawi/vendor/catt_tashkeel/models.py +356 -0
  53. rawi/vendor/catt_tashkeel/tokenizer.py +161 -0
  54. rawi/vendor/catt_tashkeel/utils.py +142 -0
  55. rawi/vendor/dizione/LICENSE +202 -0
  56. rawi/vendor/dizione/__init__.py +74 -0
  57. rawi/vendor/dizione/align.py +159 -0
  58. rawi/vendor/dizione/convert.py +417 -0
  59. rawi/vendor/dizione/data/abbreviations.txt +103 -0
  60. rawi/vendor/dizione/data/chat.txt +111 -0
  61. rawi/vendor/dizione/data/endings.txt +130 -0
  62. rawi/vendor/dizione/data/exceptions.txt +250 -0
  63. rawi/vendor/dizione/data/function_words.txt +189 -0
  64. rawi/vendor/dizione/data/homograph_fixes.txt +57 -0
  65. rawi/vendor/dizione/data/homograph_rules.txt +39 -0
  66. rawi/vendor/dizione/data/letters.txt +27 -0
  67. rawi/vendor/dizione/data/phrases.txt +63 -0
  68. rawi/vendor/dizione/data/units.txt +76 -0
  69. rawi/vendor/dizione/engine.py +280 -0
  70. rawi/vendor/dizione/g2p.py +98 -0
  71. rawi/vendor/dizione/homographs.py +201 -0
  72. rawi/vendor/dizione/morphology.py +220 -0
  73. rawi/vendor/dizione/normalize.py +1426 -0
  74. rawi/vendor/dizione/sentence.py +118 -0
  75. rawi/vendor/dizione/symbols.py +71 -0
  76. rawi/vendor/dizione/tables.py +106 -0
  77. rawi/vendor/supertonic/LICENSE +21 -0
  78. rawi/vendor/supertonic/__init__.py +1 -0
  79. rawi/vendor/supertonic/text.py +178 -0
  80. rawi/vendor/tiny_voca_ar/LICENSE +201 -0
  81. rawi/vendor/tiny_voca_ar/__init__.py +5 -0
  82. rawi/vendor/tiny_voca_ar/arabic_frontend.py +351 -0
  83. rawi/vendor/tiny_voca_ar/numbers.py +79 -0
  84. rawi/vendor/tiny_voca_ar/text.py +144 -0
  85. rawi/vendor/tiny_voca_cs/LICENSE +202 -0
  86. rawi/vendor/tiny_voca_cs/__init__.py +3 -0
  87. rawi/vendor/tiny_voca_cs/text.py +323 -0
  88. rawi_speech-0.1.0.dist-info/METADATA +639 -0
  89. rawi_speech-0.1.0.dist-info/RECORD +93 -0
  90. rawi_speech-0.1.0.dist-info/WHEEL +4 -0
  91. rawi_speech-0.1.0.dist-info/entry_points.txt +2 -0
  92. rawi_speech-0.1.0.dist-info/licenses/LICENSE +201 -0
  93. rawi_speech-0.1.0.dist-info/licenses/NOTICE +55 -0
rawi/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Rawi (راوي): local runtime for Arabic speech models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.1.0"
6
+
7
+ __all__ = ["__version__"]
rawi/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Allow ``python -m rawi``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from rawi.cli import app
6
+
7
+ if __name__ == "__main__":
8
+ app()
rawi/audio/__init__.py ADDED
File without changes
rawi/audio/io.py ADDED
@@ -0,0 +1,217 @@
1
+ """Audio decoding and encoding.
2
+
3
+ Decode: soundfile (wav/flac/ogg) → ffmpeg on PATH (mp3/m4a/webm/…) → 415 error with a fix.
4
+ Encode: wav (PCM16), flac, pcm (raw s16le) natively; mp3/opus/aac through ffmpeg.
5
+ numpy, soundfile and soxr are imported lazily.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import io
11
+ import shutil
12
+ import subprocess
13
+ import wave
14
+ from typing import TYPE_CHECKING
15
+
16
+ from rawi.errors import BadAudioError, FfmpegRequiredError, InvalidInputError
17
+
18
+ if TYPE_CHECKING:
19
+ import numpy as np
20
+ import numpy.typing as npt
21
+
22
+ FloatArray = npt.NDArray[np.float32]
23
+
24
+ NATIVE_FORMATS = ("wav", "flac", "pcm")
25
+ FFMPEG_FORMATS = ("mp3", "opus", "aac")
26
+ FORMATS = NATIVE_FORMATS + FFMPEG_FORMATS
27
+ _PREFER_FFMPEG = {"MP3"}
28
+
29
+ CONTENT_TYPES = {
30
+ "wav": "audio/wav",
31
+ "flac": "audio/flac",
32
+ "pcm": "audio/pcm",
33
+ "mp3": "audio/mpeg",
34
+ "opus": "audio/ogg",
35
+ "aac": "audio/aac",
36
+ }
37
+
38
+ _FFMPEG_ENCODE_ARGS = {
39
+ "mp3": ["-f", "mp3", "-codec:a", "libmp3lame", "-q:a", "4"],
40
+ "opus": ["-f", "ogg", "-codec:a", "libopus", "-b:a", "48k"],
41
+ "aac": ["-f", "adts", "-codec:a", "aac", "-b:a", "96k"],
42
+ }
43
+
44
+
45
+ def ffmpeg_path() -> str | None:
46
+ return shutil.which("ffmpeg")
47
+
48
+
49
+ # ---- decoding --------------------------------------------------------------------------------
50
+
51
+
52
+ def to_mono(audio: npt.NDArray[np.floating]) -> FloatArray:
53
+ import numpy as np
54
+
55
+ arr = np.asarray(audio, dtype=np.float32)
56
+ if arr.ndim == 2:
57
+ arr = arr.mean(axis=1, dtype=np.float32)
58
+ return arr.reshape(-1)
59
+
60
+
61
+ def resample(audio: FloatArray, sr_in: int, sr_out: int) -> FloatArray:
62
+ if sr_in == sr_out:
63
+ return audio
64
+ import numpy as np
65
+ import soxr
66
+
67
+ out: FloatArray = soxr.resample(audio, sr_in, sr_out).astype(np.float32, copy=False)
68
+ return out
69
+
70
+
71
+ def _decode_ffmpeg(data: bytes, target_sr: int) -> FloatArray:
72
+ import numpy as np
73
+
74
+ exe = ffmpeg_path()
75
+ if exe is None:
76
+ raise FfmpegRequiredError("this")
77
+ proc = subprocess.run(
78
+ [
79
+ exe,
80
+ "-nostdin",
81
+ "-hide_banner",
82
+ "-loglevel",
83
+ "error",
84
+ "-i",
85
+ "pipe:0",
86
+ "-f",
87
+ "f32le",
88
+ "-ac",
89
+ "1",
90
+ "-ar",
91
+ str(target_sr),
92
+ "pipe:1",
93
+ ],
94
+ input=data,
95
+ capture_output=True,
96
+ check=False,
97
+ )
98
+ if proc.returncode != 0 or not proc.stdout:
99
+ msg = proc.stderr.decode(errors="replace").strip().splitlines()[-1:] or ["no audio"]
100
+ raise BadAudioError(
101
+ f"Could not decode the audio: {msg[0]}",
102
+ fix="Send WAV, FLAC, OGG, MP3, M4A or WebM audio",
103
+ )
104
+ return np.frombuffer(proc.stdout, dtype="<f4").astype(np.float32)
105
+
106
+
107
+ def decode(data: bytes, target_sr: int | None = 16000) -> tuple[FloatArray, int]:
108
+ """Bytes of any supported file → (mono float32, sample rate). Resamples if ``target_sr``."""
109
+ if not data:
110
+ raise BadAudioError("The audio file is empty.", fix="Send a non-empty audio file")
111
+ import soundfile as sf
112
+
113
+ try:
114
+ info = sf.info(io.BytesIO(data))
115
+ # libsndfile misreports the length of VBR MP3 read from memory: prefer ffmpeg there.
116
+ if info.format in _PREFER_FFMPEG and ffmpeg_path() is not None:
117
+ raise RuntimeError("prefer ffmpeg")
118
+ raw, sr = sf.read(io.BytesIO(data), dtype="float32", always_2d=False)
119
+ except (sf.LibsndfileError, RuntimeError, TypeError):
120
+ sr = target_sr or 16000
121
+ audio = _decode_ffmpeg(data, sr)
122
+ else:
123
+ audio = to_mono(raw)
124
+ if audio.size == 0:
125
+ raise BadAudioError("The audio file has no samples.", fix="Send a non-empty audio file")
126
+ if target_sr and sr != target_sr:
127
+ audio, sr = resample(audio, sr, target_sr), target_sr
128
+ return audio, int(sr)
129
+
130
+
131
+ # ---- encoding --------------------------------------------------------------------------------
132
+
133
+
134
+ def to_pcm16(audio: npt.NDArray[np.floating]) -> bytes:
135
+ import numpy as np
136
+
137
+ clipped = np.clip(np.nan_to_num(audio, nan=0.0), -1.0, 1.0)
138
+ pcm: bytes = (clipped * 32767.0).astype("<i2").tobytes()
139
+ return pcm
140
+
141
+
142
+ def encode_wav(audio: npt.NDArray[np.floating], sample_rate: int) -> bytes:
143
+ """Mono float audio in [-1, 1] → 16-bit PCM WAV bytes."""
144
+ buf = io.BytesIO()
145
+ with wave.open(buf, "wb") as w:
146
+ w.setnchannels(1)
147
+ w.setsampwidth(2)
148
+ w.setframerate(sample_rate)
149
+ w.writeframes(to_pcm16(audio))
150
+ return buf.getvalue()
151
+
152
+
153
+ def wav_header(sample_rate: int, data_len: int = 0xFFFFFFFF - 36) -> bytes:
154
+ """A WAV header for streaming when the final length is unknown (max size placeholder)."""
155
+ import struct
156
+
157
+ return (
158
+ b"RIFF"
159
+ + struct.pack("<I", min(data_len + 36, 0xFFFFFFFF))
160
+ + b"WAVE"
161
+ + b"fmt "
162
+ + struct.pack("<IHHIIHH", 16, 1, 1, sample_rate, sample_rate * 2, 2, 16)
163
+ + b"data"
164
+ + struct.pack("<I", data_len)
165
+ )
166
+
167
+
168
+ def encode(audio: npt.NDArray[np.floating], sample_rate: int, fmt: str = "wav") -> bytes:
169
+ """Encode mono float audio. Raises a clear error for unknown formats or missing ffmpeg."""
170
+ fmt = fmt.lower()
171
+ if fmt == "wav":
172
+ return encode_wav(audio, sample_rate)
173
+ if fmt == "pcm":
174
+ return to_pcm16(audio)
175
+ if fmt == "flac":
176
+ import soundfile as sf
177
+
178
+ buf = io.BytesIO()
179
+ sf.write(buf, to_mono(audio), sample_rate, format="FLAC", subtype="PCM_16")
180
+ return buf.getvalue()
181
+ if fmt in FFMPEG_FORMATS:
182
+ exe = ffmpeg_path()
183
+ if exe is None:
184
+ err = FfmpegRequiredError(fmt)
185
+ raise InvalidInputError(err.message, fix=err.fix)
186
+ proc = subprocess.run(
187
+ [
188
+ exe,
189
+ "-nostdin",
190
+ "-hide_banner",
191
+ "-loglevel",
192
+ "error",
193
+ "-f",
194
+ "s16le",
195
+ "-ac",
196
+ "1",
197
+ "-ar",
198
+ str(sample_rate),
199
+ "-i",
200
+ "pipe:0",
201
+ *_FFMPEG_ENCODE_ARGS[fmt],
202
+ "pipe:1",
203
+ ],
204
+ input=to_pcm16(audio),
205
+ capture_output=True,
206
+ check=False,
207
+ )
208
+ if proc.returncode != 0:
209
+ raise InvalidInputError(
210
+ f"ffmpeg could not encode {fmt}: {proc.stderr.decode(errors='replace')[-200:]}",
211
+ fix="Use response_format=wav",
212
+ )
213
+ return proc.stdout
214
+ raise InvalidInputError(
215
+ f"Unsupported audio format '{fmt}'. Supported: {', '.join(FORMATS)}.",
216
+ fix="Use response_format=wav",
217
+ )
rawi/audio/vad.py ADDED
@@ -0,0 +1,48 @@
1
+ """Energy-based trimming of leading and trailing silence (Silero VAD is a later stretch goal).
2
+
3
+ Speech models such as Cohere Transcribe hallucinate on silence, so we cut it off the ends.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import TYPE_CHECKING
9
+
10
+ if TYPE_CHECKING:
11
+ import numpy as np
12
+ import numpy.typing as npt
13
+
14
+
15
+ def trim_silence(
16
+ audio: npt.NDArray[np.float32],
17
+ sample_rate: int,
18
+ threshold_db: float = -40.0,
19
+ frame_ms: float = 30.0,
20
+ pad_ms: float = 150.0,
21
+ ) -> npt.NDArray[np.float32]:
22
+ """Drop frames quieter than ``threshold_db`` (relative to the loudest frame) at both ends.
23
+
24
+ Keeps ``pad_ms`` of context around the speech. Returns the input unchanged when it is all
25
+ silence (callers decide what an empty transcript means).
26
+ """
27
+ import numpy as np
28
+
29
+ frame = max(1, int(sample_rate * frame_ms / 1000))
30
+ n = len(audio) // frame
31
+ if n == 0:
32
+ return audio
33
+ frames = audio[: n * frame].reshape(n, frame)
34
+ rms = np.sqrt(np.mean(frames.astype(np.float64) ** 2, axis=1)) + 1e-12
35
+ db = 20 * np.log10(rms / rms.max())
36
+ voiced = np.flatnonzero(db > threshold_db)
37
+ if voiced.size == 0 or rms.max() < 1e-4:
38
+ return audio
39
+ pad = int(sample_rate * pad_ms / 1000)
40
+ start = max(0, voiced[0] * frame - pad)
41
+ end = min(len(audio), (voiced[-1] + 1) * frame + pad)
42
+ return audio[start:end]
43
+
44
+
45
+ def is_silent(audio: npt.NDArray[np.float32], floor: float = 1e-4) -> bool:
46
+ import numpy as np
47
+
48
+ return audio.size == 0 or float(np.sqrt(np.mean(audio.astype(np.float64) ** 2))) < floor