swanada 1.0.0__tar.gz

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 (54) hide show
  1. swanada-1.0.0/LICENSE +21 -0
  2. swanada-1.0.0/PKG-INFO +128 -0
  3. swanada-1.0.0/README.md +108 -0
  4. swanada-1.0.0/pyproject.toml +74 -0
  5. swanada-1.0.0/python/src/swanada/__init__.py +102 -0
  6. swanada-1.0.0/python/src/swanada/audio.py +89 -0
  7. swanada-1.0.0/python/src/swanada/cli.py +203 -0
  8. swanada-1.0.0/python/src/swanada/core.py +117 -0
  9. swanada-1.0.0/python/src/swanada/decoder.py +441 -0
  10. swanada-1.0.0/python/src/swanada/denoise.py +291 -0
  11. swanada-1.0.0/python/src/swanada/en_lexicon.py +1854 -0
  12. swanada-1.0.0/python/src/swanada/engine.py +198 -0
  13. swanada-1.0.0/python/src/swanada/frontend.py +170 -0
  14. swanada-1.0.0/python/src/swanada/normalizer.py +256 -0
  15. swanada-1.0.0/python/src/swanada/streaming.py +602 -0
  16. swanada-1.0.0/python/src/swanada/vocab.py +212 -0
  17. swanada-1.0.0/python/src/swanada.egg-info/PKG-INFO +128 -0
  18. swanada-1.0.0/python/src/swanada.egg-info/SOURCES.txt +52 -0
  19. swanada-1.0.0/python/src/swanada.egg-info/dependency_links.txt +1 -0
  20. swanada-1.0.0/python/src/swanada.egg-info/entry_points.txt +2 -0
  21. swanada-1.0.0/python/src/swanada.egg-info/requires.txt +9 -0
  22. swanada-1.0.0/python/src/swanada.egg-info/top_level.txt +1 -0
  23. swanada-1.0.0/setup.cfg +4 -0
  24. swanada-1.0.0/tests/test_adversarial_prefix_locking.py +221 -0
  25. swanada-1.0.0/tests/test_adversarial_prefix_locking_chunks.py +71 -0
  26. swanada-1.0.0/tests/test_adversarial_streaming_latency.py +106 -0
  27. swanada-1.0.0/tests/test_audio_frontend.py +224 -0
  28. swanada-1.0.0/tests/test_challenger_m1_brahmic_adversarial.py +357 -0
  29. swanada-1.0.0/tests/test_challenger_m1_brahmic_deep_stress.py +384 -0
  30. swanada-1.0.0/tests/test_challenger_m1_comprehensive_matrix.py +178 -0
  31. swanada-1.0.0/tests/test_challenger_m1_comprehensive_stress.py +168 -0
  32. swanada-1.0.0/tests/test_challenger_m1_it4_adversarial_orthography.py +420 -0
  33. swanada-1.0.0/tests/test_challenger_m1_prefix_locking_deep_stress.py +273 -0
  34. swanada-1.0.0/tests/test_challenger_m1_streaming_rtf_and_latency.py +186 -0
  35. swanada-1.0.0/tests/test_challenger_m2_adversarial.py +359 -0
  36. swanada-1.0.0/tests/test_challenger_m2_audio_verification.py +114 -0
  37. swanada-1.0.0/tests/test_challenger_m2_parity_and_weight_integrity.py +399 -0
  38. swanada-1.0.0/tests/test_challenger_m3_adversarial.py +176 -0
  39. swanada-1.0.0/tests/test_challenger_m3_empirical_verification.py +283 -0
  40. swanada-1.0.0/tests/test_challenger_m3_it2_adversarial.py +254 -0
  41. swanada-1.0.0/tests/test_challenger_m3_it3_stress.py +375 -0
  42. swanada-1.0.0/tests/test_challenger_m3_it4_invariants.py +490 -0
  43. swanada-1.0.0/tests/test_challenger_m3_it4_stress.py +383 -0
  44. swanada-1.0.0/tests/test_challenger_m4_adversarial_stress.py +257 -0
  45. swanada-1.0.0/tests/test_challenger_m4_cli_stress.py +265 -0
  46. swanada-1.0.0/tests/test_challenger_m4_it6_cli_deep_stress.py +259 -0
  47. swanada-1.0.0/tests/test_challenger_m5_acoustic_churn.py +147 -0
  48. swanada-1.0.0/tests/test_challenger_m5_multilang.py +145 -0
  49. swanada-1.0.0/tests/test_ctc_decoder.py +233 -0
  50. swanada-1.0.0/tests/test_denoise_and_orthography.py +100 -0
  51. swanada-1.0.0/tests/test_multilingual_parity.py +123 -0
  52. swanada-1.0.0/tests/test_streaming.py +209 -0
  53. swanada-1.0.0/tests/test_tier5_adversarial_hardening.py +525 -0
  54. swanada-1.0.0/tests/test_tooling.py +81 -0
swanada-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hemanth HM <hemanth@h3manth.com> (https://h3manth.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
swanada-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: swanada
3
+ Version: 1.0.0
4
+ Summary: Swanada (स्वनद): In-browser, Node.js, and Python 16 kHz Multilingual Speech-to-Text for Classical Sanskrit, Indian English & 10 Indic languages via ONNX/WASM.
5
+ Author-email: Hemanth HM <hemanth@h3manth.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://hemanth.github.io/swanada/
8
+ Project-URL: Repository, https://github.com/hemanth/swanada
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: numpy>=1.24.0
13
+ Provides-Extra: neural
14
+ Requires-Dist: onnxruntime>=1.18.0; extra == "neural"
15
+ Requires-Dist: soundfile>=0.12.1; extra == "neural"
16
+ Requires-Dist: scipy>=1.11.0; extra == "neural"
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ # swanada (स्वनद)
22
+
23
+ In-browser, Node.js, and Python 16,000 Hz multilingual speech-to-text (STT) for Classical Sanskrit (`sa`), Indian English (`en`), and ten Indic languages (`hi`, `kn`, `mr`, `bn`, `ta`, `te`, `ml`, `gu`, `pa`, `or`) powered by 17-layer Conformer-CTC INT8 models running 100% client-side via ONNX/WASM with zero cloud or server dependencies.
24
+
25
+ ```bash
26
+ npm install swanada
27
+ ```
28
+
29
+ ```bash
30
+ pip install swanada
31
+ ```
32
+
33
+ ## Quick Start (JavaScript / TypeScript)
34
+
35
+ ```typescript
36
+ import { Swanada } from 'swanada';
37
+
38
+ // Initialize transcriber for Classical Sanskrit
39
+ const transcriber = await Swanada.create({
40
+ language: 'sa',
41
+ executionProvider: 'wasm',
42
+ numThreads: 4,
43
+ });
44
+
45
+ // Transcribe audio Float32Array PCM or WAV ArrayBuffer
46
+ const result = await transcriber.transcribe(audioPcmFloat32);
47
+ console.log(`Transcript (${result.language}):`, result.text);
48
+ console.log(`Duration: ${result.durationMs}ms | Latency: ${result.inferenceMs}ms | RTF: ${result.rtf}`);
49
+
50
+ // Classical Sanskrit to Roman IAST transliteration
51
+ const iast = Swanada.transliterateIast(result.text);
52
+ console.log('IAST Transliteration:', iast);
53
+
54
+ await transcriber.release();
55
+ ```
56
+
57
+ ## Quick Start (Python)
58
+
59
+ ```python
60
+ from swanada import Swanada
61
+
62
+ stt = Swanada.create(language="kn") # Kannada
63
+ result = stt.transcribe("speech_16k.wav")
64
+
65
+ print("Transcript:", result.text)
66
+ print(f"Duration: {result.duration_ms:.1f}ms | Latency: {result.inference_ms:.1f}ms | RTF: {result.rtf:.3f}")
67
+ ```
68
+
69
+ ## CLI Usage
70
+
71
+ Dual-runtime command-line interface with identical flags:
72
+
73
+ ```bash
74
+ # Node.js CLI
75
+ npx swanada speech.wav -l sa
76
+ npx swanada recitation.wav -l sa --json -o output.json
77
+ cat stream.wav | npx swanada -l hi --stream
78
+
79
+ # Python CLI
80
+ swanada speech.wav -l kn
81
+ cat stream.wav | swanada -l ta --stream
82
+ ```
83
+
84
+ ### Unified CLI Flags
85
+ - `-l, --language <lang>`: Language code (default: `sa`). Supported: `sa, en, hi, kn, mr, bn, ta, te, ml, gu, pa, or`.
86
+ - `-m, --model-dir <dir>`: Optional custom models directory.
87
+ - `-o, --output <file>`: Output text file (default: stdout).
88
+ - `--json`: Emit structured JSON with text, durationMs, inferenceMs, rtf, and tokens.
89
+ - `--stream`: Simulate chunk-by-chunk streaming transcription (320 ms quanta).
90
+ - `--iast`: Transliterate Classical Sanskrit output to Roman IAST with Vedic accents.
91
+ - `-h, --help`: Show help and usage summary.
92
+ - `-v, --version`: Show version (`swanada 1.0.0`).
93
+
94
+ ## Benchmarks
95
+
96
+ Evaluated across 480 held-out 16 kHz utterances (40 per language, `B = 1,000` bootstrap 95% CIs), 1,200 unseen `google/fleurs` + wild test clips, and 72 streaming sessions (100 ms chunks):
97
+
98
+ | Language | Code | Held-Out CER (95% CI) | Held-Out WER | Unseen Fleurs CER |
99
+ | :--- | :---: | :---: | :---: | :---: |
100
+ | Classical Sanskrit | `sa` | `5.24% [3.47%, 7.28%]` | `27.77%` | `17.10%` |
101
+ | Indian English | `en` | `5.70% [4.41%, 7.00%]` | `16.94%` | `15.61%` |
102
+ | Hindi | `hi` | `3.44% [2.34%, 4.53%]` | `12.64%` | `5.52%` |
103
+ | Kannada | `kn` | `6.03% [4.65%, 7.58%]` | `35.70%` | `5.11%` |
104
+ | Marathi | `mr` | `7.31% [4.30%, 10.50%]` | `27.52%` | `7.37%` |
105
+ | Bengali | `bn` | `7.76% [6.07%, 9.54%]` | `40.66%` | `5.71%` |
106
+ | Tamil | `ta` | `8.01% [6.28%, 9.86%]` | `38.46%` | `10.88%` |
107
+ | Telugu | `te` | `5.54% [4.01%, 7.16%]` | `30.62%` | `9.05%` |
108
+ | Malayalam | `ml` | `7.78% [5.58%, 10.13%]` | `40.27%` | `6.42%` |
109
+ | Gujarati | `gu` | `5.32% [3.42%, 7.73%]` | `23.17%` | `6.69%` |
110
+ | Punjabi | `pa` | `7.71% [4.69%, 11.34%]` | `29.47%` | `9.59%` |
111
+ | Odia | `or` | `8.94% [6.25%, 12.46%]` | `37.55%` | `8.95%` |
112
+ | **Overall (12 Langs)** | — | **`6.57% [5.94%, 7.22%]`** | **`30.06%`** | **`9.00%`** |
113
+
114
+ Shared 178 MB INT8 Conformer encoder + 515 KB per-language CTC projection heads run at `0.0325x` CPU RTF, `~8-11 ms` streaming chunk latency, and `0.00%` committed prefix churn.
115
+
116
+ ## Live Playground
117
+
118
+ - h3manth.com AI Experiments Studio: [https://h3manth.com/ai/swanada/](https://h3manth.com/ai/swanada/)
119
+ - GitHub Pages Web Studio: [https://hemanth.github.io/swanada/](https://hemanth.github.io/swanada/)
120
+
121
+ ## Model Weights & Hugging Face Hub
122
+
123
+ Quantized INT8 model weights are hosted on Hugging Face Hub:
124
+ - Repository: [https://huggingface.co/gnumanth/swanada](https://huggingface.co/gnumanth/swanada)
125
+
126
+ ## License
127
+
128
+ MIT © [Hemanth HM](https://h3manth.com)
@@ -0,0 +1,108 @@
1
+ # swanada (स्वनद)
2
+
3
+ In-browser, Node.js, and Python 16,000 Hz multilingual speech-to-text (STT) for Classical Sanskrit (`sa`), Indian English (`en`), and ten Indic languages (`hi`, `kn`, `mr`, `bn`, `ta`, `te`, `ml`, `gu`, `pa`, `or`) powered by 17-layer Conformer-CTC INT8 models running 100% client-side via ONNX/WASM with zero cloud or server dependencies.
4
+
5
+ ```bash
6
+ npm install swanada
7
+ ```
8
+
9
+ ```bash
10
+ pip install swanada
11
+ ```
12
+
13
+ ## Quick Start (JavaScript / TypeScript)
14
+
15
+ ```typescript
16
+ import { Swanada } from 'swanada';
17
+
18
+ // Initialize transcriber for Classical Sanskrit
19
+ const transcriber = await Swanada.create({
20
+ language: 'sa',
21
+ executionProvider: 'wasm',
22
+ numThreads: 4,
23
+ });
24
+
25
+ // Transcribe audio Float32Array PCM or WAV ArrayBuffer
26
+ const result = await transcriber.transcribe(audioPcmFloat32);
27
+ console.log(`Transcript (${result.language}):`, result.text);
28
+ console.log(`Duration: ${result.durationMs}ms | Latency: ${result.inferenceMs}ms | RTF: ${result.rtf}`);
29
+
30
+ // Classical Sanskrit to Roman IAST transliteration
31
+ const iast = Swanada.transliterateIast(result.text);
32
+ console.log('IAST Transliteration:', iast);
33
+
34
+ await transcriber.release();
35
+ ```
36
+
37
+ ## Quick Start (Python)
38
+
39
+ ```python
40
+ from swanada import Swanada
41
+
42
+ stt = Swanada.create(language="kn") # Kannada
43
+ result = stt.transcribe("speech_16k.wav")
44
+
45
+ print("Transcript:", result.text)
46
+ print(f"Duration: {result.duration_ms:.1f}ms | Latency: {result.inference_ms:.1f}ms | RTF: {result.rtf:.3f}")
47
+ ```
48
+
49
+ ## CLI Usage
50
+
51
+ Dual-runtime command-line interface with identical flags:
52
+
53
+ ```bash
54
+ # Node.js CLI
55
+ npx swanada speech.wav -l sa
56
+ npx swanada recitation.wav -l sa --json -o output.json
57
+ cat stream.wav | npx swanada -l hi --stream
58
+
59
+ # Python CLI
60
+ swanada speech.wav -l kn
61
+ cat stream.wav | swanada -l ta --stream
62
+ ```
63
+
64
+ ### Unified CLI Flags
65
+ - `-l, --language <lang>`: Language code (default: `sa`). Supported: `sa, en, hi, kn, mr, bn, ta, te, ml, gu, pa, or`.
66
+ - `-m, --model-dir <dir>`: Optional custom models directory.
67
+ - `-o, --output <file>`: Output text file (default: stdout).
68
+ - `--json`: Emit structured JSON with text, durationMs, inferenceMs, rtf, and tokens.
69
+ - `--stream`: Simulate chunk-by-chunk streaming transcription (320 ms quanta).
70
+ - `--iast`: Transliterate Classical Sanskrit output to Roman IAST with Vedic accents.
71
+ - `-h, --help`: Show help and usage summary.
72
+ - `-v, --version`: Show version (`swanada 1.0.0`).
73
+
74
+ ## Benchmarks
75
+
76
+ Evaluated across 480 held-out 16 kHz utterances (40 per language, `B = 1,000` bootstrap 95% CIs), 1,200 unseen `google/fleurs` + wild test clips, and 72 streaming sessions (100 ms chunks):
77
+
78
+ | Language | Code | Held-Out CER (95% CI) | Held-Out WER | Unseen Fleurs CER |
79
+ | :--- | :---: | :---: | :---: | :---: |
80
+ | Classical Sanskrit | `sa` | `5.24% [3.47%, 7.28%]` | `27.77%` | `17.10%` |
81
+ | Indian English | `en` | `5.70% [4.41%, 7.00%]` | `16.94%` | `15.61%` |
82
+ | Hindi | `hi` | `3.44% [2.34%, 4.53%]` | `12.64%` | `5.52%` |
83
+ | Kannada | `kn` | `6.03% [4.65%, 7.58%]` | `35.70%` | `5.11%` |
84
+ | Marathi | `mr` | `7.31% [4.30%, 10.50%]` | `27.52%` | `7.37%` |
85
+ | Bengali | `bn` | `7.76% [6.07%, 9.54%]` | `40.66%` | `5.71%` |
86
+ | Tamil | `ta` | `8.01% [6.28%, 9.86%]` | `38.46%` | `10.88%` |
87
+ | Telugu | `te` | `5.54% [4.01%, 7.16%]` | `30.62%` | `9.05%` |
88
+ | Malayalam | `ml` | `7.78% [5.58%, 10.13%]` | `40.27%` | `6.42%` |
89
+ | Gujarati | `gu` | `5.32% [3.42%, 7.73%]` | `23.17%` | `6.69%` |
90
+ | Punjabi | `pa` | `7.71% [4.69%, 11.34%]` | `29.47%` | `9.59%` |
91
+ | Odia | `or` | `8.94% [6.25%, 12.46%]` | `37.55%` | `8.95%` |
92
+ | **Overall (12 Langs)** | — | **`6.57% [5.94%, 7.22%]`** | **`30.06%`** | **`9.00%`** |
93
+
94
+ Shared 178 MB INT8 Conformer encoder + 515 KB per-language CTC projection heads run at `0.0325x` CPU RTF, `~8-11 ms` streaming chunk latency, and `0.00%` committed prefix churn.
95
+
96
+ ## Live Playground
97
+
98
+ - h3manth.com AI Experiments Studio: [https://h3manth.com/ai/swanada/](https://h3manth.com/ai/swanada/)
99
+ - GitHub Pages Web Studio: [https://hemanth.github.io/swanada/](https://hemanth.github.io/swanada/)
100
+
101
+ ## Model Weights & Hugging Face Hub
102
+
103
+ Quantized INT8 model weights are hosted on Hugging Face Hub:
104
+ - Repository: [https://huggingface.co/gnumanth/swanada](https://huggingface.co/gnumanth/swanada)
105
+
106
+ ## License
107
+
108
+ MIT © [Hemanth HM](https://h3manth.com)
@@ -0,0 +1,74 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "swanada"
7
+ version = "1.0.0"
8
+ description = "Swanada (स्वनद): In-browser, Node.js, and Python 16 kHz Multilingual Speech-to-Text for Classical Sanskrit, Indian English & 10 Indic languages via ONNX/WASM."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ authors = [
12
+ { name = "Hemanth HM", email = "hemanth@h3manth.com" }
13
+ ]
14
+ requires-python = ">=3.10"
15
+ dependencies = [
16
+ "numpy>=1.24.0",
17
+ ]
18
+
19
+ [project.urls]
20
+ Homepage = "https://hemanth.github.io/swanada/"
21
+ Repository = "https://github.com/hemanth/swanada"
22
+
23
+ [project.scripts]
24
+ swanada = "swanada.cli:main"
25
+
26
+ [project.optional-dependencies]
27
+ neural = [
28
+ "onnxruntime>=1.18.0",
29
+ "soundfile>=0.12.1",
30
+ "scipy>=1.11.0",
31
+ ]
32
+ dev = [
33
+ "pytest>=8.0.0",
34
+ ]
35
+
36
+ [tool.setuptools.packages.find]
37
+ where = ["python/src"]
38
+
39
+ [tool.pytest.ini_options]
40
+ pythonpath = ["python/src"]
41
+ testpaths = ["tests"]
42
+ markers = [
43
+ "tier1: Tier 1 feature coverage tests",
44
+ "tier2: Tier 2 boundary and corner case tests",
45
+ "tier3: Tier 3 cross-feature integration tests",
46
+ "tier4: Tier 4 real-world speech and benchmark tests",
47
+ "m1: Milestone 1 tests",
48
+ "m2: Milestone 2 tests",
49
+ "m3: Milestone 3 tests",
50
+ "m4: Milestone 4 tests",
51
+ "m5: Milestone 5 tests",
52
+ "f01: Feature 1 Audio Ingestion & Resampling",
53
+ "f02: Feature 2 Deterministic Log-Mel Frontend",
54
+ "f03: Feature 3 Core In-Browser ONNX/WASM Engine",
55
+ "f04: Feature 4 Linear-Time CTC Greedy Decoder",
56
+ "f05: Feature 5 Multilingual Vocabulary Registry",
57
+ "f06: Feature 6 Classical Sanskrit CTC Model",
58
+ "f07: Feature 7 Indic Languages CTC Heads",
59
+ "f08: Feature 8 Indian English Acoustic Head",
60
+ "f09: Feature 9 Streaming AudioWorklet Processor",
61
+ "f10: Feature 10 Background STT Web Worker",
62
+ "f11: Feature 11 RTF < 1.0 Protocol",
63
+ "f12: Feature 12 Offline CacheStorage Persistence",
64
+ "f13: Feature 13 JS/TS Package Parity",
65
+ "f14: Feature 14 Node.js Runtime Support",
66
+ "f15: Feature 15 Standalone Python Package",
67
+ "f16: Feature 16 Cross-Platform CLI Tools",
68
+ "f17: Feature 17 Tactile Studio Browser Playground",
69
+ "f18: Feature 18 Local Static Server",
70
+ "f19: Feature 19 Automated Browser Test Harness",
71
+ "f20: Feature 20 Held-Out Speech Audio Test Suite",
72
+ "f21: Feature 21 Empirical Accuracy & Latency Benchmarks",
73
+ "f22: Feature 22 Adversarial Hardening & Zero Regressions",
74
+ ]
@@ -0,0 +1,102 @@
1
+ """Swanada: In-browser & multi-runtime 16 kHz Multilingual Speech-to-Text."""
2
+
3
+ __version__ = "1.0.0"
4
+
5
+ from .audio import (
6
+ load_audio,
7
+ resample_audio,
8
+ parse_wav,
9
+ save_wav,
10
+ )
11
+ from .frontend import (
12
+ extract_log_mel_features,
13
+ extract_log_mel_onnx,
14
+ create_mel_filterbank,
15
+ create_padded_hann_window,
16
+ hz_to_mel,
17
+ mel_to_hz,
18
+ )
19
+ from .normalizer import (
20
+ dedup_marks,
21
+ repair_brahmic_orthography,
22
+ normalize_indic_text,
23
+ assemble_text,
24
+ join_subwords,
25
+ )
26
+ from .denoise import (
27
+ DenoiseTelemetry,
28
+ enhance_speech_with_telemetry,
29
+ denoise_pcm_16k,
30
+ )
31
+ from .decoder import (
32
+ decode_ctc,
33
+ decode_ctc_tokens,
34
+ is_special_token,
35
+ CTCDecodeResult,
36
+ CTCGreedyDecoder,
37
+ )
38
+ from .engine import (
39
+ AcousticEngine,
40
+ TranscriptionResult,
41
+ )
42
+ from .core import (
43
+ Swanada,
44
+ )
45
+ from .vocab import (
46
+ REGISTRY,
47
+ Vocabulary,
48
+ LanguageMeta,
49
+ detect_script,
50
+ devanagari_to_iast,
51
+ transliterate_iast,
52
+ SUPPORTED_LANGUAGES,
53
+ BLANK_TOKEN_ID,
54
+ UNK_TOKEN_ID,
55
+ )
56
+ from .streaming import (
57
+ StreamingCTCDecoder,
58
+ StreamingTranscript,
59
+ SwanadaStream,
60
+ )
61
+
62
+ __all__ = [
63
+ "__version__",
64
+ "Swanada",
65
+ "SwanadaStream",
66
+ "StreamingCTCDecoder",
67
+ "StreamingTranscript",
68
+ "TranscriptionResult",
69
+ "AcousticEngine",
70
+ "REGISTRY",
71
+ "Vocabulary",
72
+ "LanguageMeta",
73
+ "detect_script",
74
+ "devanagari_to_iast",
75
+ "transliterate_iast",
76
+ "SUPPORTED_LANGUAGES",
77
+ "BLANK_TOKEN_ID",
78
+ "UNK_TOKEN_ID",
79
+ "load_audio",
80
+ "resample_audio",
81
+ "parse_wav",
82
+ "save_wav",
83
+ "extract_log_mel_features",
84
+ "extract_log_mel_onnx",
85
+ "create_mel_filterbank",
86
+ "create_padded_hann_window",
87
+ "hz_to_mel",
88
+ "mel_to_hz",
89
+ "dedup_marks",
90
+ "repair_brahmic_orthography",
91
+ "normalize_indic_text",
92
+ "assemble_text",
93
+ "join_subwords",
94
+ "DenoiseTelemetry",
95
+ "enhance_speech_with_telemetry",
96
+ "denoise_pcm_16k",
97
+ "decode_ctc",
98
+ "decode_ctc_tokens",
99
+ "is_special_token",
100
+ "CTCDecodeResult",
101
+ "CTCGreedyDecoder",
102
+ ]
@@ -0,0 +1,89 @@
1
+ """Audio loading, resampling, and WAV serialization for Swanada."""
2
+
3
+ import io
4
+ import math
5
+ from pathlib import Path
6
+ from typing import Tuple, Union
7
+ import numpy as np
8
+
9
+
10
+ def resample_audio(
11
+ wav: np.ndarray,
12
+ src_sr: int,
13
+ target_sr: int = 16000,
14
+ ) -> np.ndarray:
15
+ """Resample audio signal to target sample rate.
16
+
17
+ Uses polyphase FIR resampling (scipy.signal.resample_poly) with GCD reduction,
18
+ falling back to linear interpolation if scipy is unavailable.
19
+ """
20
+ if src_sr == target_sr:
21
+ return wav.astype(np.float32)
22
+
23
+ if len(wav) == 0:
24
+ return np.zeros(0, dtype=np.float32)
25
+
26
+ try:
27
+ import scipy.signal
28
+ g = math.gcd(target_sr, src_sr)
29
+ up = target_sr // g
30
+ down = src_sr // g
31
+ resampled = scipy.signal.resample_poly(wav, up, down)
32
+ return resampled.astype(np.float32)
33
+ except Exception:
34
+ num_samples = max(1, int(round(len(wav) * target_sr / src_sr)))
35
+ t_in = np.arange(len(wav))
36
+ t_out = np.linspace(0, len(wav) - 1, num_samples)
37
+ return np.interp(t_out, t_in, wav).astype(np.float32)
38
+
39
+
40
+ def load_audio(
41
+ source: Union[str, Path, bytes, np.ndarray],
42
+ target_sr: int = 16000,
43
+ ) -> np.ndarray:
44
+ """Load audio from file path, bytes, or ndarray, converting to 16 kHz mono Float32."""
45
+ sr = target_sr
46
+
47
+ if isinstance(source, (str, Path)):
48
+ import soundfile as sf
49
+ wav, sr = sf.read(str(source), dtype="float32")
50
+ elif isinstance(source, (bytes, bytearray)):
51
+ import soundfile as sf
52
+ wav, sr = sf.read(io.BytesIO(source), dtype="float32")
53
+ elif isinstance(source, np.ndarray):
54
+ wav = source.astype(np.float32)
55
+ else:
56
+ raise TypeError(f"Unsupported audio input type: {type(source)}")
57
+
58
+ # Downmix multi-channel to mono
59
+ if wav.ndim > 1:
60
+ wav = np.mean(wav, axis=1 if wav.shape[1] < wav.shape[0] else 0)
61
+
62
+ # Scale integer PCM if unnormalized
63
+ if np.issubdtype(wav.dtype, np.integer):
64
+ wav = wav.astype(np.float32) / 32768.0
65
+
66
+ # Resample if sample rate differs
67
+ if sr != target_sr:
68
+ wav = resample_audio(wav, sr, target_sr)
69
+
70
+ return wav.astype(np.float32)
71
+
72
+
73
+ def parse_wav(data: bytes) -> Tuple[np.ndarray, int]:
74
+ """Parse raw WAV byte stream into mono Float32 array and sample rate."""
75
+ import soundfile as sf
76
+ wav, sr = sf.read(io.BytesIO(data), dtype="float32")
77
+ if wav.ndim > 1:
78
+ wav = np.mean(wav, axis=1)
79
+ return wav.astype(np.float32), sr
80
+
81
+
82
+ def save_wav(
83
+ path: Union[str, Path],
84
+ pcm: np.ndarray,
85
+ sample_rate: int = 16000,
86
+ ) -> None:
87
+ """Save Float32 audio as 16-bit PCM WAV."""
88
+ import soundfile as sf
89
+ sf.write(str(path), pcm.astype(np.float32), sample_rate, subtype="PCM_16")