<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andrew Rapo on Medium]]></title>
        <description><![CDATA[Stories by Andrew Rapo on Medium]]></description>
        <link>https://medium.com/@andrew.rapo?source=rss-fa4b7766dc10------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*tDvo9_1WS-Xrzeoh_Z_7wA.jpeg</url>
            <title>Stories by Andrew Rapo on Medium</title>
            <link>https://medium.com/@andrew.rapo?source=rss-fa4b7766dc10------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:13:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andrew.rapo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Nodejs Microservice Template for Rapid Prototyping]]></title>
            <link>https://medium.com/@andrew.rapo/a-nodejs-microservice-template-36f080fe1418?source=rss-fa4b7766dc10------2</link>
            <guid isPermaLink="false">https://medium.com/p/36f080fe1418</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[microservice-template]]></category>
            <category><![CDATA[prototyping]]></category>
            <dc:creator><![CDATA[Andrew Rapo]]></dc:creator>
            <pubDate>Tue, 14 Jun 2022 00:40:50 GMT</pubDate>
            <atom:updated>2022-06-14T11:41:10.886Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttEM6aA42heaA7hQvd3T3g.png" /></figure><p>The template described in this article would be a good starting point for any application, including commercial services destined for AWS or Azure. But it is lightweight enough to be used for quick experiments and prototypes served by, say, a Raspberry Pi. And it is simple enough to be used and customized by developers with limited back-end experience.</p><p>Key features include:</p><ul><li>An <em>express</em> Web server</li><li>A <em>ws</em> WebSocketServer</li><li>Protocol upgrade for url-based socket connections</li><li>JWT authentication and permission management</li><li>A mock JWT authentication handler (auth server)</li><li>A mini dynamic Web site handler (using <em>Handlebars</em> templates and <em>Bootstrap 5</em>)</li><li>Packaging with <em>webpack</em></li><li>A node cli client for testing socket connections</li><li>A Dockerfile for easy container deployment</li></ul><p>The microservice architecture is described in described in Figure 1:</p><figure><img alt="Figure 1 — Microservice Architecture" src="https://cdn-images-1.medium.com/max/1024/1*BYW3i_JKdnUIiZshxzxmnA.png" /><figcaption>Figure 1 — Microservice Architecture</figcaption></figure><h4>Install, Build and Start</h4><p>You can get the microservice template running in just a few steps. First, clone the <a href="https://github.com/wwlib/microservice-template">microservice-template repo</a> (on github)</p><pre>git clone <a href="/service/mailto:git@github.com">git@github.com</a>:wwlib/microservice-template.git</pre><p>Then install, build and start:</p><pre>cd microservice-template<br>npm install<br>npm run build<br>npm run start</pre><p>You should see a message like this indicating that the service is running on port 8000:</p><pre>&gt; microservice-template@0.0.1 start /Users/andrewrapo/github/wwlib/microservice-template<br>&gt; node -r dotenv/config dist/index.js</pre><pre>(USE_AUTH !== true) so NOT using mock JWT auth.<br>HTTP/WS server is ready and listening at port 8000!</pre><p>Note: By default, JWT auth is disabled. This is fine for now. See the instructions for turning it the section below about <em>Authentication and Permissions</em>.</p><h4>Testing with Curl</h4><p>The easiest way to test the service is by using Curl from a terminal window. The following curl command will make a POST request to <a href="http://localhost:8000/post">http://localhost:8000/post</a>:</p><pre>curl --location --request POST &#39;<a href="http://localhost:8000/post&#39;">http://localhost:8000/post&#39;</a> \<br>     --header &#39;Content-Type: application/json&#39; \<br>     --data-raw &#39;{<br>       &quot;utterance&quot;: &quot;hello&quot;<br>     }&#39;</pre><p>The default/example response from the server is to echo the input data along with a status message and the current userId if authentication is enabled:</p><pre>{&quot;status&quot;:&quot;OK&quot;,&quot;utterance&quot;:&quot;hello&quot;,&quot;userId&quot;:&quot;&quot;}</pre><p>See more about this response in the section below about HTTP Handlers</p><h4>Testing with the Browser</h4><p>Entering this URL into your browser, <a href="http://localhost:8000/get?utterance=greetings">http://localhost:8000/get?utterance=greetings</a> , will make a GET request to the service and similarly return:</p><pre>{&quot;status&quot;:&quot;OK&quot;,&quot;utterance&quot;:&quot;greetings&quot;,&quot;userId&quot;:&quot;&quot;}</pre><h4>Testing with the Socket CLI Client</h4><p>You can also test the service using the node socket cli in the tools folder:</p><pre>cd tools<br>node socket-cli.js</pre><p>This will start a socket session. Anything you type at the “&gt;” prompt will be echoed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2Fns1CKWfSlcdo_u7zTKg.png" /><figcaption>Figure 2 — Socket CLI for Testing</figcaption></figure><h4>Testing using the embedded Web Site</h4><p>The microservice-template serves a simple Web site with a few default routes.</p><p><strong>Dashboard</strong></p><p>The default route serves a placeholder Dashboard: <a href="http://localhost:8000/">http://localhost:8000/</a></p><p>Also: <a href="http://localhost:8000/dashboard/">http://localhost:8000/dashboard/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1LKP84e_iw2iXRmDhexyQ.png" /><figcaption>Figure 3 — Placeholder Dashboard</figcaption></figure><p>The example Dashboard displays one real stat: the number of requests made the the service. The Activity graph displays a set of fake/placeholder values that are generated on the server. The Events table is a static placeholder.</p><p><strong>Console</strong></p><p>The example console accepts commands that can control the service. One example command is implemented. Typing “reset” into the command field and clicking the Submit button will reset the counter (on the server) keeping track of the number of requests that have been made. If you then return to the Dashboard you will see that the Request Count stat has been reset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVixjHOzwBUoSAFMUMMF0A.png" /><figcaption>Figure 4 — Example Command Console</figcaption></figure><h4>Authentication and Permissions</h4><p>The microservice -template uses a JWT (JSON Web Token) mechanism for managing authentication and permissions (authorization). JWT is a widely used auth mechanism because it is ‘stateless’ — i.e. it does not require session data to be maintained by the server. Session data, like permissions, is maintained in an <em>access token</em> which is included in the header of all requests to the microservice. When auth is enabled, requests to the microservice are scrutinized before processing the transaction. The access token is decoded and validated using a secret key known only to the microservice. Then the permissions specified in the payload of the decoded token are compared to the permissions required by the service for each transaction type. If the token is valid AND contains the required permissions, the transaction is allowed and a response is sent to the client. Otherwise an error response is returned.</p><p>To communicate successfully with the microservice, a client — i.e. a Web page — must first sign in and get an access token. Usually, a client will send username/password credentials to an auth service, get a token, and then use that token to make requests to the microservice. The microservice then checks with the auth service to validate the client’s token before fulfilling the request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L82aGDbbx68HtrLWeKU-NA.png" /><figcaption>Figure 5 — Typical Standalone Auth Service</figcaption></figure><p>To keep this example as simple as possible, the microservice-template acts as its own auth server via its <em>/auth</em> route.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K88WKipLyVX6LYrX5ZzTgQ.png" /><figcaption>Figure 6 — Mock Auth Service</figcaption></figure><p>To see the JWT auth in action, copy .<em>env-example</em> to <em>.env</em> and make sure the <em>USE_AUTH</em> property is set to true (USE_AUTH=true)</p><pre>SERVER_PORT=8000<br>USE_AUTH=true</pre><p>Then start the service and make sure you see, <em>using mock JWT auth</em>.</p><pre>$ npm run start</pre><pre>&gt; microservice-template@0.0.1 start /[...]/microservice-template<br>&gt; node -r dotenv/config dist/index.js</pre><pre>(USE_AUTH === true) so using mock JWT auth.<br>HTTP/WS server is ready and listening at port 8000!</pre><p>Now go to <a href="http://localhost:8000/">http://localhost:8000</a> which should redirect to the signin page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GdUk80VmlqjesTQSF38HZQ.png" /><figcaption>Figure 7 — Signin Page</figcaption></figure><p>Enter any username and password (the mock JWT auth will accept any credentials) and you should be redirected to the dashboard page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1LKP84e_iw2iXRmDhexyQ.png" /><figcaption>Figure 8 — Default Page (Dashboard)</figcaption></figure><p>There is a fair amount going on to make this work. The call to /auth returns an <em>access</em> token which gets saved as an HTTP-only cookie in the browser. This cookie is called <em>access_token</em>. A second <em>refresh</em> token is also returned and saved in a cookie called <em>refresh_token</em>. The access_token cookie is set to expire in 1 minute. When it does expire, the refresh token will be used to request a new access token. The refresh token has a longer life, 1 day, and will be remembered even if the browser is closed. If both the access token and the refresh token expire, the user will be prompted to sign in again. There are many examples and tutorials online that provide a more detailed explanation. A couple of good ones include:</p><ul><li><a href="https://dev.to/franciscomendes10866/using-cookies-with-jwt-in-node-js-8fn">Using Cookies with JWT in Node.js</a></li><li><a href="https://indepth.dev/posts/1382/localstorage-vs-cookies">LocalStorage vs. Cookies: All You Need to Know About Storing JWT Tokens Securely in the Front-End</a></li></ul><p>You can get an access token using curl:</p><pre>curl --location --request POST &#39;<a href="http://localhost:8000/auth&#39;">http://localhost:8000/auth&#39;</a> \<br>     --header &#39;Content-Type: application/json&#39; \<br>     --data-raw &#39;{<br>       &quot;username&quot;: &quot;user1&quot;,<br>       &quot;password&quot;: &quot;12345!&quot;<br>     }&#39;</pre><p>If you make a POST request to <em>/auth </em>using Postman you will get a payload that includes bot the <em>access_token</em> and the <em>refresh_token</em>:</p><pre>{&quot;message&quot;:&quot;Logged in successfully.&quot;,&quot;access_token&quot;:&quot;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyMSIsImF1dGgiOnsicGVybWlzc2lvbnMiOlt7InNjb3BlcyI6WyJyZWFkIl0sInJlc291cmNlIjoiZXhhbXBsZSJ9XX0sImlhdCI6MTY1NTE1MzIwMiwiZXhwIjoxNjU1MTUzMjYyfQ.L7H7ivCKP0C8lVWqcGdKAY6DRaooowb44V7XUI_bBfA&quot;,&quot;refresh_token&quot;:&quot;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyMSIsImlhdCI6MTY1NTE1MzIwMiwiZXhwIjoxNjU1MjM5NjAyfQ.tIbZOehAHw_pDx4KneC7YlSSIC6pPaWnpxu9ArDD0pM&quot;,&quot;user_id&quot;:&quot;user1&quot;}</pre><p>You can then use the access token in Postman to make an authenticated request. For example: <a href="http://localhost:8000/get?utterance=hello"><em>http://localhost:8000/get?utterance=hello</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXcECXKRlFCujfoMUy1O1Q.png" /><figcaption>Figure 9 — Postman Authenticated GET</figcaption></figure><h4>JWT.io</h4><p>To get a better look at the way tokens are managed, you can go to <a href="https://jwt.io/">https://jwt.io/</a> and paste the access_token into the <em>Encoded</em> field:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqF9huhFok6u3AAb8J9hwQ.png" /><figcaption>Figure 10 — JWT.io Decoded Token</figcaption></figure><p>The decoded token includes the permissions that are used by the express auth function (in ExpressAuthFunctions.ts). When the routes are added (in index.ts) a list of required premissions can be included for each route. To illustrate, several of the protected routes have <em>example:read</em> in their permissions list (see Figure 11, below). This means that the permissions object in the decoded access token must include the <em>read</em> scope for the resource named, <em>example</em>. In a more complex service, there would be multiple resources with multiple scopes. These are defined by the service author.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQ8ehKqMn0qu_izmBZM1sA.png" /><figcaption>Figure 11 — Protected Route Permissions</figcaption></figure><h4>Source Code</h4><p>Figure 12 shows a map of the microservice source code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71hCEyErwpXPYUNdEV_rOw.png" /><figcaption>Figure 12 — Source Code Map</figcaption></figure><p><strong>HTTP Handlers</strong></p><p>As demonstrated above, the HTTP example handlers (<a href="https://github.com/wwlib/microservice-template/blob/main/src/handlers/ExampleHandlers.ts">ExampleHandlers.ts</a>) implement routes for GET and POST requests. The <em>/get</em> route handles GET requests where parameters are encoded in the query string, like: <a href="http://localhost:8000/get?utterance=hello">http://localhost:8000/get?utterance=hello</a> The response is a JSON object that echos the utterance parameter and includes the signed-in user id if it is available. The /post route handles POST requests where the parameters are included in the request body.</p><p><strong>Socket Handlers</strong></p><p>As demonstrated above, the example socket handlers (<a href="https://github.com/wwlib/microservice-template/blob/main/src/handlers/WsExampleHandlers.ts">WsExampleHandlers.ts</a>) includes an implementation of a route, <em>/ws-echo</em>, which opens a socket connection that echos any messages it receives.</p><p><strong>Site Handlers</strong></p><p>As demonstrated above, the example site handers (<a href="https://github.com/wwlib/microservice-template/blob/main/src/handlers/site/SiteHandlers.ts">site/SiteHandler.ts</a>) implement the handlers that serve the <a href="https://github.com/wwlib/microservice-template/blob/main/src/handlers/site/dashboard.handlebars.html"><em>/dashboard</em></a>, <a href="https://github.com/wwlib/microservice-template/blob/main/src/handlers/site/console.handlebars.html"><em>/console</em></a> and <a href="https://github.com/wwlib/microservice-template/blob/main/src/handlers/site/signin.handlebars.html"><em>/signin</em></a> page routes. These pages are dynamically rendered using <a href="https://www.npmjs.com/package/handlebars">Handlebars</a> templates which include variables and expressions that are evaluated at render time.</p><p><strong>Client Auth (JWT)</strong></p><p>As described above, the express auth functions (<a href="https://github.com/wwlib/microservice-template/blob/main/src/auth/ExpressAuthFunctions.ts">EspressAuthFunctions.ts</a>) are used to protect certain routes by validating the access_token and checking to make sure that any required permissions are granted in the token.</p><p><strong>Auth Server (JWT)</strong></p><p>The mock auth handlers (<a href="https://github.com/wwlib/microservice-template/blob/main/src/handlers/mockAuth/MockAuthHandlers.ts">MockAuthHandlers.ts</a> + <a href="https://github.com/wwlib/microservice-template/blob/main/src/auth/JwtAuth.ts">JwtAuth.ts</a>) implement the <em>/auth</em> route used by the signin page to get an access token.</p><p><strong>Docker</strong></p><p>The <a href="https://github.com/wwlib/microservice-template/blob/main/Dockerfile">Dockerfile</a> used to build and run a containerized version of the microservice-template using the following npm commands:</p><pre>npm run docker:build</pre><pre>npm run docker:run</pre><p><strong>Util Wrappers</strong></p><p>The express route wrapper (<a href="https://github.com/wwlib/microservice-template/blob/main/src/util/ExpressRouterWrapper.ts">ExpressRouterWrapper.ts</a>) provides convenience functions that make it easy to set up protected HTTP routes.</p><p>The socket server wrapper (<a href="https://github.com/wwlib/microservice-template/blob/main/src/util/WebSocketServerWrapper.ts">WebSocketServerWrapper.ts</a>) provides convenience function for setting up protected socket routes.</p><p><strong>Tools</strong></p><p>The socket-cli.js tool is used to test the microservice-template’s socket connection — with or without authentication.</p><h4>Customization (i.e. Time Server)</h4><p>As its name implies, the microservice-template project is only a starting point. The project is designed to make customization easy. As a quick example, the steps to add a time server feature (route) would be:</p><p>Add a <em>/time</em> handler (i.e. handlers/TimeHandler.ts) like:</p><pre>import { Request, Response } from &#39;express&#39;<br>import { StatusCodes } from &#39;http-status-codes&#39;</pre><pre>export const TimeHandler = (req: Request, res: Response) =&gt; {<br>  const time = new Date().toLocaleString()<br>  res.status(StatusCodes.OK).json({ time })<br>}</pre><p>Add an export to <em>handlers/index.ts</em></p><pre>export * from &#39;./TimeHandler&#39;</pre><p>Add a <em>/time</em> route to the main <em>/index.ts</em></p><pre>expressRouterWrapper.addGetHandler(&#39;/time&#39;, handlers.TimeHandler, [&#39;example:read&#39;])</pre><p>Rebuild and restart the service:</p><pre>npm run build<br>npm run start</pre><p>The new <a href="http://localhost:8000/time">http://localhost:8000/time</a> route should return the current time, for example:</p><pre>{&quot;time&quot;:&quot;6/13/2022, 8:10:28 PM&quot;}</pre><p>For another customization example see: <a href="https://medium.com/p/274eef3fc669/edit">Using Microsoft Orchestrator for Intent Recognition and Dispatch to Luis</a></p><h4>Conclusion</h4><p>The <a href="https://github.com/wwlib/microservice-template">microservice-template</a> is an easy-to-customize starting point for a service that may start out as a rapid prototype but grow into something more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36f080fe1418" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Microsoft Orchestrator for Intent Recognition and Dispatch to Luis]]></title>
            <link>https://medium.com/@andrew.rapo/using-microsoft-orchestrator-for-intent-recognition-and-dispatch-to-luis-274eef3fc669?source=rss-fa4b7766dc10------2</link>
            <guid isPermaLink="false">https://medium.com/p/274eef3fc669</guid>
            <category><![CDATA[luis]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[nlu]]></category>
            <category><![CDATA[orchestrator]]></category>
            <dc:creator><![CDATA[Andrew Rapo]]></dc:creator>
            <pubDate>Thu, 09 Jun 2022 01:10:56 GMT</pubDate>
            <atom:updated>2022-06-10T20:49:20.002Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wmjpyophDzRqhSF_kQsZaQ.png" /></figure><p>A common challenge for voice assistants is correctly recognizing the intent in user utterances. This can be especially challenging for general-purpose, multi-domain voice assistants. For example, imagine an assistant that is designed to be a friendly companion, in addition to being a useful source of content, and a helpful interface for smart home systems. Such an assistant will need to be able to classify a wide range of utterances, like:</p><ul><li>what’s the weather tomorrow?</li><li>do you know any martian jokes?</li><li>turn on the living room lights</li><li>i’m feeling lonely</li><li>play the latest song by taylor swift</li><li>it’s great to see you</li><li>good morning, buddy</li><li>have a good night</li></ul><p>Language understanding systems need to extract at least two kinds of information from the utterance: 1) the “intent” of the utterance — the general meaning of the utterance and 2) any discrete pieces of information in the utterance. These discrete pieces of information are often called “entities”.</p><p>An utterance like “turn on the living room lights” might be classified something like:<br>- intent: turnOnLights<br>- entities: { target: “livingRoom” }</p><p>With this information, a simple program can be invoked to turn on the specified lights.</p><p>A language understanding system like <a href="https://www.luis.ai/">Microsoft Luis</a> is powerful because it can be used to extract both intents and entities using one model — in one shot. However, it tends to be impractical to use one, big Luis model to classify a large number of intents. As the size of a model increases, it becomes harder to make changes without introducing errors. Adding training data to make the model better at recognizing one intent can inadvertently make it worse at recognizing other intents. Technologies like Luis can be mysterious. When they produce the intended results, all is good. When they don’t, it can be difficult to figure out what went wrong. In general, troubleshooting is easier with smaller models.</p><h4>Dispatch</h4><p>A common way to address the problem is to create a “dispatch” model that determines the general class of the user utterance as a first step. Then the utterance can be sent to a simpler, class-specific model to determine the intent and entities.</p><p>Not long ago the best practice was to use an ML technology like Luis to build a big dispatch-only model trained with example utterances from a collection of smaller models. This makes sense and it can work well. But Luis models often get confused by similarly-worded examples that should map to different intents. For example: In a large, complex model, “play auld lang syne” (<em>Music</em>)<em> </em>and “play space invaders” (<em>Games</em>) could easily be confused and misclassified because the structure of the utterances is so similar. As a result, using Luis for Dispatch has been deprecated in favor of using a different kind of model technology— namely deep neural nets or DNNs.</p><h4>Orchestrator</h4><p>In early 2021, Microsoft began previewing a technology called “Orchestrator” as the new best practice for dispatch scenarios. (See: <a href="https://docs.microsoft.com/en-us/composer/concept-orchestrator">Intent recognition with Orchestrator in Composer</a> ) Orchestrator was first made available as part of the Microsoft Bot Framework to help chatbots choose the most appropriate Luis model based on the chat context. Orchestrator makes use of pre-trained DNN models to classify utterances. [oversimplification ahead] It does this by locating utterances in a vast, multi-dimensional vector space defined by all of the data in the DNN training set.</p><p>The typical way to use Orchestrator with Luis is to first calculate location vectors for example utterances extracted from a set of domain-specific Luis models — remembering the model (or class) from which each example originated. Then at runtime, a location vector is calculated for each new user utterance and compared to the examples. The example that is mathematically closest to the user utterance (in the vast multi-dimensional space of the DNN) is used to determine which domain-specific Luis model to use next — i.e. which Luis model to “dispatch” to.</p><p>Like the ML technology used by Luis, deep neural nets (DNNs) are also mysterious black boxes. But the way the Orchestrator DNN locates utterances in the vector space seems to be less dependent on specific words and word order than Luis. So it is well-suited to the dispatch task. For example, Orchestrator can recognize that “Where am I?” is semantically similar to “What town is this?” even though the examples do not share any words or grammatical structure.</p><h4>Understanding Orchestrator</h4><p>To better understand and explore the potential of Orchestrator I created an demonstration project that includes several examples of building and testing a dispatch classifier. The examples use Orchestrator in three different ways:</p><ol><li>Via the Bot Framework cli tool, bf</li><li>Via JavaScript in a Jupyter Notebook</li><li>Wrapped in a node microservice, optionally deployed with Docker</li></ol><p>All of these examples are available in this github repo: <a href="https://github.com/wwlib/orchestrator-microservice">https://github.com/wwlib/orchestrator-microservice</a></p><h4>Example 1: Using Orchestrator via the Bot Framework Cli Tool</h4><p>First, clone the <a href="https://github.com/wwlib/orchestrator-microservice">examples repo</a> and then…</p><pre>cd orchestrator-microservice<br>npm install<br>cd orchestrator-files</pre><p>To see the available DNN models…</p><pre>npx bf orchestrator:basemodel:list</pre><p>This will return a list of available models, including:</p><ul><li>pretrained.20200924.microsoft.dte.00.06.en.onnx</li><li>pretrained.20210205.microsoft.dte.00.06.unicoder_multilingual.onnx</li><li>pretrained.20210218.microsoft.dte.00.06.bert_example_ner.en.onnx</li></ul><p>Download (get) a model and save it to the ./model folder…</p><pre>npx bf orchestrator:basemodel:get — versionId=pretrained.20210205.microsoft.dte.00.06.unicoder_multilingual.onnx — out=./model</pre><p>The next step is to generate a snapshot (.blu) file. To get started you can use the example Luis (.lu) files in orchestrator-files/lu/Dispatch. These incomplete example models represent the kinds of distinct domains that a general-purpose voice assistant might need to handle, including:</p><ul><li>Fitness.lu — a model for recognizing utterances about fitness and exercise</li><li>Games.lu — a model for recognizing utterances about games</li><li>Music.lu — a model for recognizing utterances about music</li><li>SmallTalk.lu — a model for recognizing general small talk</li><li>Time.lu — a model for recognizing utterances about the time, dates, holidays, etc.</li></ul><pre>cd [project-root]/orchestrator-files<br>npx bf orchestrator:create --hierarchical --in ./lu/Dispatch --out ./blu/Dispatch --model ./model</pre><p>Dispatch.blu will contain lines like:</p><pre>LABEL       EXAMPLE                   CLASSIFICATION_VECTOR<br>Fitness     teach me how to do yoga   FA16EBDB45...<br>SmallTalk   are you able to be wrong  D1B2ED9AC7...<br>SmallTalk   can you be happy          F330E5DA4D...<br>SmallTalk   do you ever feel happy    711065DA82...<br>Time        tell me the time          791301F206...</pre><p>Each example from the supplied .lu files will be labeled and assigned a location vector.</p><p>Again, for each new user utterance, a vector is calculated and compared to the examples’ vectors.</p><p>Now you can test the snapshot with the bf cli:</p><ul><li>cd [project-root]/orchestrator-files</li><li>npx bf orchestrator:query --in=./blu/Dispatch.blu --query=&quot;what time is it&quot; --model=./model</li></ul><p>Output for the query, “what time is it”</p><pre>[<br>  {<br>    &quot;label&quot;: {<br>      &quot;name&quot;: &quot;Time&quot;,<br>      &quot;label_type&quot;: 1,<br>      &quot;span&quot;: {<br>        &quot;offset&quot;: 0,<br>        &quot;length&quot;: 15<br>      }<br>    },<br>    &quot;score&quot;: 0.9997169968564052,<br>    &quot;closest_text&quot;: &quot;what time is it&quot;<br>  },<br>  ...<br>]</pre><p>The output is a ranked list of results, one for each model used to define the Dispatch.blu snapshot</p><p>The results are ranked by how close the user utterances is to the example utterances. Each result’s label is the name of the model where the example came from — in this case, the “Time” model.</p><h4>Example 2: Using Orchestrator in a JavaScript App via Jupyter Notebook</h4><p>The following <a href="https://github.com/wwlib/orchestrator-microservice/blob/main/notebooks/orchestrator-example.ipynb">Jupyter Notebook</a> makes use of the Microsoft <em>orchestrator-core</em> npm module to utilize Orchestrator from JavaScript.</p><p><a href="https://github.com/wwlib/orchestrator-microservice/blob/main/notebooks/orchestrator-example.ipynb">https://github.com/wwlib/orchestrator-microservice/blob/main/notebooks/orchestrator-example.ipynb</a></p><blockquote>Note: The code for harnessing Orchestrator via JavaScript is based on this class from the Bot Framework SDK: <a href="https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-ai-orchestrator/src/orchestratorRecognizer.ts">https://github.com/microsoft/botbuilder-js/blob/main/libraries/botbuilder-ai-orchestrator/src/orchestratorRecognizer.ts</a></blockquote><p>If you have <em>python</em>, <em>jupyter</em>, <em>node</em> and <em>npm</em> installed you can execute the JavaScript code in the the notebook by also installing <em>ijavascript</em>:</p><pre>npm install -g ijavascript<br>ijsinstall<br>cd [project-root]/notebooks<br>jupyter notebook</pre><p>Note: You don’t need to run the notebooks to see the examples and documentation.</p><p>The code from the notebook is also provided as script in the repo: <a href="https://github.com/wwlib/orchestrator-microservice/blob/main/orchestrator-files/test-example.js">https://github.com/wwlib/orchestrator-microservice/blob/main/orchestrator-files/test-example.js</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JqmqUqISUd8yDA7LvnVsoQ.png" /></figure><p>In addition to loading the required npm modules, the notebook defines two variables:</p><pre>modelFolder = &#39;../orchestrator-files/model&#39;;<br>snapshotFile = &#39;../orchestrator-files/blu/Dispatch.blu&#39;;</pre><p>The <em>initializeResolver()</em> function instantiates an <em>orchestrator</em> instance and loads the model found at path specified by <em>modelFolder. </em>Then it instantiates a <em>resolver</em> instance using the snapshot file (.blu) specified by <em>snapshotFile</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*saYzhNjJ8YB_5r6H0PouNQ.png" /></figure><p>Once initialized, the resolver can be used to <em>score</em> utterances. For example, the utterance, “I need to work out”, can be scored by calling resolver.score(utterance, 1)</p><pre>results = resolver.score(utterance, 1);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPvCHQFOrfHj-R6iWGdOlw.png" /></figure><p>The resolver returns a ranked list of results indicating which which of the snapshot labels are “closest” to the utterance. In this case, the top ranked result indicates that the utterance is most like the examples from the Fitness model.</p><pre>{<br>  closest_text: &#39;want to work out&#39;,<br>  score: 0.892648646722145,<br>  label: { name: &#39;<strong>Fitness</strong>&#39;, label_type: 1, span: [Object] }<br>}</pre><h4>Example 3: Wrapping Orchestrator in a Microservice</h4><p>The examples repo also includes an example of Orchestrator wrapped in a node-based microservice. To install and build the microservice:</p><pre>cd [project-root]<br>npm install<br>npm run build</pre><p>To download the model, generate the snapshot file and start the service:</p><pre>npm run get model<br>npm run generate<br>npm run start</pre><p>Then the service can be tested with curl:</p><pre>curl --location --request POST &#39;<a href="http://localhost:8000/intent&#39;">http://localhost:8000/intent&#39;</a> \<br>     --header &#39;Content-Type: application/json&#39; \<br>     --data-raw &#39;{<br>       &quot;utterance&quot;: &quot;what do you want to do today&quot;,<br>       &quot;resolverName&quot;: &quot;Dispatch&quot;<br>     }&#39;</pre><p>The results will look like:</p><pre>[<br>    {<br>        &quot;closest_text&quot;: &quot;what plans do you have for today&quot;,<br>        &quot;score&quot;: 0.7299530143026409,<br>        &quot;label&quot;: {<br>            &quot;name&quot;: &quot;SmallTalk&quot;,<br>            &quot;label_type&quot;: 1,<br>            &quot;span&quot;: {<br>                &quot;length&quot;: 28,<br>                &quot;offset&quot;: 0<br>            }<br>        },<br>        &quot;processingTime&quot;: 422,<br>        &quot;resolver&quot;: &quot;Dispatch&quot;<br>    },</pre><pre>...<br>]</pre><p>Or with Postman:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*By2Go_-4Osm7bfzVjl53HQ.png" /></figure><p>Or with the included socket client:</p><pre>cd [project-root]/tools<br>node socket-cli.js</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZ8BejTmhZ_qHguOPuaTBg.png" /></figure><p>Finally, the microservice implements a simple Web UI. Choose the Resolver from a pulldown and type an utterance to test, then hit RETURN (or click the Submit button)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s5-3mBsiYjX9TYVFEhwVOw.png" /></figure><p>There are three resolver options:</p><ul><li>Dispatch — uses the Dispatch.blu snapshot made from the three example Luis models: Fitness.lu, Games.lu, Music.lu, SmallTalk.lu and Time.lu</li><li>SmallTalk — uses the SmallTalk.blu snapshot made from a set of Luis models extracted from the SmallTalk.lu model — one .lu file per intent.</li><li>2-Stage — uses 2 instances of Orchestrator to accomplish a 2-stage dispatch: <em>Stage1</em> determines the model label and then if the model label is “SmallTalk” <em>Stage 2</em> determines the SmallTalk-specific intent.</li></ul><p>The goal with Orchestrator is to dispatch utterances to the most appropriate, domain-specific Luis model which will then determine the intent and entities. In this example, the Fitness.lu, Games.lu, Music.lu, and Time.lu models are relatively simple with only a handful of intents each. The SmallTalk.lu model is a little more complex and has ~15 intents of its own so to demonstrate a 2-stage dispatch, the SmallTalk.lu model has been broken into ~15 smaller .lu files — one per intent. Then a SmallTalk-specific snapshot (.blu) has been generated and used to initialize the SmallTalk resolver.</p><p>Note: A more realistic SmallTalk model might have hundreds of intents. That is when a 2-Stage dispatch would really be necessary.</p><p>Using the microservice Console UI (http://localhost:8000/console) you can test the three Resolver options with an example utterance.</p><p>The results for “<em>what do you want to do today</em>” are:</p><p><strong>Dispatch</strong> resolver</p><pre>{<br>  &quot;resovler&quot;: &quot;Dispatch&quot;,<br>  &quot;label&quot;: &quot;SmallTalk&quot;,<br>  &quot;closest_text&quot;: &quot;what do you want to do this weekend&quot;,<br>  &quot;score&quot;: 0.9354338696921423,<br>  &quot;processingTime&quot;: &quot;18 ms&quot;<br>}</pre><p>The utterance is correctly labeled, “SmallTalk”</p><p><strong>SmallTalk</strong> resolver</p><pre>{<br>  &quot;resovler&quot;: &quot;SmallTalk&quot;,<br>  &quot;label&quot;: &quot;doesHavePlansForEvent&quot;,<br>  &quot;closest_text&quot;: &quot;what do you want to do this weekend&quot;,<br>  &quot;score&quot;: 0.9053338150950618,<br>  &quot;processingTime&quot;: &quot;20 ms&quot;<br>}</pre><p>The utterance is correctly labeled with the SmallTalk intent, “doesHavePlansForEvent”</p><p><strong>2-Stage </strong>resolver</p><pre>{<br>  &quot;resolver&quot;: &quot;Dispatch -&gt; SmallTalk&quot;,<br>  &quot;label&quot;: &quot;SmallTalk -&gt; doesHavePlansForEvent&quot;,<br>  &quot;closest_text&quot;: &quot;what do you want to do this weekend&quot;,<br>  &quot;score&quot;: 0.9053338150950618,<br>  &quot;processingTime&quot;: &quot;37 ms&quot;<br>}</pre><p>The 2-stage dispatch uses the Dispatch resolver to correctly return the SmallTalk model label and then automatically uses the SmallTalk resolver to correctly determine the intent, “doesHavePlansForEvent”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SHIrzJjjZ9dGD3hkQC6HLA.png" /></figure><p>Note: Results may vary if a different base DNN model is used. The model used for these examples is<em>: pretrained.20210205.microsoft.dte.00.06.unicoder_multilingual.onnx</em></p><h4>A Workflow for Developing Orchestrator Dispatch Solutions</h4><p>Developing an Orchestrator dispatch solution is an iterative process. Every time the input examples (.lu files) change the outputs can change in unexpected ways. New errors can emerge. It is helpful to have a workflow that includes at least some sanity-check tests.</p><p><strong>Sanity-check Tests</strong></p><p>The <a href="https://github.com/wwlib/orchestrator-microservice/blob/main/notebooks/orchestrator-example.ipynb">orchestrator-example notebook</a> in the project repo includes a simple testing script. The script loads tests from a json test manifest file and then makes calls to the microservice for each test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aHR3timive44LV9heZrHJA.png" /></figure><p>The SmallTalk-manifest.json file includes tests that look like:</p><pre>{<br>    &quot;utterance&quot;: &quot;when is he arriving&quot;,<br>    &quot;label&quot;: &quot;Time&quot;<br>},<br>{<br>    &quot;utterance&quot;: &quot;I need some exercise&quot;,<br>    &quot;label&quot;: &quot;Fitness&quot;<br>},<br>{<br>    &quot;utterance&quot;: &quot;did you see the game&quot;,<br>    &quot;label&quot;: &quot;SmallTalk:didWatchEvent&quot;<br>},</pre><p>For each test utterance the expected Label is provided.</p><p>The script described in this notebook can be run via: <em>npm run test-microservice</em></p><pre>$ npm run test:microservice</pre><pre>&gt; orchestrator-microservice@0.0.1 test:microservice /[...]/orchestrator-microservice<br>&gt; node test/test-microservice.js</pre><pre>manifestPath: ./orchestrator-files/test-manifests/SmallTalk-manifest.json<br>resolverName: 2-Stage<br>37 tests completed in 952ms. Average test time: 25.72972972972973ms<br>0 errors.<br>$</pre><p><strong>Splitting the SmallTalk.lu File Into Per-intent .lu Files</strong></p><p>The experimental 2-Stage dispatch approach described above requires that the SmallTalk.lu file be split into a set of .lu files — one per intent.</p><p>The <a href="https://github.com/wwlib/orchestrator-microservice/blob/main/notebooks/intents-to-lu-files.ipynb">intents-to-lu-files notebook</a> in the project repo describes a script for splitting the SmallTalk.lu file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bIqcYazAhVqvb09uNwywFQ.png" /></figure><p>The script described in this notebook can be run via: <em>npm run intents-to-lu-files</em></p><pre>$ npm run intents-to-lu-files</pre><pre>&gt; orchestrator-microservice@0.0.1 intents-to-lu-files /[...]/orchestrator-microservice<br>&gt; cd orchestrator-files; node intentsToLuFiles.js</pre><pre>Splitting ./lu/Dispatch/SmallTalk.lu into individual .lu files...<br>Writing: ./lu/SmallTalk/didWatchEvent.lu<br>Writing: ./lu/SmallTalk/doesBelieveInThing.lu<br>Writing: ./lu/SmallTalk/doesCareAboutEvent.lu<br>Writing: ./lu/SmallTalk/doesFeelEmotionAboutThing.lu<br>Writing: ./lu/SmallTalk/doesHaveFavorite.lu<br>Writing: ./lu/SmallTalk/doesHaveLeastFavorite.lu<br>Writing: ./lu/SmallTalk/doesHaveOpinionAboutThing.lu<br>Writing: ./lu/SmallTalk/doesHavePlansForEvent.lu<br>Writing: ./lu/SmallTalk/doesHaveRelation.lu<br>Writing: ./lu/SmallTalk/doesKnowPerson.lu<br>Writing: ./lu/SmallTalk/greeting.lu<br>Writing: ./lu/SmallTalk/howQuestion.lu<br>Writing: ./lu/SmallTalk/whatQuestion.lu<br>Writing: ./lu/SmallTalk/whereQuestion.lu<br>Writing: ./lu/SmallTalk/whoQuestion.lu<br>Writing: ./lu/SmallTalk/whyQuestion.lu<br>Writing: ./lu/SmallTalk/userFeels.lu<br>Wrote 17 .lu files to: ./lu/SmallTalk/<br>Done.<br>$</pre><p><strong>An Example Workflow</strong></p><p>The workflow used to test the examples for this article includes these steps:</p><ol><li>Download the DNN model with: npm run get-model</li><li>Split the SmallTalk.lu file into per-intent .lu files with: npm run intents-to-lu-files</li><li>Generate the snapshot (.blu) files with: npm run generate</li><li>Start the microservice with: npm run start</li><li>Run the sanity-check tests with: npm run test:microservice</li><li>Review the results and make any needed changes to Fitness.lu, Games.lu, Music.lu, SmallTalk.lu or Time.lu</li><li>Stop the microservice (i.e. ctrl-c)</li><li>Repeat (Goto Step 2)</li></ol><h4>Running the Microservice via Docker</h4><p>The project repo includes a Dockerfile. To build and run the microservice with Docker:</p><p><strong>Build</strong></p><pre>docker build -t orchestrator-microservice .</pre><p>Or:</p><pre>npm run docker:build</pre><p><strong>Run</strong></p><pre>docker run -it --rm -p 8000:8000 --env-file ./.env orchestrator-microservice</pre><p>Or:</p><pre>npm run docker:run</pre><p>Note: 2gb should be enough to run the <em>pretrained.20200924.microsoft.dte.00.06.en.onnx</em> model.</p><p>However, if more memory is needed you may need to try something like:</p><pre>docker run -it -m=4g --rm -p 8000:8000 --env-file ./.env orchestrator-microservice</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2O7A_7TarutrIy7MIrJypg.png" /></figure><h4>Multilingual Recognition</h4><p>When using a multilingual DNN model like, <em>pretrained.20210205.microsoft.dte.00.06.unicoder_multilingual.onnx,</em> Orchestrator can classify utterances from a a variety of languages. For example, Orchestrator will assign both“What time is it?” and “Que hora es?” the same label — int this case, “Time”</p><h4>Limitations</h4><p>Orchestrator’s available DNN models are powerful but not perfect. It is easy to find misclassifications. In this example project, “Do you know david?” is correctly labeled as <em>SmallTalk:doesKnowPerson, </em>closest to “are you familiar with david”</p><pre>{<br>  &quot;resolver&quot;: &quot;Dispatch:SmallTalk&quot;,<br>  &quot;label&quot;: &quot;SmallTalk:doesKnowPerson&quot;,<br>  &quot;closest_text&quot;: &quot;are you familiar with david&quot;,<br>  &quot;score&quot;: 0.6574666605549864,<br>  &quot;processingTime&quot;: &quot;21 ms&quot;<br>}</pre><p>However, “Do you know joe?” is incorrectly labeled as: <em>Time</em>, closest to<em> </em>“i want to know the date”</p><pre>{<br>  &quot;resolver&quot;: &quot;Dispatch&quot;,<br>  &quot;label&quot;: &quot;Time&quot;,<br>  &quot;closest_text&quot;: &quot;i want to know the date&quot;,<br>  &quot;score&quot;: 0.3328182735289674,<br>  &quot;processingTime&quot;: &quot;12 ms&quot;<br>}</pre><p>Interesting. Also “what do you want to do today” is correctly classified as: <em>SmallTalk:doesHavePlansForEvent</em>, closest to “what plans do you have for today”.</p><pre>{<br>  &quot;resolver&quot;: &quot;Dispatch:SmallTalk&quot;,<br>  &quot;label&quot;: &quot;SmallTalk:doesHavePlansForEvent&quot;,<br>  &quot;closest_text&quot;: &quot;what plans do you have for today&quot;,<br>  &quot;score&quot;: 0.7238375153677875,<br>  &quot;processingTime&quot;: &quot;21 ms&quot;<br>}</pre><p>But, “what do you want to do today?” — <strong>with a question mark</strong> — is incorrectly labeled as: Time, closest to “do you have the current day”</p><pre>{<br>  &quot;resolver&quot;: &quot;Dispatch&quot;,<br>  &quot;label&quot;: &quot;Time&quot;,<br>  &quot;closest_text&quot;: &quot;do you have the current day&quot;,<br>  &quot;score&quot;: 0.747118860912231,<br>  &quot;processingTime&quot;: &quot;7 ms&quot;<br>}</pre><p>Because DNNs are black boxes, it is hard to know what is going on with these examples. And because Orchestrator is so new there is not a lot of documentation or discussion about its inner workings. But that will change, especially if more people begin to experiment with it.</p><h4>Summary</h4><p>Microsoft’s Orchestrator is a powerful tool for classifying utterances. It can run in the cloud or on a sufficiently powerful device. It is easy to train/configure. And as demonstrated by this article it can be used independent of Microsoft Bot Framework — within the the terms of the <a href="https://github.com/wwlib/orchestrator-microservice/blob/main/orchestrator-files/model/LICENSE.md">Microsoft License</a>. The examples in this article and accompanying repo will help to jumpstart the process of learning and experimenting, especially with dispatch scenarios.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=274eef3fc669" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Robokit: The Cognitive Services Parts]]></title>
            <link>https://medium.com/@andrew.rapo/robokit-the-cognitive-services-parts-34f57218febf?source=rss-fa4b7766dc10------2</link>
            <guid isPermaLink="false">https://medium.com/p/34f57218febf</guid>
            <category><![CDATA[social-robotics]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cognitive-services]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[robokit]]></category>
            <dc:creator><![CDATA[Andrew Rapo]]></dc:creator>
            <pubDate>Mon, 26 Aug 2019 20:15:35 GMT</pubDate>
            <atom:updated>2019-08-26T20:15:35.632Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fASu1KEEFrI2mxs4ERkY7Q.png" /></figure><p><a href="https://wwlib.org/robokit/">Robokit</a> is a nodejs project that provides a simple framework for prototyping social robot skills. This article describes the Speech To Text, NLU and Text To Speech components.</p><p><strong>See also</strong>: <a href="https://medium.com/@andrew.rapo/make-your-own-conversational-ai-social-robot-with-robokit-a-crude-approximation-of-jibo-10847e9a2661">https://medium.com/@andrew.rapo/make-your-own-conversational-ai-social-robot-with-robokit-a-crude-approximation-of-jibo-10847e9a2661</a></p><p><strong>Robokit</strong> leverages Microsoft Azure Cognitive Services through a library called, <a href="https://github.com/wwlib/cognitiveserviceslib"><em>cognitiveserviceslib</em></a>. The base abstract classes in <em>cognitiveserviceslib</em> are:</p><pre>ASRController<br>NLUController<br>TTSController</pre><p>These can be extended to work with any cognitive service. The current version of the library (v0.0.3) includes Azure-specific versions:</p><pre>AzureSpeechApiController<br>LUISController<br>AzureTTSController</pre><p><strong>Demo: Robokit + cognitiveserviceslib</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fw2xMqKO23h0%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dw2xMqKO23h0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fw2xMqKO23h0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/10735e949a8b5d197489d994df1795b5/href">https://medium.com/media/10735e949a8b5d197489d994df1795b5/href</a></iframe><p><strong>AzureSpeechApiController</strong></p><p><a href="https://github.com/wwlib/cognitiveserviceslib/blob/master/src/microsoft/AzureSpeechApiController.ts">AzureSpeechApiController.ts</a> exposes two methods for transcribing audio. RecognizeWaveBuffer(wave: Buffer): AsyncToken&lt;string&gt; takes a buffer containing wave audio data and send that to the cloud. RecognizerStart(options: any): AsyncToken&lt;string&gt; records audio for a specified amount of time (specified via options) and streams the audio to the cloud. These methods return an <em>ASRResponse</em> which includes the transcribed utterance along with an NBest list of results with confidence values.</p><pre>export type ASRResponse = {<br>    utterance: string;<br>    response?: any;<br>}</pre><p><strong>LUISController</strong></p><p><a href="https://github.com/wwlib/cognitiveserviceslib/blob/master/src/microsoft/LUISController.ts">LUISController.ts</a> exposes getIntentAndEntities(utterance: string, options?: NLURequestOptions): AsyncToken&lt;NLUIntentAndEntities&gt; which takes a text utterance and returns an NLUIntentAndEntities object which includes the <em>intent</em>, any <em>entities</em> that may have been parsed. The full response object is also returned with its ranked list of possible intents:</p><pre>export type NLUIntentAndEntities = {<br>    intent: string;<br>    entities: any;<br>    response: any;<br>}</pre><p><strong>AzureTTSController</strong></p><p><a href="https://github.com/wwlib/cognitiveserviceslib/blob/master/src/microsoft/AzureTTSController.ts">AzureTTSController.ts</a> exposes SynthesizerStart(text: string, options?: any): AsyncToken&lt;string&gt; which calls the <em>synthesizeStream()</em> method of the AzureSpeechClient class. <em>synthesizeStream()</em> makes a POST request to the speech endpoint. Received audio data in the form of a <em>NodeJS.ReadableStream</em> is concatenated into an audioData buffer and returned. If an audioContext is defined (passed into the constructor) and the autoPlay option is true, then the audio is also decoded and played. Note: The autoPlay option will only work in a browser/electron context:</p><pre>audioStreamBuffer = Buffer.concat(buffers);<br>let audioData = new Uint8Array(audioStreamBuffer).buffer;<br>if (options &amp;&amp; options.autoPlay &amp;&amp; this.audioContext) {<br>    this.audioContext.decodeAudioData(audioData, (buffer: any) =&gt; {<br>        let decodedBuffer = buffer;<br>        let bufferSource = this.audioContext.createBufferSource();<br>        bufferSource.buffer = decodedBuffer;<br>        if (this.masterVolumeGainNode) {<br>            bufferSource.connect(this.masterVolumeGainNode);<br>            bufferSource.start(this.audioContext.currentTime);<br>        }<br>    });<br>}</pre><p><strong>AzureSpeechClient</strong></p><p><em>AzureSpeechApiController </em>and <em>AzureTTSController</em> both make use of the underlying AzureSpeechClient class to talk to Azure services. This class (based on the <em>bingspeech-api-client npm</em> module) talks to Azure via REST calls and implements two key methods: recognizeStream(input: NodeJS.ReadWriteStream, locale: string = ‘en-us’): Promise&lt;VoiceRecognitionResponse&gt; and synthesizeStream(text: string, locale: string = ‘en-us’, gender: string = ‘female’): Promise&lt;NodeJS.ReadableStream&gt;</p><p>AzureSpeechClient takes care of authenticating each API call to azure by requesting an auth token as often as necessary.</p><p><strong>Measuring Cloud Latencies</strong></p><p>Several tools provided with <em>cognitiveserviceslib</em> make it easy to measure cloud latencies associated with STT, NLU and TTS. These are found in the repo’s <em>tools</em> directory and include:</p><pre>test-azure-speech.js<br>test-luis-nlu.js<br>test-azure-tts.js</pre><p><strong>test-azure-speech.js</strong> records audio, sends it to Azure and displays the transcribed utterance using an instance of <strong>AzureSpeechApiController</strong>.</p><p>azureSpeechApiController = new AzureSpeechApiController(config);</p><p>The output for a recording of “what time is it?” looks like:</p><pre><strong>$ node test-azure-speech.js</strong> <br>Recording 1 channels with sample rate 16000...<br>azureSpeechApiController: on Listening<br>Recording 8192 bytes<br>Recording 8192 bytes<br>azureSpeechApiController: on Recording_Stopped<br>Recording 3092 bytes<br>End Recording: 3030.594ms<br>response: { RecognitionStatus: &#39;Success&#39;,<br>  Offset: 300000,<br>  Duration: 5800000,<br>  NBest: <br>   [ { Confidence: 0.8806723952293396,<br>       Lexical: &#39;what time is it&#39;,<br>       ITN: &#39;What time is it&#39;,<br>       MaskedITN: &#39;What time is it&#39;,<br>       Display: &#39;What time is it?&#39; },<br>     { Confidence: 0.6446887850761414,<br>       Lexical: &#39;what time is&#39;,<br>       ITN: &#39;what time is&#39;,<br>       MaskedITN: &#39;what time is&#39;,<br>       Display: &#39;what time is&#39; },<br>     { Confidence: 0.746180534362793,<br>       Lexical: &#39;oh what time is it&#39;,<br>       ITN: &#39;oh what time is it&#39;,<br>       MaskedITN: &#39;oh what time is it&#39;,<br>       Display: &#39;oh what time is it&#39; } ] }<br>azureSpeechApiController: on RecognitionEndedEvent<br>azureSpeechApiController: utterance: what time is it<br>timeLog: {<br>  &quot;timeStart&quot;: 1566830774225,<br>  &quot;recordingStopped&quot;: 1566830777194,<br>  &quot;timeRecordingStopped&quot;: 2969,<br>  &quot;complete&quot;: 1566830777402,<br>  &quot;timeToComplete&quot;: 3177,<br>  &quot;cloudLatency&quot;: 208<br>}</pre><p><strong>Note</strong>: the cloud latency for the STT round trip is <strong>~200 milliseconds</strong>.</p><p><strong>test-luis-nlu.js</strong> sends the text of a transcribed utterance (i.e. “what time is it”) to LUIS and displays the NLU result using an instance of <strong>AzureTTSController</strong>:</p><p>azureTTSController = new AzureTTSController(config);</p><p>The output for “what time is it” looks like:</p><pre><strong>$ node test-luis-nlu.js</strong> <br>LUISController: call: {<br>  &quot;query&quot;: &quot;what time is it&quot;,<br>  &quot;topScoringIntent&quot;: {<br>    &quot;intent&quot;: &quot;launchClock&quot;,<br>    &quot;score&quot;: 0.9567336<br>  },<br>  &quot;intents&quot;: [<br>    {<br>      &quot;intent&quot;: &quot;launchClock&quot;,<br>      &quot;score&quot;: 0.9567336<br>    },<br>    {<br>      &quot;intent&quot;: &quot;launchItsMe&quot;,<br>      &quot;score&quot;: 0.0246629454<br>    },<br>    {<br>      &quot;intent&quot;: &quot;answerYes&quot;,<br>      &quot;score&quot;: 0.00616097357<br>    },<br>    {<br>      &quot;intent&quot;: &quot;launchFavoriteRobot&quot;,<br>      &quot;score&quot;: 0.00586579926<br>    },<br>    {<br>      &quot;intent&quot;: &quot;gameCommand&quot;,<br>      &quot;score&quot;: 0.0051462776<br>    },<br>    {<br>      &quot;intent&quot;: &quot;launchDoYouLike&quot;,<br>      &quot;score&quot;: 0.00475652<br>    },<br>    {<br>      &quot;intent&quot;: &quot;launchUserLikes&quot;,<br>      &quot;score&quot;: 0.003249991<br>    },<br>    {<br>      &quot;intent&quot;: &quot;launchGameInventory&quot;,<br>      &quot;score&quot;: 0.00293851155<br>    },<br>    {<br>      &quot;intent&quot;: &quot;answerNo&quot;,<br>      &quot;score&quot;: 0.002510923<br>    },<br>    {<br>      &quot;intent&quot;: &quot;None&quot;,<br>      &quot;score&quot;: 0.00229805941<br>    },<br>    {<br>      &quot;intent&quot;: &quot;launchGame&quot;,<br>      &quot;score&quot;: 0.00209691538<br>    },<br>    {<br>      &quot;intent&quot;: &quot;launchJoke&quot;,<br>      &quot;score&quot;: 0.001750315<br>    }<br>  ],<br>  &quot;entities&quot;: []<br>} null<br>NLUIntentAndEntities:  {<br>  &quot;intent&quot;: &quot;launchClock&quot;,<br>  &quot;entities&quot;: {<br>    &quot;user&quot;: &quot;Someone&quot;,<br>    &quot;userOriginal&quot;: &quot;Someone&quot;,<br>    &quot;thing&quot;: &quot;that&quot;,<br>    &quot;thingOriginal&quot;: &quot;that&quot;<br>  }<br>}<br>timeLog: {<br>  &quot;timeStart&quot;: 1566832003250,<br>  &quot;complete&quot;: 1566832003678,<br>  &quot;cloudLatency&quot;: 428<br>}</pre><p><strong>Note</strong>: The cloud latency for the NUL round trip is <strong>~430 milliseconds</strong>.</p><p><strong>test-azure-tts.js</strong> sends the text of the intended response and writes the received audio to <em>tts-out.wav</em>:</p><pre><strong>$ node test-azure-tts.js</strong> <br>azureTTSController: on Synthesizing<br>azureTTSController: on SynthesisStreamStartedEvent<br>azureTTSController: on SynthesisStreamEndedEvent<br>azureTTSController: result: The time is 10 32<br>timeLog: {<br>  &quot;timeStart&quot;: 1566832074439,<br>  &quot;synthesisStreamStarted&quot;: 1566832074554,<br>  &quot;timeToSynthesisStreamStarted&quot;: 115,<br>  &quot;synthesisStreamEnded&quot;: 1566832074705,<br>  &quot;timeToSynthesisStreamEnded&quot;: 266,<br>  &quot;complete&quot;: 1566832074705,<br>  &quot;cloudLatency&quot;: 266<br>}</pre><pre>generates: tts-out.wav</pre><p>Note: The cloud latency for the TTS round trip is <strong>~260 milliseconds</strong>.</p><p><strong>Total latency</strong> contributed by the cloud services is ~200ms + ~430ms + ~260ms = ~890ms. Around 1 second. That’s acceptable for many applications. The perception of the latency can be reduced through UI/UX feedback. In the case of a robot, this can include body movement and gestures like head tilt, eye movement, etc.</p><p><strong>Config for Azure API Calls</strong></p><p>To communicate successfully with Azure services, <em>cognitiveserviceslib </em>classes need to be instantiated with a config object that contains the following properties:</p><pre>{<br>    &quot;Microsoft&quot;: {<br>        &quot;AzureSpeechSubscriptionKey&quot;: &quot;&lt;SUBSCRIPTION-KEY&gt;&quot;,<br>        &quot;AzureSpeechTokenEndpoint&quot;: &quot;&lt;URL&gt;&quot;,<br>        &quot;AzureSpeechEndpointStt&quot;: &quot;&lt;URL&gt;&quot;,<br>        &quot;AzureSpeechEndpointTts&quot;: &quot;&lt;URL&gt;&quot;,<br>        &quot;nluLUIS_endpoint&quot;: &quot;&lt;URL&gt;&quot;,<br>        &quot;nluLUIS_appId&quot;: &quot;&lt;YOUR-LUIS-APP-ID&gt;&quot;,<br>        &quot;nluLUIS_subscriptionKey&quot;: &quot;&lt;YOUR-LUIS-SUBSCRIPTION-KEY&gt;&quot;<br>    }<br>}</pre><p><strong>Setting up Azure Services</strong></p><p>Notes about setting up Azure services for use with <em>cognitiveserviceslib and robokit </em>can be found in this article: <a href="https://medium.com/@andrew.rapo/robokit-setting-up-azure-cognitive-services-bing-speech-luis-nlu-fbb39f5dc957">https://medium.com/@andrew.rapo/robokit-setting-up-azure-cognitive-services-bing-speech-luis-nlu-fbb39f5dc957</a></p><p><strong>Conclusion</strong></p><p><em>cognitiveserviceslib</em> demonstrates how Azure’s REST APIs can be used to implement and analyze performant STT, NLU and TTS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34f57218febf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keep your Jibo talking (and dancing) with QR Commander]]></title>
            <link>https://medium.com/@andrew.rapo/keep-your-jibo-talking-and-dancing-with-qr-commander-e1f418bdac4c?source=rss-fa4b7766dc10------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1f418bdac4c</guid>
            <category><![CDATA[qr-code]]></category>
            <category><![CDATA[jibo]]></category>
            <category><![CDATA[dancing]]></category>
            <category><![CDATA[robots]]></category>
            <dc:creator><![CDATA[Andrew Rapo]]></dc:creator>
            <pubDate>Sat, 09 Mar 2019 22:30:16 GMT</pubDate>
            <atom:updated>2019-03-09T22:46:20.471Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nY1USj1hAywehF084UEknw.png" /></figure><p>This morning my Jibo downloaded <em>Release Version 2.0.0</em> which signals the beginning of an end. Some time in the near future, Jibo will lose the ability to hear and respond to voice commands because his servers will be shut down. There are a number of articles that do a good job of explaining the situation, including:</p><p><a href="https://www.wired.com/story/jibo-is-dying-eulogy/">My Jibo Is Dying and It&#39;s Breaking My Heart</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hdwwtUMKlC-egB7gGSofUw.jpeg" /></figure><p>It is a sad end. Those of us who worked on Jibo got together in September (after the company had shut down) and created a final build that leaves Jibo in the best state possible. Because Jibo’s cameras still work, we were able to add a feature that allows users to communicate with him using codes — QR codes. We call it <em>QR Commander</em>. More specifically, users can give Jibo things to say using QR codes. For example, when Jibo sees this code he will say: “It is nice to see you!”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*BGU9Ttbis_3tsHN4oUvIVA.png" /><figcaption>QR Code: It is nice to see you!</figcaption></figure><p>This code contains the text, ESML[#]It is nice to see you!</p><p><strong>ESML</strong></p><p>The prefix ESML[#] tells Jibo to interpret the text as Embodied Speech Markup Language, a special markup that can contain directives for animation, emojis, pitch, etc. This ESML tells Jibo to twerk and then say, “I’m a twerking robot”:</p><p>ESML[#]&lt;anim cat=’dance’ filter=’rom-twerk’/&gt; I’m a twerking robot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*wKXyrj23zvm2Lh5R-dyosQ.png" /><figcaption>QR Code: I’m a twerking robot</figcaption></figure><p>Sending ESML codes to Jibo is a small consolation for users who will truly miss being able to talk to him. But it will keep him dancing.</p><p>Note: Codes can only be used to send Jibo ESML instructions. They cannot be used to launch skills. This can still be accomplished through his menu.</p><p><strong>Activation</strong></p><p>QR Commander needs to be enabled using Jibo’s <em>Settings Menu</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p5vNA9hpRvXuNiGM0tsSNQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QZi1AdYIL5Nx3Jyf23LvWA.jpeg" /></figure><p>Enable QR Commander by tapping on “Yes” and then <em>swiping down to exit the menu</em>. Once activated Jibo will speak any qr-encoded ESML messages that he sees.</p><p><strong>QR Commander Web App</strong></p><p>To make it easy to generate QR Commander codes, there is a Web app at <a href="https://wwlib.org/qr-commander/">https://wwlib.org/qr-commander/</a> that will turn text into codes. The app includes a pull-down menu with a large number of ESML examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WvWTOtZZ2SDhYKeW_PcmKw.png" /><figcaption>QR Commander Web App</figcaption></figure><p><strong>Source Code</strong></p><p>The open source code for the app is on github: <a href="https://github.com/wwlib/qr-commander">https://github.com/wwlib/qr-commander</a></p><p><strong>Summary</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9xdjmzbxLnZ8_06pkLmuMg.jpeg" /></figure><p>Working at Jibo was a career highlight and a great opportunity to collaborate with a highly talented, inventive and dedicated team. Although the Last Dance update (2.0.0) signals an end, it also represents the optimistic spirit that made working at Jibo special. The servers may be shutting down, but the robot lives on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1f418bdac4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make Your Own Conversational AI/Social Robot with robokit — A Simple Approximation of Jibo]]></title>
            <link>https://medium.com/@andrew.rapo/make-your-own-conversational-ai-social-robot-with-robokit-a-crude-approximation-of-jibo-10847e9a2661?source=rss-fa4b7766dc10------2</link>
            <guid isPermaLink="false">https://medium.com/p/10847e9a2661</guid>
            <category><![CDATA[azure-cognitive-service]]></category>
            <category><![CDATA[jibo]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <category><![CDATA[social-robot]]></category>
            <category><![CDATA[voice-ui]]></category>
            <dc:creator><![CDATA[Andrew Rapo]]></dc:creator>
            <pubDate>Thu, 07 Mar 2019 03:21:58 GMT</pubDate>
            <atom:updated>2019-08-26T20:19:09.359Z</atom:updated>
            <content:encoded><![CDATA[<h3>Make Your Own Conversational AI/Social Robot with robokit — A Simple Approximation of Jibo</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJUnN3Cv0yKF48znjehZ8w.png" /></figure><p>UPDATE: August 16, 2019 — Updated to use the latest Azure speech API (v0.0.3) Details about the use of Azure cognitive services are in this article: <a href="https://medium.com/@andrew.rapo/robokit-the-cognitive-services-parts-34f57218febf">https://medium.com/@andrew.rapo/robokit-the-cognitive-services-parts-34f57218febf</a></p><p><strong>robokit</strong></p><p>[Not too long ago…] I was working at Jibo, Inc. and developing tools to help designers explore voice-driven, character-based, social robot interactions. Then in May (2018), Jibo (the company) suddenly shut down and left many of us wondering how we would fill the void when Jibo (the robot) stopped responding. I made <em>robokit</em> as an homage to Jibo and as a way to continue experimenting with conversational AI. (<a href="https://wwlib.org/robokit/">https://wwlib.org/robokit/</a>)</p><p><em>robokit</em> has an interaction model that is similar to Jibo’s. Voice interactions are initiated with a wake word (“Hey, robo”). Audio is sent to a cloud ASR service (Automatic Speech Recognition) for transcription. The text transcript is sent to a cloud NLU service (Natural Language Understanding) which returns the most likely <em>intents</em> and <em>entities</em> from the transcript. Then a logical <em>Hub</em> analyzes the NLU result and determines which <em>Skill</em> to launch, if any. Skills respond by triggering screen animations and utilizing a cloud TTS service (Text to Speech) to generate natural voice output. <em>robokit</em> has a rudimentary, on-screen <em>eye</em> that appears to scan its environment and has animation states that indicate when <em>robokit</em> is listening, thinking, etc.</p><p>Note: One of the most important aspects of a true social robot’s interaction model is <em>proactivity</em>. A robot like Jibo can initiate interactions in response to sensory input from cameras, microphones and touch sensors. For now, <em>robokit</em> only responds when the <em>wake word</em> is detected. Integrating a camera and implementing proactivity is on the todo list.</p><p><strong>Demo video</strong></p><p>The demo video (below) shows a few example interactions that are handled by simple skills:</p><ul><li>Hey, robo. What time is it? [ClockSkill.ts]</li><li>Hey robo. Tell me a joke. [JokeSkill.ts]</li><li>Hey robo. Who is your favorite robot? [FavoriteRobotSkill.ts]</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fr_Vzp8tXdkI%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dr_Vzp8tXdkI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fr_Vzp8tXdkI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/41507a44f4cf91535a50744a39c35978/href">https://medium.com/media/41507a44f4cf91535a50744a39c35978/href</a></iframe><p><strong>Github Repo</strong></p><p>The source code and documentation for <em>robokit</em> are available on github: <a href="https://github.com/wwlib/robokit">https://github.com/wwlib/robokit</a></p><p><strong>What it is</strong></p><p>More specifically, <em>robokit</em> is a very simple, straightforward Electron app that can turn a device (i.e. Mac, Raspberry Pi, etc.) into a voice-driven “robot”. It is a work in progress. It’s key features include:</p><ul><li>Hotword detection using Snowboy</li><li>Cloud ASR using Microsoft’s Bing speech api</li><li>Cloud NLU using Microsoft LUIS (and google)</li><li>Cloud Text To Speech using Microsoft Bing TTS</li><li>Screen animation using Pixi.js — authored using Adobe Animate</li><li>A simple, extensible model for developing skills — with examples</li><li>Remote Operation Mode to enable Woz prototyping (Wizard of Oz)</li><li>All wrapped in a cross-platform Electron app</li></ul><p><strong>Getting Started</strong></p><p><em>robokit</em> is intended to make learning about — and experimenting with — voice-driven, character-based interactions as easy as possible. Getting up and running takes just a few steps. These following instructions assume the <em>easiest scenario</em> — installation on an up-to-date Mac. But <em>robokit</em> runs well on linux-based devices including Raspberry Pi’s.</p><p><strong>Prerequisites</strong></p><p>There are a few <strong>prerequisites</strong> which include:</p><ul><li>node v8.11 or better</li><li>yarn (latest)</li><li>sox (a linux audio library)</li><li>a Microsoft Azure Cognitive Services account (i.e. free trial)</li></ul><p><strong>Setting up Azure Cognitive Services</strong></p><p><em>robokit</em> uses Microsoft Azure Cognitive Services for ASR (Automatic Speech Recognition, aka Speech to Text), TTS (Text to Speech) and NLU (Natural Language Understanding) For details about how to setup and configure these services see: <a href="https://medium.com/@andrew.rapo/robokit-setting-up-azure-cognitive-services-bing-speech-luis-nlu-fbb39f5dc957">https://medium.com/@andrew.rapo/robokit-setting-up-azure-cognitive-services-bing-speech-luis-nlu-fbb39f5dc957</a></p><p><strong>Setting up sox</strong></p><p><em>sox</em> is used to pipe audio to the Snowboy wake word listener and to record the 16khz mono audio needed by the cloud ASR service. Installing it on a mac is easiest using brew:</p><p>brew install sox</p><p>To help verify the sox installation, there is a jupyter notebook, <a href="https://github.com/wwlib/robokit/blob/master/docs/jupyter/hello-sox-python-mac.ipynb">hello-sox-python-mac.ipynb</a>, in the repo’s <em>docs/jupyter</em> folder:</p><p>For help setting up jupyter on a mac, see: <a href="https://www.davidculley.com/installing-python-on-a-mac/">https://www.davidculley.com/installing-python-on-a-mac/</a></p><p>If <em>sox</em> is installed correctly, the following command should produce audio of a rising sine wave: sox -r 8000 -n -d synth 3 sine 300–3000</p><p><strong>Setting up Microsoft a LUIS NLU Agent</strong></p><p>The easiest way to set up a LUIS NLU agent for use with <em>robokit</em> is to use the LUIS-knowledge-graph.json file found in the repo’s <em>docs</em> folder. This json file contains the definition for an NLU agent that will recognize phrases like “what time is it?” and “tell me a joke”.</p><p><strong>Installing</strong></p><p>With the prerequisites out of the way, installing and running <em>robokit</em> is simple:</p><pre>yarn<br>yarn rebuild</pre><p>Note: The yarn rebuild script is necessary because Snowboy needs to be re-compiled natively for use with Electron.</p><p><strong>Running</strong></p><pre>yarn start</pre><p>When <em>robokit</em> starts, the Electron app will display the “eye” in its idle state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T38kyybMdrzf8CEQbSa0qQ.png" /><figcaption>robokit eye idle</figcaption></figure><p>Open Electron’s console window using <em>Cmd-Option-i </em>and verify that the output looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9G3i-TlNxqhPtv6HRh1wvQ.png" /></figure><p>If there are no errors (i.e. red text) and the message about Recording 8192 bytes is updating continuously, then Snowboy is listening and everything is working correctly.</p><p><strong>Talking to Robo</strong></p><p>To interact with <em>robokit</em>, say, “Hey, robo.” If robokit hears the wake word the on-screen <em>eye</em> should change to display a blue outline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSsWtfEA4LcfRtwEHAiCBw.png" /></figure><p>Note: There are a number of buttons along the top of the <em>robokit</em> screen. Several of these can be used to manually trigger the eye’s animations. These include: Idle, Listen, Blink, LookLeft and LookRight. Verify that the animation system is working by clicking these button. (For now, ignore the Speech, Hotword and Music buttons.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pn7735Q6qyj9lLyNNp_3Sw.png" /></figure><p><strong>Launching the Clock Skill</strong></p><p>Let the eye return to its idle state and then say: “Hey, robo. What time is it?” For best results, pause for a moment after “Hey, robo” and then say, “What time is it?” slowly and clearly. If <em>robokit</em> hears you correctly, you will hear a female TTS voice announce the time. That’s <em>Bing TTS</em>’s default voice. Ideally, the Electron console output will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aVh0Kr1Q98XCjMIOSS2vsA.png" /></figure><p>To get the desired result, a lot of things have to work correctly, including the Azure Speech apis and the LUIS NLU service. So if you did hear the female voice announcing the time — CONGRATULATIONS! If not, there is no better way to really learn how something works that to troubleshoot errors. See the <strong><em>Troubleshooting</em></strong> section at then end of this article for help with this.</p><p><strong>The <em>robokit</em> Architecture and Source Code</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNUk36KCxGDBkXFW5I-39Q.png" /><figcaption>robokit architecture</figcaption></figure><p>The <em>robokit</em> source tree looks like:</p><pre>src<br>├── main<br>│   └── main.ts<br>└── renderer<br>    ├── AsyncToken.ts<br>    ├── <strong>HotwordController</strong>.ts<br>    ├── <strong>NLUController</strong>.ts<br>    ├── <strong>ASRController</strong>.ts<br>    ├── <strong>TTSController</strong>.ts<br>    ├── log.ts<br>    ├── microsoft<br>    │   ├── <strong>BingSpeechApiController</strong>.ts<br>    │   ├── <strong>BingTTSController</strong>.ts<br>    │   └── <strong>LUISController</strong>.ts<br>    ├── pixijs<br>    │   └── <strong>PixijsManager</strong>.ts<br>    ├── <strong>renderer</strong>.ts<br>    ├── rom<br>    │   ├── ClientCertificate.ts<br>    │   ├── <strong>RomManager</strong>.ts<br>    │   ├── SocketClient.ts<br>    │   ├── SocketServer.ts<br>    │   ├── commands<br>    │   │   ├── BlinkCommandHandler.ts<br>    │   │   ├── CommandHandler.ts<br>    │   │   ├── IdentCommandHandler.ts<br>    │   │   ├── LookAtCommandHandler.ts<br>    │   │   └── TtsCommandHandler.ts<br>    │   └── log.ts<br>    ├── skills<br>    │   ├── <strong>ClockSkill</strong>.ts<br>    │   ├── <strong>FavoriteRobotSkill</strong>.ts<br>    │   ├── <strong>Hub</strong>.ts<br>    │   ├── <strong>JokeSkill</strong>.ts<br>    │   └── <strong>Skill</strong>.ts<br>    ├── snowboy<br>    │   └── <strong>SnowboyController</strong>.ts<br>    ├── utils<br>    │   └── Log.ts<br>    └── ww<br>        └── WwMusicController.ts</pre><p>Because<em> robokit</em> is an Electron app there are two subtrees: <em>main</em> and <em>renderer</em>. The renderer subtree contains the important code, including renderer.ts which serves as the main entry point. This is where all subsystem are initialized and managers are started, including:</p><ul><li>PixijsManager — screen animation rendering</li><li>Hub — central nervous system (i.e. skill life cycle management)</li><li>RomManager — remote operation via SocketServer</li></ul><p>When all of the UI setup is complete, the startHotword() function instantiates a new HotwordController (<em>SnowboyController</em>) and starts the wake word <em>recognizer</em>.</p><p>When the wake word is detected, the startRecognizer() function instantiates a new ASRController (<em>BingSpeechApiController</em>) which records the next 3 seconds of audio and sends it to the Bing cloud ASR service. (Yes, this is a very simplistic approach to End of Speech (EOS) handling)</p><p>Then the startNLU(utterance) function is called which sends the transcribed utterance from Bing ASR to the LUIS cloud NLU service:</p><pre>function startNLU(utterance: string) {<br>    const nluController: NLUController = new LUISController();</pre><pre>    let t: AsyncToken&lt;NLUIntentAndEntities&gt; = <br>        <strong>nluController.getIntentAndEntities</strong>(utterance);</pre><pre>    t.complete<br>        .then((intentAndEntities: NLUIntentAndEntities) =&gt; {<br>            console.log(`NLUIntentAndEntities: `, <br>                        intentAndEntities);<br>            <strong>Hub.Instance().handleLaunchIntent</strong>(intentAndEntities, <br>                                              utterance);<br>        })<br>        .catch((error: any) =&gt; {<br>            console.log(error);<br>  });<br>}</pre><p>The result (<em>intentAndEntities</em>) returned from LUIS is passed to the the Hub, the “central nervous system” of <em>robokit</em>…</p><p>Hub.Instance().handleLaunchIntent(intentAndEntities, utterance);</p><p>The Hub analyzes the NLU result and launches the appropriate skill:</p><pre>handleLaunchIntent(intentAndEntities: NLUIntentAndEntities, <br>  utterance: string): void {<br>    let <strong>launchIntent</strong> = intentAndEntities.intent;<br>    let skill: Skill | undefined = <br>        this.launchIntentMap.get(launchIntent);<br>    if (skill) {<br>        <strong>skill.launch(intentAndEntities, utterance)</strong>;<br>        skill.running = true;<br>    }<br>}</pre><p>Skills are registered with the Hub to include them in the launchIntentMap:</p><pre>registerSkill(skill: Skill): void {<br>    console.log(`HUB: registerSkill: `, skill);<br>    <strong>this.skillMap</strong>.set(skill.id, skill);<br>    this.launchIntentMap.set(skill.launchIntent, skill);<br>}</pre><p>Skills manage robokit’s output in the form of TTS audio prompts. TTS prompts are generated by calling the Bing TTS cloud service via the <em>BingTTSController</em>. Audio received from Bing TTS is then played back via Electron/Chrome’s WebAudio api.</p><p>Pixi.js screen animations are controlled via <em>PixijsManager</em> with animation directives like:</p><pre>eyeInstance.gotoAndStop(&#39;idle&#39;);<br>eyeInstance.eye.eye_blue.visible = false;</pre><p><strong>Skills</strong></p><p><em>robokit</em> skills extend the <em>Skill</em> class (<em>src/skills/Skill.ts</em>) which looks like:</p><pre>export default abstract class Skill {</pre><pre>    public id: string;<br>    public launchIntent: string = &#39;&#39;;<br>    public running: boolean = false;</pre><pre>    constructor(id: string, launchIntent: string) {<br>        this.id = id;<br>        this.launchIntent = launchIntent;<br>    }</pre><pre>    abstract launch(intentAndEntities: NLUIntentAndEntities,<br>        utterance: string): void;</pre><pre>}</pre><p>The launchIntent property is used by the Hub to decide when to <em>launch</em> a particular skill. The launch(intentAndEntities: NLUIntentAndEntities,<br> utterance: string) method — which must be overridden — is called by the Hub to when the skill’s declared launchIntent matches the NLU results.</p><p><strong>The Clock Skill</strong></p><p>The <em>ClockSkill</em> class extends the <em>Skill</em> class and implements the launch() method. ClockSkill’s constructor() sets its <em>id</em> property to ‘clockSkill’ and sets the <em>launchIntent</em> to ‘launchClock’, allowing it to be identified by the Hub when NLU results are received.</p><pre>export default class ClockSkill extends Skill {</pre><pre>    constructor() {<br>        super(&#39;clockSkill&#39;, &#39;launchClock&#39;);<br>    }</pre><pre>    launch(intentAndEntities: NLUIntentAndEntities, <br>        utterance: string) :void {<br>            let time: Date = new Date();<br>            let hours: number = time.getHours(); //&#39;9&#39;;<br>            if (hours &gt; 12) {<br>                hours -= 12;<br>            }<br>            let minutes: number =  time.getMinutes(); //&#39;35&#39;<br>            let minutesPrefix: string = (minutes &lt; 10) ? &#39;oh&#39; : &#39;&#39;;<br>            let timePrompt: string = <br>                `The time is ${hours} ${minutesPrefix} ${minutes}`;<br>            <strong>Hub.Instance().startTTS(timePrompt);</strong><br>    }<br>}</pre><p>This very simple approach can be used to implement a wide range of skills.</p><p><strong>The Speech API Classes</strong></p><p>The <em>src/microsoft</em> folder contains three classes that use Microsoft’s <a href="https://www.npmjs.com/package/bingspeech-api-client"><em>bingspeech-api-client</em></a> module to manage communication with cloud ASR, NLU and TTS. They are: <a href="https://github.com/wwlib/robokit/blob/master/src/renderer/microsoft/BingSpeechApiController.ts"><em>BingSpeechApiController</em></a>, <a href="https://github.com/wwlib/robokit/blob/master/src/renderer/microsoft/BingTTSController.ts"><em>BingTTSController</em></a>, and <a href="https://github.com/wwlib/robokit/blob/master/src/renderer/microsoft/LUISController.ts"><em>LUISController</em></a>. Each of these extends a base class, making it easier to incorporate other cloud integrations like google’s <em>dialogflow</em>, etc. The corresponding base classes (in the top level of <em>src</em>) are: <em>ASRController</em>, <em>TTSController</em> and <em>NLUController</em>.</p><p>All of the speech api controller classes make use of an AsyncToken class to help manage asynchronous cloud results. AsyncToken extends EventEmitter and ads a property called, complete, a reference to the promise returned by async cloud calls. This makes it easy to report status events while waiting for the promise to complete. The <em>AsyncToken</em> class looks like:</p><pre>import { EventEmitter } from &#39;events&#39;;</pre><pre>export default class AsyncToken&lt;T&gt; extends <strong>EventEmitter</strong> {</pre><pre>    public <strong>complete</strong>: Promise&lt;T&gt;;</pre><pre>    constructor() {<br>        super();<br>    }<br>}</pre><p><em>ASRController</em> looks like:</p><pre>export default abstract class ASRController {</pre><pre>    abstract <strong>RecognizerStart</strong>(options?: any): <strong>AsyncToken</strong>&lt;string&gt;;</pre><pre>}</pre><p><em>TTSController</em> look like:</p><pre>export default abstract class TTSController {</pre><pre>    abstract <strong>SynthesizerStart</strong>(text: string, options?: any): <br>        <strong>AsyncToken</strong>&lt;string&gt;;</pre><pre>}</pre><p>And NLUController looks like:</p><pre>export type <strong>NLUIntentAndEntities</strong> = {<br>    intent: string;<br>    entities: any;<br>}</pre><pre>export type <strong>NLURequestOptions</strong> = {<br>    languageCode?: string;<br>    contexts?: string[];<br>    sessionId?: string;<br>}</pre><pre>export enum <strong>NLULanguageCode</strong> {<br>    en_US = &#39;en-US&#39;<br>}</pre><pre>export default abstract class NLUController {</pre><pre>  <strong>constructor</strong>() {<br>  }</pre><pre>  abstract <strong>set config</strong>(config: any);</pre><pre>  abstract <strong>call</strong>(query: string, languageCode: string, <br>    context: string, sessionId?: string): Promise&lt;any&gt;;</pre><pre>  abstract <strong>getEntitiesWithResponse</strong>(response: any): any | undefined;</pre><pre>  abstract <strong>getIntentAndEntities</strong>(utterance: string, <br>    options?: NLURequestOptions): AsyncToken&lt;NLUIntentAndEntities&gt;;<br>}</pre><p>The <em>NLUIntentAndEntities</em> type is used to map an intent (string) to an object containing NLU results.</p><p>The <em>NLURequestOptions</em> type is used to provide the set of options that most cloud NLU services require (Microsoft, google, etc.)</p><p>The abstract methods, set config(config), call(query, languageCode, context, sessionId), getEntitiesWithResponse(response), getIntentAndEntities(utterance, options) must be overridden to handle the specific requirements of the cloud NLU service.</p><p><strong>For example: <em>LUISController</em></strong></p><p>As mentioned above, the <em>LUISController</em> class extends <em>NLUController. </em>getIntentAndEntities() instantiates an <em>AsyncToken</em> to manage the asynchronous cloud NLU request and then executes the LUIS-specific <strong>call()</strong> method:</p><pre><strong>getIntentAndEntities</strong>(utterance: string, <br>  options?: NLURequestOptions): <strong>AsyncToken&lt;NLUIntentAndEntities&gt;</strong> {<br>    options = options || {};<br>    let <strong>defaultOptions</strong>: NLURequestOptions =  {<br>        languageCode: NLULanguageCode.en_US,<br>        contexts: undefined,<br>        sessionId: undefined<br>    }<br>    options = Object.assign(defaultOptions, options);</pre><pre>  let <strong>token</strong> = new AsyncToken&lt;NLUIntentAndEntities&gt;();<br>    token.complete = <br>      new Promise&lt;NLUIntentAndEntities&gt;((resolve, reject) =&gt; {<br>        <strong>this.call</strong>(utterance)<br>            .then((response: LUISResponse) =&gt; {<br>                let intentAndEntities: NLUIntentAndEntities = {<br>                    intent: &#39;&#39;,<br>                    entities: undefined<br>                }<br>                if (response &amp;&amp; response.topScoringIntent) {<br>                    intentAndEntities = {<br>                        intent: response.topScoringIntent.intent,<br>                        entities:    <br>                          <strong>this.getEntitiesWithResponse</strong>(response)<br>                    }<br>                }<br>                resolve(intentAndEntities);<br>            })<br>            .catch((err: any) =&gt; {<br>                reject(err);<br>            });<br>    });<br>    return token;<br>}</pre><p>call(query) uses request() to send the query (utterance) to the appropriate LUIS cloud endpoint with the required authentication tokens in the query string parameters:</p><pre><strong>call</strong>(query: string): Promise&lt;any&gt; {<br>    let <strong>endpoint</strong> = this.endpoint;<br>    let <strong>luisAppId</strong> = this.luisAppId;<br>    let queryParams = {<br>        &quot;<strong>subscription-key</strong>&quot;: this.subscriptionKey,<br>        &quot;timezoneOffset&quot;: &quot;0&quot;,<br>        &quot;verbose&quot;: true,<br>        &quot;q&quot;: query<br>    }</pre><pre>    let <strong>luisRequest</strong> = endpoint + luisAppId + &#39;?&#39; + <br>      querystring.stringify(queryParams);</pre><pre>    return new Promise((resolve, reject) =&gt; {<br>        <strong>request</strong>(luisRequest,<br>            ((error: string, response: any, body: any) =&gt; {<br>                if (error) {<br>                    console.log(`error:`, response, error);<br>                    reject(error);<br>                } else {<br>                    let body_obj: any = JSON.parse(body);<br>                    resolve(body_obj);<br>                }<br>            }));<br>    });<br>}</pre><p>Then getEntitiesWithResponse(response) parses the LUIS-specific response into the more general form expected by the Hub and Skills.</p><pre><strong>getEntitiesWithResponse</strong>(response: LUISResponse): any {<br>    let entitiesObject: any = {<br>        user: &#39;Someone&#39;,<br>        userOriginal: &#39;Someone&#39;,<br>        thing: &#39;that&#39;,<br>        thingOriginal: &#39;that&#39;<br>    };</pre><pre>    response.entities.forEach((entity: LUISEntity) =&gt; {<br>        entitiesObject[`${entity.type}Original`] = entity.entity;<br>        if (entity.resolution &amp;&amp; entity.resolution.values) {<br>            entitiesObject[`${entity.type}`] = <br>              entity.resolution.values[0];<br>        }<br>    });</pre><pre>    return entitiesObject;<br>}</pre><p><strong>The HotwordController and Snowboy</strong></p><p><em>Snowboy</em> is a lightweight, free-for-developers hotword/wake-word detector. (<a href="https://snowboy.kitt.ai/">https://snowboy.kitt.ai)</a> It provides one of the key robot-like aspect of robokit — the ability to automatically respond to voice interactions. Like the speech api controller classes, the <em>HotwordController</em> class provides an abstract interface that is extended by the implementation-specific <em>SnowboyController</em>. The base class, <em>HotwordController,</em> looks like:</p><pre>export type <strong>HotwordResult</strong> = {<br>    hotword: string;<br>    index?: number;<br>    buffer?: any;<br>}</pre><pre>export default abstract class HotwordController {</pre><pre>    abstract <strong>RecognizerStart</strong>(options?: any): <br>      <strong>AsyncToken&lt;HotwordResult&gt;</strong>;</pre><pre>}</pre><p><a href="https://github.com/wwlib/robokit/blob/master/src/renderer/snowboy/SnowboyController.ts"><em>SnowboyController</em></a> looks like:</p><pre>const record = require(&#39;<strong>node-record-lpcm16</strong>&#39;);<br>import { <strong>Detector</strong>, <strong>Models</strong> } from &#39;<strong>snowboy</strong>&#39;;</pre><pre>...</pre><pre>const modelPath: string = <br>  path.resolve(root, &#39;resources/models/HeyRobo.pmdl&#39;);</pre><pre>...</pre><pre>export default class SnowboyController extends HotwordController{</pre><pre>  public models: Models<br>  public detector: Detector;<br>  public mic: any;</pre><pre>  constructor() {<br>    super();<br>    this.models = new Models();<br>    this.models.add({<br>      file: modelPath,<br>      sensitivity: &#39;0.5&#39;,<br>      hotwords : &#39;snowboy&#39;<br>    });<br>  }</pre><pre>...</pre><pre>}</pre><p><em>SnowboyController</em> uses the npm module, <a href="https://www.npmjs.com/package/node-record-lpcm16"><em>node-record-lpcm16</em></a>, to pipe audio to the snowboy <em>Detector</em>. The <em>Detector</em> and <em>Models</em> classes are imported from the npm <a href="https://www.npmjs.com/package/snowboy"><em>snowboy</em></a> module. The <em>Models</em> class loads a recognition model file which is used by the <em>Detector</em> to analyze the audio stream. There are several models included in the <em>resources/models</em> folder including <em>HeyRobo.pmdl</em>. This model was generated using the tools at snowboy.kitt.ai and based on three wave files containing examples of “Hey, robo.” The wave files are in the <em>audio</em> folder: <a href="https://github.com/wwlib/robokit/blob/master/audio/hey-robo1.wav">hey-robo1.wav</a>, hey-robo2.wav, and hey-robo3.wav. Because the<em>HeyRobo.pmd</em> model is based on a dataset of just three wave files (and just one user, me) it will likely not work well for everyone. A customized, user-specific model can be generated from wav files using the snowboy tools. Or, to try a more general model, edit this line to use the ‘snowboy.pmdl’ file instead:</p><pre>const modelPath: string = <br>  path.resolve(root, &#39;resources/models/snowboy.pmdl&#39;);</pre><p>And remember to say “Snowboy” instead of “Hey, Robo” to get <em>robokit’s</em> attention.</p><p>The RecognizerStart(options: any) method instantiates the snowboy <em>Detector</em> class and uses <em>record</em> to pipe audio to the <em>Detector</em>. Again, <em>record</em> uses <em>sox</em> to access the host’s microphone.</p><pre><strong>RecognizerStart</strong>(options: any): AsyncToken&lt;HotwordResult&gt; {<br>  let sampleRate = 16000;<br>  if (options &amp;&amp; options.sampleRate) {<br>    sampleRate = options.sampleRate;<br>  }<br>  let token = new AsyncToken&lt;HotwordResult&gt;();<br>  token.complete = new Promise&lt;HotwordResult&gt;((resolve: any, <br>      reject: any) =&gt; {<br>    process.nextTick(() =&gt; {token.emit(&#39;Listening&#39;);});</pre><pre>    this.detector = <strong>new Detector</strong>({<br>      resource: commonResPath,<br>      models: this.models,<br>      audioGain: 2.0,<br>      applyFrontend: true<br>    });</pre><pre>    this.detector.on(&#39;<strong>silence</strong>&#39;, () =&gt; {<br>      token.emit(&#39;silence&#39;);<br>    });</pre><pre>    this.detector.on(&#39;<strong>sound</strong>&#39;, (buffer) =&gt; {<br>      token.emit(&#39;sound&#39;);<br>    });</pre><pre>    this.detector.on(&#39;<strong>error</strong>&#39;, (error: any) =&gt; {<br>      console.log(&#39;error&#39;, error);<br>      reject(error);<br>    });</pre><pre>    this.detector.on(&#39;<strong>hotword</strong>&#39;, function (index, hotword, buffer) {<br>      record.stop();<br>      token.emit(&#39;hotword&#39;);<br>      resolve({hotword: hotword, index: index, buffer: buffer});<br>    });</pre><pre>    this.mic = <strong>record</strong>.start({<br>      threshold: 0,<br>      sampleRate: sampleRate,<br>      verbose: true,<br>    });</pre><pre>    this.mic.<strong>pipe</strong>(this.detector as any);<br>  });</pre><pre>  return token;<br>}</pre><p><em>SnowboyController</em> emits several events via the AsyncToken that is returned by RecognizerStart(). The events include: <em>Listening</em>, <em>silence</em>, <em>sound</em>, <em>error</em> and <em>hotword</em>. The <em>hotword</em> event is used in <em>renderer.ts</em> to activate the <em>eye’s</em> blue outline animation.</p><p><strong>Troubleshooting</strong></p><p>For a vastly simplified approximation of a social robot, <em>robokit</em> is still fairly complex. If everything doesn’t work the first time, there are several key integration points that can be tested/validated independently. A good strategy is to test in the following order:</p><p><em>Presentation Layer</em></p><p>First, does the app start up and display the on-screen eye? If not, the console log should provide some indication of why. The presentation layer of the app is a very simple Pixi.js renderer with some HTML buttons to trigger/test the animations. Any issues here can likely be resolved by google-ing error messages.</p><p><em>Sox</em></p><p><em>Sox</em> is a well-known library and there is plenty of helpful information about it. As mentioned above, the <a href="https://github.com/wwlib/robokit/blob/master/docs/jupyter/hello-sox-python-mac.ipynb">hello-sox-python-mac.ipynb</a> Jupyter notebook demonstrates a number of ways to validate the sox installation from the command line.</p><p><em>Snowboy</em></p><p>To test the <em>snowboy</em> wake word recognizer by itself, there is a JavaScript file in the <em>tools</em> folder, test-snowboy.js, that will instantiate the recognizer, start listening and indicate when the wake word (“Hey, robo”) is heard. Run this script like:</p><pre>cd [robokit]/tools<br>node test-snowboy.js</pre><p>Then say, “Hey, robo.” The console output should look like this:</p><pre>$ node test-snowboy.js <br>/Users/.../github/wwlib/robokit/resources/models/HeyRobo.pmdl<br>/Users/.../github/wwlib/robokit/resources/common.res<br>Recording 1 channels with sample rate 16000...<br>Recording 8192 bytes<br>Recording 8192 bytes<br>Recording 8192 bytes<br>Recording 8192 bytes<br>Recording 8192 bytes<br>Recording 8192 bytes<br>Recording 8192 bytes<br>renderer: startHotword: on hotword: <br>HotWord: result: { hotword: &#39;snowboy&#39;,<br>  index: 1,<br>  buffer: &lt;Buffer 9f fe b4 fe ca fe e5 fe 07 ff 39 ff 74 ff aa ff de ff 0b 00 46 00 6c 00 95 00 bf 00 dd 00 f4 00 fc 00 fe 00 eb 00 d1 00 c6 00 b9 00 9c 00 7e 00 64 00 ... &gt; }<br>Recording 442 bytes<br>End Recording: 1940.446ms</pre><p>If there are errors, they can be addressed more easily using the <em>snowboy</em> test script.</p><p><em>The Cloud Speech API Calls</em></p><p>Issues with the cloud speech api calls will most likely be caused by errors in the cloud setup and/or in the config information used to authenticate api calls. Most importantly, the <em>data/config.json</em> file must contain valid authentication information. Note: use <em>data/config-example.json</em> as a starting point and save it as <em>data/config.json</em>.</p><pre>{<br>    &quot;Microsoft&quot;: {<br>        &quot;BingSubscriptionKey&quot;: &quot;&lt;YOUR-BING-SUBSCRIPTION-KEY&gt;&quot;,<br>        &quot;nluLUIS_endpoint&quot;: &quot;&lt;<a href="https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/">E</a>NDPOINT-URL&gt;&quot;,<br>        &quot;nluLUIS_appId&quot;: &quot;&lt;YOUR-LUIS-APP-ID&gt;&quot;,<br>        &quot;nluLUIS_subscriptionKey&quot;: &quot;&lt;YOUR-LUIS-SUBSCRIPTION-KEY&gt;&quot;<br>    }<br>}</pre><p>In the tools folder there are three JavaScript files that can be used to test the ASR, TTS and NLU apis.</p><pre>test-bing-speech.js<br>test-bing-tts.js<br>test-luis-nlu.js</pre><p>Details for setting up <em>robokit’s</em> NLU and using these testing tools are in the article: <a href="https://medium.com/@andrew.rapo/robokit-setting-up-azure-cognitive-services-bing-speech-luis-nlu-fbb39f5dc957">https://medium.com/@andrew.rapo/robokit-setting-up-azure-cognitive-services-bing-speech-luis-nlu-fbb39f5dc957</a></p><p><strong>PixiAnimate and Pixi.js</strong></p><p><strong>robokit’s</strong> eye animations are authored using <em>Adobe Animate’s</em> familiar timeline animation features and rendered using <em>Pixi.js</em>. For details see: <a href="https://medium.com/@andrew.rapo/robokit-using-adobe-animate-and-the-pixianimate-extension-to-create-webgl-pixi-js-a862a0f0296a">https://medium.com/@andrew.rapo/robokit-using-adobe-animate-and-the-pixianimate-extension-to-create-webgl-pixi-js-a862a0f0296a</a></p><p><strong>Remote Operation Mode (Rom)</strong></p><p><em>robokit</em> includes a socket server that allows it to receive connections from — and be operated remotely — by a remote controller app. Remote control is a powerful way to test and study human-robot interactions while fully autonomous software is being designed developed. Real time remote control by a human operator (puppeteering) is often referred to as <strong>Woz</strong> prototyping (“pay no attention to that man behind the curtain…”). <em>robokit</em> is Woz-ready.</p><p><em>robokit</em> is also designed to enable <em>Remote Operation Mode</em> development where an autonomous client controller app acts as the robot’s <em>brain </em>by intercepting UI events from <em>robokit</em> and then remote controlling <em>robokit</em> based on its own logic. For an example of a <em>Remote Operation Mode</em> controller that is compatible with <em>robokit</em>, see: <strong>robocommander</strong> (<em>http://robocommander.io)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5FfSxhTjpdBKFqv-hf1yUA.png" /><figcaption>robokit Remote Operation Mode (i.e. via robocommander)</figcaption></figure><p><strong>Summary</strong></p><p>If you have always dreamed of creating your own social“robot” — one that you can interact with in a natural, voice-driven way — then <em>robokit</em> is a great place to start. This simple framework demonstrates how to leverage the powerful, cloud-based cognitive services that are now readily available. And by getting <em>robokit</em> working you will be a long way toward understanding what is going on inside a more sophisticated robot like Jibo.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10847e9a2661" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[robokit: Setting up Azure Cognitive Services: Bing Speech & LUIS NLU]]></title>
            <link>https://medium.com/@andrew.rapo/robokit-setting-up-azure-cognitive-services-bing-speech-luis-nlu-fbb39f5dc957?source=rss-fa4b7766dc10------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbb39f5dc957</guid>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Andrew Rapo]]></dc:creator>
            <pubDate>Thu, 07 Mar 2019 02:56:32 GMT</pubDate>
            <atom:updated>2019-03-07T05:03:56.212Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GCksuM8J2lztUDOBndFd-Q.png" /></figure><p><strong>robokit</strong></p><p><a href="https://github.com/wwlib/robokit"><em>robokit</em></a> is an open source project that provides a foundation for developing conversational ai/social robot applications. It is described in details here: <a href="https://medium.com/@andrew.rapo/make-your-own-conversational-ai-social-robot-with-robokit-a-crude-approximation-of-jibo-10847e9a2661">https://medium.com/@andrew.rapo/make-your-own-conversational-ai-social-robot-with-robokit-a-crude-approximation-of-jibo-10847e9a2661</a></p><p>This article explains how to set up Microsoft cognitive services for use with <em>robokit</em>.</p><p><strong>Azure services</strong></p><p>From the main <strong>Azure services</strong> page (<em>https://portal.azure.com</em>), click on the <em>Cognitive Services</em> icon to get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l73GbLE6tMJob46cII_tNg.png" /></figure><p>On the All resources page, create a new cognitive services resource:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLgMp1bLjv3SdBirWXu72g.png" /></figure><p>On the <strong>Quick start</strong> page for the new resource, click on the <strong>keys</strong> link to get the keys needed for the <em>robokit</em> <em>config.json</em> file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_6XuhszYeneJjsURfyRl8w.png" /></figure><p><strong>configuring <em>robokit</em></strong></p><p>Copy <em>robokit’s</em> <em>data/config-example.json</em> file to <em>data/config.json.</em></p><pre>{<br>    &quot;Microsoft&quot;: {<br>        &quot;BingSTTSubscriptionKey&quot;: &quot;&lt;YOUR-BING-SUBSCRIPTION-KEY&gt;&quot;,<br>        &quot;nluLUIS_endpoint&quot;: &quot;<a href="https://">https://</a>...&quot;,<br>        &quot;nluLUIS_appId&quot;: &quot;&lt;YOUR-LUIS-APP-ID&gt;&quot;,<br>        &quot;nluLUIS_subscriptionKey&quot;: &quot;&lt;YOUR-LUIS-SUBSCRIPTION-KEY&gt;&quot;<br>    }<br>}</pre><p>Now use one of the two keys for the BingSTTSubscriptionKey property in the<em> config.json</em> file.</p><pre>&quot;BingSTTSubscriptionKey&quot;: &quot;&lt;YOUR-BING-SUBSCRIPTION-KEY&gt;&quot;,</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_FGpRcjNE0jP0wI9qn5dQ.png" /></figure><p>Note that the Free pricing tier allows 5k calls per month, plenty to get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sqVfRgReCefVRwKcd_J0QQ.png" /></figure><p>On the <strong>Metrics</strong> page you can keep track of your call usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQFa0B-XNsBpLCk-SPClJw.png" /></figure><p><strong>Setting up LUIS NLU</strong></p><p>The main LUIS setup page (<a href="https://www.luis.ai/">https://www.luis.ai</a>) uses the same login credentials as the other Azure cognitive services. To set up an NLU app for <em>robokit</em>, click on the <strong>Import new app</strong> link…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AM-mX6roooLvh4Q9I1XQfw.png" /></figure><p>…and upload the LUIS-knowledge-graph.json file found in <em>robokit’s</em> <em>docs</em> folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rn2kHZRDW13HimZs7uKGzA.png" /></figure><p>This will create a new <em>app</em> called <em>knowledge-graph</em>. Use the <em>Application ID</em> from the <strong>Application Information</strong> page for the nluLUIS_appId property in the <em>robokit</em> <em>config.json</em>.</p><pre>&quot;nluLUIS_appId&quot;: &quot;&lt;YOUR-LUIS-APP-ID&gt;&quot;,</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UyUzv4QgKPnhpXZV5fDsCg.png" /></figure><p>Use the <em>Authoring Key</em> and the <em>Endpoint</em> url from the <strong>Keys and Endpoints</strong> page for the nluLUIS_subscriptionKey property in the <em>robokit</em> <em>config.json</em>.</p><pre>&quot;nluLUIS_endpoint&quot;: &quot;https://...&quot;,<br>&quot;nluLUIS_subscriptionKey&quot;: &quot;&lt;YOUR-LUIS-SUBSCRIPTION-KEY&gt;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XuUXa4Ra8UkdnLiVjtz8YA.png" /></figure><p>Your <em>data/config.json</em> file should now be complete.</p><p><strong>Intents and Entities</strong></p><p>The <em>knowledge-graph</em> app includes a number of <em>intents</em> used by <em>robokit</em>, including launchClock, launchJoke, launchFavorite robot, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*awyYiRKpVS1Q-Xdghm8yJg.png" /></figure><p><em>Intents</em> are trained using a number of example phrases. For example, the launchClock intent is trained using example phrases like: “check the time” and “what time is it” so that it can recognize general time-related <em>utterances</em>. Intents can be thought of as actions or <em>verbs</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQ4qTzrXil70E00V2odGpQ.png" /></figure><p><em>Entities</em> can be thought of as nouns or subjects contained in utterances. A LUIS app can be trained to recognize specific, important entities like objects in a game or user names.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gIrTeFgCCWfuluN0RFBKRA.png" /></figure><p>For example, the <em>user</em> entity is trained using a list of names…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-bbiaHN0g4G1T3HuzIxwCg.png" /></figure><p>The <em>launchItsMe</em> <em>intent</em> recognizes utterances like, “Hey robo, it’s me, Andrew” and returns user property {user: “Andrew”} along with the intent {intent: “launchItsMe”}.</p><p><strong>Testing the Cognitive Services</strong></p><p>robokit’s tools folder contains several javascript files that can be used to test the cognitive services configuration. To test the STT (Speech to Text) api, run node test-bing-speech.js and say something like: “This is a test.” The console log should look like:</p><pre>$ node test-bing-speech.js<br>[Function: BingSpeechApiController]<br>{ Microsoft: <br>   { BingSTTSubscriptionKey: &#39;&#39;,<br>     nluLUIS_endpoint: &#39;<a href="https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/&#39;">&#39;</a>,<br>     nluLUIS_appId: &#39;&#39;,<br>     nluLUIS_subscriptionKey: &#39;&#39; }<br>}<br>Recording 1 channels with sample rate 16000...<br>bingSpeechApiController: on Listening<br>Recording 8192 bytes<br>Recording 8192 bytes<br>Recording 8192 bytes<br>Recording 8192 bytes<br>Recording 1120 bytes<br>End Recording: 2825.077ms<br>bingSpeechApiController: on RecognitionEndedEvent<br>bingSpeechApiController: utterance: <strong>this is a test</strong><br>bingSpeechApiController: on Recording_Stopped</pre><p>Running node test-bing-tts.js will send the string, “This is a test of bing t t s” to the cloud. The generated TTS audio will then be saved in a new file: tts-out.wav. The console output should look like this:</p><pre>$ node test-bing-tts.js <br>[Function: BingTTSController]<br>{ Microsoft: <br>  { <br>     BingSTTSubscriptionKey: &#39;&#39;,<br>     nluLUIS_endpoint: &#39;&#39;,<br>     nluLUIS_appId: &#39;&#39;,<br>     nluLUIS_subscriptionKey: &#39;&#39; <br>  }<br>}<br>bingTTSController: on Synthesizing<br>bingTTSController: on SynthesisEndedEvent<br>bingTTSController: result: This is a test of bing t t s</pre><p>Finally, executing node test-luis-nlu.js will send the test utterance, “what time is it” to the cloud. The console output should look like this:</p><pre>$ node test-luis-nlu.js<br>[Function: LUISController]</pre><pre>{ Microsoft: <br>  { <br>     BingSTTSubscriptionKey: &#39;&#39;,<br>     nluLUIS_endpoint: &#39;&#39;,<br>     nluLUIS_appId: &#39;&#39;,<br>     nluLUIS_subscriptionKey: &#39;&#39; <br>  }<br>}</pre><pre>LUISController: call: {<br>  &quot;<strong>query</strong>&quot;: &quot;<strong>what time is it</strong>&quot;,<br>  &quot;<strong>topScoringIntent</strong>&quot;: {<br>    &quot;intent&quot;: &quot;<strong>launchClock</strong>&quot;,<br>    &quot;score&quot;: <strong>0.95850873</strong><br>  },<br>  &quot;<strong>intents</strong>&quot;: [<br>    {<br>      &quot;intent&quot;: &quot;<strong>launchClock</strong>&quot;,<br>      &quot;score&quot;: <strong>0.95850873</strong><br>    },<br>    {<br>      &quot;intent&quot;: &quot;launchItsMe&quot;,<br>      &quot;score&quot;: 0.008585685<br>    },<br>    {<br>      &quot;intent&quot;: &quot;answerYes&quot;,<br>      &quot;score&quot;: 0.00772720156<br>    },<br>    {<br>      &quot;intent&quot;: &quot;launchFavoriteRobot&quot;,<br>      &quot;score&quot;: 0.00586581044<br>    },<br>    {<br>      &quot;intent&quot;: &quot;gameCommand&quot;,<br>      &quot;score&quot;: 0.003221985<br>    },<br>    {<br>      &quot;intent&quot;: &quot;launchGameInventory&quot;,<br>      &quot;score&quot;: 0.00309769<br>    },<br>    {<br>      &quot;intent&quot;: &quot;answerNo&quot;,<br>      &quot;score&quot;: 0.002760447<br>    },<br>    {<br>      &quot;intent&quot;: &quot;launchDoYouLike&quot;,<br>      &quot;score&quot;: 0.002700645<br>    },<br>    {<br>      &quot;intent&quot;: &quot;None&quot;,<br>      &quot;score&quot;: 0.00250991737<br>    },<br>    {<br>      &quot;intent&quot;: &quot;launchGame&quot;,<br>      &quot;score&quot;: 0.00226563332<br>    },<br>    {<br>      &quot;intent&quot;: &quot;launchJoke&quot;,<br>      &quot;score&quot;: 0.00209666253<br>    },<br>    {<br>      &quot;intent&quot;: &quot;launchUserLikes&quot;,<br>      &quot;score&quot;: 0.0007963245<br>    }<br>  ],<br>  &quot;entities&quot;: []<br>} null</pre><pre>NLUIntentAndEntities:  {<br>  &quot;<strong>intent</strong>&quot;: &quot;<strong>launchClock</strong>&quot;,<br>  &quot;entities&quot;: {<br>    &quot;user&quot;: &quot;Someone&quot;,<br>    &quot;userOriginal&quot;: &quot;Someone&quot;,<br>    &quot;thing&quot;: &quot;that&quot;,<br>    &quot;thingOriginal&quot;: &quot;that&quot;<br>  }<br>}</pre><p>Note that the LUIS results contains a lot of useful information, including a ranked list of likely intents. For now, the <em>LUISController</em> class always picks the intent with the highest score.</p><p><strong>Summary</strong></p><p>If all of the cloud api calls return successfully, <em>robokit’s</em> cognitive services should be configured correctly.</p><p>For more information about <a href="https://github.com/wwlib/robokit"><em>robokit</em></a>, see: <a href="https://medium.com/@andrew.rapo/make-your-own-conversational-ai-social-robot-with-robokit-a-crude-approximation-of-jibo-10847e9a2661">https://medium.com/@andrew.rapo/make-your-own-conversational-ai-social-robot-with-robokit-a-crude-approximation-of-jibo-10847e9a2661</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbb39f5dc957" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[robokit: Using Adobe Animate and the PixiAnimate Extension to create WebGL Pixi.js]]></title>
            <link>https://medium.com/@andrew.rapo/robokit-using-adobe-animate-and-the-pixianimate-extension-to-create-webgl-pixi-js-a862a0f0296a?source=rss-fa4b7766dc10------2</link>
            <guid isPermaLink="false">https://medium.com/p/a862a0f0296a</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Andrew Rapo]]></dc:creator>
            <pubDate>Thu, 07 Mar 2019 02:45:13 GMT</pubDate>
            <atom:updated>2019-03-07T03:25:38.360Z</atom:updated>
            <content:encoded><![CDATA[<h3>robokit: Using Adobe Animate and the PixiAnimate Extension to create WebGL Pixi.js Screen Animations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UEKsVKljSuNJLOziWRwO8w.png" /></figure><p><strong>robokit</strong></p><p><a href="https://github.com/wwlib/robokit"><em>robokit</em></a> is an open source project that provides a foundation for developing conversational ai/social robot applications. It is described in detail here: <a href="https://medium.com/@andrew.rapo/make-your-own-conversational-ai-social-robot-with-robokit-a-crude-approximation-of-jibo-10847e9a2661">https://medium.com/@andrew.rapo/make-your-own-conversational-ai-social-robot-with-robokit-a-crude-approximation-of-jibo-10847e9a2661</a></p><p>This article explains how to use the <em>PixiAnimate</em> extension for <em>Adobe Animate</em> to create screen animations for <em>robokit</em> that are rendered by<em> Pixi.js</em>.</p><p><strong>Adobe Animate and the PixiAnimate Extension</strong></p><p><a href="https://www.adobe.com/products/animate.html"><em>Adobe Animate</em></a> is part of Adobe’s Creative Cloud suite of applications and it is the most powerful tool available for creating timeline-based 2D animations. Using its <a href="https://www.adobe.io/apis/creativecloud/animate.html">Custom Platform SDK</a>, <em>Adobe Animate</em> can be extended to generate output for any platform. The open source <a href="https://www.adobeexchange.com/creativecloud.details.14345.pixianimate.html"><em>PixiAnimate</em></a> extension was developed at <em>Jibo, Inc.</em> so that <em>Adobe Animate</em> could be used to author high-performance, WebGL-based screen animations for Jibo’s Electron/Chrome display system. The <em>PixiAnimate</em> extension exports timeline animations as JavaScript and JSON objects that can be rendered and controlled by <em>Pixi.js</em>.</p><p><strong>Pixi.js</strong></p><p><a href="http://www.pixijs.com/"><em>Pixi.js</em></a> is a fast, flexible 2D WebGL renderer and animation system created by <a href="http://www.goodboydigital.com/">Goodboy Digital</a>.</p><p><strong><em>robokit</em> screen animations</strong></p><p><em>robokit’s</em> “eye” animations help convey information about its state and contribute to the (limited) impression that <em>robokit</em> is alert and aware. The eye can blink, look left, look right and display a highlight ring (blue). These animations are authored using <em>Adobe Animate’s</em> familiar timeline animation features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ML1c24bHVsw6yXZecLuXA.png" /></figure><p><em>Shapes</em> like the eye are defined using vectors and/or bitmaps. Animations are defined on the timeline using <em>frame labels</em>, <em>frame actions</em> and <em>animation tweens</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AqOKNkT3T-hEt7tyDc-VzA.png" /></figure><p>The <em>PixiAnimate</em> extension exports all of the shape, image and animation data as JavaScript and JSON objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*klq8HdGo7vylQXawOFFtFA.png" /></figure><p>The animations can then be loaded and controlled by JavaScript code that looks like:</p><pre>const eyeClassPath = root + &#39;<strong>/assets/eye/eye.js</strong>&#39;;<br>const eyeClass: any = require(eyeClassPath);</pre><pre>this.canvasElement = document.getElementById(&quot;stage&quot;) <br>    as HTMLCanvasElement;<br>this.renderer = PIXI.autoDetectRenderer(1280, 720, {<br>    view: this.canvasElement,<br>    backgroundColor: 0x0,<br>    antialias: true<br>});</pre><pre>this.stage = new PIXI.Container();<br>this._loaderCallback = (instance: any, loader: any):void =&gt; {<br>    this.eyeInstance = instance;<br>    this.eyeInstance.<strong>gotoAndStop(&#39;idle&#39;)</strong>;<br>    this.eyeInstance.eye.eye_blue.visible = false;<br>}<br>animate.load(eyeClass.library.eye, this.stage, <br>    this._loaderCallback as any, basePath);</pre><p>Animations can be played by referencing the labels defined on the timeline in Adobe Animate, like:</p><pre>this.eyeInstance.<strong>gotoAndStop(&#39;idle&#39;)</strong>;<br>this.eyeInstance.<strong>gotoAndPlay(&#39;blink&#39;);</strong></pre><p><strong>Installation</strong></p><p>Step 1: Get Adobe Animate through the Creative Cloud installer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*R3-czm1hWVFVsPfrCgJMhA.png" /></figure><p>Step 2: Install the <a href="https://www.adobeexchange.com/creativecloud.details.14345.pixianimate.html"><em>PixiAnimate</em></a> extension:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DIv2-6o5nykpPg11G0Cpvw.png" /></figure><p>Step 3: Verify that <em>PixiAnimate</em> is installed. It should show up as a new document type in <em>Adobe Animate</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fYChERrB5Uz_z70RtP5NXA.png" /></figure><p>Step 4: Open the <em>robokit/assets/eye/eye.fla</em> file:</p><p>Step 5: Make some additions, edits, adjustments, etc.</p><p>Step 6: Use the <em>File-&gt;Publish Settings…</em> menu to invoke the <em>PixiAnimate</em> exporter and generate new <em>eye</em> JavaScript and JSON files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*7D33nqop6WG3Hg_dPav1Dg.png" /></figure><p>Note: The output can be tested by navigating to the <em>robokit/assets/eye</em> folder and starting a local web server like http-server:</p><pre>npm install -g http-server<br>cd [robokit]/assets/eye<br>http-server</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WL9O_vVNZXs19iPi1iaaSw.png" /></figure><p><strong>Summary</strong></p><p>The <em>PixiAnimate</em> extension makes it possible to use <em>Adobe Animate</em> to author high-performance 2D animations for WebGL that can run on everything from a Mac to a Raspberry Pi (to Jibo).</p><p>For more information about <a href="https://github.com/wwlib/robokit"><em>robokit</em></a>, see: <a href="https://medium.com/@andrew.rapo/make-your-own-conversational-ai-social-robot-with-robokit-a-crude-approximation-of-jibo-10847e9a2661">https://medium.com/@andrew.rapo/make-your-own-conversational-ai-social-robot-with-robokit-a-crude-approximation-of-jibo-10847e9a2661</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a862a0f0296a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Adobe’s JavaScript-based ExtendScript (jsx) to Automate Photoshop Workflow Tasks]]></title>
            <link>https://medium.com/@andrew.rapo/using-adobes-javascript-based-extendscript-jsx-to-automate-photoshop-workflow-tasks-f3b6690650d9?source=rss-fa4b7766dc10------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3b6690650d9</guid>
            <category><![CDATA[workflow]]></category>
            <category><![CDATA[scripting]]></category>
            <category><![CDATA[bezier-curves]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[photoshop]]></category>
            <dc:creator><![CDATA[Andrew Rapo]]></dc:creator>
            <pubDate>Wed, 27 Feb 2019 15:05:23 GMT</pubDate>
            <atom:updated>2019-02-27T15:42:04.795Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GluKrKSSK-K2_YuDcbhOeg.png" /></figure><p><strong>Automating Photoshop Workflow Tasks</strong></p><p>This article describes an approach to <em>automating the Photoshop workflow</em> for an interactive storybook project. The project involves dozens (maybe hundreds) of Photoshop files with numerous layers that must be turned into bezier paths and exported for use in an <em>interactive storybook engine</em>. Although many of the steps can be done manually, a much better approach is to use ExtendScript, a variation of JavaScript that is built into many of Adobe’s applications. Not only can this save time, it can also provide a way to extract data from PSD files that can’t be accessed manually — like bezier path data.</p><p><strong>ExtendScript (jsx)</strong></p><p>Not to be confused with React’s .jsx files, ExtendScript files usually have a .jsx extension and contain a combination of JavaScript and special, Adobe-specific directives.</p><p><strong>Examples Repo</strong></p><p>All of the code examples described in this article are available in this github repo: <a href="https://github.com/mitmedialab/storybook-photoshop-jsx">https://github.com/mitmedialab/storybook-photoshop-jsx</a></p><p><strong>Hello World</strong></p><p>A good way to get started is with <em>hello-world.jsx</em> (<a href="https://github.com/mitmedialab/storybook-photoshop-jsx/blob/master/jsx-examples/hello-world.jsx">jsx-examples/hello-world.jsx</a>)</p><pre>alert(&#39;Hello, world.&#39;);</pre><p>Run the script by opening it in Photoshop: <em>File-&gt;Scripts-&gt;Browse…</em> then navigate to the script. You should see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*1rocC_icBtD89c0wemqPWQ.png" /></figure><p><strong>A Real-world Example: Peaches.psd</strong></p><p>The <em>peaches.psd</em> file (<a href="https://github.com/mitmedialab/storybook-photoshop-jsx/tree/master/psd/peaches.psd">psd/peaches.psd</a>) contains a hypothetical scene from an interactive storybook and includes four layers:</p><ul><li>guide_tl (a <strong>guide</strong> layer)</li><li>seed (an <strong>object</strong> layer containing an image of the peach seed/pit)</li><li>peach (an <strong>object</strong> layer containing an image of the peach)</li><li>bg (the <strong>background </strong>layer)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TzQPvx0r4x1ZdY2KIZIEaA.png" /><figcaption>peaches.psd</figcaption></figure><p>The above-mentioned storybook engine needs information from each layer so it can manipulate the objects in the scene. In particular, the outlines of each object need to be exported as as bezier point data. The engine also needs info from the guide layer which indicates where text can be drawn in the scene — in this case, the top left corner (i.e. ‘tl’). Finally the engine needs a jpeg image that includes all the layers except the guide layer(s).</p><p><strong>The Scripts</strong></p><p>All of this is accomplished by a script called <em>process-file.jsx</em> which <em>#includes</em> a handful of scripts so it can make use of the functions defined in each of them. All of the functions could be included in one long script, but this modular approach has advantages. It makes it easy to utilize and troubleshoot each script individually. And it makes the project easier to explain. The complete set of scripts includes:</p><ul><li><strong>get-layers.jsx</strong>: gathers layer data into a JSON object</li><li><strong>get-layer-path.jsx</strong>: creates a new Work Path for the layer</li><li><strong>get-bounds.jsx</strong>: gets the bounds of the current selection</li><li><strong>get-path-data.jsx</strong>: gathers bezier point data into a JSON object</li><li><strong>export-svg.jsx</strong>: exports an svg file version of a path</li><li><strong>save-image.jsx</strong>: saves a jpeg version of the file, excluding guide layers</li><li><strong>process-file.jsx</strong>: choreographs all of the above scripts</li></ul><p><strong>Testing the script with: do-[script-name].jsx</strong></p><p>Each of the above-mentioned scripts acts as a mini library, defining a number of functions. To make running/testing easier, each script has a companion script that can be used to run/test it. These are named like <em>do-[script-name].jsx</em>. For example, <em>do-get-layers.jsx</em> will execute the primary function in <em>get-layers.jsx, </em>getLayerData() , and return the resulting JSON object.</p><p><strong>get-layers.jsx</strong></p><p><em>get-layers.jsx</em> defines a function, getLayerData(), that returns metadata about all the layers in the PSD. The code looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2419bb2f497690ae20727018c5379531/href">https://medium.com/media/2419bb2f497690ae20727018c5379531/href</a></iframe><p>In the above code, var allLayers = app.activeDocument.layers; returns an array containing references to all of the layers in the active document (PSD) and allLayers[i].name provides access to each layer’s name. The JSON returned by getLayerData() looks like:</p><pre>{<br>  &quot;layerNames&quot;: [<br>    &quot;guide_tl&quot;,<br>    &quot;seed&quot;,<br>    &quot;peach&quot;,<br>    &quot;bg&quot;<br>  ],<br>  &quot;layerCount&quot;: 4,<br>  &quot;layers&quot;: [<br>    {<br>      &quot;type&quot;: &quot;GUIDE&quot;,<br>      &quot;name&quot;: &quot;guide_tl&quot;<br>    },<br>    {<br>      &quot;type&quot;: &quot;OBJ&quot;,<br>      &quot;name&quot;: &quot;seed&quot;<br>    },<br>    {<br>      &quot;type&quot;: &quot;OBJ&quot;,<br>      &quot;name&quot;: &quot;peach&quot;<br>    },<br>    {<br>      &quot;type&quot;: &quot;BG&quot;,<br>      &quot;name&quot;: &quot;bg&quot;<br>    }<br>  ]<br>}</pre><p><strong>get-layer-path.jsx</strong></p><p><em>get-layer-path.jsx</em> defines getPathWithLayerName(layerName) which creates a new <em>Work Path</em> and returns both metadata about that path and a reference to the new path, itself.</p><p>The getTightSelectionWithLayerName(layerName) function creates a new selection that includes only the non-transparent pixels on the specified layer. This is accomplished by simulating the menu action <em>Select-&gt;All</em> followed by simulating a click on the <em>Move</em> tool and then simulating using the arrow keys to <em>nudge</em> the selection right and then left. (If anyone knows a more code-oriented way to accomplish this, let me know!)</p><p><strong>Btw</strong>: A good way to figure out how to simulate manual UI interactions in Photoshop is to use the ScriptingListenerPlugin provided by Adobe: <a href="https://helpx.adobe.com/photoshop/kb/downloadable-plugins-and-content.html#ScriptingListenerplugin">https://helpx.adobe.com/photoshop/kb/downloadable-plugins-and-content.html#ScriptingListenerplugin</a></p><p>Finally, selectionToWorkPath() generates a new path (Work Path) based on the selection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Yf8pg2_AEYEM_yf1c69Aw.png" /></figure><p>The <em>get-layer-path.jsx</em> code looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0aee0945f4308c2bfdd796623fa7e3c/href">https://medium.com/media/b0aee0945f4308c2bfdd796623fa7e3c/href</a></iframe><p><strong>get-bounds.jsx</strong></p><p>get-bounds.jsx defines the function, getSelectionBounds(), which return a JSON object containing parameters describing the bounds of the current selection:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e241508b1e3edca1b1cd52bd17562a80/href">https://medium.com/media/e241508b1e3edca1b1cd52bd17562a80/href</a></iframe><p>The JSON returned looks like:</p><pre>{<br>  &quot;xLeft&quot;: 363,<br>  &quot;yTop&quot;: 281,<br>  &quot;xRight&quot;: 837,<br>  &quot;yBottom&quot;: 606<br>}</pre><p><strong>get-path-data.jsx</strong></p><p><em>get-path-data.jsx</em> defines two functions which take a path object as an argument and return either an SVG or bezier representation of the path. pathToSvgData(path) returns an SVG string which looks like:</p><pre>M689 281C710.435221285203 282.050722610512 734.938543937045 281.48934292098 751 288C823.962562426532 317.576037297225 869.579783631659 413.905746219374 810 493C787.119662197185 523.374451440617 755.729558281528 536.583852141727 708 543C687.6687 542.3334 667.3313 541.6666 647 541C638.632720583811 545.328833790592 635.113792760834 555.358477449161 628 561C603.358734520226 580.541510353059 574.502693773079 596.390451588511 538 604C436.012088397763 625.260950097228 348.762579462231 531.646136186465 365 434C367.957429932036 416.215056558162 367.058265877123 400.856198210928 373 387C397.407713092162 330.080908117657 455.515078242546 356.540803684843 518 346C533.154518570513 343.443530363851 571.662669952291 351.680893824889 574 350C594.880015894225 324.146012684335 609.3388741798 298.195654143152 644 286</pre><p>pathToBezierData(path) returns a JSON object containing an array of bezier points, each of which has an <em>anchor</em> point, a <em>leftDirection</em> point and a <em>rightDirection</em> point:</p><pre>[<br>  {<br>    &quot;anchor&quot;: {<br>      &quot;x&quot;: 689,<br>      &quot;y&quot;: 281<br>    },<br>    &quot;leftDirection&quot;: {<br>      &quot;x&quot;: 710.435221285203,<br>      &quot;y&quot;: 282.050722610512<br>    },<br>    &quot;rightDirection&quot;: {<br>      &quot;x&quot;: 675.597084969992,<br>      &quot;y&quot;: 286.152049962991<br>    }<br>  },</pre><pre>...</pre><pre><br>  {<br>    &quot;anchor&quot;: {<br>      &quot;x&quot;: 644,<br>      &quot;y&quot;: 286<br>    },<br>    &quot;leftDirection&quot;: {<br>      &quot;x&quot;: 655.968336099604,<br>      &quot;y&quot;: 281.788893629799<br>    },<br>    &quot;rightDirection&quot;: {<br>      &quot;x&quot;: 609.3388741798,<br>      &quot;y&quot;: 298.195654143152<br>    }<br>  }<br>]</pre><p><strong>export-svg.jsx</strong></p><p><em>export-svg.jsx</em> defines exportSvgWithPathData(svgPathData, filename, documentBounds) which embeds the SVG path data in an xml object and saves it to the filesystem:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98beb1cb52e56f1c806e7a6ca6647ef0/href">https://medium.com/media/98beb1cb52e56f1c806e7a6ca6647ef0/href</a></iframe><p><strong>save-image.jsx</strong></p><p><em>save-image.jsx</em> defines saveJpeg(name) which writes the current PSD to a .jpg file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffa583e2f859b92731e6f34165a2b428/href">https://medium.com/media/ffa583e2f859b92731e6f34165a2b428/href</a></iframe><p><strong>process-file.jsx</strong></p><p>As noted at the start of the article, <em>process-file.jsx</em> choreographs the activities of all the other scripts to accomplish the following:</p><ul><li>Creates a JSON object to hold metadata from the PSD</li><li>Resizes the PSD, if necessary</li><li>Finds the bounds (size) of the PSD</li><li>Iterates through the layers of the PSD</li><li>Determines the type of each layer</li><li>Generates a path outline for each object layer</li><li>Saves the path data to an SVG file</li><li>Adds the bezier path data to the JSON object</li><li>Hides all guide layers</li><li>Saves the JSON data to a file</li><li>Saves a .jpg version of the PSD to a file</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba04158f079d08075c006426c8f3bb4b/href">https://medium.com/media/ba04158f079d08075c006426c8f3bb4b/href</a></iframe><p><strong>do-storybook-palette.jsx</strong></p><p>All of the scripts mentioned above can be easily invoked through the <em>File-Scripts-&gt;Browse…</em> menu, but there are ways to add custom UI to Photoshop. The best way to do this is by developing a custom Panel using the ExtendScript SDK. However, this is a fairly involved process. A simpler approach that may be adequate in some situations is to use a non-modal dialog — a Palette. The <em>do-storybook-palette.jsx</em> script instantiates a UI Palette that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rc2cpl6sbsDmR6Q6o5jp5g.png" /><figcaption>do-storybook-palette.jsx</figcaption></figure><p>This Palette is persistent and will float above the standard Photoshop UI until it is canceled. Because it is non-modal, you can keep working as normal while it is active. The buttons on the panel can be used to trigger scripts and it is easy to configure the panel with additional buttons and fields. The code looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de224d36727cb0b9bc92cb73c9b339d6/href">https://medium.com/media/de224d36727cb0b9bc92cb73c9b339d6/href</a></iframe><p>As a way to streamline the process of invoking scripts, this approach works well.</p><p><strong>Note</strong>: The responsiveness of the standard Photoshop UI is degraded when this kind of panel is active so use it only when needed.</p><p><strong>Summary</strong></p><p>Photoshop scripting is powerful. It has been around for a long time and it is easy to use. The examples in this article are designed to support a specific, interactive storybook project, but they can be repurposed and adapted and should make it easy to get started with Adobe ExtendScript.</p><p>(This code in this article was developed for <strong><em>Adobe Photoshop CC 2019</em></strong> and has only been tested on this version.)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3b6690650d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Create-React-App + Craco to build apps for both the Web and Electron]]></title>
            <link>https://medium.com/@andrew.rapo/using-create-react-app-craco-to-build-apps-for-both-the-web-and-electron-8f4ab827877f?source=rss-fa4b7766dc10------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f4ab827877f</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[electron]]></category>
            <category><![CDATA[craco]]></category>
            <category><![CDATA[create-react-app]]></category>
            <dc:creator><![CDATA[Andrew Rapo]]></dc:creator>
            <pubDate>Thu, 20 Dec 2018 22:11:16 GMT</pubDate>
            <atom:updated>2019-11-01T19:08:07.491Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Create-React-App + Craco + Typescript to build apps for both the Web and Electron</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1lrrtI2lfyUfuVb0WONz5Q.png" /></figure><p>[UPDATE: November 1, 2019 — Updated to use @craco/craco 5.61, react-scripts 3.2.0 and Electron 7]</p><p>I often build tools and prototypes that need to work well, look good and be shared easily. When I was at Jibo we used Electron for both SDK tools and the on-robot presentation layer. In my current role as a developer/designer working with the Personal Robots Group at the MIT Media Lab I am creating a content authoring tool that needs to be deployed both on the Web and as a standalone app.</p><p>Because it can easily embed a Web app, Electron is a good option for the standalone version. And after a fair amount of experimentation and research I have settled on React as the best choice for the UI. Combining React and Electron is straightforward when making <em>either</em> a Web app <em>or</em> an Electron app. Supporting both has been tricky until now — until <a href="https://www.npmjs.com/package/@craco/craco"><em>@craco/craco</em></a>.</p><p><strong>create-react-app + @craco/craco = awesome</strong></p><p>One of the best things about React is <strong>create-react-app</strong>, a CLI tool for setting up and maintaining a react project. With create-react-app it is easy to setup a project for Web development because details about configuring things like webpack are handled automatically. On the down side, if you need to change the webpack config you must first <em>eject</em> the project, i.e. disconnect if from automatic-control-by-create-react-app. This is irreversible and once ejected it is up to you to manually keep your project in sync with updates to react-scripts, etc. Craco solves this problem.</p><p>With <strong>create-react-app 2</strong>, you can use the <a href="https://www.npmjs.com/package/@craco/craco">craco npm module</a> to override the webpack config so it targets electron. This is accomplished using a craco config file that looks like this: <em>craco.config.js</em></p><pre>let target = &#39;web&#39;;<br>if (process.env.REACT_APP_MODE === &#39;electron&#39;) {<br>  target = &#39;electron-renderer&#39;<br>}<br>console.log(`craco.config.js: setting webpack target to: ${target}`);</pre><pre>module.exports = {<br>    webpack: {<br>        configure: {<br>            target: target<br>        }<br>    }<br>};</pre><p>I have created a project to demonstrate this using React + Typescript. The source code is in this <a href="https://github.com/wwlib/cra-craco-electron-example">github repo</a>. The project builds a simple app that behaves appropriately whether running in the browser or in Electron.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FczSLNh2XLAk%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DczSLNh2XLAk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FczSLNh2XLAk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/96021dad6eda568ece636c8a9f28b103/href">https://medium.com/media/96021dad6eda568ece636c8a9f28b103/href</a></iframe><p>In the Atom editor, the project looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9tYnsYYrEwe2rynfNaHVmA.png" /></figure><p>When running in the browser the app displays a message indicating that “Directory listing is not available in the browser.” The Web version of the app does not have filesystem access (of course):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UINg0MqJOCH-9n7JHlMHoQ.png" /><figcaption>The example app running in the browser.</figcaption></figure><p>However, when running in electron the app displays the directory listing — because Electron does have access to the filesystem. Cool:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zyaoKGD_9dHTjGsOhCC1ig.png" /><figcaption>The example project running in Electron.</figcaption></figure><p><strong>Dependencies: package.json</strong></p><p>In addition to the dependencies that are included by create-react-app, the example project uses several additional dependencies:</p><pre>&quot;<a href="http://twitter.com/craco/craco">@craco/craco</a>&quot;: &quot;^5.6.1&quot;,<br>&quot;electron&quot;: &quot;^7.0.0&quot;,<br>&quot;electron-builder&quot;: &quot;^22.1.0&quot;,<br>&quot;env-cmd&quot;: &quot;^10.0.1&quot;,<br>&quot;npm-watch&quot;: &quot;^0.6.0&quot;</pre><p><a href="https://www.npmjs.com/package/electron"><em>electron</em></a> is used to launch/run the electron build<em>. </em><a href="https://www.npmjs.com/package/electron-builder"><em>electron-builder</em></a> is included in the project to demonstrate how to generate a native (i.e. MacOS), distributable standalone build. <a href="https://www.npmjs.com/package/env-cmd"><em>env-cmd</em></a> is used to embed environment-specific variables in the builds (details below). And <a href="https://www.npmjs.com/package/npm-watch"><em>npm-watch</em></a> is used to automatically build/rebuild the electron version (again, details below).</p><p><strong>Leveraging environment variables</strong></p><p>When running as a standalone app in Electron, the app can utilize features like file system access. When running in the browser, filesystem access is not available. The example app uses environment variables to know what features are available. During the build process, the <a href="https://www.npmjs.com/package/env-cmd">env-cmd</a> module is used to embed environment variables in the build from one of two .env files:</p><p>.env.electron</p><pre>REACT_APP_NAME=myApp<br>REACT_APP_MODE=electron</pre><p>.env.web</p><pre>REACT_APP_NAME=myApp<br>REACT_APP_MODE=web</pre><p>When the app runs it can decide when to use and/or require certain features:</p><pre>let fs: any;<br>if (process.env.REACT_APP_MODE == &#39;electron&#39;) {<br>    console.log(`REQUIRING fs-extra`);<br>    fs = require(&#39;fs-extra&#39;);<br>}</pre><pre>and...</pre><pre>getDirectoryListing(): string {<br>    if (process.env.REACT_APP_MODE == &#39;electron&#39;) {<br>        let files = fs.readdirSync(&#39;.&#39;);<br>        return JSON.stringify(files, null, 2);<br>    } else {<br>        return &#39;Directory listing is not available in the browser.&#39;<br>    }<br>}</pre><p><strong>Modifying scripts in package.json</strong></p><p>The default package.json provided by create-react-app includes scripts that look like:</p><pre>&quot;start&quot;: &quot;react-scripts start&quot;,<br>&quot;build&quot;: &quot;react-scripts build&quot;,<br>&quot;test&quot;: &quot;react-scripts test&quot;,</pre><p>To use craco, these scripts are modified to look like:</p><pre>&quot;start&quot;: &quot;craco start&quot;,<br>&quot;build&quot;: &quot;craco build&quot;,<br>&quot;test&quot;: &quot;craco test&quot;,</pre><p>This lets craco intercept the commands and make the necessary changes to the webpack config. In the example projects, the build scripts are further modified to support both the Web and Electron scenarios:</p><pre>&quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;yarn start:electron&quot;,<br>    &quot;start:web&quot;: &quot;env-cmd .env.web craco&quot;,<br>    &quot;start:electron&quot;: &quot;electron .&quot;,<br>    &quot;start:electron-dev&quot;: &quot;electron electron-dev.js&quot;,<br>    &quot;build&quot;: &quot;yarn build:electron&quot;,<br>    &quot;build:web&quot;: &quot;craco build&quot;,<br>    &quot;build:electron&quot;: &quot;env-cmd .env.electron craco&quot;,<br>    &quot;watch:electron&quot;: &quot;npm-watch&quot;,<br>    &quot;test&quot;: &quot;craco test&quot;,<br>    &quot;eject&quot;: &quot;react-scripts eject&quot;,<br>    &quot;pack&quot;: &quot;electron-builder --dir&quot;,<br>    &quot;dist&quot;: &quot;electron-builder&quot;<br>},</pre><p><strong>Building for the Web</strong></p><p><strong>start:web </strong>is used to launch the typical Web development mode using <em>.env.web</em> and <em>craco.config.js</em>. This starts a Web server, launches a Web browser and automatically rebuilds and reloads the Web app when changes are detected.</p><p><strong>Building for Electron</strong></p><p>For Electron, a similar result is accomplished by using <strong>watch:electron</strong> to automatically build and rebuild the electron version when changes are detected. A special entry in package.json lets <a href="https://www.npmjs.com/package/npm-watch">npm-watch</a><em> </em>know to run the <strong>build:electron</strong> script whenever the source code changes, using <em>.env.electron</em> and <em>craco.config.js</em>.</p><pre>&quot;watch&quot;: {<br>  &quot;build:electron&quot;: &quot;src/**/*.*&quot;<br>},</pre><p>In a separate console tab/window, <strong>start:electron-dev</strong> launches Electron using a special entry point, <em>electron-dev.js</em>, that restarts electron whenever a new build is detected.</p><pre>function debounce(func, ms) {<br>    let ts;<br>    return function() {<br>        clearTimeout(ts);<br>        ts = setTimeout(() =&gt; func.apply(this, arguments), ms);<br>    };<br>}</pre><pre>if (process.env.NODE_ENV !== &#39;production&#39;) {<br>    const watchPath = path.join(__dirname, &quot;./build/static&quot;);</pre><pre>fs.watch(<br>        watchPath,<br>        { encoding: &#39;buffer&#39; },<br>        debounce((eventType, filename) =&gt; {<br>            watchPathExists = fs.existsSync(watchPath);<br>            console.log(`Reloading electron: ${watchPathExists}`);<br>            if (watchPathExists) {<br>                mainWindow.destroy();<br>                createWindow();<br>            }<br>        }, 50)</pre><pre>);<br>}</pre><p>When the app is distributed, Electron uses the <em>main</em> entry in package.json to know where to find its non-dev entry point file: <em>public/electron.js</em>. To let Electron know where to find other files that it needs, the <em>homepage</em> entry is set to “./”:</p><pre>&quot;main&quot;: &quot;public/electron.js&quot;,<br>&quot;homepage&quot;: &quot;./&quot;,</pre><p><strong>Generating a native build</strong></p><p>The <strong>dist</strong> script uses the <a href="https://www.npmjs.com/package/electron-builder">electron-builder</a> module to generate a native, distributable standalone version of the app, which can be found in the <em>dist</em> folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cTL5h0ebRNfANledCJ0Pfg.png" /><figcaption>The native build generated by electron-builder — in the dist folder.</figcaption></figure><p><strong>Trying it out</strong></p><p>If you are familiar with create-react-app this will all be familiar. Even if you are not, getting the example project running is pretty straightforward. If you have node (i.e. v8.12.0) and yarn installed, you just need to checkout <a href="https://github.com/wwlib/cra-craco-electron-example">the repo</a> and complete a few simple steps:</p><pre>git clone <a href="/service/mailto:git@github.com">git@github.com</a>:wwlib/cra-craco-electron-example.git</pre><pre>cd cra-craco-electron-example</pre><pre>(for the browser version)<br>yarn<br>yarn start:web</pre><pre>(for the electron version)<br>yarn watch:electron</pre><pre>(in a separate console)<br>yarn start:electron-dev</pre><p>See the README (and the source code) for additional info.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f4ab827877f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>