├── .github ├── FUNDING.yml └── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── custom.md │ ├── feature_request.md │ └── new_feature.md ├── .gitignore ├── LICENSE ├── README.md ├── README.md.meta ├── Runtime.meta ├── Runtime ├── ASR.meta ├── ASR │ ├── ContinuousSpeechRecognition.cs │ └── ContinuousSpeechRecognition.cs.meta ├── DeepSpeechClient.meta ├── DeepSpeechClient │ ├── DeepSpeech.cs │ ├── DeepSpeech.cs.meta │ ├── Enums.meta │ ├── Enums │ │ ├── ErrorCodes.cs │ │ └── ErrorCodes.cs.meta │ ├── Extensions.meta │ ├── Extensions │ │ ├── NativeExtensions.cs │ │ └── NativeExtensions.cs.meta │ ├── Interfaces.meta │ ├── Interfaces │ │ ├── IDeepSpeech.cs │ │ └── IDeepSpeech.cs.meta │ ├── LICENSE │ ├── Models.meta │ ├── Models │ │ ├── CandidateTranscript.cs │ │ ├── CandidateTranscript.cs.meta │ │ ├── DeepSpeechStream.cs │ │ ├── DeepSpeechStream.cs.meta │ │ ├── Metadata.cs │ │ ├── Metadata.cs.meta │ │ ├── TokenMetadata.cs │ │ └── TokenMetadata.cs.meta │ ├── NativeImp.cs │ ├── NativeImp.cs.meta │ ├── Structs.meta │ ├── Structs │ │ ├── CandidateTranscript.cs │ │ ├── CandidateTranscript.cs.meta │ │ ├── Metadata.cs │ │ ├── Metadata.cs.meta │ │ ├── TokenMetadata.cs │ │ └── TokenMetadata.cs.meta │ ├── VX.Speech.DeepSpeechClient.asmdef │ └── VX.Speech.DeepSpeechClient.asmdef.meta ├── VX.Speech.Runtime.asmdef └── VX.Speech.Runtime.asmdef.meta ├── Tests.meta ├── Tests ├── Editor.meta └── Runtime.meta ├── package.json ├── package.json.meta ├── ~Samples.meta └── ~Samples └── SpeechExample.meta /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: voxelltech 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: ["paypal.me/voxelltechnologies"] 13 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Custom issue template 3 | about: Describe this issue template's purpose here. 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 11 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/new_feature.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: New Feature 3 | about: Creating a new feature for this project. 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Summary** 11 | 12 | A quick intro or summary on the feature you want to create. 13 | 14 | **Intended Outcome** 15 | 16 | - What is the use case of this? 17 | - How will it affect/benefit the project? 18 | 19 | **How will it work?** 20 | 21 | - How to use this feature? 22 | 23 | *finally, please assign yourself to this issue if you intend to work on this new feature thanks!* 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ 2 | __pycache__/ 3 | checkpoints/ 4 | inference/ 5 | env/ 6 | temp/ 7 | 8 | # This .gitignore file should be placed at the root of your Unity project directory 9 | # 10 | # Get latest from https://github.com/github/gitignore/blob/master/Unity.gitignore 11 | # 12 | /[Ll]ibrary/ 13 | /[Tt]emp/ 14 | /[Oo]bj/ 15 | /[Bb]uild/ 16 | /[Bb]uilds/ 17 | /[Ll]ogs/ 18 | /[Uu]ser[Ss]ettings/ 19 | /[Rr]ecordings/ 20 | /[Rr]eleases/ 21 | /[Rr]elease/ 22 | 23 | 24 | # MemoryCaptures can get excessive in size. 25 | # They also could contain extremely sensitive data 26 | /[Mm]emoryCaptures/ 27 | 28 | # Asset meta data should only be ignored when the corresponding asset is also ignored 29 | !/[Aa]ssets/**/*.meta 30 | 31 | # Uncomment this line if you wish to ignore the asset store tools plugin 32 | # /[Aa]ssets/AssetStoreTools* 33 | 34 | # Autogenerated Jetbrains Rider plugin 35 | /[Aa]ssets/Plugins/Editor/JetBrains* 36 | 37 | # Visual Studio cache directory 38 | .vs/ 39 | 40 | # Gradle cache directory 41 | .gradle/ 42 | 43 | # Autogenerated VS/MD/Consulo solution and project files 44 | ExportedObj/ 45 | .consulo/ 46 | *.csproj 47 | *.unityproj 48 | *.sln 49 | *.suo 50 | *.tmp 51 | *.user 52 | *.userprefs 53 | *.pidb 54 | *.booproj 55 | *.svd 56 | *.pdb 57 | *.mdb 58 | *.opendb 59 | *.VC.db 60 | 61 | # Unity3D generated meta files 62 | *.pidb.meta 63 | *.pdb.meta 64 | *.mdb.meta 65 | 66 | # Unity3D generated file on crash reports 67 | sysinfo.txt 68 | 69 | # Builds 70 | *.apk 71 | *.aab 72 | *.unitypackage 73 | *.unitypackage.meta 74 | *.exe 75 | 76 | # Crashlytics generated file 77 | crashlytics-build.properties 78 | 79 | # Packed Addressables 80 | /[Aa]ssets/[Aa]ddressable[Aa]ssets[Dd]ata/*/*.bin* 81 | 82 | # Temporary auto-generated Android Assets 83 | /[Aa]ssets/[Ss]treamingAssets/aa.meta 84 | /[Aa]ssets/[Ss]treamingAssets/aa/* 85 | 86 | # Tensorflow trained checkpoints and weights 87 | *.h5 88 | *.h5.meta 89 | *.pbmm 90 | *.pbmm.meta 91 | *.tflite 92 | *.tflite.meta 93 | 94 | # API keys 95 | *.apikey 96 | 97 | # pycaches 98 | *.pyc 99 | 100 | # audio files 101 | AudioClips/ 102 | *.mp3 103 | *.wav 104 | *.audio 105 | 106 | # license 107 | LICENSE.meta 108 | 109 | # large libraries 110 | native/ 111 | tensorflow.dll 112 | tensorflow.dll.meta -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 Voxell Technologies 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Unity Automatic Speech Recognition 2 | 3 | > Discalimer: Currently, the AutomaticSpeechRecognition.cs script is not working as intended. For some reasons, it couldn't recognize a single word I say. Please make a pull request if you figured out how to solve this issue! 4 | 5 | ## What does this package contatins?? 6 | 7 | This package provides a fully functional cross platform Automatic Speech Recognition using deep learning models intergrated in Unity with C#!!! Anyone can use this package in any way they want as long as they credit the author(s) and also respect the [license](LICENSE) agreement. 8 | 9 | ### DeepSpeech 10 | 11 | [DeepSpeech](https://github.com/mozilla/DeepSpeech) is used as the backend of this package. In order to use DeepSpeech, the source code had to be copied manually as there are some unwanted stuffs in the DLL package. 12 | 13 | ## Installation 14 | 15 | This package depends on: 16 | - [UnityUtil](https://github.com/voxell-tech/UnityUtil) 17 | 18 | 1. Clone the [UnityUtil](https://github.com/voxell-tech/UnityUtil) repository into your project's `Packages` folder. 19 | 2. Download the unitypackage dependencies from [Google Drive](https://drive.google.com/drive/u/5/folders/1WOaWVwdCD9p0oq7S3atoJfLt9V0HND1u) and extract it into Unity. 20 | 3. Clone this repository into your project's Packages folder. 21 | 4. In Unity, go into `native/DeepSpeechClient`, you can choose either CPU or GPU version of DeepSpeech, GPU version is way faster than CPU inferencing. 22 | 5. And you are ready to go! 23 | 24 | ## Support the project! 25 | 26 | 27 | patreon 28 | 29 | 30 | 31 | kofi 32 | 33 | 34 | ## Join the community! 35 | 36 | 37 | discord 38 | 39 | 40 | 41 | ## License 42 | 43 | This repository as a whole is licensed under the GNU Public License, Version 3. Individual files may have a different, but compatible license. 44 | 45 | See [license file](./LICENSE) for details. -------------------------------------------------------------------------------- /README.md.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 2866cceb4931b584ca9b303113dfa764 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Runtime.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 7ee71cd2fab5dc1409e8529bfcf8fb84 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Runtime/ASR.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: f4320df74c29ef047a8728368fb8bfba 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Runtime/ASR/ContinuousSpeechRecognition.cs: -------------------------------------------------------------------------------- 1 | // code belongs to https://github.com/Babilinski/deep-speech-unity 2 | 3 | using UnityEngine; 4 | using System; 5 | using System.Collections.Concurrent; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using DeepSpeechClient; 9 | using DeepSpeechClient.Interfaces; 10 | using DeepSpeechClient.Models; 11 | using Voxell; 12 | using Voxell.Inspector; 13 | 14 | public class ContinuousSpeechRecognition : MonoBehaviour 15 | { 16 | [SerializeField] public KeyCode pushToTalkKey = KeyCode.Space; 17 | 18 | [SerializeField] public bool autoDetectVoice = false; 19 | 20 | [Header("DeepSpeech")] 21 | [StreamingAssetFilePath] public string modelPath; 22 | [StreamingAssetFilePath] public string externalScorerPath; 23 | [InspectOnly] public string resultText; 24 | 25 | [Header("Voice Detection Settings")] 26 | [SerializeField, Tooltip("Time in seconds of detected silence before voice request is sent")] 27 | protected float _silenceTimer = 1.0f; 28 | 29 | [SerializeField, Tooltip("The minimum volume to detect voice input for"), Range(0.0f, 1.0f)] 30 | protected float _minimumSpeakingSampleValue = 0.5f; 31 | 32 | // Audio Detection 33 | private float _timeAtSilenceBegan; 34 | private bool _audioDetected; 35 | private bool _clearData; 36 | private float[] _lastBuffer; 37 | 38 | // Audio Stuff 39 | [InspectOnly] public AudioClip _clip = null; 40 | private string _device = null; 41 | 42 | // Conditions 43 | private bool transmitToggled = false; 44 | private bool _recording = false; 45 | 46 | // Sampling 47 | private int _previousPosition = 0; 48 | private int _sampleIndex = 0; 49 | private int _recordFrequency = 0; 50 | private int _recordSampleSize = 0; 51 | private int _targetFrequency = 0; 52 | private int _targetSampleSize = 0; 53 | private float[] _sampleBuffer = null; 54 | private int _frequency; 55 | private int _sampleSize; 56 | 57 | // Deep Speech 58 | private IDeepSpeech _sttClient; 59 | 60 | /// 61 | /// Stream used to feed data into the acoustic model. 62 | /// 63 | private DeepSpeechStream _sttStream; 64 | 65 | // Threading 66 | private bool _hasStream; 67 | private readonly ConcurrentQueue _threadedBufferQueue = new ConcurrentQueue(); 68 | private int _threadSafeBoolBackValue = 0; 69 | 70 | public bool StreamingIsBusy 71 | { 72 | get => (Interlocked.CompareExchange(ref _threadSafeBoolBackValue, 1, 1) == 1); 73 | set 74 | { 75 | if (value) Interlocked.CompareExchange(ref _threadSafeBoolBackValue, 1, 0); 76 | else Interlocked.CompareExchange(ref _threadSafeBoolBackValue, 0, 1); 77 | } 78 | } 79 | 80 | private void Start() 81 | { 82 | _sttClient = new DeepSpeech(FileUtilx.GetStreamingAssetFilePath(modelPath)); 83 | _sttClient.EnableExternalScorer(FileUtilx.GetStreamingAssetFilePath(externalScorerPath)); 84 | // If you want to add bias to a word. Only supports single words. 85 | //_sttClient.AddHotWord("select",20.0f); 86 | 87 | // You can also add a negative value 88 | //_sttClient.AddHotWord("cue",-250.0f); 89 | 90 | _frequency = _sttClient.GetModelSampleRate(); 91 | _sampleSize = _frequency / 2; 92 | 93 | StartRecording(); 94 | } 95 | private void FixedUpdate() 96 | { 97 | if (!_recording) 98 | { 99 | return; 100 | } 101 | 102 | bool transmit = transmitToggled || Input.GetKey(pushToTalkKey); 103 | int currentPosition = Microphone.GetPosition(_device); 104 | 105 | // This means we wrapped around 106 | if (currentPosition < _previousPosition) 107 | { 108 | while (_sampleIndex < _recordFrequency) 109 | { 110 | ReadSample(transmit); 111 | } 112 | 113 | _sampleIndex = 0; 114 | } 115 | 116 | // Read non-wrapped samples 117 | _previousPosition = currentPosition; 118 | 119 | while (_sampleIndex + _recordSampleSize <= currentPosition) 120 | { 121 | ReadSample(transmit); 122 | } 123 | } 124 | 125 | void Resample(float[] src, float[] dst) 126 | { 127 | if (src.Length == dst.Length) 128 | { 129 | Array.Copy(src, 0, dst, 0, src.Length); 130 | } 131 | else 132 | { 133 | //TODO: Low-pass filter 134 | float rec = 1.0f / (float) dst.Length; 135 | 136 | for (int i = 0; i < dst.Length; ++i) 137 | { 138 | float interp = rec * (float) i * (float) src.Length; 139 | dst[i] = src[(int) interp]; 140 | } 141 | } 142 | } 143 | 144 | void ReadSample(bool transmit) 145 | { 146 | // Extract data 147 | _clip.GetData(_sampleBuffer, _sampleIndex); 148 | // Grab a new sample buffer 149 | float[] targetSampleBuffer = new float[_sampleSize]; 150 | 151 | // Resample our real sample into the buffer 152 | Resample(_sampleBuffer, targetSampleBuffer); 153 | 154 | 155 | // Forward index 156 | _sampleIndex += _recordSampleSize; 157 | 158 | // Auto detect speech, but no need to do if we're pushing a key to transmit 159 | if (autoDetectVoice && !transmit) 160 | { 161 | // Determine if the microphone noise levels have been loud enough 162 | float maxVolume = 0.0f; 163 | for (int i = 0; i < _sampleBuffer.Length; i++) 164 | { 165 | if (_sampleBuffer[i] > maxVolume) 166 | { 167 | maxVolume = _sampleBuffer[i]; 168 | } 169 | } 170 | 171 | if (maxVolume >= _minimumSpeakingSampleValue) 172 | { 173 | transmit = true; 174 | _audioDetected = true; 175 | _clearData = false; 176 | } 177 | else 178 | { 179 | if (_audioDetected == true) // User first stopped talking after talking 180 | { 181 | _timeAtSilenceBegan = Time.time; 182 | _audioDetected = false; 183 | } 184 | else 185 | { 186 | if (Time.time - _timeAtSilenceBegan > _silenceTimer) 187 | { 188 | _audioDetected = false; 189 | _clearData = true; 190 | } 191 | else 192 | { 193 | transmit = true; 194 | } 195 | } 196 | } 197 | } 198 | 199 | // If we have an event, and 200 | if (transmit && !_clearData) 201 | { 202 | if (_hasStream == false) 203 | { 204 | _sttStream = _sttClient.CreateStream(); 205 | _hasStream = true; 206 | } 207 | 208 | if (_lastBuffer != null) 209 | { 210 | float[] longArray = new float[_lastBuffer.Length + targetSampleBuffer.Length]; 211 | Array.Copy(_lastBuffer, longArray, _lastBuffer.Length); 212 | Array.Copy(targetSampleBuffer, 0, longArray, _lastBuffer.Length, targetSampleBuffer.Length); 213 | TransmitBuffer(longArray); 214 | _lastBuffer = null; 215 | } 216 | else 217 | { 218 | TransmitBuffer(targetSampleBuffer); 219 | } 220 | } 221 | else if (_clearData || !autoDetectVoice) 222 | { 223 | if (_hasStream && StreamingIsBusy == false) 224 | { 225 | _hasStream = false; 226 | _sttClient.FreeStream(_sttStream); 227 | _lastBuffer = targetSampleBuffer; 228 | } 229 | } 230 | } 231 | 232 | void TransmitBuffer(float[] buffer) 233 | { 234 | short[] sampleShorts = AudioFloatToInt16(buffer); 235 | _threadedBufferQueue.Enqueue(sampleShorts); 236 | if (StreamingIsBusy == false) 237 | { 238 | Task.Run(ThreadedWork).ConfigureAwait(false); 239 | } 240 | } 241 | 242 | private async void ThreadedWork() 243 | { 244 | StreamingIsBusy = true; 245 | while (_threadedBufferQueue.Count > 0) 246 | { 247 | if (_threadedBufferQueue.TryDequeue(out short[] voiceResult)) 248 | { 249 | _sttClient.FeedAudioContent(_sttStream, voiceResult, Convert.ToUInt32(voiceResult.Length)); 250 | string output = _sttClient.IntermediateDecode(_sttStream); 251 | // debugging logs, TODO: remove this 252 | if (output != resultText) Debug.Log(resultText); 253 | resultText = output; 254 | await Task.Delay(10); 255 | } 256 | } 257 | 258 | StreamingIsBusy = false; 259 | } 260 | private static short[] AudioFloatToInt16(float[] data) 261 | { 262 | Int16 maxValue = short.MaxValue; 263 | short[] shorts = new short[data.Length]; 264 | 265 | for (int i = 0; i < shorts.Length; i++) 266 | shorts[i] = Convert.ToInt16(data[i] * maxValue); 267 | 268 | return shorts; 269 | } 270 | 271 | public bool StartRecording() 272 | { 273 | if (_recording) 274 | { 275 | Debug.LogError("Already recording"); 276 | return false; 277 | } 278 | 279 | _targetFrequency = _frequency; 280 | _targetSampleSize = _sampleSize; 281 | 282 | Microphone.GetDeviceCaps(_device, out var minFreq, out var maxFreq); 283 | 284 | _recordFrequency = minFreq == 0 && maxFreq == 0 ? 44100 : maxFreq; 285 | _recordSampleSize = _recordFrequency / (_targetFrequency / _targetSampleSize); 286 | 287 | _clip = Microphone.Start(_device, true, 1, _recordFrequency); 288 | _sampleBuffer = new float[_recordSampleSize]; 289 | _recording = true; 290 | 291 | _sttStream = _sttClient.CreateStream(); 292 | return _recording; 293 | } 294 | } -------------------------------------------------------------------------------- /Runtime/ASR/ContinuousSpeechRecognition.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: dfef8eb66726e954fbb4c198ee990e8f 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 0b3c6d901f865d040a091c0140f69322 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/DeepSpeech.cs: -------------------------------------------------------------------------------- 1 | using DeepSpeechClient.Interfaces; 2 | using DeepSpeechClient.Extensions; 3 | 4 | using System; 5 | using System.IO; 6 | using DeepSpeechClient.Enums; 7 | using DeepSpeechClient.Models; 8 | 9 | namespace DeepSpeechClient 10 | { 11 | /// 12 | /// Concrete implementation of . 13 | /// 14 | public class DeepSpeech : IDeepSpeech 15 | { 16 | private unsafe IntPtr** _modelStatePP; 17 | 18 | /// 19 | /// Initializes a new instance of class and creates a new acoustic model. 20 | /// 21 | /// The path to the frozen model graph. 22 | /// Thrown when the native binary failed to create the model. 23 | public DeepSpeech(string aModelPath) 24 | { 25 | CreateModel(aModelPath); 26 | } 27 | 28 | #region IDeepSpeech 29 | 30 | /// 31 | /// Create an object providing an interface to a trained DeepSpeech model. 32 | /// 33 | /// The path to the frozen model graph. 34 | /// Thrown when the native binary failed to create the model. 35 | private unsafe void CreateModel(string aModelPath) 36 | { 37 | string exceptionMessage = null; 38 | if (string.IsNullOrWhiteSpace(aModelPath)) 39 | { 40 | exceptionMessage = "Model path cannot be empty."; 41 | } 42 | if (!File.Exists(aModelPath)) 43 | { 44 | exceptionMessage = $"Cannot find the model file: {aModelPath}"; 45 | } 46 | 47 | if (exceptionMessage != null) 48 | { 49 | throw new FileNotFoundException(exceptionMessage); 50 | } 51 | var resultCode = NativeImp.DS_CreateModel(aModelPath, 52 | ref _modelStatePP); 53 | EvaluateResultCode(resultCode); 54 | } 55 | 56 | /// 57 | /// Get beam width value used by the model. If SetModelBeamWidth was not 58 | /// called before, will return the default value loaded from the model file. 59 | /// 60 | /// Beam width value used by the model. 61 | public unsafe uint GetModelBeamWidth() 62 | { 63 | return NativeImp.DS_GetModelBeamWidth(_modelStatePP); 64 | } 65 | 66 | /// 67 | /// Set beam width value used by the model. 68 | /// 69 | /// The beam width used by the decoder. A larger beam width value generates better results at the cost of decoding time. 70 | /// Thrown on failure. 71 | public unsafe void SetModelBeamWidth(uint aBeamWidth) 72 | { 73 | var resultCode = NativeImp.DS_SetModelBeamWidth(_modelStatePP, aBeamWidth); 74 | EvaluateResultCode(resultCode); 75 | } 76 | 77 | /// 78 | /// Add a hot-word. 79 | /// 80 | /// Words that don't occur in the scorer (e.g. proper nouns) or strings that contain spaces won't be taken into account. 81 | /// 82 | /// Some word 83 | /// Some boost. Positive value increases and negative reduces chance of a word occuring in a transcription. Excessive positive boost might lead to splitting up of letters of the word following the hot-word. 84 | /// Thrown on failure. 85 | public unsafe void AddHotWord(string aWord, float aBoost) 86 | { 87 | var resultCode = NativeImp.DS_AddHotWord(_modelStatePP, aWord, aBoost); 88 | EvaluateResultCode(resultCode); 89 | } 90 | 91 | /// 92 | /// Erase entry for a hot-word. 93 | /// 94 | /// Some word 95 | /// Thrown on failure. 96 | public unsafe void EraseHotWord(string aWord) 97 | { 98 | var resultCode = NativeImp.DS_EraseHotWord(_modelStatePP, aWord); 99 | EvaluateResultCode(resultCode); 100 | } 101 | 102 | /// 103 | /// Clear all hot-words. 104 | /// 105 | /// Thrown on failure. 106 | public unsafe void ClearHotWords() 107 | { 108 | var resultCode = NativeImp.DS_ClearHotWords(_modelStatePP); 109 | EvaluateResultCode(resultCode); 110 | } 111 | 112 | /// 113 | /// Return the sample rate expected by the model. 114 | /// 115 | /// Sample rate. 116 | public unsafe int GetModelSampleRate() 117 | { 118 | return NativeImp.DS_GetModelSampleRate(_modelStatePP); 119 | } 120 | 121 | /// 122 | /// Evaluate the result code and will raise an exception if necessary. 123 | /// 124 | /// Native result code. 125 | private void EvaluateResultCode(ErrorCodes resultCode) 126 | { 127 | if (resultCode != ErrorCodes.DS_ERR_OK) 128 | { 129 | throw new ArgumentException(NativeImp.DS_ErrorCodeToErrorMessage((int)resultCode).PtrToString()); 130 | } 131 | } 132 | 133 | /// 134 | /// Frees associated resources and destroys models objects. 135 | /// 136 | public unsafe void Dispose() 137 | { 138 | NativeImp.DS_FreeModel(_modelStatePP); 139 | } 140 | 141 | /// 142 | /// Enable decoding using an external scorer. 143 | /// 144 | /// The path to the external scorer file. 145 | /// Thrown when the native binary failed to enable decoding with an external scorer. 146 | /// Thrown when cannot find the scorer file. 147 | public unsafe void EnableExternalScorer(string aScorerPath) 148 | { 149 | if (string.IsNullOrWhiteSpace(aScorerPath)) 150 | { 151 | throw new FileNotFoundException("Path to the scorer file cannot be empty."); 152 | } 153 | if (!File.Exists(aScorerPath)) 154 | { 155 | throw new FileNotFoundException($"Cannot find the scorer file: {aScorerPath}"); 156 | } 157 | 158 | var resultCode = NativeImp.DS_EnableExternalScorer(_modelStatePP, aScorerPath); 159 | EvaluateResultCode(resultCode); 160 | } 161 | 162 | /// 163 | /// Disable decoding using an external scorer. 164 | /// 165 | /// Thrown when an external scorer is not enabled. 166 | public unsafe void DisableExternalScorer() 167 | { 168 | var resultCode = NativeImp.DS_DisableExternalScorer(_modelStatePP); 169 | EvaluateResultCode(resultCode); 170 | } 171 | 172 | /// 173 | /// Set hyperparameters alpha and beta of the external scorer. 174 | /// 175 | /// The alpha hyperparameter of the decoder. Language model weight. 176 | /// The beta hyperparameter of the decoder. Word insertion weight. 177 | /// Thrown when an external scorer is not enabled. 178 | public unsafe void SetScorerAlphaBeta(float aAlpha, float aBeta) 179 | { 180 | var resultCode = NativeImp.DS_SetScorerAlphaBeta(_modelStatePP, 181 | aAlpha, 182 | aBeta); 183 | EvaluateResultCode(resultCode); 184 | } 185 | 186 | /// 187 | /// Feeds audio samples to an ongoing streaming inference. 188 | /// 189 | /// Instance of the stream to feed the data. 190 | /// An array of 16-bit, mono raw audio samples at the appropriate sample rate (matching what the model was trained on). 191 | public unsafe void FeedAudioContent(DeepSpeechStream stream, short[] aBuffer, uint aBufferSize) 192 | { 193 | NativeImp.DS_FeedAudioContent(stream.GetNativePointer(), aBuffer, aBufferSize); 194 | } 195 | 196 | /// 197 | /// Closes the ongoing streaming inference, returns the STT result over the whole audio signal. 198 | /// 199 | /// Instance of the stream to finish. 200 | /// The STT result. 201 | public unsafe string FinishStream(DeepSpeechStream stream) 202 | { 203 | return NativeImp.DS_FinishStream(stream.GetNativePointer()).PtrToString(); 204 | } 205 | 206 | /// 207 | /// Closes the ongoing streaming inference, returns the STT result over the whole audio signal, including metadata. 208 | /// 209 | /// Instance of the stream to finish. 210 | /// Maximum number of candidate transcripts to return. Returned list might be smaller than this. 211 | /// The extended metadata result. 212 | public unsafe Metadata FinishStreamWithMetadata(DeepSpeechStream stream, uint aNumResults) 213 | { 214 | return NativeImp.DS_FinishStreamWithMetadata(stream.GetNativePointer(), aNumResults).PtrToMetadata(); 215 | } 216 | 217 | /// 218 | /// Computes the intermediate decoding of an ongoing streaming inference. 219 | /// 220 | /// Instance of the stream to decode. 221 | /// The STT intermediate result. 222 | public unsafe string IntermediateDecode(DeepSpeechStream stream) 223 | { 224 | return NativeImp.DS_IntermediateDecode(stream.GetNativePointer()).PtrToString(); 225 | } 226 | 227 | /// 228 | /// Computes the intermediate decoding of an ongoing streaming inference, including metadata. 229 | /// 230 | /// Instance of the stream to decode. 231 | /// Maximum number of candidate transcripts to return. Returned list might be smaller than this. 232 | /// The STT intermediate result. 233 | public unsafe Metadata IntermediateDecodeWithMetadata(DeepSpeechStream stream, uint aNumResults) 234 | { 235 | return NativeImp.DS_IntermediateDecodeWithMetadata(stream.GetNativePointer(), aNumResults).PtrToMetadata(); 236 | } 237 | 238 | /// 239 | /// Return version of this library. The returned version is a semantic version 240 | /// (SemVer 2.0.0). 241 | /// 242 | public unsafe string Version() 243 | { 244 | return NativeImp.DS_Version().PtrToString(); 245 | } 246 | 247 | /// 248 | /// Creates a new streaming inference state. 249 | /// 250 | public unsafe DeepSpeechStream CreateStream() 251 | { 252 | IntPtr** streamingStatePointer = null; 253 | var resultCode = NativeImp.DS_CreateStream(_modelStatePP, ref streamingStatePointer); 254 | EvaluateResultCode(resultCode); 255 | return new DeepSpeechStream(streamingStatePointer); 256 | } 257 | 258 | /// 259 | /// Destroy a streaming state without decoding the computed logits. 260 | /// This can be used if you no longer need the result of an ongoing streaming 261 | /// inference and don't want to perform a costly decode operation. 262 | /// 263 | public unsafe void FreeStream(DeepSpeechStream stream) 264 | { 265 | NativeImp.DS_FreeStream(stream.GetNativePointer()); 266 | stream.Dispose(); 267 | } 268 | 269 | /// 270 | /// Use the DeepSpeech model to perform Speech-To-Text. 271 | /// 272 | /// A 16-bit, mono raw audio signal at the appropriate sample rate (matching what the model was trained on). 273 | /// The number of samples in the audio signal. 274 | /// The STT result. Returns NULL on error. 275 | public unsafe string SpeechToText(short[] aBuffer, uint aBufferSize) 276 | { 277 | return NativeImp.DS_SpeechToText(_modelStatePP, aBuffer, aBufferSize).PtrToString(); 278 | } 279 | 280 | /// 281 | /// Use the DeepSpeech model to perform Speech-To-Text, return results including metadata. 282 | /// 283 | /// A 16-bit, mono raw audio signal at the appropriate sample rate (matching what the model was trained on). 284 | /// The number of samples in the audio signal. 285 | /// Maximum number of candidate transcripts to return. Returned list might be smaller than this. 286 | /// The extended metadata. Returns NULL on error. 287 | public unsafe Metadata SpeechToTextWithMetadata(short[] aBuffer, uint aBufferSize, uint aNumResults) 288 | { 289 | return NativeImp.DS_SpeechToTextWithMetadata(_modelStatePP, aBuffer, aBufferSize, aNumResults).PtrToMetadata(); 290 | } 291 | 292 | #endregion 293 | } 294 | } 295 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/DeepSpeech.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: af3b8ce42407bf24095d663ae30ec1c8 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Enums.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 381457edee2984d42b66daa9009ad441 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Enums/ErrorCodes.cs: -------------------------------------------------------------------------------- 1 | namespace DeepSpeechClient.Enums 2 | { 3 | /// 4 | /// Error codes from the native DeepSpeech binary. 5 | /// 6 | internal enum ErrorCodes 7 | { 8 | // OK 9 | DS_ERR_OK = 0x0000, 10 | 11 | // Missing invormations 12 | DS_ERR_NO_MODEL = 0x1000, 13 | 14 | // Invalid parameters 15 | DS_ERR_INVALID_ALPHABET = 0x2000, 16 | DS_ERR_INVALID_SHAPE = 0x2001, 17 | DS_ERR_INVALID_SCORER = 0x2002, 18 | DS_ERR_MODEL_INCOMPATIBLE = 0x2003, 19 | DS_ERR_SCORER_NOT_ENABLED = 0x2004, 20 | 21 | // Runtime failures 22 | DS_ERR_FAIL_INIT_MMAP = 0x3000, 23 | DS_ERR_FAIL_INIT_SESS = 0x3001, 24 | DS_ERR_FAIL_INTERPRETER = 0x3002, 25 | DS_ERR_FAIL_RUN_SESS = 0x3003, 26 | DS_ERR_FAIL_CREATE_STREAM = 0x3004, 27 | DS_ERR_FAIL_READ_PROTOBUF = 0x3005, 28 | DS_ERR_FAIL_CREATE_SESS = 0x3006, 29 | DS_ERR_FAIL_INSERT_HOTWORD = 0x3008, 30 | DS_ERR_FAIL_CLEAR_HOTWORD = 0x3009, 31 | DS_ERR_FAIL_ERASE_HOTWORD = 0x3010 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Enums/ErrorCodes.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 42ea312535a2f7e44991527b2e0f69c7 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Extensions.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 7d1304d04b2b72f4b9eb62811583d0ff 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Extensions/NativeExtensions.cs: -------------------------------------------------------------------------------- 1 | using DeepSpeechClient.Structs; 2 | using System; 3 | using System.Runtime.InteropServices; 4 | using System.Text; 5 | 6 | namespace DeepSpeechClient.Extensions 7 | { 8 | internal static class NativeExtensions 9 | { 10 | /// 11 | /// Converts native pointer to UTF-8 encoded string. 12 | /// 13 | /// Native pointer. 14 | /// Optional parameter to release the native pointer. 15 | /// Result string. 16 | internal static string PtrToString(this IntPtr intPtr, bool releasePtr = true) 17 | { 18 | int len = 0; 19 | while (Marshal.ReadByte(intPtr, len) != 0) ++len; 20 | byte[] buffer = new byte[len]; 21 | Marshal.Copy(intPtr, buffer, 0, buffer.Length); 22 | if (releasePtr) 23 | NativeImp.DS_FreeString(intPtr); 24 | string result = Encoding.UTF8.GetString(buffer); 25 | return result; 26 | } 27 | 28 | /// 29 | /// Converts a pointer into managed TokenMetadata object. 30 | /// 31 | /// Native pointer. 32 | /// TokenMetadata managed object. 33 | private static Models.TokenMetadata PtrToTokenMetadata(this IntPtr intPtr) 34 | { 35 | var token = Marshal.PtrToStructure(intPtr); 36 | var managedToken = new Models.TokenMetadata 37 | { 38 | Timestep = token.timestep, 39 | StartTime = token.start_time, 40 | Text = token.text.PtrToString(releasePtr: false) 41 | }; 42 | return managedToken; 43 | } 44 | 45 | /// 46 | /// Converts a pointer into managed CandidateTranscript object. 47 | /// 48 | /// Native pointer. 49 | /// CandidateTranscript managed object. 50 | private static Models.CandidateTranscript PtrToCandidateTranscript(this IntPtr intPtr) 51 | { 52 | var managedTranscript = new Models.CandidateTranscript(); 53 | var transcript = Marshal.PtrToStructure(intPtr); 54 | 55 | managedTranscript.Tokens = new Models.TokenMetadata[transcript.num_tokens]; 56 | managedTranscript.Confidence = transcript.confidence; 57 | 58 | //we need to manually read each item from the native ptr using its size 59 | var sizeOfTokenMetadata = Marshal.SizeOf(typeof(TokenMetadata)); 60 | for (int i = 0; i < transcript.num_tokens; i++) 61 | { 62 | managedTranscript.Tokens[i] = transcript.tokens.PtrToTokenMetadata(); 63 | transcript.tokens += sizeOfTokenMetadata; 64 | } 65 | 66 | return managedTranscript; 67 | } 68 | 69 | /// 70 | /// Converts a pointer into managed Metadata object. 71 | /// 72 | /// Native pointer. 73 | /// Metadata managed object. 74 | internal static Models.Metadata PtrToMetadata(this IntPtr intPtr) 75 | { 76 | var managedMetadata = new Models.Metadata(); 77 | var metadata = Marshal.PtrToStructure(intPtr); 78 | 79 | managedMetadata.Transcripts = new Models.CandidateTranscript[metadata.num_transcripts]; 80 | 81 | //we need to manually read each item from the native ptr using its size 82 | var sizeOfCandidateTranscript = Marshal.SizeOf(typeof(CandidateTranscript)); 83 | for (int i = 0; i < metadata.num_transcripts; i++) 84 | { 85 | managedMetadata.Transcripts[i] = metadata.transcripts.PtrToCandidateTranscript(); 86 | metadata.transcripts += sizeOfCandidateTranscript; 87 | } 88 | 89 | NativeImp.DS_FreeMetadata(intPtr); 90 | return managedMetadata; 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Extensions/NativeExtensions.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 4fc0de4cfa449f44f9e3fe28bb651462 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Interfaces.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 705d49647dfc1014a86ac780c892190e 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Interfaces/IDeepSpeech.cs: -------------------------------------------------------------------------------- 1 | using DeepSpeechClient.Models; 2 | using System; 3 | using System.IO; 4 | 5 | namespace DeepSpeechClient.Interfaces 6 | { 7 | /// 8 | /// Client interface for DeepSpeech 9 | /// 10 | public interface IDeepSpeech : IDisposable 11 | { 12 | /// 13 | /// Return version of this library. The returned version is a semantic version 14 | /// (SemVer 2.0.0). 15 | /// 16 | unsafe string Version(); 17 | 18 | /// 19 | /// Return the sample rate expected by the model. 20 | /// 21 | /// Sample rate. 22 | unsafe int GetModelSampleRate(); 23 | 24 | /// 25 | /// Get beam width value used by the model. If SetModelBeamWidth was not 26 | /// called before, will return the default value loaded from the model 27 | /// file. 28 | /// 29 | /// Beam width value used by the model. 30 | unsafe uint GetModelBeamWidth(); 31 | 32 | /// 33 | /// Set beam width value used by the model. 34 | /// 35 | /// The beam width used by the decoder. A larger beam width value generates better results at the cost of decoding time. 36 | /// Thrown on failure. 37 | unsafe void SetModelBeamWidth(uint aBeamWidth); 38 | 39 | /// 40 | /// Enable decoding using an external scorer. 41 | /// 42 | /// The path to the external scorer file. 43 | /// Thrown when the native binary failed to enable decoding with an external scorer. 44 | /// Thrown when cannot find the scorer file. 45 | unsafe void EnableExternalScorer(string aScorerPath); 46 | 47 | /// 48 | /// Add a hot-word. 49 | /// 50 | /// Some word 51 | /// Some boost 52 | /// Thrown on failure. 53 | unsafe void AddHotWord(string aWord, float aBoost); 54 | 55 | /// 56 | /// Erase entry for a hot-word. 57 | /// 58 | /// Some word 59 | /// Thrown on failure. 60 | unsafe void EraseHotWord(string aWord); 61 | 62 | /// 63 | /// Clear all hot-words. 64 | /// 65 | /// Thrown on failure. 66 | unsafe void ClearHotWords(); 67 | 68 | /// 69 | /// Disable decoding using an external scorer. 70 | /// 71 | /// Thrown when an external scorer is not enabled. 72 | unsafe void DisableExternalScorer(); 73 | 74 | /// 75 | /// Set hyperparameters alpha and beta of the external scorer. 76 | /// 77 | /// The alpha hyperparameter of the decoder. Language model weight. 78 | /// The beta hyperparameter of the decoder. Word insertion weight. 79 | /// Thrown when an external scorer is not enabled. 80 | unsafe void SetScorerAlphaBeta(float aAlpha, float aBeta); 81 | 82 | /// 83 | /// Use the DeepSpeech model to perform Speech-To-Text. 84 | /// 85 | /// A 16-bit, mono raw audio signal at the appropriate sample rate (matching what the model was trained on). 86 | /// The number of samples in the audio signal. 87 | /// The STT result. Returns NULL on error. 88 | unsafe string SpeechToText(short[] aBuffer, 89 | uint aBufferSize); 90 | 91 | /// 92 | /// Use the DeepSpeech model to perform Speech-To-Text, return results including metadata. 93 | /// 94 | /// A 16-bit, mono raw audio signal at the appropriate sample rate (matching what the model was trained on). 95 | /// The number of samples in the audio signal. 96 | /// Maximum number of candidate transcripts to return. Returned list might be smaller than this. 97 | /// The extended metadata. Returns NULL on error. 98 | unsafe Metadata SpeechToTextWithMetadata(short[] aBuffer, 99 | uint aBufferSize, 100 | uint aNumResults); 101 | 102 | /// 103 | /// Destroy a streaming state without decoding the computed logits. 104 | /// This can be used if you no longer need the result of an ongoing streaming 105 | /// inference and don't want to perform a costly decode operation. 106 | /// 107 | unsafe void FreeStream(DeepSpeechStream stream); 108 | 109 | /// 110 | /// Creates a new streaming inference state. 111 | /// 112 | unsafe DeepSpeechStream CreateStream(); 113 | 114 | /// 115 | /// Feeds audio samples to an ongoing streaming inference. 116 | /// 117 | /// Instance of the stream to feed the data. 118 | /// An array of 16-bit, mono raw audio samples at the appropriate sample rate (matching what the model was trained on). 119 | unsafe void FeedAudioContent(DeepSpeechStream stream, short[] aBuffer, uint aBufferSize); 120 | 121 | /// 122 | /// Computes the intermediate decoding of an ongoing streaming inference. 123 | /// 124 | /// Instance of the stream to decode. 125 | /// The STT intermediate result. 126 | unsafe string IntermediateDecode(DeepSpeechStream stream); 127 | 128 | /// 129 | /// Computes the intermediate decoding of an ongoing streaming inference, including metadata. 130 | /// 131 | /// Instance of the stream to decode. 132 | /// Maximum number of candidate transcripts to return. Returned list might be smaller than this. 133 | /// The extended metadata result. 134 | unsafe Metadata IntermediateDecodeWithMetadata(DeepSpeechStream stream, uint aNumResults); 135 | 136 | /// 137 | /// Closes the ongoing streaming inference, returns the STT result over the whole audio signal. 138 | /// 139 | /// Instance of the stream to finish. 140 | /// The STT result. 141 | unsafe string FinishStream(DeepSpeechStream stream); 142 | 143 | /// 144 | /// Closes the ongoing streaming inference, returns the STT result over the whole audio signal, including metadata. 145 | /// 146 | /// Instance of the stream to finish. 147 | /// Maximum number of candidate transcripts to return. Returned list might be smaller than this. 148 | /// The extended metadata result. 149 | unsafe Metadata FinishStreamWithMetadata(DeepSpeechStream stream, uint aNumResults); 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Interfaces/IDeepSpeech.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: ba34251101b1ae249bfa40a17cca0787 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Models.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 82be5aab17e7ffc499ac6046f7e8484f 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Models/CandidateTranscript.cs: -------------------------------------------------------------------------------- 1 | namespace DeepSpeechClient.Models 2 | { 3 | /// 4 | /// Stores the entire CTC output as an array of character metadata objects. 5 | /// 6 | public class CandidateTranscript 7 | { 8 | /// 9 | /// Approximated confidence value for this transcription. 10 | /// 11 | public double Confidence { get; set; } 12 | /// 13 | /// List of metada tokens containing text, timestep, and time offset. 14 | /// 15 | public TokenMetadata[] Tokens { get; set; } 16 | } 17 | } -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Models/CandidateTranscript.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 8bda0d2f0186f584b8653620c0eb71be 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Models/DeepSpeechStream.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DeepSpeechClient.Models 4 | { 5 | /// 6 | /// Wrapper of the pointer used for the decoding stream. 7 | /// 8 | public class DeepSpeechStream : IDisposable 9 | { 10 | private unsafe IntPtr** _streamingStatePp; 11 | 12 | /// 13 | /// Initializes a new instance of . 14 | /// 15 | /// Native pointer of the native stream. 16 | public unsafe DeepSpeechStream(IntPtr** streamingStatePP) 17 | { 18 | _streamingStatePp = streamingStatePP; 19 | } 20 | 21 | /// 22 | /// Gets the native pointer. 23 | /// 24 | /// Thrown when the stream has been disposed or not yet initialized. 25 | /// Native pointer of the stream. 26 | internal unsafe IntPtr** GetNativePointer() 27 | { 28 | if (_streamingStatePp == null) 29 | throw new InvalidOperationException("Cannot use a disposed or uninitialized stream."); 30 | return _streamingStatePp; 31 | } 32 | 33 | public unsafe void Dispose() => _streamingStatePp = null; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Models/DeepSpeechStream.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 41f82be5a93393a4a9cb30eaa357dd54 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Models/Metadata.cs: -------------------------------------------------------------------------------- 1 | namespace DeepSpeechClient.Models 2 | { 3 | /// 4 | /// Stores the entire CTC output as an array of character metadata objects. 5 | /// 6 | public class Metadata 7 | { 8 | /// 9 | /// List of candidate transcripts. 10 | /// 11 | public CandidateTranscript[] Transcripts { get; set; } 12 | } 13 | } -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Models/Metadata.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: cbce661f18c040442b2d602a19629197 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Models/TokenMetadata.cs: -------------------------------------------------------------------------------- 1 | namespace DeepSpeechClient.Models 2 | { 3 | /// 4 | /// Stores each individual character, along with its timing information. 5 | /// 6 | public class TokenMetadata 7 | { 8 | /// 9 | /// Char of the current timestep. 10 | /// 11 | public string Text; 12 | /// 13 | /// Position of the character in units of 20ms. 14 | /// 15 | public int Timestep; 16 | /// 17 | /// Position of the character in seconds. 18 | /// 19 | public float StartTime; 20 | } 21 | } -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Models/TokenMetadata.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: b3e8eb30c186fa74399598cf74f4c016 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/NativeImp.cs: -------------------------------------------------------------------------------- 1 | using DeepSpeechClient.Enums; 2 | 3 | using System; 4 | using System.Runtime.InteropServices; 5 | 6 | namespace DeepSpeechClient 7 | { 8 | /// 9 | /// Wrapper for the native implementation of libPath 10 | /// 11 | internal static class NativeImp 12 | { 13 | private const string libPath = "libdeepspeech"; 14 | #region Native Implementation 15 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl, 16 | CharSet = CharSet.Ansi, SetLastError = true)] 17 | internal static extern IntPtr DS_Version(); 18 | 19 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 20 | internal unsafe static extern ErrorCodes DS_CreateModel(string aModelPath, 21 | ref IntPtr** pint); 22 | 23 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 24 | internal unsafe static extern IntPtr DS_ErrorCodeToErrorMessage(int aErrorCode); 25 | 26 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 27 | internal unsafe static extern uint DS_GetModelBeamWidth(IntPtr** aCtx); 28 | 29 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 30 | internal unsafe static extern ErrorCodes DS_SetModelBeamWidth(IntPtr** aCtx, 31 | uint aBeamWidth); 32 | 33 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 34 | internal unsafe static extern ErrorCodes DS_CreateModel(string aModelPath, 35 | uint aBeamWidth, 36 | ref IntPtr** pint); 37 | 38 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 39 | internal unsafe static extern int DS_GetModelSampleRate(IntPtr** aCtx); 40 | 41 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 42 | internal static unsafe extern ErrorCodes DS_EnableExternalScorer(IntPtr** aCtx, 43 | string aScorerPath); 44 | 45 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 46 | internal static unsafe extern ErrorCodes DS_AddHotWord(IntPtr** aCtx, 47 | string aWord, 48 | float aBoost); 49 | 50 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 51 | internal static unsafe extern ErrorCodes DS_EraseHotWord(IntPtr** aCtx, 52 | string aWord); 53 | 54 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 55 | internal static unsafe extern ErrorCodes DS_ClearHotWords(IntPtr** aCtx); 56 | 57 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 58 | internal static unsafe extern ErrorCodes DS_DisableExternalScorer(IntPtr** aCtx); 59 | 60 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 61 | internal static unsafe extern ErrorCodes DS_SetScorerAlphaBeta(IntPtr** aCtx, 62 | float aAlpha, 63 | float aBeta); 64 | 65 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl, 66 | CharSet = CharSet.Ansi, SetLastError = true)] 67 | internal static unsafe extern IntPtr DS_SpeechToText(IntPtr** aCtx, 68 | short[] aBuffer, 69 | uint aBufferSize); 70 | 71 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl, SetLastError = true)] 72 | internal static unsafe extern IntPtr DS_SpeechToTextWithMetadata(IntPtr** aCtx, 73 | short[] aBuffer, 74 | uint aBufferSize, 75 | uint aNumResults); 76 | 77 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 78 | internal static unsafe extern void DS_FreeModel(IntPtr** aCtx); 79 | 80 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 81 | internal static unsafe extern ErrorCodes DS_CreateStream(IntPtr** aCtx, 82 | ref IntPtr** retval); 83 | 84 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 85 | internal static unsafe extern void DS_FreeStream(IntPtr** aSctx); 86 | 87 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 88 | internal static unsafe extern void DS_FreeMetadata(IntPtr metadata); 89 | 90 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 91 | internal static unsafe extern void DS_FreeString(IntPtr str); 92 | 93 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl, 94 | CharSet = CharSet.Ansi, SetLastError = true)] 95 | internal static unsafe extern void DS_FeedAudioContent(IntPtr** aSctx, 96 | short[] aBuffer, 97 | uint aBufferSize); 98 | 99 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 100 | internal static unsafe extern IntPtr DS_IntermediateDecode(IntPtr** aSctx); 101 | 102 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 103 | internal static unsafe extern IntPtr DS_IntermediateDecodeWithMetadata(IntPtr** aSctx, 104 | uint aNumResults); 105 | 106 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl, 107 | CharSet = CharSet.Ansi, SetLastError = true)] 108 | internal static unsafe extern IntPtr DS_FinishStream(IntPtr** aSctx); 109 | 110 | [DllImport(libPath, CallingConvention = CallingConvention.Cdecl)] 111 | internal static unsafe extern IntPtr DS_FinishStreamWithMetadata(IntPtr** aSctx, 112 | uint aNumResults); 113 | #endregion 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/NativeImp.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: e1cec61fb105dc64a9c9536646bf3af9 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Structs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 3f03f2bd13253694e9ed90601695ff93 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Structs/CandidateTranscript.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace DeepSpeechClient.Structs 5 | { 6 | [StructLayout(LayoutKind.Sequential)] 7 | internal unsafe struct CandidateTranscript 8 | { 9 | /// 10 | /// Native list of tokens. 11 | /// 12 | internal unsafe IntPtr tokens; 13 | /// 14 | /// Count of tokens from the native side. 15 | /// 16 | internal unsafe int num_tokens; 17 | /// 18 | /// Approximated confidence value for this transcription. 19 | /// 20 | internal unsafe double confidence; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Structs/CandidateTranscript.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: dc7b3b01ef83ca448820b79f2f160093 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Structs/Metadata.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace DeepSpeechClient.Structs 5 | { 6 | [StructLayout(LayoutKind.Sequential)] 7 | internal unsafe struct Metadata 8 | { 9 | /// 10 | /// Native list of candidate transcripts. 11 | /// 12 | internal unsafe IntPtr transcripts; 13 | /// 14 | /// Count of transcripts from the native side. 15 | /// 16 | internal unsafe int num_transcripts; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Structs/Metadata.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 25e91876a4c50d04a94ca53b46d60f19 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Structs/TokenMetadata.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace DeepSpeechClient.Structs 5 | { 6 | [StructLayout(LayoutKind.Sequential)] 7 | internal unsafe struct TokenMetadata 8 | { 9 | /// 10 | /// Native text. 11 | /// 12 | internal unsafe IntPtr text; 13 | /// 14 | /// Position of the character in units of 20ms. 15 | /// 16 | internal unsafe int timestep; 17 | /// 18 | /// Position of the character in seconds. 19 | /// 20 | internal unsafe float start_time; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/Structs/TokenMetadata.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: ef2a6d53830238a498aacb2a0a2e0703 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/VX.Speech.DeepSpeechClient.asmdef: -------------------------------------------------------------------------------- 1 | { 2 | "name": "VX.Speech.DeepSpeechClient", 3 | "rootNamespace": "", 4 | "references": [], 5 | "includePlatforms": [], 6 | "excludePlatforms": [], 7 | "allowUnsafeCode": true, 8 | "overrideReferences": false, 9 | "precompiledReferences": [], 10 | "autoReferenced": true, 11 | "defineConstraints": [], 12 | "versionDefines": [], 13 | "noEngineReferences": false 14 | } -------------------------------------------------------------------------------- /Runtime/DeepSpeechClient/VX.Speech.DeepSpeechClient.asmdef.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 40edeadb9ac5b04429c09420ca142019 3 | AssemblyDefinitionImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Runtime/VX.Speech.Runtime.asmdef: -------------------------------------------------------------------------------- 1 | { 2 | "name": "VX.Speech.Runtime", 3 | "rootNamespace": "", 4 | "references": [ 5 | "GUID:b23efe0d0bd83184681bd63517e3c327", 6 | "GUID:40edeadb9ac5b04429c09420ca142019", 7 | "GUID:5c2b5ba89f9e74e418232e154bc5cc7a", 8 | "GUID:fbc9f7bf5edea4a74a8942a98af6fe07" 9 | ], 10 | "includePlatforms": [], 11 | "excludePlatforms": [], 12 | "allowUnsafeCode": false, 13 | "overrideReferences": false, 14 | "precompiledReferences": [], 15 | "autoReferenced": true, 16 | "defineConstraints": [], 17 | "versionDefines": [], 18 | "noEngineReferences": false 19 | } -------------------------------------------------------------------------------- /Runtime/VX.Speech.Runtime.asmdef.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 87cb64168a5f7104bbbae7d0fb35581c 3 | AssemblyDefinitionImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Tests.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: de40a637b6b801d40bcc92d222313bbc 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Tests/Editor.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: bcf0911674a31ba4ea5329e49c9c6022 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Tests/Runtime.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 96928c91dd2c1c34cbbe7f792aa810e5 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "voxell.speech", 3 | "displayName": "VX ASR", 4 | "author": "Nixon", 5 | "description": "Speech functionality for Unity (TTS and ASR).", 6 | "keywords": [ 7 | "speech", 8 | "voxell" 9 | ], 10 | "license": "Apache 2.0", 11 | "unity": "2019.4", 12 | "unityRelease": "0f1", 13 | "version": "0.3.0", 14 | "dependencies": { 15 | "voxell.util": "1.0.0" 16 | }, 17 | "samples": [ 18 | { 19 | "displayName": "SpeechExample", 20 | "description": "ASR Examples", 21 | "path": "~Samples/SpeechExample" 22 | } 23 | ] 24 | } -------------------------------------------------------------------------------- /package.json.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 28f840159ebdd22488722d797f6ae339 3 | PackageManifestImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /~Samples.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 948f977ab175b004aa64d23eaff62c4d 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /~Samples/SpeechExample.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: b44c6cc7426a1114989c59c14e45a17b 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | --------------------------------------------------------------------------------