├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── cloud-speech-recognition ├── README.md └── getting-started │ ├── README.md │ ├── asrapi │ └── __init__.py │ ├── main.py │ └── sample.wav └── natural-language-understanding ├── README.md ├── speech-input └── README.md └── text-input ├── README.md ├── main.py └── nluapi └── __init__.py /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask instance folder 57 | instance/ 58 | 59 | # Scrapy stuff: 60 | .scrapy 61 | 62 | # Sphinx documentation 63 | docs/_build/ 64 | 65 | # PyBuilder 66 | target/ 67 | 68 | # IPython Notebook 69 | .ipynb_checkpoints 70 | 71 | # pyenv 72 | .python-version 73 | 74 | # celery beat schedule file 75 | celerybeat-schedule 76 | 77 | # dotenv 78 | .env 79 | 80 | # virtualenv 81 | venv/ 82 | ENV/ 83 | 84 | # Spyder project settings 85 | .spyderproject 86 | 87 | # Rope project settings 88 | .ropeproject 89 | 90 | # ========================= 91 | # Operating System Files 92 | # ========================= 93 | 94 | # OSX 95 | # ========================= 96 | 97 | .DS_Store 98 | .AppleDouble 99 | .LSOverride 100 | 101 | # Thumbnails 102 | ._* 103 | 104 | # Files that might appear in the root of a volume 105 | .DocumentRevisions-V100 106 | .fseventsd 107 | .Spotlight-V100 108 | .TemporaryItems 109 | .Trashes 110 | .VolumeIcon.icns 111 | 112 | # Directories potentially created on remote AFP share 113 | .AppleDB 114 | .AppleDesktop 115 | Network Trash Folder 116 | Temporary Items 117 | .apdisk 118 | 119 | # Windows 120 | # ========================= 121 | 122 | # Windows image file caches 123 | Thumbs.db 124 | ehthumbs.db 125 | 126 | # Folder config file 127 | Desktop.ini 128 | 129 | # Recycle Bin used on file shares 130 | $RECYCLE.BIN/ 131 | 132 | # Windows Installer files 133 | *.cab 134 | *.msi 135 | *.msm 136 | *.msp 137 | 138 | # Windows shortcuts 139 | *.lnk 140 | -------------------------------------------------------------------------------- /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 {yyyy} {name of copyright owner} 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 | # Quickstart Samples: 2 | 3 | ## OLAMI HTTP APIs 4 | 5 | This is a repository that contains Python (**Python 3 is required**) code examples for using OLAMI HTTP APIs, an offering within **OLAMI Open AI**. 6 | 7 | OLAMI website and documentation: [http://olami.ai](http://olami.ai) 8 | 9 | The repo is organized as follows: 10 | 11 | * [Natural Language Understanding Samples](natural-language-understanding) 12 | * [Example for Text Input](natural-language-understanding/text-input) 13 | * [Example for Speech Input](natural-language-understanding/speech-input) 14 | 15 | * [Cloud Speech Recognition Samples](cloud-speech-recognition) 16 | * [Getting Started](cloud-speech-recognition/getting-started) 17 | 18 | * * * 19 | 20 | ### OLAMI NLP modeling (OSL design) examples 21 | 22 | See Repository : [olami-osl-examples](https://github.com/olami-developers/olami-osl-examples) 23 | 24 | -------------------------------------------------------------------------------- /cloud-speech-recognition/README.md: -------------------------------------------------------------------------------- 1 | # Cloud Speech Recognition API Samples 2 | 3 | This directory contains sample code for using Cloud Speech Recognition API. 4 | 5 | OLAMI website and documentation: [http://olami.ai](http://olami.ai) 6 | 7 | Samples: 8 | 9 | * [Getting Started](getting-started) -------------------------------------------------------------------------------- /cloud-speech-recognition/getting-started/README.md: -------------------------------------------------------------------------------- 1 | # Cloud Speech Recognition API Samples 2 | 3 | This directory contains sample code for using Cloud Speech Recognition API. 4 | 5 | OLAMI website and documentation: [http://olami.ai](http://olami.ai) 6 | 7 | ## Audio File Requirements 8 | 9 | The audio file is required in WAV file format PCM, **mono** recording with a sample rate of **16000 (16 KHz)** and a bit resolution of **16 bits**. 10 | 11 | ## Run the application: 12 | 13 | > 1. Replace **your_python_bin** to your Python binary path. 14 | > 2. Replace **api_url, your_app_key, your_app_secret, your_audio_file** in accordance to your needs and your own data. 15 | > 3. Replace **compress_flag** to `1` if the audio file is a Speex audio, otherwise `0` 16 | 17 | ``` 18 | your_python_bin main.py api_url your_app_key your_app_secret your_audio_file compress_flag 19 | ``` 20 | 21 | - For example: (Simplified Chinese Request with the sample.wav file) 22 | 23 | ``` 24 | python main.py https://cn.olami.ai/cloudservice/api 172c5b7b7121407ba572da444a999999 2115d0888bd049549581b7a0a6888888 ./sample.wav 0 25 | ``` 26 | 27 | - For example: (Traditional Chinese Request with the sample.wav file) 28 | 29 | ``` 30 | python main.py https://tw.olami.ai/cloudservice/api 999888777666555444333222111000aa 111222333444555666777888999000aa ./sample.wav 0 31 | ``` 32 | 33 | -------------------------------------------------------------------------------- /cloud-speech-recognition/getting-started/asrapi/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Copyright 2017, VIA Technologies, Inc. & OLAMI Team. 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | ''' 15 | import time 16 | import hashlib 17 | import urllib.request, urllib.error 18 | 19 | class SpeechAPISample: 20 | API_NAME_ASR = "asr"; 21 | 22 | apiBaseUrl = '' 23 | appKey = '' 24 | appSecret = '' 25 | cookies = '' 26 | 27 | def __init__(self): 28 | pass 29 | 30 | '''Setup your authorization information to access OLAMI services. 31 | 32 | :param appKey the AppKey you got from OLAMI developer console. 33 | :param appSecret the AppSecret you from OLAMI developer console. ''' 34 | def setAuthorization(self, appKey, appSecret): 35 | self.appKey = appKey 36 | self.appSecret = appSecret 37 | 38 | 39 | '''Setup localization to select service area, this is related to different 40 | server URLs or languages, etc. 41 | 42 | :param apiBaseURL URL of the API service.''' 43 | def setLocalization(self, apiBaseURL): 44 | self.apiBaseUrl = apiBaseURL 45 | 46 | 47 | '''Send an audio file to speech recognition service. 48 | 49 | :param apiName the API name for 'api=xxx' HTTP parameter. 50 | :param seqValue the value of 'seq' for 'seq=xxx' HTTP parameter. 51 | :param finished TRUE to finish upload or FALSE to continue upload. 52 | :param filePath the path of the audio file you want to upload. 53 | :param compressed TRUE if the audio file is a Speex audio.''' 54 | def sendAudioFile(self, apiName, seqValue, finished, filePath, compressed): 55 | '''Read the input audio file''' 56 | with open(filePath, "rb") as audioFile: 57 | af = audioFile.read() 58 | bAudioData = bytearray(af) 59 | if (bAudioData is None): 60 | return "[ERROR] File not found!"; 61 | 62 | ''' composite post data field''' 63 | postData = str(self.getBasicQueryString(apiName, seqValue)) 64 | postData += "&compress=" + ("1" if compressed else "0") 65 | postData += "&stop=" + ("1" if finished else "0") 66 | 67 | ''' Request speech recognition service by HTTP POST ''' 68 | url = str(self.apiBaseUrl) + "?" + str(postData) 69 | headers = { 'Connection' : "Keep-Alive", 70 | 'Content-Type' : "application/octet-stream" } 71 | req = urllib.request.Request(url,bAudioData,headers) 72 | with urllib.request.urlopen(req) as f: 73 | getResponse = f.read().decode() 74 | 75 | '''Now you can check the status here.''' 76 | print("Sending 'POST' request to URL : " + self.apiBaseUrl) 77 | print("Post parameters : " + str(postData)) 78 | print("Response Code : " + str(f.getcode())) 79 | 80 | '''Get cookie''' 81 | self.cookies = f.getheader('Set-Cookie') 82 | if (self.cookies is None): 83 | return "Failed to get cookies."; 84 | print("Cookies : " + str(self.cookies)) 85 | 86 | '''Get the response''' 87 | return str(getResponse) 88 | 89 | 90 | ''' Get the speech recognition result for the audio you sent. 91 | 92 | :param apiName the API name for 'api=xxx' HTTP parameter. 93 | :param seqValue the value of 'seq' for 'seq=xxx' HTTP parameter. ''' 94 | def getRecognitionResult(self, apiName, seqValue): 95 | query = self.getBasicQueryString(apiName, seqValue) + "&stop=1" 96 | 97 | '''Request speech recognition service by HTTP GET''' 98 | url = str(self.apiBaseUrl) + "?" + str(query) 99 | req = urllib.request.Request(url,headers = {'Cookie': self.cookies}) 100 | with urllib.request.urlopen(req) as f: 101 | getResponse = f.read().decode() 102 | 103 | '''Now you can check the status here.''' 104 | print("Sending 'GET' request to URL : " + self.apiBaseUrl) 105 | print("get parameters : " + str(query)) 106 | print("Response Code : " + str(f.getcode())) 107 | 108 | '''Get the response''' 109 | return str(getResponse) 110 | 111 | 112 | '''Generate and get a basic HTTP query string 113 | 114 | :param apiName the API name for 'api=xxx' HTTP parameter. 115 | :param seqValue the value of 'seq' for 'seq=xxx' HTTP parameter.''' 116 | def getBasicQueryString(self, apiName, seqValue): 117 | timestamp = int(round(time.time() * 1000)) 118 | 119 | '''Prepare message to generate an MD5 digest.''' 120 | signMsg = str(self.appSecret) 121 | signMsg += 'api='+apiName 122 | signMsg += 'appkey='+str(self.appKey) 123 | signMsg += 'timestamp='+str(timestamp) 124 | signMsg += str(self.appSecret) 125 | 126 | '''Generate MD5 digest.''' 127 | md = hashlib.md5() 128 | md.update(signMsg.encode('utf-8')) 129 | sign = md.hexdigest() 130 | 131 | '''Assemble all the HTTP parameters you want to send''' 132 | postData = '_from=python' 133 | postData +='&appkey='+str(self.appKey) 134 | postData +='&api='+apiName 135 | postData +='×tamp='+str(timestamp) 136 | postData +='&sign='+str(sign) 137 | postData +='&seq=' +seqValue 138 | 139 | return str(postData) 140 | 141 | 142 | -------------------------------------------------------------------------------- /cloud-speech-recognition/getting-started/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Copyright 2017, VIA Technologies, Inc. & OLAMI Team. 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | ''' 15 | 16 | from asrapi import SpeechAPISample 17 | import argparse 18 | import time 19 | 20 | def main(): 21 | parser = argparse.ArgumentParser() 22 | parser.add_argument("url", type=str, 23 | help="server base URL according to servicing area") 24 | parser.add_argument("appKey", type=str, 25 | help="your app key which get from server of servicing area") 26 | parser.add_argument("appSecret", type=str, 27 | help="your app secret which get from server of servicing area") 28 | parser.add_argument("audioFilePath", type=str, 29 | help="the audio file you want to upload") 30 | parser.add_argument("compressFlag", type=int, default=0,choices=[0,1], 31 | help="set 1 if the audio file is a Speex audio") 32 | parser.add_argument("-v", "--verbose", help="increase output verbosity", 33 | action="store_true") 34 | args = parser.parse_args() 35 | 36 | compressed = True if args.compressFlag is "1" else False 37 | 38 | asrApi = SpeechAPISample() 39 | asrApi.setLocalization(args.url) 40 | asrApi.setAuthorization(args.appKey, args.appSecret) 41 | 42 | '''Start sending audio file for recognition''' 43 | print("\n----- Test Speech API, seq=nli,seg -----\n") 44 | print("\nSend audio file... \n"); 45 | responseString = asrApi.sendAudioFile(asrApi.API_NAME_ASR, 46 | "nli,seg", True, args.audioFilePath, compressed) 47 | print("\n\nResult:\n\n" , responseString, "\n") 48 | 49 | ''' Try to get recognition result if uploaded successfully. 50 | We just check the state by a lazy way :P , you should do it by JSON.''' 51 | if ("error" not in responseString.lower()): 52 | print("\n----- Get Recognition Result -----\n") 53 | time.sleep(1) #delay for 1 second 54 | ''' Try to get result until the end of the recognition is complete ''' 55 | while (True): 56 | responseString = asrApi.getRecognitionResult( 57 | asrApi.API_NAME_ASR, "nli,seg") 58 | print("\n\nResult:\n\n" , responseString ,"\n") 59 | ''' Well, check by lazy way...again :P , do it by JSON please. ''' 60 | if ("\"final\":true" not in responseString.lower()): 61 | print("The recognition is not yet complete.") 62 | if ("error" in responseString.lower()): 63 | break 64 | time.sleep(2) #delay for 2 second 65 | else: 66 | break 67 | 68 | print("\n\n") 69 | 70 | 71 | if __name__ == '__main__': 72 | main() -------------------------------------------------------------------------------- /cloud-speech-recognition/getting-started/sample.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/olami-developers/olami-api-quickstart-python-samples/5d7f7b6d62642f0dd1357aa11e44ffe2ee799e75/cloud-speech-recognition/getting-started/sample.wav -------------------------------------------------------------------------------- /natural-language-understanding/README.md: -------------------------------------------------------------------------------- 1 | # Natural Language Understanding API Samples 2 | 3 | This directory contains sample code for using Natural Language Understanding API. 4 | 5 | Samples: 6 | 7 | * [Recognize your text input](text-input) 8 | * [Recognize your speech input](speech-input) -------------------------------------------------------------------------------- /natural-language-understanding/speech-input/README.md: -------------------------------------------------------------------------------- 1 | Natural Language Understanding by Speech-Input **is already integrated to Cloud Speech Recognition API**. 2 | 3 | Please refer to [Cloud Speech Recognition Samples](../../cloud-speech-recognition) 4 | 5 | * * * 6 | 7 | OLAMI website and documentation: [http://olami.ai](http://olami.ai) -------------------------------------------------------------------------------- /natural-language-understanding/text-input/README.md: -------------------------------------------------------------------------------- 1 | # Natural Language Understanding API Samples 2 | 3 | This directory contains sample code for using Natural Language Understanding API. 4 | 5 | OLAMI website and documentation: [http://olami.ai](http://olami.ai) 6 | 7 | ## Run the application (by Python 3): 8 | 9 | > 1. Replace **your_python_bin** to your Python binary path. 10 | > 2. Replace **api_url, your_app_key, your_app_secret, your_text_input** in accordance to your needs and your own data. 11 | 12 | ``` 13 | your_python_bin main.py api_url your_app_key your_app_secret your_text_input 14 | ``` 15 | 16 | - For example: (Simplified Chinese Request with the text "我爱欧拉蜜") 17 | 18 | ``` 19 | python main.py https://cn.olami.ai/cloudservice/api 172c5b7b7121407ba572da444a999999 2115d0888bd049549581b7a0a6888888 我爱欧拉蜜 20 | ``` 21 | 22 | - For example: (Traditional Chinese Request with the text "我愛歐拉蜜") 23 | 24 | ``` 25 | python main.py https://tw.olami.ai/cloudservice/api 999888777666555444333222111000aa 111222333444555666777888999000aa 我愛歐拉蜜 26 | ``` 27 | -------------------------------------------------------------------------------- /natural-language-understanding/text-input/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Copyright 2017, VIA Technologies, Inc. & OLAMI Team. 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | ''' 15 | 16 | from nluapi import NluAPISample 17 | import argparse 18 | 19 | def main(): 20 | parser = argparse.ArgumentParser() 21 | parser.add_argument("url", type=str, 22 | help="server base URL according to servicing area") 23 | parser.add_argument("appKey", type=str, 24 | help="your app key which get from server of servicing area") 25 | parser.add_argument("appSecret", type=str, 26 | help="your app secret which get from server of servicing area") 27 | parser.add_argument("inputText", type=str, 28 | help="input text which you want to talk with olami") 29 | parser.add_argument("-v", "--verbose", help="increase output verbosity", 30 | action="store_true") 31 | args = parser.parse_args() 32 | 33 | nluApi = NluAPISample() 34 | nluApi.setLocalization(args.url) 35 | nluApi.setAuthorization(args.appKey, args.appSecret) 36 | 37 | print("\n---------- Test NLU API, api=seg ----------\n"); 38 | print("\nResult:\n\n", nluApi.getRecognitionResult(nluApi.API_NAME_SEG, args.inputText)) 39 | 40 | print("\n---------- Test NLU API, api=nli ----------\n"); 41 | print("\nResult:\n\n", nluApi.getRecognitionResult(nluApi.API_NAME_NLI, args.inputText)) 42 | 43 | 44 | if __name__ == '__main__': 45 | main() -------------------------------------------------------------------------------- /natural-language-understanding/text-input/nluapi/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | Copyright 2017, VIA Technologies, Inc. & OLAMI Team. 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | ''' 15 | import time 16 | import hashlib 17 | import urllib.request, urllib.error 18 | 19 | class NluAPISample: 20 | API_NAME_SEG = "seg"; 21 | API_NAME_NLI = "nli"; 22 | 23 | apiBaseUrl = '' 24 | appKey = '' 25 | appSecret = '' 26 | 27 | def __init__(self): 28 | pass 29 | 30 | 31 | def setAuthorization(self, appKey, appSecret): 32 | self.appKey = appKey 33 | self.appSecret = appSecret 34 | 35 | 36 | '''Setup localization to select service area, this is related to different 37 | server URLs or languages, etc. 38 | 39 | :param language the language type.''' 40 | def setLocalization(self, apiBaseURL): 41 | self.apiBaseUrl = apiBaseURL 42 | 43 | '''Get the NLU recognition result for your input text. 44 | 45 | :param inputText the text you want to recognize.''' 46 | def getRecognitionResult(self, apiName, inputText): 47 | timestamp = int(round(time.time() * 1000)) 48 | 49 | '''Prepare message to generate an MD5 digest.''' 50 | signMsg = str(self.appSecret) 51 | signMsg += 'api='+apiName 52 | signMsg += 'appkey='+str(self.appKey) 53 | signMsg += 'timestamp='+str(timestamp) 54 | signMsg += str(self.appSecret) 55 | 56 | '''Generate MD5 digest.''' 57 | md = hashlib.md5() 58 | md.update(signMsg.encode('utf-8')) 59 | sign = md.hexdigest() 60 | 61 | '''Assemble all the HTTP parameters you want to send''' 62 | rq = '{\"data_type\":\"stt\",\"data\":{\"input_type\":1,\"text\":\"'+inputText+'\"}}' 63 | postData = '_from=python' 64 | postData += '&appkey='+str(self.appKey) 65 | postData +='&api='+apiName 66 | postData +='×tamp='+str(timestamp) 67 | postData +='&sign='+str(sign) 68 | postData +='&rq=' 69 | 70 | if (apiName == self.API_NAME_SEG): 71 | postData += inputText 72 | elif(apiName == self.API_NAME_NLI): 73 | postData += rq 74 | 75 | '''Request NLU service by HTTP POST''' 76 | req = urllib.request.Request(self.apiBaseUrl,postData.encode("utf-8")) 77 | with urllib.request.urlopen(req) as f: 78 | getResponse = f.read().decode('utf-8') 79 | 80 | 81 | '''Now you can check the status here.''' 82 | print("Sending 'POST' request to URL : " + self.apiBaseUrl) 83 | print("Post parameters : " + str(postData)) 84 | print("Response Code : " + str(f.getcode())) 85 | 86 | '''Get the response''' 87 | return str(getResponse) 88 | --------------------------------------------------------------------------------