├── .gitignore
├── .gitmodules
├── .travis.yml
├── .yamllint.yml
├── CONTRIBUTING.md
├── Dockerfile
├── LICENSE
├── MAINTAINERS.md
├── README-ja.md
├── README.md
├── cfcreds.env
├── doc
└── source
│ └── images
│ └── architecture.png
├── genTTStoken.js
├── handleIncomingSMS.js
├── identifyMsgLang.js
├── iotPub.py
├── scripts
└── resources.sh
├── sendSMS.js
├── setup.sh
├── test-requirements.txt
├── tests
├── test-flake8.sh
├── test-shellcheck.sh
└── test-yamllint.sh
└── translateText.js
/.gitignore:
--------------------------------------------------------------------------------
1 | cfcreds.env
2 |
3 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "openwhisk-package-mqtt-watson"]
2 | path = openwhisk-package-mqtt-watson
3 | url = https://github.com/kkbankol-ibm/openwhisk-package-mqtt-watson.git
4 | [submodule "language-translation-ui"]
5 | path = language-translation-ui
6 | url = https://github.com/IBM/language-translation-ui.git
7 |
8 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | ---
2 | language: python
3 | python: 2.7
4 | cache: pip
5 |
6 | matrix:
7 | fast_finish: true
8 |
9 | env:
10 | - TEST_RUN="echo Soon"
11 |
12 | before_install:
13 | - sudo apt-get install shellcheck
14 | - pip install -U -r test-requirements.txt
15 |
16 | install: true
17 |
18 | before_script:
19 | - "./tests/test-flake8.sh"
20 | - "./tests/test-shellcheck.sh"
21 | - "./tests/test-yamllint.sh"
22 |
23 | script: "$TEST_RUN"
24 |
25 | git:
26 | submodules: false
27 |
--------------------------------------------------------------------------------
/.yamllint.yml:
--------------------------------------------------------------------------------
1 | ---
2 | rules:
3 | braces:
4 | min-spaces-inside: 0
5 | max-spaces-inside: 0
6 | min-spaces-inside-empty: 0
7 | max-spaces-inside-empty: 0
8 | brackets:
9 | min-spaces-inside: 0
10 | max-spaces-inside: 0
11 | min-spaces-inside-empty: 0
12 | max-spaces-inside-empty: 0
13 | colons:
14 | max-spaces-before: 0
15 | max-spaces-after: 1
16 | commas:
17 | max-spaces-before: 0
18 | min-spaces-after: 1
19 | max-spaces-after: 1
20 | comments:
21 | require-starting-space: true
22 | min-spaces-from-content: 2
23 | comments-indentation: enable
24 | document-end: disable
25 | document-start:
26 | present: true
27 | empty-lines:
28 | max: 2
29 | max-start: 0
30 | max-end: 0
31 | hyphens:
32 | max-spaces-after: 1
33 | indentation:
34 | spaces: consistent
35 | indent-sequences: true
36 | check-multi-line-strings: false
37 | key-duplicates: enable
38 | line-length:
39 | max: 80
40 | allow-non-breakable-words: true
41 | allow-non-breakable-inline-mappings: true
42 | level: warning
43 | new-line-at-end-of-file: enable
44 | new-lines:
45 | type: unix
46 | trailing-spaces: enable
47 | truthy: enable
48 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | This is an open source project, and we appreciate your help!
4 |
5 | We use the GitHub issue tracker to discuss new features and non-trivial bugs.
6 |
7 | In addition to the issue tracker, [#journeys on
8 | Slack](https://dwopen.slack.com) is the best way to get into contact with the
9 | project's maintainers.
10 |
11 | To contribute code, documentation, or tests, please submit a pull request to
12 | the GitHub repository. Generally, we expect two maintainers to review your pull
13 | request before it is approved for merging. For more details, see the
14 | [MAINTAINERS](MAINTAINERS.md) page.
15 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM ubuntu:16.04
2 | RUN apt-get update -y && \
3 | apt-get install git curl -y
4 | RUN curl -fsSL https://clis.ng.bluemix.net/install/linux | sh
5 | COPY . /root/
6 | RUN . /root/cfcreds.env && \
7 | bx login -u ${CF_USERNAME} -p ${CF_PASSWORD} -a https://api.ng.bluemix.net && \
8 | bx plugin install cloud-functions -f
9 | RUN /root/setup.sh
10 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/MAINTAINERS.md:
--------------------------------------------------------------------------------
1 | # Maintainers Guide
2 |
3 | This guide is intended for maintainers - anybody with commit access to one or
4 | more Code Pattern repositories.
5 |
6 | ## Methodology
7 |
8 | This repository does not have a traditional release management cycle, but
9 | should instead be maintained as a useful, working, and polished reference at
10 | all times. While all work can therefore be focused on the master branch, the
11 | quality of this branch should never be compromised.
12 |
13 | The remainder of this document details how to merge pull requests to the
14 | repositories.
15 |
16 | ## Merge approval
17 |
18 | The project maintainers use LGTM (Looks Good To Me) in comments on the pull
19 | request to indicate acceptance prior to merging. A change requires LGTMs from
20 | two project maintainers. If the code is written by a maintainer, the change
21 | only requires one additional LGTM.
22 |
23 | ## Reviewing Pull Requests
24 |
25 | We recommend reviewing pull requests directly within GitHub. This allows a
26 | public commentary on changes, providing transparency for all users. When
27 | providing feedback be civil, courteous, and kind. Disagreement is fine, so long
28 | as the discourse is carried out politely. If we see a record of uncivil or
29 | abusive comments, we will revoke your commit privileges and invite you to leave
30 | the project.
31 |
32 | During your review, consider the following points:
33 |
34 | ### Does the change have positive impact?
35 |
36 | Some proposed changes may not represent a positive impact to the project. Ask
37 | whether or not the change will make understanding the code easier, or if it
38 | could simply be a personal preference on the part of the author (see
39 | [bikeshedding](https://en.wiktionary.org/wiki/bikeshedding)).
40 |
41 | Pull requests that do not have a clear positive impact should be closed without
42 | merging.
43 |
44 | ### Do the changes make sense?
45 |
46 | If you do not understand what the changes are or what they accomplish, ask the
47 | author for clarification. Ask the author to add comments and/or clarify test
48 | case names to make the intentions clear.
49 |
50 | At times, such clarification will reveal that the author may not be using the
51 | code correctly, or is unaware of features that accommodate their needs. If you
52 | feel this is the case, work up a code sample that would address the pull
53 | request for them, and feel free to close the pull request once they confirm.
54 |
55 | ### Does the change introduce a new feature?
56 |
57 | For any given pull request, ask yourself "is this a new feature?" If so, does
58 | the pull request (or associated issue) contain narrative indicating the need
59 | for the feature? If not, ask them to provide that information.
60 |
61 | Are new unit tests in place that test all new behaviors introduced? If not, do
62 | not merge the feature until they are! Is documentation in place for the new
63 | feature? (See the documentation guidelines). If not do not merge the feature
64 | until it is! Is the feature necessary for general use cases? Try and keep the
65 | scope of any given component narrow. If a proposed feature does not fit that
66 | scope, recommend to the user that they maintain the feature on their own, and
67 | close the request. You may also recommend that they see if the feature gains
68 | traction among other users, and suggest they re-submit when they can show such
69 | support.
70 |
--------------------------------------------------------------------------------
/README-ja.md:
--------------------------------------------------------------------------------
1 | *他の言語で読む: [English](README.md).*
2 |
3 | [](https://travis-ci.org/IBM/serverless-language-translation)
4 |
5 | # サーバーレスの多言語対応会議室をデプロイする
6 |
7 | このコードパターンでは、異なる国の言語を話すクライアントが互いに途切れなく意思疎通できる通信チャネルを作成する方法を提案します。OpenWhisk、Watson Text to Speech、Watson Language Translatorを使用した多言語チャットルームを作成します。
8 |
9 | このパターンは MQTT メッセージング・プロトコルを使用して、各クライアントが 1 つ以上のチャネルを「パブリッシュ」および「サブスクライブ」できるようにします。各クライアントがリクエストで使用した言語とペイロードのタイプは、チャネルの構成によって判別されます (例えば、fromClient/french/audio)。
10 |
11 | 呼び出されるクラウド関数の順序は、メッセージの送信先チャネルによって判別されます。例えば、メッセージを fromClient/english/audio に送信すると、Watson® Speech to Text サービスを通じて音声ペイロードが実行されて、その結果が翻訳サービスに転送されます。そして翻訳サービスによる結果が、すべての参加クライアントに配信されるという仕組みです。
12 |
13 | このコード・パターンをひと通り完了すると、以下の方法に関する理解が深まります。
14 |
15 | * IBM Cloud Functions のアクション/トリガーをデプロイする
16 | * Watson IoT Platform とやり取りする
17 | * Cloud Foundry アプリケーションをセットアップする
18 |
19 | 
20 |
21 | ## Flow
22 |
23 | 1. クライアントからメッセージを受信します。クライアントは Web ブラウザー、CLI、OpenWhisk アクション、SMS テキストなどです。
24 | 2. メッセージのペイロードに音声ファイルが含まれている場合は、音声がテキストに変換されます。
25 | 3. 変換されたテキストが、サポートされている他の言語に翻訳されます。
26 | 4. SMS からメッセージが送信された場合は、送信者の電話番号が etcd キー・バリュー型ストアに追加されます。この例では etcd を使用して、サブスクライバーの電話番号と言語のリストを保持します。また、調整可能な TTL 値を使用して、サブスクライバーが 300 秒以上会話に参加していない場合、そのサブスクライバーの電話番号を削除します。
27 | 5. 翻訳されたメッセージ/音声ストリームが MQTT ブローカー上のさまざまなチャネルにパブリッシュされると、MQTT ブローカーによってサブスクライブ済みクライアントにメッセージが配信されます。
28 |
29 | ## 含まれるコンポーネント
30 |
31 | * [OpenWhisk](https://console.ng.bluemix.net/openwhisk): 拡張性の高いサーバーレス環境でオンデマンドでコードを実行できます。
32 | * [Watson Text to Speech](https://www.ibm.com/watson/jp-ja/developercloud/text-to-speech.html): テキストから自然な音声を合成します。
33 | * [Watson Language Translator](https://www.ibm.com/watson/jp-ja/developercloud/language-translator.html): コンテンツのテキストを、ある言語から別の言語にリアルタイムで翻訳します。
34 |
35 | ## 利用した技術
36 |
37 | * [Messaging](https://developer.ibm.com/messaging/message-hub/): メッセージングは、マイクロサービスなどの緩やかに分離されたアーキテクチャパターンを使用する最新のアプリケーションにとって重要な技術です。
38 | * [Node.js](https://nodejs.org/): サーバー側のJavaScriptコードを実行するためのオープンソースのJavaScriptランタイム環境です。
39 | * [OpenWhisk](https://www.ibm.com/cloud-computing/bluemix/openwhisk): イベントに応答してコードを実行できるオープンソースのイベント駆動型プラットフォームです。 これはIBMクラウド機能の基盤技術です。
40 |
41 | # ビデオを観る
42 | [](https://www.youtube.com/watch?v=eXY0uh_SeKs)
43 |
44 | ## 前提条件
45 | ホストされたオファリングと対話するには、IBM Cloud CLIを事前にインストールする必要があります。 最新のCLIリリースは
46 | [こちら](https://console.bluemix.net/docs/cli/reference/bluemix_cli/download_cli.html#download_install) にあります。インストール用スクリプトは上記のリンクで管理されており、以下のいずれかのコマンドで実行できます。
47 |
48 | ```
49 | # Mac OSX
50 | curl -fsSL https://clis.ng.bluemix.net/install/osx | sh
51 |
52 | # Linux
53 | curl -fsSL https://clis.ng.bluemix.net/install/linux | sh
54 |
55 | # Powershell
56 | iex(New-Object Net.WebClient).DownloadString('https://clis.ng.bluemix.net/install/powershell')
57 | ```
58 | インストールが完了したら、バージョンを表示してCLIが動作していることを確認します
59 | ```
60 | bx -v
61 | ```
62 | "Cloud Functions" プラグインもインストールしてください
63 | ```
64 | bx plugin install Cloud-Functions -r Bluemix
65 | ```
66 |
67 | IBM Cloud Cliがすでにインストールされている場合、Cloud Functionsプラグインが最新のバージョンであることを確認してください
68 | ```
69 | bx plugin update cloud-functions
70 | ```
71 |
72 |
73 | # 手順
74 | 1. [サービスの作成](#1-create-services)
75 | 2. [MQTT Feed のデプロイ](#2-deploy-mqtt-feed)
76 | 3. [Actions のアップロード](#3-upload-actions)
77 | 4. [Triggers の作成](#4-create-triggers)
78 | 5. [Rules の作成](#5-create-rules)
79 | 6. [UI のデプロイ](#6-deploy-ui)
80 |
81 |
82 | ### 1. サービスの作成
83 |
84 | 必要な IBM Cloud サービスを作成します。
85 | - [Speech To Text](https://console.bluemix.net/catalog/services/speech-to-text)
86 | - [Text To Speech](https://console.bluemix.net/catalog/services/text-to-speech)
87 | - [Watson IoT Platform](https://console.bluemix.net/catalog/services/internet-of-things-platform)
88 | - [Watson Language Translator](https://console.bluemix.net/catalog/services/language-translator)
89 |
90 | SMS統合のため、次のサードパーティ・サービスを作成します。
91 |
92 | - [Twilio](https://console.bluemix.net/catalog/services/twilio-programmable-sms)
93 | - [Redis](https://console.bluemix.net/catalog/services/redis-cloud)
94 |
95 | 各サービスは、以下の手順でプロビジョニング(準備)できます。
96 |
97 | [https://console.bluemix.net/](https://console.bluemix.net/) の IBM Cloud ダッシュボードに移動し、右上の `Catalog` ボタンをクリックします。
98 |
99 |
100 |
101 |
102 | サービスの名前を入力し、結果欄のアイコンを選択します。
103 |
104 |
105 |
106 |
107 | 料金プランを選択して `Create` をクリックします。 IBM Liteアカウントに導入する場合は、無料の `Lite` プランを選択してください。
108 |
109 |
110 |
111 |
112 | #### 追加の設定: Watson IoTサービスの資格情報を生成する
113 |
114 | プロビジョニングされた後、Watson IoT Platformサービスは、ブローカに接続するための一連の資格情報を生成する必要があるため、追加の構成が必要になります。 IoT Platformダッシュボードに入り、左側のメニューから `DEVICE` を選択し `Add Device` ボタンをクリックしてください。
115 |
116 |
117 |
118 |
119 |
120 | 次に、デバイスタイプとIDを指定します。
121 |
122 |
123 |
124 |
125 | その後のいくつかのタブ(デバイス情報、グループ、セキュリティ)はデフォルト設定のままで大丈夫です。
126 |
127 |
128 |
129 |
130 |
131 | `Finish` ボタンをクリックすると、デバイスが登録され、メッセージをIoTプラットフォームに公開するために使用できる一連の認証情報が生成されます。デバイスのタイプとデバイスIDを記録し、両方を `cfcreds.env` ファイルに記載します。
132 |
133 | MQTT Brokerをパブリッシュしてサブスクライブできるようにするため、異なる資格証明セットを生成する必要があります。左のメニューで `APPS` オプションを選択し、次に `Generate API Key` ボタンをクリックします。
134 |
135 |
136 |
137 |
138 |
139 | `Information` 欄は空白のままにして次へ進みます。
140 | `Permissions` (権限)タブでは、`Backend Trusted Application` (バックエンドの信頼済みアプリケーション)ロールを選択します。選択後は `Generate Key` をクリック。
141 |
142 |
143 |
144 |
145 |
146 | その結果、APIキーと認証トークンが得られます。これらは、MQTTクライアントのユーザー名とパスワードとして使用します。設定を少し簡単にするには、これらの値を `IOT_API_KEY` および `IOT_APP_AUTH_TOKEN` として `cfcreds.env` ファイルに記載します。
147 |
148 |
149 |
150 |
151 |
152 | `IOT_ORG_ID`、`IOT_DEVICE_TYPE`、`IOT_DEVICE_ID`、`IOT_AUTH_TOKEN`、`IOT_API_TOKEN` の値は、cfcreds.env ファイルに記載したはずです。この例では、npm [mqtt.js](https://www.npmjs.com/package/mqtt) パッケージを使用しました。このパッケージは `npm install -g mqtt` でインストールすることができます。次に、MQTT publish/subscribe コマンドをテスト実行して、信任状が有効であることを確認します。
153 |
154 | 1つのタブでMQTTブローカーを登録する
155 | ```
156 | source cfcreds.env
157 | mqtt_sub -i "a:${IOT_ORG_ID}:test" -u "${IOT_API_KEY}" -P "${IOT_AUTH_TOKEN}" -h "${IOT_ORG_ID}.messaging.internetofthings.ibmcloud.com" -p 1883 -t "iot-2/type/${IOT_DEVICE_TYPE}/id/${IOT_DEVICE_ID}/evt/fromClient/fmt/json"
158 |
159 | ```
160 |
161 | そして、別のタブで公開する
162 | ```
163 | source cfcreds.env
164 | mqtt_pub -i "a:${IOT_ORG_ID}:client_pub" -u "${IOT_API_KEY}" -P "${IOT_AUTH_TOKEN}" -h 'agf5n9.messaging.internetofthings.ibmcloud.com' -p 1883 -t "iot-2/type/${IOT_DEVICE_TYPE}/id/${IOT_DEVICE_ID}/evt/fromClient/fmt/json" -m '{
165 | "d" : {
166 | "sourceLanguage" : "en",
167 | "payload" : "test",
168 | "client": "client1"
169 | }
170 | }'
171 | ```
172 |
173 |
174 | ### 2. MQTT Feed のデプロイ
175 |
176 | openwhisk-package-mqtt-watson サブモジュールにある [こちら](https://github.com/kkbankol-ibm/openwhisk-package-mqtt-watson) の MQTT Feedパッケージをインストールします。この "Feed" により、OpenWhiskは1つ以上のMQTTトピックをサブスクライブし、受信メッセージに応答してアクションを呼び出すことができます。フィードがIBM Cloud機能とどのように機能するかについては、これらの [ドキュメント](https://github.com/apache/incubator-openwhisk/blob/master/docs/feeds.md) を参照してください。
177 |
178 |
179 | ### 3. Actions のアップロード
180 | 次のコマンドを使用して、各 "Action" をCloud Functionsコードベースにアップロードします。
181 | ```
182 | bx wsk action create translateText translateText.js
183 | bx wsk action create sendSMS sendSMS.js
184 | bx wsk action create iotPub iotPub.py
185 | bx wsk action create handleIncomingSMS handleIncomingSMS.js
186 | ```
187 |
188 | 各 "Action" が作成された後、対応するサービスのデフォルトの資格情報を設定もしくはバインドします。
189 | ```
190 | # Most IBM Cloud native service credentials can be easily imported to a Cloud function using the "service bind" command
191 | # bx wsk service bind
192 | bx wsk service bind language_translator translateText
193 | bx wsk service bind language_translator handleIncomingSMS
194 |
195 |
196 | # Credentials for the Watson IoT Platform and third party services can be set using the "update command"
197 | # bx wsk action update -p
198 | bx wsk action update iotPub -p iot_org_id "${IOT_ORG_ID}" -p iot_device_id "${IOT_DEVICE_ID}" -p iot_device_type "${IOT_DEVICE_TYPE}" -p iot_auth_token "${IOT_AUTH_TOKEN}" -p iot_api_key "${IOT_API_KEY}"
199 | bx wsk action update sendSMS -p twilioNumber "${TWILIO_NUMBER}" -p twilioSid "${TWILIO_SID}" -p twilioAuthToken "${TWILIO_AUTH_TOKEN}" -p redisUsername "${REDIS_USER}" -p redisPassword "${REDIS_PASSWORD}" -p redisHost "${REDIS_HOST}" -p redisPort "${REDIS_PORT}"
200 | bx wsk action update handleIncomingSMS -p twilioNumber "${TWILIO_NUMBER}" -p twilioSid "${TWILIO_SID}" -p twilioAuthToken "${TWILIO_AUTH_TOKEN}" -p redisUsername "${REDIS_USER}" -p redisPassword "${REDIS_PASSWORD}" -p redisHost "${REDIS_HOST}" -p redisPort "${REDIS_PORT}"
201 | ```
202 |
203 |
204 | ### 4. Triggers の作成
205 | イベントを表現する各 "Trigger" を作成します。
206 | ```
207 | bx wsk trigger create audioMsgReceived
208 | bx wsk trigger create txtMsgReceived
209 | bx wsk trigger create SMSMsgReceived
210 | bx wsk trigger create msgTranslated
211 | ```
212 |
213 |
214 | ### 5. Rules の作成
215 | 特定の "Trigger" がアクティブになったときに "Action" を実行する各 "Rule" を作成します。
216 | ```
217 | # bx wsk rule create RULE_NAME TRIGGER_NAME ACTION_NAME
218 | bx wsk rule create handleTxtMessage txtMsgReceived translateText
219 | bx wsk rule create handleMQTTMessage mqttMsgReceived translateText
220 | bx wsk rule create publishtoIOT msgTranslated iotPub
221 | bx wsk rule create publishtoSMS msgTranslated sendSMS
222 | ```
223 |
224 | フィードがデプロイされ、"Rule" が確立されたら、以下のようにフィードに登録されたトピックにMQTTメッセージを送信してプロセスをテストします。
225 | ```
226 | source cfcreds.env
227 | mqtt_pub -i "a:${IOT_ORG_ID}:client_pub" -u "${IOT_API_KEY}" -P "${IOT_AUTH_TOKEN}" -h 'agf5n9.messaging.internetofthings.ibmcloud.com' -p 1883 -t "iot-2/type/${IOT_DEVICE_TYPE}/id/${IOT_DEVICE_ID}/evt/fromClient/fmt/json" -m '{
228 | "d" : {
229 | "sourceLanguage" : "en",
230 | "payload" : "test",
231 | "client": "client1"
232 | }
233 | }'
234 | ```
235 |
236 | このコマンドが発行されるとすぐに、一連のアクションとトリガーが呼び出されることが Cloud Functions のログで確認できるはずです。このログは [https://console.bluemix.net/openwhisk/dashboard](https://console.bluemix.net/openwhisk/dashboard) にアクセスするか、別のタブで `bx wsk activation poll` を実行することで表示できます 。
237 |
238 |
239 | ### 6. UI のデプロイ
240 |
241 | もしサーバー側のロジックだけが必要であれば、ここで手順は終了です。
242 |
243 | ただし、オプションで https://github.com/IBM/language-translation-ui で提供されるUIをデプロイできます。この UI は `IOT_ORG_ID`、`IOT_DEVICE_TYPE`、`IOT_DEVICE_ID`、`IOT_AUTH_TOKEN`、`IOT_API_TOKEN` の値が環境変数に定義されていることを期待して動作しますので、`cfcreds.env` ファイルをあらかじめ用意しておいてください。
244 |
245 | ```
246 | git clone https://github.com/IBM/language-translation-ui
247 | cd language-translation-ui
248 | npm install
249 | npm start
250 | ```
251 |
252 | npm startコマンドが成功すると、http://127.0.0.1:8080 でUIにアクセスできるはずです。
253 |
254 | ## 開発者向けノート
255 |
256 | Flow:
257 |
258 | - トピックへのJSONオブジェクトとして受信されたMQTTメッセージ `iot-2/type/'${deviceType}/id/${orgId}/evt/${eventName}/fmt/json`
259 | ```
260 | {
261 | client: "client_1234",
262 | payload: "hello",
263 | sourceLanguage: "en"
264 | }
265 | ```
266 |
267 | - トピックに関連付けられた "Trigger" は、メッセージのペイロード/言語をトランスレータの "Action" に転送します。
268 | - トランスレータ "Action" は、ループを介してメッセージペイロードを渡します。各アイテムは、元のメッセージが翻訳される言語です。翻訳が完了すると、別のトリガーが起動され、2つの他の「公開」Actionが同時に開始されます。
269 | - ある "Action" はすべてのMQTTクライアントに結果を公開します。
270 | - もう1つの "Action" は、RedisのSMS加入者番号/言語を検索し、結果をTwilio経由で送信します。
271 |
272 | # ライセンス
273 | [Apache 2.0](LICENSE)
274 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | *Read this in other languages: [日本語](README-ja.md).*
2 |
3 | [](https://travis-ci.org/IBM/serverless-language-translation)
4 |
5 | # Deploy a Serverless Multilingual Conference Room
6 |
7 | In this code pattern, we will create the workings for a multilingual chat room using OpenWhisk, Watson Text to Speech and Watson Language Translator. The MQTT messaging protocol is also leveraged, which allows each client to publish and subscribe to one or more channels. This repository contains a series of serverless functions which are called in sequence determined by the channel to which a message is submitted.
8 |
9 | When the reader has completed this code pattern, they will understand how to:
10 |
11 | * Deploy Cloud Function actions and triggers
12 | * Interact with the Watson IoT platform
13 | * Set up a CloudFoundry application
14 |
15 | 
16 |
17 | ## Flow
18 |
19 | 1. Message received from a client, which can be a web browser, CLI, OpenWhisk action, SMS text, etc.
20 | 2. If message payload contains an audio file, it is transcribed to text.
21 | 3. Transcribed text is translated to other supported languages.
22 | 4. If message is sent via SMS, sender phone number is added to an etcd key-value store. etcd is used here to maintain a list of subscribers’ phone numbers, as well as their respective languages. An adjustable TTL value is used here to remove numbers from the store if the subscriber does not participate in the conversation for 300 seconds.
23 | 5. Translated messages/audio streams are published to various channels on the MQTT broker, which then distributes the messages among subscribing clients.
24 |
25 | ## Included components
26 |
27 | * [IBM Cloud Functions](https://www.ibm.com/cloud/functions): Execute code on demand in a highly scalable, serverless environment.
28 | * [Watson Text to Speech](https://www.ibm.com/cloud/watson-text-to-speech): Converts written text into natural sounding audio in a variety of languages and voices.
29 | * [Watson Language Translator](https://www.ibm.com/cloud/watson-language-translator): Translate text from one language to another. Take text from across the globe and present it in the language of your choice.
30 |
31 | ## Featured technologies
32 |
33 | * [Messaging](https://developer.ibm.com/messaging/message-hub/): Messaging is a key technology for modern applications using loosely decoupled architecture patterns such as microservices.
34 | * [Node.js](https://nodejs.org/): An open-source JavaScript run-time environment for executing server-side JavaScript code.
35 | * [OpenWhisk](https://www.ibm.com/cloud-computing/bluemix/openwhisk): An open source event-driven platform that allows you to execute code in response to an event. This is the underlying technology for the IBM Cloud Functions offering
36 |
37 | # Watch the Video
38 | [](https://www.youtube.com/watch?v=eXY0uh_SeKs)
39 |
40 | ## Prerequisites:
41 | To interact with the hosted offerings, the IBM Cloud CLI will need to be installed beforehand. Instructions can be found [here](https://cloud.ibm.com/docs/cli?topic=cloud-cli-install-ibmcloud-cli).
42 |
43 | After installation is complete, confirm the CLI is working by printing the version
44 | ```
45 | ibmcloud -v
46 | ```
47 | And then install the "Cloud Functions" plugin with
48 | ```
49 | ibmcloud plugin install cloud-functions
50 | ```
51 |
52 | If the IBM Cloud CLI was already installed, please make sure the Cloud Functions plugin is the latest version with
53 | ```
54 | ibmcloud plugin update cloud-functions
55 | ```
56 |
57 |
58 | # Steps
59 | 1. [Create Services](#1-create-services)
60 | 2. [Deploy MQTT Feed](#2-deploy-mqtt-feed)
61 | 3. [Upload Actions](#3-upload-actions)
62 | 4. [Create Triggers](#4-create-triggers)
63 | 5. [Create Rules](#5-create-rules)
64 | 6. [Deploy UI](#6-deploy-ui)
65 |
66 | ### 1. Create Services
67 |
68 | Create the required IBM Cloud services.
69 | - [Speech To Text](https://cloud.ibm.com/catalog/services/speech-to-text)
70 | - [Text To Speech](https://cloud.ibm.com/catalog/services/text-to-speech)
71 | - [Watson IoT Platform](https://cloud.ibm.com/catalog/services/internet-of-things-platform)
72 | - [Watson Language Translator](https://cloud.ibm.com/catalog/services/language-translator)
73 |
74 | For SMS integration, create the following third party services.
75 | - [Twilio](https://cloud.ibm.com/catalog/services/twilio-programmable-sms)
76 | - [Redis](https://cloud.ibm.com/catalog/services/databases-for-redis)
77 |
78 | Each service can be provisioned with the following steps
79 |
80 | Navigate to the IBM Cloud dashboard at [https://cloud.ibm.com](https://cloud.ibm.com) and click the "Catalog" button in the upper right
81 |
82 |
83 |
84 |
85 | Type in the name of the service and select the resulting icon
86 |
87 |
88 |
89 |
90 | Select the pricing plan and click "Create". If deploying on an IBM Lite account, be sure to select the free "Lite" plan
91 |
92 |
93 |
94 |
95 | #### Additional Configuration: Generate Watson IoT service credentials
96 | After being provisioned, the Watson IoT Platform service will need a bit of additional configuration, as we'll need to generate a set of credentials for connecting to the broker. We can do so by entering the IoT Platform dashboard, selecting "Devices" from the left hand menu, and then clicking the "Add Device" button.
97 |
98 |
99 |
100 |
101 |
102 | Next, provide a device type and ID.
103 |
104 |
105 |
106 |
107 | The next few tabs (Device Information, Groups, Security) can be left as is with the default settings.
108 |
109 |
110 |
111 |
112 |
113 | Clicking the "Finish" button will register a device and generate a set of credentials that can be used to publish messages to the IoT Platform. Be sure to take note of the Device type and Device ID, and place both in the `cfcreds.env` file.
114 |
115 | We'll need to generate a different set of credentials to be able to publish and subscribe to the MQTT Broker
116 |
119 |
120 | We can do so by selecting the "Apps" option in the left hand menu. Then, click the "Generate API Key" button
121 |
122 |
123 |
124 |
125 | We can leave the fields in the "Information" blank and click next.
126 | In the "Permissions" tab, we'll select the "Backend Trusted Application" role. Once this is selected, click "Generate Key"
127 |
128 |
129 |
130 |
131 | The result will give us an API Key and Authentication Token. These can be supplied as the username and password for a MQTT client. To make setup a bit easier, place these values in the `cfcreds.env` file as IOT_API_KEY and IOT_APP_AUTH_TOKEN
132 |
133 |
134 |
135 |
136 | At this point, the values `IOT_ORG_ID`, `IOT_DEVICE_TYPE`, `IOT_DEVICE_ID`, `IOT_AUTH_TOKEN`, and `IOT_API_TOKEN` should be in the cfcreds.env file. In this example, we used the npm [mqtt.js](https://www.npmjs.com/package/mqtt) package, which can be installed with `npm install -g mqtt`. And then, we can run a sample MQTT publish/subscribe command to confirm that the credentials are valid.
137 |
138 | Subscribe to the MQTT broker in one tab
139 | ```
140 | source cfcreds.env
141 | mqtt_sub -i "a:${IOT_ORG_ID}:test" -u "${IOT_API_KEY}" -P "${IOT_AUTH_TOKEN}" -h "${IOT_ORG_ID}.messaging.internetofthings.ibmcloud.com" -p 1883 -t "iot-2/type/${IOT_DEVICE_TYPE}/id/${IOT_DEVICE_ID}/evt/fromClient/fmt/json"
142 |
143 | ```
144 |
145 | And then publish in another
146 | ```
147 | source cfcreds.env
148 | mqtt_pub -i "a:${IOT_ORG_ID}:client_pub" -u "${IOT_API_KEY}" -P "${IOT_AUTH_TOKEN}" -h 'agf5n9.messaging.internetofthings.ibmcloud.com' -p 1883 -t "iot-2/type/${IOT_DEVICE_TYPE}/id/${IOT_DEVICE_ID}/evt/fromClient/fmt/json" -m '{
149 | "d" : {
150 | "sourceLanguage" : "en",
151 | "payload" : "test",
152 | "client": "client1"
153 | }
154 | }'
155 | ```
156 |
157 | ### 2. Deploy MQTT Feed
158 |
159 | Install the MQTT package/feed found in the openwhisk-package-mqtt-watson submodule [here](https://github.com/kkbankol-ibm/openwhisk-package-mqtt-watson). This "feed" enables OpenWhisk to subscribe to one or more MQTT topics and invoke actions in response to incoming messages. To see more on how feeds work with IBM Cloud Functions, please visit these [documents](https://github.com/apache/incubator-openwhisk/blob/master/docs/feeds.md)
160 |
161 | ### 3. Upload Actions
162 | Upload each "Action" to the Cloud Functions codebase with the following commands.
163 | ```
164 | ibmcloud fn action create translateText translateText.js
165 | ibmcloud fn action create sendSMS sendSMS.js
166 | ibmcloud fn action create iotPub iotPub.py
167 | ibmcloud fn action create handleIncomingSMS handleIncomingSMS.js
168 | ```
169 |
170 | After each action is created, set or bind default credentials for the corresponding services.
171 | ```
172 | # Most IBM Cloud native service credentials can be easily imported to a Cloud function using the "service bind" command
173 | # ibmcloud fn service bind
174 | ibmcloud fn service bind language_translator translateText
175 | ibmcloud fn service bind language_translator handleIncomingSMS
176 |
177 |
178 | # Credentials for the Watson IoT Platform and third party services can be set using the "update command"
179 | # ibmcloud fn action update -p
180 | ibmcloud fn action update iotPub -p iot_org_id "${IOT_ORG_ID}" -p iot_device_id "${IOT_DEVICE_ID}" -p iot_device_type "${IOT_DEVICE_TYPE}" -p iot_auth_token "${IOT_AUTH_TOKEN}" -p iot_api_key "${IOT_API_KEY}"
181 | ibmcloud fn action update sendSMS -p twilioNumber "${TWILIO_NUMBER}" -p twilioSid "${TWILIO_SID}" -p twilioAuthToken "${TWILIO_AUTH_TOKEN}" -p redisUsername "${REDIS_USER}" -p redisPassword "${REDIS_PASSWORD}" -p redisHost "${REDIS_HOST}" -p redisPort "${REDIS_PORT}"
182 | ibmcloud fn action update handleIncomingSMS -p twilioNumber "${TWILIO_NUMBER}" -p twilioSid "${TWILIO_SID}" -p twilioAuthToken "${TWILIO_AUTH_TOKEN}" -p redisUsername "${REDIS_USER}" -p redisPassword "${REDIS_PASSWORD}" -p redisHost "${REDIS_HOST}" -p redisPort "${REDIS_PORT}"
183 | ```
184 |
185 | ### 4. Create Triggers
186 | Create `Triggers` to represent events.
187 | ```
188 | ibmcloud fn trigger create audioMsgReceived
189 | ibmcloud fn trigger create txtMsgReceived
190 | ibmcloud fn trigger create SMSMsgReceived
191 | ibmcloud fn trigger create msgTranslated
192 | ```
193 |
194 | ### 5. Create Rules
195 | Create `Rules`, which execute actions when certain triggers are activated.
196 | ```
197 | # ibmcloud fn rule create RULE_NAME TRIGGER_NAME ACTION_NAME
198 | ibmcloud fn rule create handleTxtMessage txtMsgReceived translateText
199 | ibmcloud fn rule create handleMQTTMessage mqttMsgReceived translateText
200 | ibmcloud fn rule create publishtoIOT msgTranslated iotPub
201 | ibmcloud fn rule create publishtoSMS msgTranslated sendSMS
202 | ```
203 |
204 | After the Feed has been deployed and the rules have been established, test the process by sending a MQTT message to the topic registered with the feed like so
205 | ```
206 | source cfcreds.env
207 | mqtt_pub -i "a:${IOT_ORG_ID}:client_pub" -u "${IOT_API_KEY}" -P "${IOT_AUTH_TOKEN}" -h 'agf5n9.messaging.internetofthings.ibmcloud.com' -p 1883 -t "iot-2/type/${IOT_DEVICE_TYPE}/id/${IOT_DEVICE_ID}/evt/fromClient/fmt/json" -m '{
208 | "d" : {
209 | "sourceLanguage" : "en",
210 | "payload" : "test",
211 | "client": "client1"
212 | }
213 | }'
214 | ```
215 |
216 | As soon as this command is published, we should be able to see a series of actions and triggers being called in the Cloud Functions logs. These logs can be viewed by visiting [https://cloud.ibm.com/openwhisk/dashboard](https://cloud.ibm.com/openwhisk/dashboard) or by running `ibmcloud fn activation poll` in a separate tab.
217 |
218 |
219 | ### 6. Deploy UI
220 |
221 | If all you need is the server side logic, you can stop here. But optionally, you can deploy the UI provided by https://github.com/IBM/language-translation-ui. Be sure to source the `cfcreds.env` file beforehand, as the UI expects the `IOT_ORG_ID`, `IOT_DEVICE_TYPE`, `IOT_DEVICE_ID`, `IOT_AUTH_TOKEN`, and `IOT_API_TOKEN` values to be set as environment variables
222 |
223 | ```
224 | git clone https://github.com/IBM/language-translation-ui
225 | cd language-translation-ui
226 | npm install
227 | npm start
228 | ```
229 |
230 | When the npm start command succeeds, you should be able to access the UI at http://127.0.0.1:8080
231 |
232 | ## Developer Notes
233 |
234 | Flow:
235 |
236 | - MQTT message received as JSON object to topic `iot-2/type/'${deviceType}/id/${orgId}/evt/${eventName}/fmt/json`
237 | ```
238 | {
239 | client: "client_1234",
240 | payload: "hello",
241 | sourceLanguage: "en"
242 | }
243 | ```
244 |
245 | - Trigger associated with topic forwards message payload/language to translator action.
246 | - Translator action passes message payload through a loop, where each item is a language that the original message will be translated to. After translation is complete, another trigger will be fired, which kicks off two other "publish" actions simultaneously.
247 | - One action publishes results to all MQTT clients
248 | - The other action looks up SMS subscriber numbers/language in Redis and sends them the result via Twilio.
249 |
250 |
255 |
256 | # Links
257 |
258 |
259 | ## License
260 | This code pattern is licensed under the Apache Software License, Version 2. Separate third party code objects invoked within this code pattern are licensed by their respective providers pursuant to their own separate licenses. Contributions are subject to the [Developer Certificate of Origin, Version 1.1](https://developercertificate.org/) and the [Apache License, Version 2](https://www.apache.org/licenses/LICENSE-2.0.txt).
261 |
262 | [Apache License FAQ](https://www.apache.org/foundation/license-faq.html#WhatDoesItMEAN)
263 |
--------------------------------------------------------------------------------
/cfcreds.env:
--------------------------------------------------------------------------------
1 | CF_USERNAME=
2 | CF_PASSWORD=
3 | IOT_ORG_ID=
4 | IOT_AUTH_TOKEN=
5 | IOT_API_KEY=
6 | IOT_DEVICE_TYPE=
7 | IOT_DEVICE_ID=
8 | TWILIO_SID=
9 | TWILIO_AUTH_TOKEN=
10 | TWILIO_NUMBER=
11 | REDIS_USER=
12 | REDIS_PASSWORD=
13 | REDIS_HOST=
14 | REDIS_PORT=
15 |
--------------------------------------------------------------------------------
/doc/source/images/architecture.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IBM/serverless-language-translation/ca8d8f2f0c189b00f6b570fd6452373e187d4c93/doc/source/images/architecture.png
--------------------------------------------------------------------------------
/genTTStoken.js:
--------------------------------------------------------------------------------
1 | /*Copyright 2018 IBM Corp. All Rights Reserved.
2 |
3 | Licensed under the Apache License, Version 2.0 (the "License");
4 | you may not use this file except in compliance with the License.
5 | You may obtain a copy of the License at
6 |
7 | http://www.apache.org/licenses/LICENSE-2.0
8 |
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 | // UI sends an empty message to this topic, action generates a text to speech token as a response
17 | // bound to MQTT channel
18 | // 'iot-2/type/MQTTDevice/id/965d11de/evt/tokenreq/fmt/json'
19 | var mqtt = require('mqtt')
20 | var watson = require('watson-developer-cloud')
21 | var ttsAuthorization = new watson.authorization({
22 | password: params.TTS_PASSWD,
23 | username: params.TTS_USERNAME,
24 | url: 'https://stream.watsonplatform.net/authorization/api/v1/token', //watson.TextToSpeechV1.URL
25 | version: 'v1'
26 | });
27 | var mqttClient = mqtt.connect(mqtt_broker, mqtt_options);
28 |
29 | function main(params) {
30 | ttsAuthorization.getToken({url: "https://stream.watsonplatform.net/text-to-speech/api"}, function (err, token) {
31 | if (!token) {
32 | console.log('error:', err);
33 | } else {
34 | console.log("sending token " + token.toString())
35 | mqttClient.publish('iot-2/type/MQTTDevice/id/965d11de/evt/token/fmt/json', token)
36 | }
37 | })
38 | return {payload: "TTS token generated"}
39 | }
40 |
--------------------------------------------------------------------------------
/handleIncomingSMS.js:
--------------------------------------------------------------------------------
1 | /*Copyright 2018 IBM Corp. All Rights Reserved.
2 |
3 | Licensed under the Apache License, Version 2.0 (the "License");
4 | you may not use this file except in compliance with the License.
5 | You may obtain a copy of the License at
6 |
7 | http://www.apache.org/licenses/LICENSE-2.0
8 |
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 | // executed as webaction
17 |
18 | // when SMS messages are received, we need to
19 | // add phone number as a subscriber for x seconds. if key already exists,
20 | // identify sender message language
21 | // forward message to translateText
22 | var bluebird = require('bluebird')
23 | var openwhisk = require('openwhisk')
24 | var redis = require('redis')
25 | bluebird.promisifyAll(redis.RedisClient.prototype)
26 |
27 | function main(params) {
28 | // get twilioSid and twilioAuthToken from
29 | // https://www.twilio.com/console
30 | var ow = openwhisk()
31 | var redisConfig = {
32 | user: params.redisUsername,
33 | password: params.redisPassword,
34 | host: params.redisHost,
35 | port: params.redisPort
36 | }
37 | var cursor = '0'
38 |
39 | var LanguageTranslatorV2 = require('watson-developer-cloud/language-translator/v2');
40 | if (params.__bx_creds && params.__bx_creds.language_translator) {
41 | config = {
42 | username: params.__bx_creds.language_translator.username,
43 | password: params.__bx_creds.language_translator.password,
44 | url: params.__bx_creds.language_translator.url,
45 | version: "v2",
46 | type: "bound_creds"
47 | }
48 | } else {
49 | config = {
50 | username: params.language_translator_username,
51 | password: params.language_translator_password,
52 | url: 'https://gateway.watsonplatform.net/language-translator/api/',
53 | version: "v2",
54 | type: "user_provided"
55 | }
56 | }
57 | var language_translator = new LanguageTranslatorV2(config)
58 | var redisClient = redis.createClient(redisConfig)
59 | // check kv for number.
60 | // if number isn't registered, identify language and add as key
61 | return redisClient.scanAsync(cursor, 'MATCH', "*" + params.From).then(
62 | function (res) {
63 | var keys = res[1]
64 | // if key exists in store
65 | return new Promise((resolve, reject) => {
66 | if (keys.length > 0) {
67 | // reset TTL
68 | var key = keys[0]
69 | redisClient.expire(key, 300)
70 | resolve(
71 | {
72 | payload: params.Body,
73 | client: "smsclient" + '_' + key.split(':')[1],
74 | senderNumber: params.From,
75 | sourceLanguage: key.split(':')[0]
76 | }
77 | )}
78 | else {
79 | language_translator.identify(
80 | {
81 | text: params.Body,
82 | headers: {
83 | 'X-Watson-Technology-Preview': '2017-07-01'
84 | }
85 | },
86 | function(err, languages) {
87 | if (err) {
88 | console.log('error:', err);
89 | } else {
90 | var key = languages['languages'][0].language + ':' + params.From
91 | redisClient.set(key, params.From)
92 | redisClient.expire(key, 300)
93 | resolve({
94 | payload: params.Body,
95 | client: "smsclient" + '_' + key.split(':')[1],
96 | senderNumber: params.From,
97 | sourceLanguage: key.split(':')[0]
98 | })
99 | }
100 | })
101 | }
102 | }).then(result => {
103 | return ow.triggers.invoke({
104 | name: 'msgReceived',
105 | params: result
106 | })
107 | })
108 | })
109 |
110 | }
111 |
--------------------------------------------------------------------------------
/identifyMsgLang.js:
--------------------------------------------------------------------------------
1 | /*Copyright 2018 IBM Corp. All Rights Reserved.
2 |
3 | Licensed under the Apache License, Version 2.0 (the "License");
4 | you may not use this file except in compliance with the License.
5 | You may obtain a copy of the License at
6 |
7 | http://www.apache.org/licenses/LICENSE-2.0
8 |
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 | // bound to MQTT channel
17 | // 'iot-2/type/MQTTDevice/id/965d11de/evt/fromClient/fmt/json'
18 |
19 | // TODO,
20 | // delete this and use whisk package instead
21 | // wsk action invoke myWatsonTranslator/languageId --blocking --result --param payload "Ciel bleu a venir"
22 |
23 | var msgJSON = (JSON.parse(params.message))
24 | console.log(msgJSON)
25 | var originLang = msgJSON.d.language
26 | var msgPayload = msgJSON.d.message
27 | var clientName = msgJSON.d.client
28 |
29 | var language_translator = watson.language_translator({
30 | username: params.language_translation_username,
31 | password: params.language_translation_password,
32 | version: 'v2'
33 | }
34 | )
35 |
36 | function main(params) {
37 | return new Promise(function(resolve, reject) {
38 | language_translator.identify({ text: msgPayload},
39 | function(err, identifiedLanguages) {
40 | if (err)
41 | console.log(err)
42 | else
43 | resolve({
44 | language: identifiedLanguages[0]
45 | });
46 | })
47 | })
48 | }
49 |
--------------------------------------------------------------------------------
/iotPub.py:
--------------------------------------------------------------------------------
1 | # Copyright 2018 IBM Corp. All Rights Reserved.
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
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 requests
16 |
17 | HOST = 'messaging.internetofthings.ibmcloud.com'
18 | PORT = 1883
19 | PATH = '.' + HOST + ':' + PORT + '/api/v0002/application/types/'
20 |
21 |
22 | def main(dict):
23 | iot_org_id = dict['iot_org_id']
24 | iot_device_id = dict['iot_device_id']
25 | iot_device_type = dict['iot_device_type']
26 | iot_auth_token = dict['iot_auth_token']
27 | iot_api_key = dict['iot_api_key']
28 | requests.post('http://' + iot_org_id + PATH + iot_device_type +
29 | '/devices/' + iot_device_id + '/events/toClients',
30 | headers={'Content-Type': 'application/json'},
31 | json={
32 | 'payload': dict['payload'],
33 | 'client': dict['client'],
34 | 'language': dict['language'] or dict['sourceLanguage']},
35 | auth=(iot_api_key, iot_auth_token))
36 | return {'msg': dict['payload']}
37 |
--------------------------------------------------------------------------------
/scripts/resources.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # This script contains functions used by many of the scripts found in scripts/
4 | # and tests/.
5 |
6 | test_failed(){
7 | echo -e >&2 "\033[0;31m$1 test failed!\033[0m"
8 | exit 1
9 | }
10 |
11 | test_passed(){
12 | echo -e "\033[0;32m$1 test passed!\033[0m"
13 | }
14 |
15 | is_pull_request(){
16 | if [[ "$TRAVIS_PULL_REQUEST" != "false" ]]; then
17 | echo -e "\033[0;33mPull Request detected; not running $1!\033[0m"
18 | exit 0
19 | fi
20 | }
21 |
--------------------------------------------------------------------------------
/sendSMS.js:
--------------------------------------------------------------------------------
1 | /*Copyright 2018 IBM Corp. All Rights Reserved.
2 |
3 | Licensed under the Apache License, Version 2.0 (the "License");
4 | you may not use this file except in compliance with the License.
5 | You may obtain a copy of the License at
6 |
7 | http://www.apache.org/licenses/LICENSE-2.0
8 |
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 | // called after "msgTranslated trigger is fired
17 | function main(params) {
18 | // get twilioSid and twilioAuthToken from
19 | // https://www.twilio.com/console
20 | const twilioClient = require('twilio')(params.twilioSid, params.twilioAuthToken)
21 | var redis = require('redis')
22 | const bluebird = require('bluebird')
23 | var cursor = '0'
24 |
25 | bluebird.promisifyAll(redis.RedisClient.prototype);
26 |
27 | var redisConfig = {
28 | user: params.redisUsername,
29 | password: params.redisPassword,
30 | host: params.redisHost,
31 | port: params.redisPort
32 | }
33 | const redisClient = redis.createClient(redisConfig)
34 |
35 | function sendSMS(recipient) {
36 | twilioClient.messages.create({
37 | to: recipient,
38 | from: params.twilioNumber,
39 | body: params.payload,
40 | }, function(err, message) {
41 | if (err) {
42 | console.log('error:', err);
43 | }
44 | else {
45 | console.log(message);
46 | }
47 | })
48 | }
49 |
50 | // loop through all SMS clients subscribed to given language, text translation result
51 | redisClient.scanAsync(cursor, 'MATCH', params.language + ":*").then(
52 | function (res) {
53 | var keys = res[1]
54 | for (key in keys) {
55 | redisClient.getAsync(keys[key]).then(
56 | function(number) {
57 | if ((params.senderNumber) && (params.senderNumber == number)) {
58 | console.log("skipping")
59 | } else{
60 | console.log("sending text to " + number)
61 | sendSMS(number)
62 | }
63 | })
64 | }
65 | })
66 | }
67 |
--------------------------------------------------------------------------------
/setup.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | source cfcreds.env
3 |
4 | echo "Deploy Cloud Functions"
5 | bx wsk action create translateText translateText.js
6 | bx wsk action create sendSMS sendSMS.js
7 | bx wsk action create iotPub iotPub.py
8 | bx wsk action create handleIncomingSMS handleIncomingSMS.js
9 |
10 | echo "Import service credentials to corresponding Cloud Functions"
11 | bx wsk service bind language_translator translateText
12 | bx wsk service bind language_translator handleIncomingSMS
13 | bx wsk action update iotPub -p iot_org_id "${IOT_ORG_ID}" -p iot_device_id "${IOT_DEVICE_ID}" -p iot_device_type "${IOT_DEVICE_TYPE}" -p iot_auth_token "${IOT_AUTH_TOKEN}"
14 | bx wsk action update sendSMS -p twilioNumber "${TWILIO_NUMBER}" -p twilioSid "${TWILIO_SID}" -p twilioAuthToken "${TWILIO_AUTH_TOKEN}" -p redisUsername "${REDIS_USER}" -p redisPassword "${REDIS_PASSWORD}" -p redisHost "${REDIS_HOST}" -p redisPort "${REDIS_PORT}"
15 | bx wsk action update handleIncomingSMS -p twilioNumber "${TWILIO_NUMBER}" -p twilioSid "${TWILIO_SID}" -p twilioAuthToken "${TWILIO_AUTH_TOKEN}" -p redisUsername "${REDIS_USER}" -p redisPassword "${REDIS_PASSWORD}" -p redisHost "${REDIS_HOST}" -p redisPort "${REDIS_PORT}"
16 |
17 |
18 | echo "Create Triggers"
19 | bx wsk trigger create audioMsgReceived
20 | bx wsk trigger create txtMsgReceived
21 | bx wsk trigger create SMSMsgReceived
22 | bx wsk trigger create msgTranslated
23 |
24 | echo "Create Rules"
25 | # bx wsk rule create RULE_NAME TRIGGER_NAME ACTION_NAME
26 | bx wsk rule create handleTxtMessage txtMsgReceived translateText
27 | bx wsk rule create handleMQTTMessage mqttMsgReceived translateText
28 | bx wsk rule create publishtoIOT msgTranslated iotPub
29 | bx wsk rule create publishtoSMS msgTranslated sendSMS
30 |
--------------------------------------------------------------------------------
/test-requirements.txt:
--------------------------------------------------------------------------------
1 | flake8
2 | yamllint
3 |
--------------------------------------------------------------------------------
/tests/test-flake8.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash -e
2 |
3 | # shellcheck disable=SC1090
4 | source "$(dirname "$0")"/../scripts/resources.sh
5 |
6 | num_proc=$(grep processor /proc/cpuinfo | tail -1 | cut -d ' ' -f2)
7 | ((num_proc++))
8 |
9 | #shellcheck disable=SC2046,SC2086
10 | if flake8 --jobs="$num_proc" --show-source --statistics $(dirname $0)/../.; then
11 | test_passed "$0"
12 | else
13 | test_failed "$0"
14 | fi
15 |
--------------------------------------------------------------------------------
/tests/test-shellcheck.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash -e
2 |
3 | # shellcheck disable=SC1090
4 | source "$(dirname "$0")"/../scripts/resources.sh
5 |
6 | if find . -name '*.sh' -print0 | xargs -n1 -0 shellcheck -x -s bash; then
7 | test_passed "$0"
8 | else
9 | test_failed "$0"
10 | fi
11 |
--------------------------------------------------------------------------------
/tests/test-yamllint.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash -e
2 |
3 | # shellcheck disable=SC1090
4 | source "$(dirname "$0")"/../scripts/resources.sh
5 |
6 | if find . \( -name '*.yml' -o -name '*.yaml' \) -print0 | xargs -n1 -0 yamllint -c .yamllint.yml; then
7 | test_passed "$0"
8 | else
9 | test_failed "$0"
10 | fi
11 |
--------------------------------------------------------------------------------
/translateText.js:
--------------------------------------------------------------------------------
1 | /*Copyright 2018 IBM Corp. All Rights Reserved.
2 |
3 | Licensed under the Apache License, Version 2.0 (the "License");
4 | you may not use this file except in compliance with the License.
5 | You may obtain a copy of the License at
6 |
7 | http://www.apache.org/licenses/LICENSE-2.0
8 |
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 | // translate incoming message to all supported languages
17 | //
18 | // bound to MQTT channel
19 | // 'iot-2/type/MQTTDevice/id/965d11de/evt/txtFromClient/fmt/json'
20 |
21 | // expects params for payload, language, and translation creds
22 | var LanguageTranslatorV2 = require('watson-developer-cloud/language-translator/v2');
23 | var openwhisk = require('openwhisk')
24 |
25 | function main(params) {
26 | var ow = openwhisk();
27 | if (params.body && JSON.parse(params.body).d) {
28 | msgVals = JSON.parse(params.body).d
29 | } else {
30 | msgVals = params
31 | }
32 |
33 | if (params.__bx_creds && params.__bx_creds.language_translator) {
34 | config = {
35 | username: params.__bx_creds.language_translator.username,
36 | password: params.__bx_creds.language_translator.password,
37 | url: params.__bx_creds.language_translator.url,
38 | version: "v2",
39 | type: "bound_creds"
40 | }
41 | } else {
42 | config = {
43 | username: params.language_translator_username,
44 | password: params.language_translator_password,
45 | url: 'https://gateway.watsonplatform.net/language-translator/api/',
46 | version: "v2",
47 | type: "user_provided"
48 | }
49 | }
50 | var language_translator = new LanguageTranslatorV2(config)
51 | // var languages = ['ar', 'es', 'fr', 'en', 'it', 'de', 'pt']
52 | var supportedLanguages = ['es', 'fr', 'en']
53 | var languages = supportedLanguages.filter(
54 | function(lang) {
55 | return lang != msgVals.sourceLanguage
56 | });
57 | var translations = languages.map(function (targetLanguage) {
58 | return new Promise((resolve, reject) => {
59 | language_translator.translate(
60 | {
61 | text: msgVals.payload,
62 | source: msgVals.sourceLanguage,
63 | target: targetLanguage,
64 | headers: {
65 | 'X-Watson-Technology-Preview': '2017-07-01'
66 | }
67 | },
68 | function(err, translation) {
69 | if (err) {
70 | console.log('error:', err);
71 | } else {
72 | console.log("translation complete");
73 | resolve(translation['translations'][0])
74 | }
75 | }
76 | )
77 | }).then(result =>
78 | ow.triggers.invoke({
79 | name: 'msgTranslated',
80 | params: {
81 | payload: result.translation,
82 | client: msgVals.client,
83 | language: targetLanguage
84 | }
85 | })
86 | )
87 | })
88 |
89 | translations.push(
90 | ow.actions.invoke({
91 | name: 'iotPub',
92 | params: {
93 | payload: msgVals.payload,
94 | client: msgVals.client,
95 | language: msgVals.sourceLanguage
96 | }
97 | })
98 | )
99 | return Promise.all(translations).then(function (results) {
100 | console.log(results);
101 | return resolve({payload: "Translations complete"});
102 | });
103 | }
104 |
--------------------------------------------------------------------------------