shruti-onnx 0.2.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.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,46 @@
1
+ Metadata-Version: 2.4
2
+ Name: shruti-onnx
3
+ Version: 0.2.0
4
+ Summary: Shruti: offline speech-to-text, one language and English in one small model, in ONNX Runtime (32 MB).
5
+ Author: Udgam Labs
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://huggingface.co/udgamlabs/Shruti-ONNX
8
+ Project-URL: Source, https://github.com/udgamlabs/shruti
9
+ Keywords: speech-recognition,speech-to-text,onnx,offline,on-device
10
+ Requires-Python: >=3.9
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: numpy
14
+ Requires-Dist: onnxruntime>=1.17
15
+ Requires-Dist: huggingface_hub
16
+ Provides-Extra: audio
17
+ Requires-Dist: soundfile; extra == "audio"
18
+ Requires-Dist: soxr; extra == "audio"
19
+ Dynamic: license-file
20
+
21
+ # shruti-onnx
22
+
23
+ Shruti: offline speech-to-text, one small model per language. Each model covers its language, English, and the two mixed. Models and full results: [udgamlabs/Shruti-ONNX](https://huggingface.co/udgamlabs/Shruti-ONNX).
24
+
25
+ Languages: Assamese, Bengali, Bodo, Dogri, Gujarati, Hindi, Kannada, Kashmiri, Konkani, Maithili, Malayalam, Manipuri, Marathi, Nepali, Odia, Punjabi, Sanskrit, Santali, Sindhi, Tamil, Telugu, Urdu. Use the word or the code.
26
+
27
+ ```bash
28
+ pip install shruti-onnx
29
+ ```
30
+
31
+ ```python
32
+ from shruti_onnx import Shruti
33
+
34
+ asr = Shruti.load("urdu") # or "ur"; variant="int8" for low memory on ARM
35
+ print(asr.transcribe("clip.wav")["text"]) # language detected; language="en" to set English
36
+ ```
37
+
38
+ Command line: `shruti-onnx clip.wav --lang urdu`. `loops="cut"` removes a repeat and what follows it.
39
+
40
+ ## Where it falls short
41
+
42
+ Nine of these languages (Dogri, Hindi, Kannada, Konkani, Odia, Punjabi, Sindhi, Tamil, Telugu) failed our written comparison against the original engine, and none met every rule. The model card names each miss and its size. On Linux x86, use the default 4-bit build: the int8 and sherpa-onnx builds were less accurate there on the machine we tested. A model can get stuck repeating a phrase; the text stays as the model wrote it unless you ask to cut it. The 4-bit build needs about 1 GB of memory once loaded in ONNX Runtime.
43
+
44
+ Apache-2.0. Built on [Cactus Whistle](https://huggingface.co/Cactus-Compute/whistle).
45
+
46
+ **About Udgam Labs.** Udgam Labs is an independent AI research lab. [udgamlabs.com](https://udgamlabs.com)
@@ -0,0 +1,26 @@
1
+ # shruti-onnx
2
+
3
+ Shruti: offline speech-to-text, one small model per language. Each model covers its language, English, and the two mixed. Models and full results: [udgamlabs/Shruti-ONNX](https://huggingface.co/udgamlabs/Shruti-ONNX).
4
+
5
+ Languages: Assamese, Bengali, Bodo, Dogri, Gujarati, Hindi, Kannada, Kashmiri, Konkani, Maithili, Malayalam, Manipuri, Marathi, Nepali, Odia, Punjabi, Sanskrit, Santali, Sindhi, Tamil, Telugu, Urdu. Use the word or the code.
6
+
7
+ ```bash
8
+ pip install shruti-onnx
9
+ ```
10
+
11
+ ```python
12
+ from shruti_onnx import Shruti
13
+
14
+ asr = Shruti.load("urdu") # or "ur"; variant="int8" for low memory on ARM
15
+ print(asr.transcribe("clip.wav")["text"]) # language detected; language="en" to set English
16
+ ```
17
+
18
+ Command line: `shruti-onnx clip.wav --lang urdu`. `loops="cut"` removes a repeat and what follows it.
19
+
20
+ ## Where it falls short
21
+
22
+ Nine of these languages (Dogri, Hindi, Kannada, Konkani, Odia, Punjabi, Sindhi, Tamil, Telugu) failed our written comparison against the original engine, and none met every rule. The model card names each miss and its size. On Linux x86, use the default 4-bit build: the int8 and sherpa-onnx builds were less accurate there on the machine we tested. A model can get stuck repeating a phrase; the text stays as the model wrote it unless you ask to cut it. The 4-bit build needs about 1 GB of memory once loaded in ONNX Runtime.
23
+
24
+ Apache-2.0. Built on [Cactus Whistle](https://huggingface.co/Cactus-Compute/whistle).
25
+
26
+ **About Udgam Labs.** Udgam Labs is an independent AI research lab. [udgamlabs.com](https://udgamlabs.com)
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "shruti-onnx"
7
+ version = "0.2.0"
8
+ description = "Shruti: offline speech-to-text, one language and English in one small model, in ONNX Runtime (32 MB)."
9
+ requires-python = ">=3.9"
10
+ license = "Apache-2.0"
11
+ readme = "README.md"
12
+ authors = [{ name = "Udgam Labs" }]
13
+ keywords = ["speech-recognition", "speech-to-text", "onnx", "offline", "on-device"]
14
+ dependencies = ["numpy", "onnxruntime>=1.17", "huggingface_hub"]
15
+
16
+ [project.optional-dependencies]
17
+ audio = ["soundfile", "soxr"]
18
+
19
+ [project.urls]
20
+ Homepage = "https://huggingface.co/udgamlabs/Shruti-ONNX"
21
+ Source = "https://github.com/udgamlabs/shruti"
22
+
23
+ [project.scripts]
24
+ shruti-onnx = "shruti_onnx:main"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,297 @@
1
+ """Shruti: offline speech-to-text, one language and English in one small model, in ONNX Runtime.
2
+
3
+ from shruti_onnx import Shruti
4
+ asr = Shruti.load("tamil") # a plain word or a code ("ta"); see LANGUAGES
5
+ print(asr.transcribe("clip.wav")["text"])
6
+
7
+ Shruti.load("ta", variant="int8") # low memory; the default is the 4-bit build, the smallest download
8
+ asr.transcribe(samples_16k, language="en") # None (the default) detects: the model's language or English
9
+
10
+ Decoding is 5-beam search with length-normalised scores, which reproduces the Cactus engine's transcripts. The
11
+ search is the same as the research runner udgam-voice/asr/onnx/shruti_onnx.py (tested equal in tests/).
12
+ """
13
+ import json
14
+ import os
15
+ import wave
16
+
17
+ import numpy as np
18
+ import onnxruntime as ort
19
+
20
+ __version__ = "0.2.0"
21
+ DEFAULT_REPO = "udgamlabs/Shruti-ONNX"
22
+ BASE_TAGS = ("en", "de", "fr", "es", "it", "nl", "pl") # Cactus Whistle's tags; a Shruti model adds its own language
23
+ VARIANTS = {"4bit": "onnx", "int8": "onnx-int8"}
24
+ _ALL_LANGUAGES = {"as": "Assamese", "bn": "Bengali", "brx": "Bodo", "doi": "Dogri", "gu": "Gujarati", "hi": "Hindi", "kn": "Kannada", "ks": "Kashmiri",
25
+ "kok": "Konkani", "mai": "Maithili", "ml": "Malayalam", "mni": "Manipuri", "mr": "Marathi", "ne": "Nepali", "or": "Odia", "pa": "Punjabi",
26
+ "sa": "Sanskrit", "sat": "Santali", "sd": "Sindhi", "ta": "Tamil", "te": "Telugu", "ur": "Urdu"}
27
+ RELEASED = ("as", "bn", "brx", "doi", "gu", "hi", "kn", "kok", "ks", "mai", "ml", "mni", "mr", "ne", "or", "pa", "sa", "sat", "sd", "ta", "te", "ur") # set by set_release.py
28
+ LANGUAGES = {c: _ALL_LANGUAGES[c] for c in RELEASED}
29
+ _ALIASES = {"bangla": "bn", "oriya": "or", "meitei": "mni", "meetei": "mni", "panjabi": "pa"}
30
+ LOOPS_DEFAULT = "off"
31
+ RATE = 16000
32
+
33
+
34
+ def language_code(name):
35
+ """"urdu", "Urdu" or "ur" -> "ur". Raises ValueError listing the languages."""
36
+ key = str(name).strip().lower()
37
+ if key in _ALL_LANGUAGES:
38
+ return key
39
+ for code, word in _ALL_LANGUAGES.items():
40
+ if key == word.lower():
41
+ return code
42
+ if key in _ALIASES:
43
+ return _ALIASES[key]
44
+ raise ValueError(f"unknown language {name!r}; choose one of: " + ", ".join(f"{w} ({c})" for c, w in sorted(LANGUAGES.items(), key=lambda x: x[1])))
45
+
46
+
47
+ def read_audio(path):
48
+ """16 kHz mono float32 samples from a file: soundfile when installed, else 16/24/32-bit PCM WAV via the standard
49
+ library. Other sample rates are resampled (soxr when installed, else linear interpolation)."""
50
+ try:
51
+ import soundfile as sf
52
+ x, rate = sf.read(path, dtype="float32", always_2d=True)
53
+ x = x.mean(1)
54
+ except ImportError:
55
+ with wave.open(path, "rb") as w:
56
+ ch, width, rate, n = w.getnchannels(), w.getsampwidth(), w.getframerate(), w.getnframes()
57
+ raw = w.readframes(n)
58
+ if width == 3:
59
+ b = np.frombuffer(raw, np.uint8).reshape(-1, 3)
60
+ x = (b[:, 0].astype(np.int32) | (b[:, 1].astype(np.int32) << 8) | (b[:, 2].astype(np.int8).astype(np.int32) << 16))
61
+ x = x / 8388608.0
62
+ else:
63
+ x = np.frombuffer(raw, {1: np.uint8, 2: np.int16, 4: np.int32}[width]).astype(np.float64)
64
+ x = (x - 128) / 128.0 if width == 1 else x / float(2 ** (8 * width - 1))
65
+ x = x.reshape(-1, ch).mean(1).astype(np.float32)
66
+ return resample(x, rate)
67
+
68
+
69
+ def resample(x, rate):
70
+ if rate == RATE:
71
+ return np.asarray(x, np.float32)
72
+ try:
73
+ import soxr
74
+ return soxr.resample(x, rate, RATE).astype(np.float32)
75
+ except ImportError:
76
+ n = int(round(len(x) * RATE / rate))
77
+ return np.interp(np.arange(n) * rate / RATE, np.arange(len(x)), x).astype(np.float32)
78
+
79
+
80
+ class Shruti:
81
+ """Runs the three graphs: frontend (audio -> features), encoder (features -> audio memory), decoder (one token
82
+ at a time, with its state carried between calls)."""
83
+
84
+ def __init__(self, folder, threads=2):
85
+ so = ort.SessionOptions()
86
+ so.intra_op_num_threads = threads
87
+ so.inter_op_num_threads = 1
88
+ load = lambda f: ort.InferenceSession(os.path.join(folder, f), so, providers=["CPUExecutionProvider"]) # noqa
89
+ self.frontend, self.encoder, self.decoder = load("frontend.onnx"), load("encoder.onnx"), load("decoder.onnx")
90
+ meta = json.load(open(os.path.join(folder, "shruti.json"), encoding="utf-8"))
91
+ self.vocab, self.cfg = meta["vocab"], meta["config"]
92
+ self.text, self.bos, self.eos = self.cfg["text"], self.cfg["bos"], self.cfg["eos"]
93
+ self.tags = {lang: self.text + i for i, lang in enumerate(self.cfg["languages"])}
94
+ own = [x for x in self.cfg["languages"] if x not in BASE_TAGS]
95
+ self.languages = (own[0], "en") # the model's own language and English: what it was trained on
96
+ self.state_names = [i.name for i in self.decoder.get_inputs()][2:]
97
+ shapes = {i.name: i.shape for i in self.decoder.get_inputs()}
98
+ self.state_shapes = {n: [d if isinstance(d, int) else 0 for d in shapes[n]] for n in self.state_names}
99
+
100
+ @classmethod
101
+ def load(cls, language, variant="4bit", model=DEFAULT_REPO, threads=2):
102
+ """language: a plain word or a code ("urdu" or "ur"); see LANGUAGES.
103
+ variant: "4bit" (32 MB, the smallest download) or "int8" (53 MB, about 120 MB of memory instead of about 1 GB).
104
+ model: a Hugging Face repo id, or a local folder holding <code>/onnx/ and <code>/onnx-int8/."""
105
+ code = language_code(language)
106
+ if code not in LANGUAGES and not os.path.isdir(model):
107
+ raise ValueError(f"{_ALL_LANGUAGES[code]} is not in this release; choose one of: " + ", ".join(f"{w} ({c})" for c, w in sorted(LANGUAGES.items(), key=lambda x: x[1])))
108
+ if variant not in VARIANTS:
109
+ raise ValueError(f"variant must be one of {list(VARIANTS)}, not {variant!r}")
110
+ rel = f"{code}/{VARIANTS[variant]}"
111
+ if os.path.isdir(model):
112
+ path = model
113
+ else:
114
+ from huggingface_hub import snapshot_download
115
+ path = snapshot_download(model, allow_patterns=[f"{rel}/*"])
116
+ if not os.path.isdir(os.path.join(path, rel)):
117
+ raise FileNotFoundError(f"no {rel} folder in {model}: this language is not in this release; see its table of languages")
118
+ asr = cls(os.path.join(path, rel), threads)
119
+ if asr.languages[0] != code:
120
+ raise ValueError(f"{rel} holds a {asr.languages[0]!r} model, not {code!r}")
121
+ return asr
122
+
123
+ def detok(self, ids):
124
+ """Pieces to text (sentencepiece rules: a leading ▁ is a space, <0xNN> pieces are raw UTF-8 bytes)."""
125
+ out, raw = [], bytearray()
126
+ for i in ids:
127
+ p = self.vocab[i]
128
+ if len(p) == 6 and p.startswith("<0x") and p.endswith(">"):
129
+ raw.append(int(p[3:5], 16))
130
+ continue
131
+ if raw:
132
+ out.append(raw.decode("utf-8", "ignore"))
133
+ raw.clear()
134
+ if not (p.startswith("<") and p.endswith(">")):
135
+ out.append(p)
136
+ if raw:
137
+ out.append(raw.decode("utf-8", "ignore"))
138
+ return "".join(out).replace("▁", " ").strip()
139
+
140
+ def init_state(self, B):
141
+ st = {}
142
+ for n in self.state_names:
143
+ shp = list(self.state_shapes[n])
144
+ if n == "pos":
145
+ st[n] = np.zeros(1, np.int64)
146
+ continue
147
+ shp[0] = B
148
+ st[n] = np.zeros(shp, np.int64 if n == "hist" else np.float32)
149
+ return st
150
+
151
+ def step(self, tokens, cross, st):
152
+ r = self.decoder.run(None, {"tokens": tokens, "cross": cross, **st})
153
+ return r[0][:, 0], dict(zip(self.state_names, r[1:]))
154
+
155
+ def encode(self, wav):
156
+ feats = self.frontend.run(None, {"audio": wav[None].astype(np.float32)})[0]
157
+ n = np.array([len(wav) // self.cfg["hop"]], np.int64)
158
+ return self.encoder.run(None, {"features": feats, "frames": n})[0]
159
+
160
+ @staticmethod
161
+ def logsoftmax(x):
162
+ x = x - x.max(-1, keepdims=True)
163
+ return x - np.log(np.exp(x).sum(-1, keepdims=True))
164
+
165
+ def transcribe(self, audio, language=None, beams=5, numbers="words", window_s=30.0, length_norm=True,
166
+ tok_per_s=12.0, loops=LOOPS_DEFAULT):
167
+ """audio: a file path, or 16 kHz mono float32 samples in [-1, 1].
168
+ language: None detects between the model's own language and English; or name either one ("tamil", "ta", "english", "en").
169
+ beams: 5 (the engine's search) or 1 (greedy, faster).
170
+ numbers: "words" (as spoken: "ढाई सौ रुपये") or "digits" ("₹250"; Hindi model only, needs the
171
+ udgam_textnorm normaliser, not on PyPI yet).
172
+ loops: "off" keeps the model's output as it is; "cut" keeps the first copy of a repeated pattern and drops
173
+ everything after it.
174
+ Up to 30 s is one pass; longer audio is cut into equal windows of at most 30 s.
175
+ -> {"text", "language", "tokens"}"""
176
+ if language is not None:
177
+ language = "en" if str(language).strip().lower() in ("en", "english") else language_code(language)
178
+ if language not in self.languages:
179
+ raise ValueError(f"this is the {LANGUAGES[self.languages[0]]} model: language must be {self.languages[0]!r}, 'en' or None to detect, not {language!r}")
180
+ if numbers == "digits" and self.languages[0] != "hi":
181
+ raise ValueError('numbers="digits" is tested for the Hindi model only')
182
+ if loops not in ("off", "cut"):
183
+ raise ValueError('loops must be "off" or "cut"')
184
+ wav = read_audio(audio) if isinstance(audio, (str, os.PathLike)) else np.asarray(audio, np.float32)
185
+ if len(wav) == 0 or np.abs(wav).max() < 1e-4: # digital silence -> empty, as the Cactus engine returns
186
+ return {"text": "", "language": language, "tokens": []}
187
+ n = max(1, int(np.ceil(len(wav) / (window_s * RATE))))
188
+ parts = [self._transcribe(w, language, beams, tok_per_s, length_norm, loops) for w in np.array_split(wav, n)]
189
+ text = " ".join(p["text"] for p in parts if p["text"])
190
+ lang = parts[0]["language"]
191
+ if numbers == "digits":
192
+ try:
193
+ from udgam_textnorm import denormalize
194
+ except ImportError as e:
195
+ raise ImportError('numbers="digits" needs the udgam_textnorm number normaliser, which is not on PyPI yet') from e
196
+ text = denormalize(text, lang, style="digits")
197
+ elif numbers != "words":
198
+ raise ValueError('numbers must be "words" or "digits"')
199
+ return {"text": text, "language": lang, "tokens": [t for p in parts for t in p["tokens"]]}
200
+
201
+ @staticmethod
202
+ def cut_loops(ids, max_period=8, repeats=3):
203
+ """Cut a token loop (a pattern of up to 8 tokens repeated 3+ times back to back): keep its first copy."""
204
+ n = len(ids)
205
+ for start in range(n):
206
+ for k in range(1, max_period + 1):
207
+ if start + k * repeats > n:
208
+ break
209
+ pat = ids[start:start + k]
210
+ if all(ids[start + r * k:start + (r + 1) * k] == pat for r in range(1, repeats)):
211
+ return ids[:start + k]
212
+ return ids
213
+
214
+ def _transcribe(self, wav, language, beams, tok_per_s, length_norm, loops):
215
+ tidy = self.cut_loops if loops == "cut" else (lambda ids: ids)
216
+ cross = self.encode(wav)
217
+ cap = int(min(self.cfg["max_tokens"] - 2, len(wav) / RATE * tok_per_s + 8))
218
+ st = self.init_state(1)
219
+ if language is None:
220
+ lg, st = self.step(np.array([[self.bos]], np.int64), cross, st)
221
+ language = max(self.languages, key=lambda lang: lg[0, self.tags[lang]])
222
+ lg, st = self.step(np.array([[self.tags[language]]], np.int64), cross, st)
223
+ else:
224
+ lg, st = self.step(np.array([[self.bos, self.tags[language]]], np.int64), cross, st)
225
+ lg[:, self.text:] = -np.inf
226
+ if beams <= 1:
227
+ ids = []
228
+ for _ in range(cap):
229
+ k = int(lg[0].argmax())
230
+ if k == self.eos:
231
+ break
232
+ ids.append(k)
233
+ lg, st = self.step(np.array([[k]], np.int64), cross, st)
234
+ lg[:, self.text:] = -np.inf
235
+ ids = tidy(ids)
236
+ return {"text": self.detok(ids), "language": language, "tokens": ids}
237
+ norm = (lambda sc, s: sc / (len(s) + 1)) if length_norm else (lambda sc, s: sc)
238
+ lp = self.logsoftmax(lg[0])
239
+ first = np.argsort(-lp)[:beams]
240
+ seqs = [[int(k)] for k in first]
241
+ scores = lp[first].astype(np.float64)
242
+ finished = [(scores[i], s[:-1]) for i, s in enumerate(seqs) if s[-1] == self.eos]
243
+ live = [i for i, s in enumerate(seqs) if s[-1] != self.eos]
244
+ seqs, scores = [seqs[i] for i in live], scores[live]
245
+ st = {n: (v if n == "pos" else np.repeat(v, len(seqs), 0)) for n, v in st.items()}
246
+ for _ in range(cap - 1):
247
+ if not seqs:
248
+ break
249
+ lg, st = self.step(np.array([[s[-1]] for s in seqs], np.int64), cross, st)
250
+ lg[:, self.text:] = -np.inf
251
+ cand = scores[:, None] + self.logsoftmax(lg)
252
+ new_seqs, new_scores, src = [], [], []
253
+ for flat in np.argsort(-cand, axis=None)[: 2 * beams]:
254
+ b, k = divmod(int(flat), cand.shape[1])
255
+ if k == self.eos:
256
+ finished.append((cand[b, k], seqs[b]))
257
+ else:
258
+ new_seqs.append(seqs[b] + [k])
259
+ new_scores.append(cand[b, k])
260
+ src.append(b)
261
+ if len(new_seqs) == beams:
262
+ break
263
+ best_done = max((norm(sc, s) for sc, s in finished), default=-np.inf)
264
+ if len(finished) >= beams and (not new_scores or
265
+ max(norm(sc, s) for sc, s in zip(new_scores, new_seqs)) < best_done):
266
+ break
267
+ seqs, scores = new_seqs, np.array(new_scores)
268
+ st = {n: (v if n == "pos" else v[src]) for n, v in st.items()}
269
+ if not finished:
270
+ finished = list(zip(scores, seqs))
271
+ best = tidy(max(finished, key=lambda f: norm(*f))[1])
272
+ return {"text": self.detok(best), "language": language, "tokens": best}
273
+
274
+
275
+ def main(argv=None):
276
+ import argparse
277
+ p = argparse.ArgumentParser(prog="shruti-onnx", description="Offline speech-to-text: one language and English in one small model.")
278
+ p.add_argument("audio", nargs="+", help="audio files (WAV; other formats with `pip install soundfile`)")
279
+ p.add_argument("--lang", required=True, help="which model: a plain word or a code, e.g. tamil or ta")
280
+ p.add_argument("--int8", action="store_true", help="the low-memory build (53 MB download, ~120 MB of memory)")
281
+ p.add_argument("--model", default=DEFAULT_REPO, help="Hugging Face repo id or local folder")
282
+ p.add_argument("--force-language", help="skip detection: the model's own language or en")
283
+ p.add_argument("--numbers", choices=["words", "digits"], default="words")
284
+ p.add_argument("--greedy", action="store_true", help="faster, slightly less accurate")
285
+ p.add_argument("--threads", type=int, default=2)
286
+ a = p.parse_args(argv)
287
+ try:
288
+ asr = Shruti.load(a.lang, "int8" if a.int8 else "4bit", a.model, a.threads)
289
+ except ValueError as e:
290
+ p.error(str(e))
291
+ for f in a.audio:
292
+ r = asr.transcribe(f, language=a.force_language, beams=1 if a.greedy else 5, numbers=a.numbers)
293
+ print(f"{f}\t{r['language']}\t{r['text']}")
294
+
295
+
296
+ if __name__ == "__main__":
297
+ main()
@@ -0,0 +1,3 @@
1
+ from . import main
2
+
3
+ main()
@@ -0,0 +1,46 @@
1
+ Metadata-Version: 2.4
2
+ Name: shruti-onnx
3
+ Version: 0.2.0
4
+ Summary: Shruti: offline speech-to-text, one language and English in one small model, in ONNX Runtime (32 MB).
5
+ Author: Udgam Labs
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://huggingface.co/udgamlabs/Shruti-ONNX
8
+ Project-URL: Source, https://github.com/udgamlabs/shruti
9
+ Keywords: speech-recognition,speech-to-text,onnx,offline,on-device
10
+ Requires-Python: >=3.9
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: numpy
14
+ Requires-Dist: onnxruntime>=1.17
15
+ Requires-Dist: huggingface_hub
16
+ Provides-Extra: audio
17
+ Requires-Dist: soundfile; extra == "audio"
18
+ Requires-Dist: soxr; extra == "audio"
19
+ Dynamic: license-file
20
+
21
+ # shruti-onnx
22
+
23
+ Shruti: offline speech-to-text, one small model per language. Each model covers its language, English, and the two mixed. Models and full results: [udgamlabs/Shruti-ONNX](https://huggingface.co/udgamlabs/Shruti-ONNX).
24
+
25
+ Languages: Assamese, Bengali, Bodo, Dogri, Gujarati, Hindi, Kannada, Kashmiri, Konkani, Maithili, Malayalam, Manipuri, Marathi, Nepali, Odia, Punjabi, Sanskrit, Santali, Sindhi, Tamil, Telugu, Urdu. Use the word or the code.
26
+
27
+ ```bash
28
+ pip install shruti-onnx
29
+ ```
30
+
31
+ ```python
32
+ from shruti_onnx import Shruti
33
+
34
+ asr = Shruti.load("urdu") # or "ur"; variant="int8" for low memory on ARM
35
+ print(asr.transcribe("clip.wav")["text"]) # language detected; language="en" to set English
36
+ ```
37
+
38
+ Command line: `shruti-onnx clip.wav --lang urdu`. `loops="cut"` removes a repeat and what follows it.
39
+
40
+ ## Where it falls short
41
+
42
+ Nine of these languages (Dogri, Hindi, Kannada, Konkani, Odia, Punjabi, Sindhi, Tamil, Telugu) failed our written comparison against the original engine, and none met every rule. The model card names each miss and its size. On Linux x86, use the default 4-bit build: the int8 and sherpa-onnx builds were less accurate there on the machine we tested. A model can get stuck repeating a phrase; the text stays as the model wrote it unless you ask to cut it. The 4-bit build needs about 1 GB of memory once loaded in ONNX Runtime.
43
+
44
+ Apache-2.0. Built on [Cactus Whistle](https://huggingface.co/Cactus-Compute/whistle).
45
+
46
+ **About Udgam Labs.** Udgam Labs is an independent AI research lab. [udgamlabs.com](https://udgamlabs.com)
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ shruti_onnx/__init__.py
5
+ shruti_onnx/__main__.py
6
+ shruti_onnx.egg-info/PKG-INFO
7
+ shruti_onnx.egg-info/SOURCES.txt
8
+ shruti_onnx.egg-info/dependency_links.txt
9
+ shruti_onnx.egg-info/entry_points.txt
10
+ shruti_onnx.egg-info/requires.txt
11
+ shruti_onnx.egg-info/top_level.txt
12
+ tests/test_same_as_research_runner.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ shruti-onnx = shruti_onnx:main
@@ -0,0 +1,7 @@
1
+ numpy
2
+ onnxruntime>=1.17
3
+ huggingface_hub
4
+
5
+ [audio]
6
+ soundfile
7
+ soxr
@@ -0,0 +1 @@
1
+ shruti_onnx
@@ -0,0 +1,36 @@
1
+ """The package must transcribe exactly like the Gate 0 research runner (udgam-voice/asr/onnx/shruti_onnx.py), with
2
+ its frozen decoder settings (beam 5, length-normalised), on the phone-test clips; plus file reading and digits.
3
+ Run (onnx venv): python tests/test_same_as_research_runner.py <model_dir> [n_clips]"""
4
+ import importlib.util
5
+ import os
6
+ import sys
7
+
8
+ import soundfile as sf
9
+
10
+ HERE = os.path.dirname(os.path.abspath(__file__))
11
+ TRAIN = os.path.abspath(os.path.join(HERE, "../../../.."))
12
+ sys.path.insert(0, os.path.join(HERE, ".."))
13
+ from shruti_onnx import Shruti # noqa: E402
14
+
15
+ spec = importlib.util.spec_from_file_location("research", os.path.join(TRAIN, "udgam-voice/asr/onnx/shruti_onnx.py"))
16
+ research = importlib.util.module_from_spec(spec)
17
+ spec.loader.exec_module(research)
18
+
19
+ model, n = sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 20
20
+ pkg, ref = Shruti(model), research.Shruti(model, threads=2)
21
+ clips = os.path.join(TRAIN, "udgam-voice/asr/work/phone_test/clips")
22
+ same = 0
23
+ names = sorted(os.listdir(clips))[:n]
24
+ for c in names:
25
+ path = os.path.join(clips, c)
26
+ w, _ = sf.read(path, dtype="float32")
27
+ a = pkg.transcribe(path)["text"] # from the file, language detected
28
+ b = ref.transcribe(w, language=None, beams=5, length_norm=True)["text"]
29
+ same += a == b
30
+ if a != b:
31
+ print("DIFF", c, "\n pkg:", a, "\n ref:", b)
32
+ print(f"package == research runner on {same}/{len(names)} clips")
33
+ sys.path.insert(0, os.path.join(TRAIN, "textnorm/v1/python"))
34
+ r = pkg.transcribe(os.path.join(clips, "fl08.wav"), numbers="digits")
35
+ print("digits:", r["language"], r["text"])
36
+ assert same == len(names)