<?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 Arthur Tonelli on Medium]]></title>
        <description><![CDATA[Stories by Arthur Tonelli on Medium]]></description>
        <link>https://medium.com/@arthurltonelli?source=rss-3a532135d9fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tBlx4vZRKIcGe-__c4rR7A.jpeg</url>
            <title>Stories by Arthur Tonelli on Medium</title>
            <link>https://medium.com/@arthurltonelli?source=rss-3a532135d9fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 23:07:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arthurltonelli/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[Creating artistic live video filters with deep neural networks]]></title>
            <link>https://medium.com/data-science/creating-artistic-live-video-filters-with-deep-neural-networks-36f8f5a9ac69?source=rss-3a532135d9fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/36f8f5a9ac69</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[style-transfer]]></category>
            <category><![CDATA[coreml]]></category>
            <category><![CDATA[iphone]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Arthur Tonelli]]></dc:creator>
            <pubDate>Mon, 29 Jun 2020 16:21:29 GMT</pubDate>
            <atom:updated>2020-06-29T18:02:18.100Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using CoreML for complex video filters and effects for iPhone</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9AVfSixwhhZLRlew" /><figcaption>Photo by <a href="https://unsplash.com/@veeterzy?utm_source=medium&amp;utm_medium=referral">veeterzy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In a <a href="https://towardsdatascience.com/learning-tensorflow-2-with-style-eab12fd94365">previous project</a>, I worked on replicating fast neural style transfer, transforming an image by taking the artistic styling from one image and applying it to another image through deep neural networks. While transforming images in a python notebook works well, it is not very accessible to the average user. I wanted to deploy the model on an iOS device similar to the <a href="https://prisma-ai.com/">Prisma app</a> made popular a few years ago. More than that, I wanted to test the limits of a generative model and transform frames on live video feed. The goal of this project was to run a generative model on real time video, exploring what is possible given the current boundaries of the technology. There are a few things that made this possible — 1) scaling inputs, 2) utilizing the device’s GPU, and 3) simplifying the model. Since this builds upon the previous project, some familiarity with the previous post will be helpful.</p><h3>Scaling Inputs</h3><p>Many phones today can take stunning 4k videos, including the iPhone XS that I developed on. While the A12 chip in the device is powerful, it would be far too slow to use a deep neural network on every frame of that size. Usually video frames are downscaled for image recognition on devices and the model is run on a subset of frames. For instance, an object recognition app may run a model every second on a 224 x 244 frame, instead of 30 times per second on a 4096 x 2160 frame. That works in an object detection use case, as objects don’t change that much between frames.</p><p>This obviously won’t work for stylizing video frames. Having only a single stylized frame flicker every second would not be appealing to a user. However, there are some takeaways from this. First, it is completely reasonable to downscale the frame size. It is common for video to be streamed at 360p and scaled up to the device’s 1080p screen. Second, perhaps running a model on 30 frames per second is not necessary and a slower frame rate would be sufficient.</p><p>There is a trade-off between model resolution and frame rate, as there are a limited number of computations the GPU can make in a second. You may see some video chat platforms have a slower frame rate or more buffering when using convolutions for video effects (i.e. changing the background). To get a sense of what different frame rates and input shapes looked like, I created a few stylized videos on a computer with the original neural network and OpenCV. I settled on a goal frame rate of 15 fps with 480 x 853 inputs. I found these to still be visually appealing as well as recognizable numbers for benchmark testing.</p><h3>Utilizing the GPU</h3><p>I used tfcoreml and coremltools to transform the Tensorflow model to a CoreML model. A gist of the complete method can be found below. There were a couple of considerations with this. First, I moved to batch normalization instead of instance normalization. This was because CoreML does not have an instance normalization layer out of the box, and this simplified the implementation since only one frame would be in each batch at interference time. A custom method could also be used in tfcoreml to convert the instance normalization layer.</p><p>Next, the tensor shapes differ between TensorFlow and CoreML. The TensorFlow model has an out in (B, W, H, CH) while CoreML supports (B, CH, W, H) for images. After converting the model to a CoreML model, I edited the model spec to have a transpose layer to adjust to shape. Only after changing the model output shape to the format (B, CH, W, H) did I change the output type to an image. This something that has to manually be done on the model spec; as of this writing tfcoreml supports images as inputs as a parameter but not outputs.</p><p>Additionally, since I downscaled the images to pass them through the network, I was able to add an upscaling layer using coremltools to bring the image to to a reasonable 1920 x 1080 frame size. An alternative would be to resize the pixel buffer after getting the result of the network, but this would either involve work from the CPU or additional queueing on the GPU. CoreML’s resize layer has a bilinear scaling and provided satisfactory upscaling with few feature or pixel artifacts. Since this resizing layer is not based on convolutions, it also added minimal time to the model inference time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e7ba41eba1967c29095a928831c06c3/href">https://medium.com/media/9e7ba41eba1967c29095a928831c06c3/href</a></iframe><p>One final way I utilized the GPU was in displaying the frames. Since I added custom processing to the frames, I could not send them directly to standard AVCaptureVideoPreviewLayer. I used an MTKView from the Metal Kit to present the frames, which utilizes the GPU. While the Metal shader was a simple pass through function (the input was returned as the output), the drawing proved performant and the queues in the view were also helpful in the event that a frame was dropped.</p><h3>Simplifying the model architecture</h3><p>The original model architecture had five residual convolutional layers. While very performant on a standard GPU this was too deep for a the A12 processor, at least for a typical frame rate. One primary component for the neural net to learning a variety of textures is the five residual blocks. If a texture is simple, the later residual layers may look closer to identity filters. If the texture is more complex, <em>all</em> layers may have meaningful filters. I experimented with trimming out some of these blocks for a more performant network, at the cost of not being able to learn some highly complex textures. Additionally, I experimented with separable convolutional layers instead of traditional fully connected layers, as used in other light weight architectures such as MobileNets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*PeY1m8ky67UQKLpV9BTgVQ.png" /><figcaption>Architectures used on the A12 testing. The grayed convolutional residual blocks (2–4) were experimented on by removing or using separable convolutional layers in the blocks.</figcaption></figure><p>I tested several different architectures on a computer GPU to narrow down the most performant networks with minimal degradation in texture. I kept the downscaling and upscaling from the original architecture largely consistent though I only used 3 x 3 sized kernels. Some changes (reducing the residual blocks to 1, narrowing the number of filters to 64) had fast inference times, but had a high degradation in quality. Afterward the GPU testing I tested the models on an iPhone XS with an A12 chip.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*kPqvk-mNfIUec34KiOfdYw.png" /><figcaption>Results (in milliseconds) of various model architectures.</figcaption></figure><p>These are the results (in milliseconds) of a benchmark test of 100 iterations, with an input frame size of 480 x 853. The first frame was omitted since it was an outlier from the model “starting up”. One interesting take from these results is that the separable convolutional blocks did not make the network more performant. Separable convolutional layers are often difficult to implement for efficiency. I’ve read a variety cases in which the separable layers do not perform as anticipated in different environments, which could be the case here as well and this deserves more investigation.</p><p>I used the 3 full (not separable) residual blocks for the following results. This model worked very well on a variety of styles and cases. With 15 fps being 66 milliseconds per frame, this implementation was probably the upper bound of the device with this implementation as there were a couple of occurrences of dropped frames or lag.</p><h3>Results and Considerations</h3><p>Below are some examples with different styles and textures applied. These results display much more complex effects for video on a mobile device than currently popular effects that only use shaders or a single filter.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FAYck1iMWUgk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DAYck1iMWUgk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FAYck1iMWUgk%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/da4d02a7a7f3171b3f9c283dc6be04b5/href">https://medium.com/media/da4d02a7a7f3171b3f9c283dc6be04b5/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fe6wo1penFOs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3De6wo1penFOs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fe6wo1penFOs%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/ce5d7acc31d2f4956cd9c65c9c9928e3/href">https://medium.com/media/ce5d7acc31d2f4956cd9c65c9c9928e3/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKh77tzQLDpw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKh77tzQLDpw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKh77tzQLDpw%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/21028300e19b07128c894b3f25fb9f9a/href">https://medium.com/media/21028300e19b07128c894b3f25fb9f9a/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FlHqX3dBSr9s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DlHqX3dBSr9s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FlHqX3dBSr9s%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/16e3205525aff923c4f2753bc358ac6a/href">https://medium.com/media/16e3205525aff923c4f2753bc358ac6a/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMZ2TCMnbLEY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMZ2TCMnbLEY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMZ2TCMnbLEY%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/accbb6628c762eee37eebe5fb725b421/href">https://medium.com/media/accbb6628c762eee37eebe5fb725b421/href</a></iframe><p>One learning from this experiment is that the trimmed neural architecture does not generalize on all styles, since there are fewer layers to decompose the image. This is most apparent on complex styles that transform the objects in the image more. Transformation with neural networks is a difficult problem to solve so this is not surprising. The mosaic style is a great example of this problem. My implementation repeats similar tessellations in the image compared to the more complex features <a href="https://www.youtube.com/watch?v=iq_lMdB80jY">other implementations</a> contain, which use the full network in post processing. Simpler styles, on the other hand, such as “The Scream” and the generic sketch texture performed quite well and were similar to what would be anticipated from the full architecture.</p><p>Another shortcoming was the lack of generalized hyper-parameters. With the trimmed network, I found no single reliable set of hyper-parameters that worked for most styles. Once again, the mosaic style had room for improvement here, as content component was sacrificed with the hope of having more complex style features.</p><p>With future advancements in hardware, being able to use larger neural networks is inevitable. Along with more complex networks, more complex styles, textures, and even object transformations may be possible. For now, this shows that a variety of filters and effects can be developed for use in real time video content like social media.</p><h4>Related Work</h4><p><em>Real Time Video Neural Style Transfer, </em>Kate Baumli, Daniel Diamont, and John Sigmon — <a href="https://towardsdatascience.com/real-time-video-neural-style-transfer-9f6f84590832">https://towardsdatascience.com/real-time-video-neural-style-transfer-9f6f84590832</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36f8f5a9ac69" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/creating-artistic-live-video-filters-with-deep-neural-networks-36f8f5a9ac69">Creating artistic live video filters with deep neural networks</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning TensorFlow 2 with Style]]></title>
            <link>https://medium.com/data-science/learning-tensorflow-2-with-style-eab12fd94365?source=rss-3a532135d9fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/eab12fd94365</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[style-transfer]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Arthur Tonelli]]></dc:creator>
            <pubDate>Fri, 27 Mar 2020 04:41:13 GMT</pubDate>
            <atom:updated>2020-04-03T03:01:01.580Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting familiar with TensorFlow 2 by implementing fast neural style transfer</h4><figure><img alt="The fog rolling the hills of Mount Tamalpais, stylized with “The Scream” by Edvard Munch" src="https://cdn-images-1.medium.com/max/1024/1*sEIeH-e2uhXCP8rhOLoB0g.jpeg" /><figcaption>Personal photo of the fog rolling over Mount Tamalpais stylized with The Scream by Edvard Munch</figcaption></figure><h3>Background</h3><p>For the past few years, I’ve taken a strong interest in computer vision and spent a fair bit of my time taking courses, reading papers, and doing side projects related to the field. It’s a great overlap with my passion for photography. One computer vision project that caught my attention was neural style transfer, first proposed by Leon Gatys et al¹ and particularly fast style transfer later proposed by Justin Johnson et al². Recently while working with the code, I found much of it dated, lacking support, and therefore difficult to work with. While having some familiarity with other machine learning frameworks, I took this as an opportunity to update the code and gain deeper knowledge of TensorFlow 2. Since fast style transfer includes a generative network and more complex loss function it provided a great project for learning some of the nuances of TensorFlow, as opposed to a basic classification model.</p><p>The goal of this article is to highlight some core features and key learnings of working with TensorFlow 2 and how they apply to fast style transfer. I will reference core concepts related to neural style transfer but glance over others, so some familiarity would be helpful. I’ve provided a couple of helpful resources below if you are completely new to the problem.</p><h3>Brief Overview</h3><p>The goal of style transfer is to take a content image, we’ll call <em>C</em>, and an image with style, <em>S</em>, to create a transformed image, <em>Y</em>, with the style of <em>S</em> applied to <em>C</em>. In other words, we want a mix of the content of <em>C </em>with the style of <em>S</em>, as seen in the image below<em>.</em></p><figure><img alt="Three images; a woman standing near an ocean, a mosaic artwork, and the woman at the ocean stylized with mosaic" src="https://cdn-images-1.medium.com/max/1024/1*CtVVUqPbGItIIU9MHcuXWg.jpeg" /><figcaption>Representation of applying the style of one image to the content of another image to create a transformed, stylized image.</figcaption></figure><p>In the original style transfer work by Gatys et al¹, a base image with random noise, <em>X</em>, is passed into a trained VGG network and the output from designated layers is used to abstract what features are activated. The L2 loss of the output from designated content layers between <em>X</em> and <em>C</em> can help learn content. The L2 loss of the gram matrices of output from designated style filters between <em>X</em> and <em>S</em> can help learn style. This layer extraction can be seen in the <em>Loss Network</em> to the right in the image below. While <em>X</em> starts out an image with random noise and over many iterations, it is trained and transformed to <em>Y</em>. There is a tutorial on this original implementation from the TensorFlow team <a href="https://www.tensorflow.org/tutorials/generative/style_transfer">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-yY7xBhDv2e6DeoSbSjWMA.png" /><figcaption>Fast style transfer network architecture proposed by Johnson et al, Note: My implementation uses the VGG19 vs VGG16, Source: <a href="https://arxiv.org/abs/1603.08155">Perceptual Losses for Real-Time Style Transfer and Super-Resolution</a> (2016)</figcaption></figure><p>In the case of fast style transfer, a generative neural network is trained to transform any image, instead of a single image being trained and transformed. In the architecture above proposed by Johnson et al², a content image is passed into the transform network then the <em>transformed output image</em> is passed into the VGG network. From there, the transformed image undergoes a similar loss to the original style transfer model using the extracted style and content layers. To train the generative network many different content images will be used over many iterations. It takes a lot longer to train, but the inference time can be up to 1000 times faster!</p><p>In the example below, the same content image is passed through the network at different points of training. As the number of training iterations, <em>i</em>, increases the transformed image, <em>X</em>, converges towards our desired mix of content and style.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f_HK8-SjcZUH5qBQj5EfhA.gif" /><figcaption>An example of how the generative model changes over many iterations. Over time the model trains and the transformed output, Xᵢ, will converge to our desired mix of style and content, Yᵢ, by optimizing the loss function L(Cᵢ, S, Xᵢ).</figcaption></figure><h3>Models</h3><p>To build the model I focused on using the built in features of TensorFlow. Between TensorFlow Core, Keras, and TensorFlow Add-ons, there are a lot of tools that can be utilized.</p><h4>Custom Layers</h4><p>TensorFlow 2 makes it very easy to compose these layers into custom layers. In an example below, you’ll see how I built a 2D convolutional layer and residual block specific to the model. These layers will be used to build the generative transformation network.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2082a46a6a6580cb3bcf2ba825465bd5/href">https://medium.com/media/2082a46a6a6580cb3bcf2ba825465bd5/href</a></iframe><p>When inheriting from the Layer class, attributes and methods will be recursively called. For instance, when accessing trainable variables in the custom layer, <em>all trainable variables</em> of <em>all layers</em> making up that custom layer will be returned. This also goes for calling on trainable variables from a model using the custom layers, making variable access very intuitive.</p><h4>The Transform Network</h4><p>The Keras functional model is used to build the generative neural network. The functional model in Keras is a bit more versatile than the sequential model since the latter is primarily for stacking layers. With the functional model, one can build more complex neural architectures, such as shared layer models and multiple output models. These models resemble nodes on a graph compared to individually stacked layers. This is exemplified in other architectures such as ResNet, InceptionNet, and MobileNets. Since we have a few residual blocks, the functional model will be a bit friendlier to use.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13bfe4b4a2b5ac456757cd8a9846edd0/href">https://medium.com/media/13bfe4b4a2b5ac456757cd8a9846edd0/href</a></iframe><p>Since we composed our custom layers, it is still very intuitive to follow. First, instantiate the layers then pass a Keras input through the callables of the layers, in the desired manner to establish the graph underlying the model. Finally, the outputs of all layers and the original inputs are used to create a tf.keras.Model instance and build the graph. I created a generic class to act as a wrapper for the model.* As mentioned above, the call to model.trainable_variables will return all the trainable variables from our custom layers.</p><p>*Note, you can also create inherited models and still use the functional model which has some benefits, but I found it more ridged and difficult to work with.</p><h4>The VGG19 Model</h4><p>The Keras library contains a few common networks, including the VGG networks. They can be created with certain pre-trained weights and the option to trim the last fully connected layers. This is extremely helpful if you want to use transfer learning for a given problem and need to use different classification layers. My implementation uses the VGG19 network instead of the VGG16, though a variety of image recognition networks could be used.</p><p>As mentioned in the overview, we will pass our transformed images, <em>Xᵢ</em>, through the VGG net and extract a few of the output layers. Instead of a classifier as an output, we will want to have multiple layers as outputs. Remember how the functional model was suitable for multiple outputs? A new functional model can be created using the VGG network. The VGG inputs are passed into the new model and the outputs of the desired layers are passed as the model outputs. When the new model is called, the tensors will be passed through the VGG model and the outputs at those layers will be returned.</p><p>Below is an example snippet outputting the first layer of the first convolution block (conv1_1) and the second layer of the third convolution block (conv3_2), along with sample outputs for a couple of the channels. These outputs represent the portions of the image that activated when the pre-trained filters convolved over the image. The shallow output from conv1_1 activates simple features like edges to decompose the image, while the deeper output activates on more complex information (in this case it looks like shadows).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21c3349613f9801206e72c2a3a87701a/href">https://medium.com/media/21c3349613f9801206e72c2a3a87701a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*odwF7wAJ7SvOn_Kxr_Y80g.png" /><figcaption>a) Original RGB image passed through the VGG19, b) Output of 17th filter (indexed at 1) of the conv1_1 layer, c) Output of 6th filter (indexed at 1) of the conv3_2 layer; Note image c is smaller due to pooling</figcaption></figure><p>The L2 loss between layers is then used to compare the content outputs of <em>Xᵢ</em> and <em>Cᵢ</em>. With regards to content, if a “wheel” feature of car image activates on our original image and also activates on the transformed image, the content is still matching strongly and the loss will be lower. Likewise, the L2 loss between gram matrices is used to compare <em>Xᵢ</em> and <em>S</em> for which style features were activated features.</p><h3>Training Weights with GradientTape</h3><p>One of the bigger changes in TensorFlow 2 is the switch to eager execution. In previous versions of TensorFlow, a computational graph would first be manually built and only afterward tensors would be passed in and called upon. This is less intuitive and difficult to work with. Now, EagerTensors can be set and called by up by computations. The computational graph is abstracted away and is set up and executed under the hood. Like in many other cases with lazy vs eager evaluation, I’ve found this a bit easier to comprehend and much easier to debug.</p><p>In TensorFlow 2, classification problems are well supported in the Keras API. However, this is less friendly if you need to create a custom training loop, train specific variables, or have special inputs for the loss function. In these instances, GradientTape can be used to track the trainable variables during execution, get the gradients, then apply the gradients with an optimizer. This is well suited for the fast style transfer model since training involves a generative network with a custom training loop and passing several different inputs to the loss function.</p><h4>Watched Variables</h4><p>Within the GradientTape context, trainable variables are “watched” and tracked during the forward pass. When backpropagation is later performed, the watched variables will have the respective changes applied to them based on their gradients. While trainable variables <em>can</em> be tracked and tuned in training, watched variables <em>will be tracked</em> so they can be tuned by the optimizer.</p><p>Trainable variables can be implicitly watched without calling watch within the GradientTape context. For more fine-grained control you can turn this off in the constructor for GradientTape, and only variables explicitly “watched” in the block will be tracked for automatic differentiation. The GradientTape context also allows you to get watched variables which is helpful for debugging. With multiple models, I found setting the watched variables on my own more practical than relying on implicit calls.</p><p>Once variables are watched, the tensors are passed through the models and the losses are calculated. For fast style transfer, we’ll do our forward pass through our generator network, get the transformed image, <em>Xᵢ</em>, then pass that image through the VGG classification network. In the example below, I create the gradient tape context, watch the proper variables, then do a forward pass. Afterward, I use the loss to get the appropriate gradients, then these gradients are then used by the optimizer to adjust the trainable variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed1961c551e6b1b728bcc11ecd83634c/href">https://medium.com/media/ed1961c551e6b1b728bcc11ecd83634c/href</a></iframe><h3>Results</h3><p>Now for the fun part! After hours of training the network on each style, these were all taken with the default training parameters to serve as a generic baseline. Note that some models could be tuned more finely or longer for better results. For instance, in “The Scream” implementation there are a couple of untrained spots that started as white.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJ3j_6Ge4kxva9Q941mx_A.png" /><figcaption>Results for the network with 1) the style images for training, 2) the Chicago image, often used as a baseline, and 3) a personal image to show variation</figcaption></figure><p>Being passionate about photography, art, and deep learning, this was an extremely fun project to take on. I found TensorFlow 2 much easier to work with than previous versions. Despite having several models and a few moving parts, it was easy to call on components and get insight into the networks. I found logging variables extremely helpful within the context of developing in a Colab notebook. I know some engineers will also set up unit tests based on variable names and tensor shapes which I would probably do in a more formal environment.</p><p>Of course, the majority of debugging came with data-related issues. One error was due to incorrectly downscaling images, abstracting too much “style”. The photo at the top of this page was a happy little accident from this, even though at the time the network was not performing similarly to previous implementations. Another error was simply because I used a very high-resolution photo of an artwork and the network actually pulled the texture of the canvas as style!</p><p>I hope you learned a little bit about deep learning and working with TensorFlow2. If you are interested in looking more at the code that I used, or other topics related to style transfer, deep learning, or computer vision I included some resources below.</p><h3>Additional Resources</h3><h4>Project</h4><ul><li>Colab for this project: <a href="https://colab.research.google.com/drive/1xp_QU6ppXOoTs4vNcL41QJk0uz_OOP01#scrollTo=XM1bqoGdgCbX&amp;forceEdit=true&amp;sandboxMode=true">Fast Style Transfer TensorFlow 2</a></li><li>Github Repo for this project: <a href="https://github.com/altonelli/fast-style-transfer-tf2">altonelli, fast-style-transfer-tf2</a></li></ul><h4>External</h4><p>I used both of these courses a couple of years ago to introduce myself to ML and computer vision</p><ul><li><a href="https://www.coursera.org/learn/machine-learning">Andrew Ng’s Machine Learning course on Coursera</a></li><li><a href="http://cs231n.stanford.edu/">Stanford CS231n: Convolutional Neural Networks for Visual Recognition</a></li></ul><p>Aside from the original research articles, these articles and implementations are great resources for neural style transfer</p><ul><li><a href="https://towardsdatascience.com/artistic-style-transfer-b7566a216431">Artistic Style Transfer, F D on Medium</a></li><li><a href="https://www.tensorflow.org/tutorials/generative/style_transfer">TensorFlow’s tutorial on traditional style transfer</a>, mentioned in Brief Overview</li><li><a href="https://github.com/lengstrom/fast-style-transfer">lengstrom, fast-style-transfer, Github</a></li><li><a href="https://github.com/hwalsuklee/tensorflow-fast-style-transfer">hwalsuklee, tensorflow-fast-style-transfer, Github</a></li></ul><h3>References</h3><p>[1] L. Gatys, A. Ecker, M. Bethge, <a href="https://arxiv.org/abs/1508.06576">A Neural Algorithm of Artistic Style</a> (2015): <a href="https://arxiv.org/abs/1508.06576">https://arxiv.org/abs/1508.06576</a></p><p>[2] J. Johnson, A. Alahi, L. Fei-Fei, <a href="https://arxiv.org/abs/1603.08155">Perceptual Losses for Real-Time Style Transfer and Super-Resolution</a> (2016): <a href="https://arxiv.org/abs/1603.08155">https://arxiv.org/abs/1603.08155</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eab12fd94365" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/learning-tensorflow-2-with-style-eab12fd94365">Learning TensorFlow 2 with Style</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Cal Day To Night]]></title>
            <link>https://medium.com/@arthurltonelli/creating-cal-day-to-night-b35f8afe745a?source=rss-3a532135d9fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/b35f8afe745a</guid>
            <category><![CDATA[editing]]></category>
            <category><![CDATA[photoshop]]></category>
            <category><![CDATA[photography]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[photos]]></category>
            <dc:creator><![CDATA[Arthur Tonelli]]></dc:creator>
            <pubDate>Tue, 27 Nov 2018 19:06:01 GMT</pubDate>
            <atom:updated>2018-11-27T20:52:17.005Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating Cal Day to Night</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LfCa1prr-lCbY8ZNWuobbg.jpeg" /><figcaption>“Cal Day to Night” — My time series photo of UC Berkeley from dawn to night</figcaption></figure><p>Photography is one of my greatest passions, especially since graduating from Berkeley. In particular, I am fascinated by the fact that cameras do not capture a true “snapshot” in time, but an entire collection of moments from the time the button is pushed to the moment the shutter finally closes. This idea caused me to experiment more with long exposures in my more recent work.</p><p>Photographer Stephen Wilkes extends the concept of capturing moments across time in his <a href="https://www.stephenwilkes.com/fine-art/day-to-night/5669b80b-ba14-414a-a39f-5b130a771fd0">“Day To Night” project</a>. For a single composition, he captures thousands of photos over the course of 24 hours and then blends and stitches them together to create one seamless photo. The results are awe-inspiring. He compresses time into a single photo, collecting a multitude of moments that happened during that day.</p><p>Since seeing Wilkes’ “Day to Night” project I have wanted to try my own. I usually only take photos every couple of months, though UC Berkeley’s campus lights during Big Game week usually encourages me to experiment with new techniques. This year I decided to give Day to Night a shot (pun intended). The result was nearly 40 photos merged together to give the viewer a perspective of UC Berkeley over the course of a full day, from sunrise, through the day to dusk, and into the night. It’s been a special project for me and I’m extremely happy with the result. I’d like to share what went into it, from capturing the images through final edits.</p><h3>Taking the photos</h3><h4>Set up</h4><p>In an ideal world, I would be able to take all of the photos without moving my camera over a 24 hour period. However, with work and having a life beyond photography, this was not possible. Instead, I had to keep all settings of my tripod and camera exactly the same between shots to shoot from the same focal point. I also had to use my remote to ensure I would not nudge the camera for each shot.</p><p>I first found the vantage point I wanted. Starting in the day time, I knew that I would want to capture the sun rising the next morning. I used an AR sun tracking app to find out exactly where the sun would rise the next morning and set up my camera to frame from the prospective sunrise to the edge of Doe Library.</p><p>After taking photos of the scene and passersby during the day and night, I marked on the ground where each leg of my tripod was. I also marked the tripod for each of the settings and took photos of everything with my phone for reference. I then carried the tripod, unfolded, back to my car and set it up identically the next morning. To be perfectly honest this got everything <em>close</em> but not perfect. As careful as I was, slight nudges during set up, adjusting focus, etc… caused some nuances and I had to nudge them a few pixels here or there in post-processing.</p><h4>Unpredictability</h4><p>The week that I took photos was the week of the California fires. I had no idea what would come of the photos. There was a high likelihood that they could be flat or haze-filled from the smoke. The clouds and smoke ended up completely blocking the sunrise point from which I was hoping to capture a “starburst.” However, as luck would have it, I arrived so early in the morning that I captured an incredible red sunrise reflecting off of the clouds. I believe that any scene can be framed and composed well to take a good photo, but sometimes it’s nice to get lucky!</p><h3>Selecting the images</h3><p>One of my goals for this photo was to not only create a scenic blend of each time of the day, but to also capture a perspective of daily life at Cal. Both of these begins with having a good supply of photos while shooting. I took nearly 500 photos while I was out, using various apertures, filters, and exposures to get a variety colors and features in the scene as well as people about their business.</p><p>Almost obsessively I tried to take photos when I saw something interesting. For the sky, this was based upon the color of the sunrise and the look of the clouds. For the daily activities, I based this on people meeting on Memorial Glade, cyclists, students with professors, and sightseers passing by. Eventually, I narrowed these down to a subset of photos that had specific characteristics that represented the whole. With the poor air quality, it was strongly advised to wear masks for the smoke. The rivalry football game was eventually rescheduled due to the smoke, and unfortunately that is what the week will primarily be remembered by. Capturing people in this setting was important to me as a discrete record in time.</p><h3>Editing</h3><p>I use Photoshop sparingly to edit photos and prefer lighter editors, like Polarr and Lightroom. My current style of editing is to work with the light and color of the photo rather than effecting the tangible objects. However, this project required using layers, selection, and blending and made for a great exercise in learning those and other Photoshop tools.</p><h4>Layering</h4><p>When starting the editing process, I selected a plain photo of the scene which I call the key photo. This photo was a neutral daytime photo with average lighting. From the key photo I could see all important features and reference colors for layers I would add on top. Next, I started selecting from photos of the sky, followed by building and environment features, and layered them on top. Whenever I overlaid these photos regarding the general setting, I ensured that there was significant overlap of the layers for blending. I did some initial blending here to make sure the features I wanted would show through, though most was in the final step.</p><p>An important thing I found was that some layers from different periods of the day should be interlaced together. For instance, in the sky, the blue daylight is on top of (and covering) the clouds of the sunrise. However, on top to the blue sky I placed a single pink cloud to be blended in, then on top of that single cloud I placed the white cloud from the daytime. This interlacing of photos from different times helped to create a smoother transition which I found more appealing than blending alone.</p><p>The final layers that I added were the people themselves. These started as rough selection copy and pastes, then afterwards I tediously cut miscellaneous pixels and normalized the colors when possible.</p><h4>Blending</h4><p>As I mentioned above, it was import to have a decent amount of overlap between layers for the blending. The first step in blending was adding an opacity gradient to the layer on top. I did this by adding a layer mask and applying a gradient to the mask. Admittedly, within each gradient there was a lot of trial and error!</p><p>After the layer opacities were set, I noticed there were still edges that could be smoother and places that a large gradient was not going to be able to effectively treat. For these areas I used the easer and smudge tool, and significantly decreased the opacity of the tools, thereby also minimizing their effect.</p><h3>Feedback</h3><p>One of the most difficult things to do is ask for feedback, and even more so accept critical feedback. However, this was by far the most important thing I did throughout editing. There were times where my eyes completely missed something that looked bad and others in which I had a suspicion but did not want to go through the work of making a change. My friends and family caught these faults and overall the photo turned out significantly better! Additionally, the process of iterating between editing and reviewing allowed me to catch areas that needed to be touched up, even if they weren’t mentioned in the feedback. Many thanks to everyone who I badgered for critiques!</p><p>This was by far the most ambitious and difficult photography project I’ve taken on, and also one of my favorites. Not only is the final print something that I can’t wait to hang in my house, but I learned a lot while developing Cal Day to Night. I’m excited for the next Day to Night project I take on!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b35f8afe745a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an IoT device with Alexa, AWS, Python and Raspberry Pi - Part IV]]></title>
            <link>https://medium.com/@arthurltonelli/building-an-iot-device-with-alexa-aws-python-and-raspberry-pi-part-iv-8725923daad0?source=rss-3a532135d9fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/8725923daad0</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Arthur Tonelli]]></dc:creator>
            <pubDate>Sat, 31 Mar 2018 14:58:32 GMT</pubDate>
            <atom:updated>2018-03-31T14:59:34.875Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x30Ed3hdgPNn37y6." /><figcaption>“Colorful lines of code on a MacBook screen” by <a href="https://unsplash.com/@casparrubin?utm_source=medium&amp;utm_medium=referral">Caspar Rubin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you followed along up to now you should have a set of working IoT lights. I gave only briefly overviews of what the code was doing. Now I will review some of key code snippets that are the foundation for the project. Overall, the <a href="https://github.com/altonelli/my_painting">repo</a> should be well documented if you want to take a closer look.</p><h3>AWS Lambda Function</h3><p>The core of the Lambda function is very similar to many Alexa demo apps, though I modularized some of logic. The Lambda handler receives an event dictionary (which contains our request and intent data) and a context object of runtime data. If the request type is an intent, we call upon the appropriate function for behavior we want to skill to exhibit.</p><p>The behavior functions take action on intents, the key information we set up the Alexa Skill to decipher from the user. As an example, below is <em>update_power_state</em> in <a href="https://github.com/altonelli/my_painting/blob/21aa6c4b679828fc08fd9774ea1776f4aa8ee943/lambda_function/behaviors.py#L33-L57">behaviors.py</a>. After we retrieve the value of power state, we ensure that it is in fact one of our two valid values (“ON” or “OFF”) and update the shadow accordingly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07349f03aec464c8665055d8dc6b2ea9/href">https://medium.com/media/07349f03aec464c8665055d8dc6b2ea9/href</a></iframe><p>The Lambda function has to return a response dictionary for Alexa to give a verbal response, which we return after updating the shadow. The functions in <a href="https://github.com/altonelli/my_painting/blob/master/lambda_function/response_builders.py">response_builders.py</a> build python dictionaries appropriately formatted to contain a card title (for screen displays), a speechlet or output text for Alexa to read and session information. The speech output text is key to the verbal user interface of Alexa. In the above code, I found a simple “OK” in confirmation sufficient, though you will see in <a href="https://github.com/altonelli/my_painting/blob/master/lambda_function/behaviors.py#L77-L87"><em>update_brightness</em></a> that I confirm with the user either the brightness, the power state, or that the request was not valid.</p><p>Another major role of the Lambda function is to update the IoT shadow. AWS Lambda has Boto preinstalled, so we create an IoT data client with Boto and update on the “/shadow/update” topic with the JSON payload. We only update the <em>desired</em> state, it is up to the Pi to receive that data and update the <em>reported</em> state accordingly. We are only sending the data we want to update with this request (say brightness to 50). Only that attribute and value of the shadow will be updated, other fields not included in the payload will remain the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e2fa1eb28e8a5874c9447206eeace9f/href">https://medium.com/media/8e2fa1eb28e8a5874c9447206eeace9f/href</a></iframe><p>After we we receive the response we print the new desired state, which is logged in CloudWatch.</p><h3>Raspberry Pi</h3><h4>IoT Client</h4><p>Interaction with the IoT shadow is done through MQTT publish and subscribe functions. This is fairly easy to implement using the AWSIoTMQTTClient. A key aspect is the <em>topic</em> in which we publish and subscribe to. If you are unfamiliar with publish-subscribe message queues, the topic is the channel that a message is published/subscribed to. To start with a consistent shadow we publish the current settings of the lights to both the reported and desired states.</p><p>The parameters for publish consists of a topic, a payload and the quality of service (QoS). The topic will help our AWS IoT broker to filter messages and the payload is simply JSON of the data we want to update. The QoS is the type of connection to maintain with the broker. You can read more <a href="http://www.steves-internet-guide.com/understanding-mqtt-qos-levels-part-1/">here</a> but for simplicity 0 means the message will be sent <em>at most once</em> and 1 means that the message will be sent <em>at least once</em>. We publish all updates to the “/shadow/update” topic with a QoS of 0, then AWS IoT will update the shadow and send messages to appropriate subscribers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3abf0efc8aa95a959dd87901dd37b74e/href">https://medium.com/media/3abf0efc8aa95a959dd87901dd37b74e/href</a></iframe><p>The parameters for subscribe are the topic, the QoS and the callback for when the subscriber receives a message. When we publish on the “/shadow/update” topic, the broker will send a message to subscribers of the “/shadow/update/accepted”, “/shadow/update/documents” and (if there is a difference between desired and reported) “/shadow/update/delta” topics. The Lights object checks <em>all</em> attributes in the shadow, which will only be available to “/shadow/update/documents”, so we subscribe to this topic. “/shadow/update/accepted” only sends the updated attributes.</p><p>When the shadow is updated, we retrieve and parse the payload and update the lights accordingly. We then publish another update to the “/shadow/update” topic of the reported state of the lights.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29b3023faee4a7b3cdc5ed924650e787/href">https://medium.com/media/29b3023faee4a7b3cdc5ed924650e787/href</a></iframe><h4>GPIO and Lights</h4><p>The key method to changing the LED lights is <em>_update_color</em> which will use PWM to change the color of each LED. Pigpio defaults to a PWM range of 0–255, hence ensuring the value is in that range. <em>_update_color</em> sets each respective pin to the PWM value for the color.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d40a9851d69f9dac7209f622d1d377db/href">https://medium.com/media/d40a9851d69f9dac7209f622d1d377db/href</a></iframe><p>I repeatedly call <em>_update_color</em> in <em>_update_brightness</em> to incrementally adjust the brightness, creating a fade effect. After, or if there is already no difference between the current/display brightness and the brightness setting, we set the lights to the brightness of the shadow.</p><p>Thats it for now! Thanks for reading and I hope this was a brief and helpful intro to IoT and building a smart device. I included a file of a few (somewhat) <a href="http://planetpixelemporium.com/tutorialpages/light.html">real world RGB values for lighting</a>. Try them out, or even add an intent to change the color. I’d like to add different fading and dimming features in the future. If you have any questions, I’d love to hear them. Thanks again!</p><p>Helpful? Enjoy? Additional questions? Feedback in the form of 👏👏 or comments below always welcome!</p><p>Or, feel free to say hi at <a href="http://hello@arthurtonelli.me/">hello@arthurtonelli.me</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8725923daad0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an IoT device with Alexa, AWS, Python and Raspberry Pi - Part III]]></title>
            <link>https://medium.com/@arthurltonelli/building-an-iot-device-with-alexa-aws-python-and-raspberry-pi-part-iii-c1d383aa88c5?source=rss-3a532135d9fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1d383aa88c5</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Arthur Tonelli]]></dc:creator>
            <pubDate>Sat, 31 Mar 2018 14:58:00 GMT</pubDate>
            <atom:updated>2018-03-31T14:58:46.004Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8FEejGEGmAdnAVHikr10Q.jpeg" /></figure><p>Up to this point, we have set up an Alexa Skill that updates an IoT shadow and gives a response back to the user. Now we need to connect a device to read the shadow and actually reflect what the user asked of it. We will be using the Raspberry Pi to set up an MQTT (Message Queuing Telemetry Transport) connection to the Thing endpoint and then turn on the lights accordingly using the GPIO pins.</p><h3>The Lights</h3><h4>A brief overview</h4><p>I live in the software world, so this was a fun experiment to learn a hair more about circuits. I am by no means an expert in circuits but I will explain a bit of what is going on. The lights are 12V but the GPIO pins can only output a 3.3V potential. Thus, the 12V power supply powers the LEDs and the GPIO pins will trigger the MOSFETs. N-Channel MOSFETs are a type of transistor in which when the <strong>gate</strong> terminal receives a small potential, it allows the current to pass from the <strong>drain</strong> to the <strong>source</strong> terminals. This effectively creates a switch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*ismyRBeKTwL3nygmT0xN8w.png" /><figcaption>From Fairchild Semiconductor Datasheet</figcaption></figure><p>The brightness of is controlled by pulse width modulation, or PWM. This means that the GPIO pin will alternate between sending 3.3V to the MOSFET and 0V in different frequencies. This rapidly closes and opens the circuit, turning on and off the light to give the appearance of changing the brightness. With each MOSFET controlling a different color, we can get an array of colors for the lights to display.</p><h4>Setting up the lights</h4><p>I stuck very closely to <a href="https://dordnung.de/raspberrypi-ledstrip/">this tutorial</a> for setting up the lights on a bread board. Again, you will want to use SMD5050 LED RGB lights and for the N-channel MOSFETs I used P30N06LE’s.</p><p>Below is my final breadboard. The only major difference from the tutorial’s breadboard to mine was that I used a gate resistor on each of the MOSFETs. Each GPIO pin has both a physical pin number and a GPIO port, though the Pigpio library recognizes the pin by GPIO number. For reference (and in the code later) I used GPIO port 4 for red (pin 7), GPIO port 17 for green(pin 11), GPIO port 22 for blue (pin 15) and pin 6 for ground.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J4r4XtwyaEs4puIYA-mU-g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bL4dc0NKu4v3LgtQRRpNGw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lgzwvjeqDIfv86LDy8y96Q.jpeg" /><figcaption>The final breadboard (without resistors) and soldered PCB board are pictured below. (Note: the Vcc wire is white and the wire from the green GPIO port to the green MOSFET gate is grey).</figcaption></figure><h3>The Raspberry Pi</h3><h4>Setting up the Raspberry Pi</h4><p>If your Raspberry Pi is not set up with Rasperbian, I recommend <a href="https://medium.com/@jay_proulx/headless-raspberry-pi-zero-w-setup-with-ssh-and-wi-fi-8ddd8c4d2742">this tutorial</a>.* After its set up, we’ll SSH to the Raspberry Pi in a separate terminal window.</p><pre>$ ssh <a href="/service/mailto:pi@192.168.pi.ip">pi@192.168.pi.ip</a></pre><p>Then secure copy the certificates we originally downloaded in <a href="https://medium.com/@altonelli/building-an-iot-device-with-alexa-aws-python-and-raspberry-pi-part-ii-8ad84f24a3ee"><strong>Part II</strong></a> to the Raspberry Pi. There should be a .credentials directory in the root of your Pi.</p><pre>$ scp ~/&lt;path_to_certs&gt;/XXXXX-certificate.pem.crt pi@raspberrypi:~/.credentials/XXXXX-certificate.pem.crt<br>$ scp ~/&lt;path_to_certs&gt;/XXXXX-private.pem.key pi@raspberrypi:~/.credentials/XXXXX-private.pem.key<br>$ scp ~/&lt;path_to_certs&gt;/XXXXX-public.pem.key pi@raspberrypi:~/.credentials/XXXXX-public.pem.key<br>$ scp ~/&lt;path_to_certs&gt;/root-ca.pem pi@raspberrypi:~/.credentials/root-ca.pem</pre><p>Next from the ssh session, we’ll clone the repo, create a .env file and add the appropriate information. Afterwards, do not forget to source the environment variables.</p><pre>pi@raspberrypi:$ git clone <a href="https://github.com/altonelli/my_painting.git">https://github.com/altonelli/my_painting.git</a><br>pi@raspberrypi:$ cd my_painting<br>pi@raspberrypi:$ touch .env<br>pi@raspberrypi:$ vi .env<br>pi@raspberrypi:$ source .env</pre><p>The .env file should look like the following. Be sure to source the file to set the environment variables afterwards.</p><pre>#General AWS credentials for Pi<br>export AWS_IOT_CERTIFICATE_FILENAME=&quot;~/&lt;path_to_credentials&gt;/XXXXX-certificate.pem.crt&quot;<br>export AWS_IOT_PRIVATE_KEY_FILENAME=&quot;~/&lt;path_to_credentials&gt;/XXXXX-private.pem.key&quot;<br>export AWS_IOT_PUBLIC_KEY_FILENAME=&quot;~/&lt;path_to_credentials&gt;/XXXXX-public.pem.key&quot;<br>export AWS_IOT_ROOT_CA_FILENAME=&quot;~/&lt;path_to_credentials&gt;/root-ca.pem&quot;<br>#IoT Information<br>export AWS_IOT_MQTT_HOST=&quot;XXXXX.iot.us-east-1.amazonaws.com&quot;<br>export AWS_IOT_MQTT_PORT=8883<br>export AWS_IOT_MQTT_PORT_UPDATE=8443<br>export AWS_IOT_MQTT_CLIENT_ID=&quot;my_painting&quot;<br>export AWS_IOT_MY_THING_NAME=&quot;my_painting&quot;<br>#Alexa Skill Information<br>export AWS_ALEXA_SKILLS_KIT_ID=&quot;amzn1.ask.skill.XXXXX&quot;</pre><p>Pigpio is a C library to connect to the GPIO pins. We’ll first need to install this library so that we can use our Pigpio python library. We will also need to have a Pigpio daemon running before we run our code. Run the following commands before installing the requirements and running the program.</p><pre>pi@raspberrypi:$ sudo apt-get install pigpio<br>pi@raspberrypi:$ sudo pigpiod</pre><p>If you ever need to kill the daemons, you can run sudo killall pigpiod. You can also run sudo systemctl enable pigpiod to have the daemon start at boot.</p><p>Finally, install the dependencies. You can test that the lights are in fact working by running the lights.py file and it will run a demo of changing the brightness.</p><pre>pi@raspberrypi:$ pip install -r raspberry_pi/requirements.txt<br>pi@raspberrypi:$ python raspberry_pi/lights.py</pre><h4>Running the program</h4><p>Finally, we get to run the program and use our IoT lights! As a brief overview, the core of the app is the AWS IoT Python SDK. With this SDK, we set up an MQTT connection to our Thing’s endpoint and publish and subscribe to updates on the shadow. If you are unfamiliar with MQTT, its is a lightweight messaging protocol for use with low power devices. The program will subscribe to the shadow endpoint on the “/shadow/update/documents” topic. Topics help the broker filter messages. If an update is published to the “/shadow/update” topic, the broker will send a message to the subscribers of the documents topic (our Raspberry Pi). Upon receiving the message, our program will compare the <em>desired</em> state to the current state of the lights (also the <em>reported</em> state). If there is a difference, the program will update the lights accordingly through the GPIO pins and send an update to the shadow endpoint to update the <em>reported</em> state.</p><p>You can run the following command and the Pi will connect and begin reading the shadow. Upon start up, it will push a default state of “Off” and brightness at 100% to the shadow.</p><pre>pi@raspberrypi:$ python raspberry_pi/shadow_client.py</pre><p>There is a logger in the program, so we should see updates when the Pi receives messages, even if the lights are not set up. Let’s try interacting with the Alexa Skills test console or an Alexa enabled device. Boom! We should see the changes both on the lights and in the terminal.</p><p>One final note, we will likely want to run the program and close out our ssh and terminal session. For this, we can run the program with nohup and in the background.</p><pre>pi@raspberrypi:$ nohup python raspberry_pi/shadow_client.py $</pre><p>Congrats! We’ve set up an IoT device! With some minor familiarity, AWS makes it very easy to create an Alex Skill and IoT device. We won’t worry about distribution, this skill will only be used on our home network through our developer account.</p><p>If you just wanted to set up the lights to listen to your commands, that’s it! If you want to know a bit more about what the code is actually doing, I will review key portions of the code in <a href="https://medium.com/@arthurltonelli/building-an-iot-device-with-alexa-aws-python-and-raspberry-pi-part-iv-8725923daad0"><strong>Part IV</strong></a>. Thanks for reading!</p><p>Helpful? Enjoy? Additional questions? Feedback in the form of 👏👏 or comments below always welcome!</p><p>Or, feel free to say hi at <a href="http://hello@arthurtonelli.me/">hello@arthurtonelli.me</a>!</p><p>*When mounting the file system you may need to use <strong>sudo fuse-ext2 /dev/disk# /Volumes/Raspbian </strong>instead of <strong>sudo mount -t fuse-ext2 /dev/disk# /Volumes/Raspbian</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1d383aa88c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an IoT device with Alexa, AWS, Python and Raspberry Pi - Part II]]></title>
            <link>https://medium.com/@arthurltonelli/building-an-iot-device-with-alexa-aws-python-and-raspberry-pi-part-ii-8ad84f24a3ee?source=rss-3a532135d9fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ad84f24a3ee</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Arthur Tonelli]]></dc:creator>
            <pubDate>Sat, 31 Mar 2018 14:56:10 GMT</pubDate>
            <atom:updated>2018-03-31T14:59:00.791Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_kAAnZ6IF_EU2_1z." /><figcaption>Photo by <a href="https://unsplash.com/@hckmstrrahul?utm_source=medium&amp;utm_medium=referral">Rahul Chakraborty</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In <a href="https://medium.com/@altonelli/building-an-iot-device-with-alexa-aws-python-and-raspberry-pi-274d941ef3c3"><strong>Part I</strong></a><strong>,</strong> I reviewed how to set up the Alexa Skill interaction model. In this part we will be going over setting up AWS Lambda and IoT handle the logic from the Alexa. Much of this is management between different Amazon services. This can be done through the CLI but for the walk through I will be using the console and attaching images.</p><h3>Creating an IAM Role</h3><p>Before we get too crazy, we will first need to create an IAM role for the Lambda function. If your unfamiliar with AWS, the policies allow interactions between different services. Our policy will allow the function to read and write to AWS IoT. First let’s visit the <a href="http://console.aws.amazon.com/iam/home">IAM console</a>.</p><p>Go to the “Roles” tab and select “Create role”. On the following page select “AWS service”, “Lambda” and then “Next: Permissions”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4SZo3V1aTbgSIP58VGyz0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T08I5TQc-jX7wckyQNsk0Q.png" /></figure><p>Search and select the policies “AWSIoTDataAccess” and “AWSLambdaBasicExecutionRole” to attach them to the role. This will allow us to read and write to the AWS IoT shadow and write logs via CloudWatch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ATPjufee9g2W5OCvglMK8w.png" /></figure><p>Name the role (something like “lambda_iot_exectution”) and make sure we have those two policies attached. Finally, select “Create role” and we’ll use the role later when creating the Lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2_Irktv6AR820KcFng2cw.png" /></figure><h3>Creating an IoT Thing</h3><p>Next we’ll create an AWS IoT <strong>Thing</strong>, which is the AWS representation of our smart device. The shadow is the state of a given Thing. We will be using an endpoint specific to the thing to subscribe and publish updates to the shadow via the Raspberry Pi and the Lambda function. Certificates and IAM roles are used to manage privacy.</p><p>First up, we’ll visit the <a href="http://console.aws.amazon.com/iot/home">IoT console</a>. Change the region to <strong>US-East-1 (N. Virginia)</strong>. At the time of this writing, this is the only US region for handling Alexa Skills and Lambda functions. Next we’ll go to “Manage”, “Things” and select “Register a thing”. On the following page select “Create a single thing”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7AKaLXxHE1EhtLPfEn4HGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NUg4eZ0NlCv431GaYAFzFQ.png" /></figure><p>Name the thing (my_painting) and select “Next”. Specifying a <em>type</em> of thing is not necessary. Next select “Create certificate”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6YbiKBYjUScL7FZHrTNJCg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dAQuZHKc3bTB9Hdj2mQixg.png" /></figure><p><strong>It is important to download all of these immediately.</strong> The public and private keys CANNOT be downloaded after closing the page. The root CA will likely open a new page. Save it as a .pem file. Move all of these to a safe folder. We will later copy them onto the Pi. After select “Activate” and “Done”. We will create and attach a policy next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQ3TixUUZuUajQxLOsdKUQ.png" /></figure><p>Go to the “Secure” and “Policies” tab. Select “Create a policy”. Name the policy (my_painting_policy) and add the action “iot:*”, resource ARN “*” and check “Allow” for the effect. This will give all clients all IoT permissions on the Thing. If we were developing this beyond a simple tutorial we would further restrict this. Finally select “Create”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x8JDctTXocjcRVSpA4aSZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ZRhCPeqxy3G5nq6NEb4gQ.png" /></figure><p>This new policy now has to be applied to the certificate. Go to “Secure” and “Certificates” and select the certificate we just created. Go to “Policies”, “Actions” and “Attach policy”. Check the policy we just created and select “Attach”. The certificate should be activated, if not select the “Active/Inactive” button under the certificate name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3d0eHcwG6_VBoo2bgSL-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lsQxR-Pk2Sh4_fLvJ5C0hw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vj4c6yCdRGPMdhaD9_pmzg.png" /></figure><p>Now we have an IoT Thing! If you go back to the “Manage” and “Things” tab and select the new “my_painting” thing, you can see details about it, including the shadow and endpoints. For now, select “Interact”, note the HTTPS endpoint and add it to our .env file. We’ll be using that in the Lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4C8H5LkZqkl7LRx_gDSLWQ.png" /></figure><h3>Creating a Lambda Function</h3><p>Finally, its time to add the logic to the Skill we made in <a href="https://medium.com/@altonelli/building-an-iot-device-with-alexa-aws-python-and-raspberry-pi-274d941ef3c3"><strong>Part I</strong></a>. Go to the <a href="http://console.aws.amazon.com/lambda/home">Lambda console</a> and select “Create function”. Again, <strong>make sure have the region set for US-East-1 (N. Virginia)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cflT8M7vAyG2ZVxDnyoUPA.png" /></figure><p>Select “Author from scratch” and name the function (my_painting). Select “Python 3.6”, “Choose an existing role”, the role we just made (lambda_iot_execution) and finally “Create function”. Once created, we will see AWS IoT and Amazon CloudWatch Logs in the resources the function has access to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7N3z6wlXLsSNFHAbRDkug.png" /></figure><p>Next, we have to connect our Alexa Skill as a trigger to our new function. Select “Alexa Skills Kit” in the list of triggers to the left, then highlight the new trigger. Select “Enable” Skill ID verification, then enter in the Skill ID from <a href="https://medium.com/@altonelli/building-an-iot-device-with-alexa-aws-python-and-raspberry-pi-274d941ef3c3"><strong>Part I</strong></a>. Select “Add” then “Save”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iS7C9PXA4iTU_qLwkFXPPw.png" /></figure><p>Going back to the Lambda endpoint we discussed in <a href="https://medium.com/@altonelli/building-an-iot-device-with-alexa-aws-python-and-raspberry-pi-274d941ef3c3"><strong>Part I</strong></a>, its now time to add it! Copy the ARN in the upper right of the Lambda function page and go back to the <a href="https://developer.amazon.com/alexa/console/ask&#39;">Alexa Skill Editor</a>. Go to the “Endpoint” tab, select “AWS Lambda ARN”, enter the ARN in the default region and select “Save Endpoints”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBvyQg4iAuOdUBXwpgyTfQ.png" /><figcaption>Back to the Alexa Skill Console</figcaption></figure><p>Finally everything is connected but we <em>still</em> do not have any logic in the actual function! This is as easy as uploading a ZIP file of part of the repo. First zip the file.</p><pre>$ cd ~/&lt;path_to_repo&gt;/lambda_function/<br>$ zip -r lambda_function.zip .</pre><p>In the Lambda console, select the “my_painting” Lambda function, “Upload a .ZIP file” for <em>Code entry type</em>, the ZIP file and “Upload”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYS__kK0nVYQOxI7RWPWwg.png" /></figure><p>We now need to enter the necessary environment variables, which should look like the following. Finally, select “Save” and we will see the section “Function code” populate to a Cloud9 IDE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*osZNhQlrSJkvVZ58e8AMoQ.png" /></figure><p>We are all set! We should be able to test the Skill and update the my_painting shadow.</p><h3>Testing</h3><p>Go back to the Alexa console and select “Build model”. This will take several minutes. Afterwards to go “Test”, enable testing and enter a phrase for in the Alexa test console. Try “tell my painting to turn on the lights”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3s73hlMsErC7xakflKxOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*s3r61yty_dO5ubLBfIZ-pA.png" /></figure><p>We will first see the immediate response from Alexa. If we now go back the the IoT console, select our “my_painting” thing and “Shadow” you will now see that the shadow has been updated!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T50rBdZvIEyW0fq_oji-mw.png" /></figure><h3>Review</h3><p>Now we have a simple interaction with Alexa. Without the IoT section, we could have could implemented the Lambda function to perform a simple task and have a fully functioning Alexa Skill.</p><p>Later, I will take a deeper dive into some of the core sections of code but I will give a high level review of what we accomplished in this part. We have a Lambda function receiving and <em>event</em> from the Alexa Skill. In this event, we have information on the <em>session</em> and the <em>request</em>. We look at request for an <em>intent</em> and handle accordingly. This could be asking to turn on/off the lights, changing the brightness, or asking for help.</p><p>For intents that will change the state of our IoT Thing, we send an update to the IoT Thing endpoint and update the Thing shadow. The shadow has a state that is a dictionary including the <em>desired</em> state and the <em>reported</em> state. The <em>desired</em> state is updated with what we <em>want</em> the state of the thing to reflect. The <em>reported</em> state is the updated with the current state of the thing. If there is ever a difference, a <em>delta</em> attribute will be present with the difference. We will be updating both the desired and reported states from the Pi in <a href="https://medium.com/@altonelli/building-an-iot-device-with-alexa-aws-python-and-raspberry-pi-part-iii-c1d383aa88c5"><strong>Part III</strong></a> and generally want the desired state to reflect the reported state.</p><p>Regardless of the intent, we generate a response which Alexa will say to the user. All of these services are able to work together because of the roles and policies we put in place.</p><p>Now we can give a command to Alexa but we still need to have our Raspberry Pi listen for the update and update the lights. We will do this in <a href="https://medium.com/@altonelli/building-an-iot-device-with-alexa-aws-python-and-raspberry-pi-part-iii-c1d383aa88c5"><strong>Part III</strong></a> next!</p><p>Helpful? Enjoy? Additional questions? Feedback in the form of 👏👏 or comments below always welcome!</p><p>Or, feel free to say hi at <a href="http://hello@arthurtonelli.me/">hello@arthurtonelli.me</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ad84f24a3ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an IoT device with Alexa, AWS, Python and Raspberry Pi]]></title>
            <link>https://medium.com/@arthurltonelli/building-an-iot-device-with-alexa-aws-python-and-raspberry-pi-274d941ef3c3?source=rss-3a532135d9fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/274d941ef3c3</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Arthur Tonelli]]></dc:creator>
            <pubDate>Sat, 31 Mar 2018 14:55:01 GMT</pubDate>
            <atom:updated>2018-03-31T14:59:16.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gtGzDILcNijRd7VUtjrYnA.jpeg" /><figcaption>The final product</figcaption></figure><p>I recently used AWS and a Raspberry Pi to create my own smart lights. In this series, I will guide you through setting up a strand of LED lights to respond to Amazon Alexa. I will mainly be using Python and AWS. To give credit where credit is due, as well as, to provide some great resources, I primarily used <a href="https://medium.com/@jay_proulx/headless-raspberry-pi-zero-w-setup-with-ssh-and-wi-fi-8ddd8c4d2742">Jay Proulx’s tutorial</a> on setting up the Pi and <a href="https://dordnung.de/raspberrypi-ledstrip/">David Ordnung’s tutorial</a> to set up the wiring for the LEDs to the Pi. I highly recommend referring to these and I will only briefly add some notes, as they have very detailed documentation.</p><h4>Background</h4><p>In college I acquired this painting of a sea port with translucent windows for lights to shine through. After using a series (no pun intended) of LED lights and cheap controllers that would break, I turned to my friends and said “I’m tired of this, I can build a better solution.” Here is a bit of my experience set up in a way that any level of software developer can follow. By the end of this tutorial you will be able to turn on, off and dim lights with Alexa. Perhaps you’ll even add your own functionality afterwards. Please note all, commands will be for a Linux system.</p><p>The article will be broken into the following components:</p><h4>Part I: Initial set up and the Alexa Skill Kit</h4><h4><a href="https://medium.com/@altonelli/building-an-iot-device-with-alexa-aws-python-and-raspberry-pi-part-ii-8ad84f24a3ee">Part II: Setting up AWS IAM, IoT and Lambda</a></h4><h4><a href="https://medium.com/@altonelli/building-an-iot-device-with-alexa-aws-python-and-raspberry-pi-part-iii-c1d383aa88c5">Part III: Setting up the Raspberry Pi and Lights</a></h4><h4><a href="https://medium.com/@arthurltonelli/building-an-iot-device-with-alexa-aws-python-and-raspberry-pi-part-iv-8725923daad0">Part IV: Review of code</a></h4><h3>What you will need</h3><ul><li><a href="https://www.amazon.com/CanaKit-Raspberry-Wireless-Starter-Official/dp/B06XJQV162/ref=sr_1_4?s=electronics&amp;ie=UTF8&amp;qid=1522387067&amp;sr=1-4&amp;keywords=Raspberry+Pi+Zero+W">Raspberry Pi Zero W with Rasperian installed and a 5 V power supply</a></li><li><a href="https://www.amazon.com/Sunnest-Waterproof-300leds-Flexible-Controller/dp/B07571JKPC/ref=sr_1_9?ie=UTF8&amp;qid=1522387239&amp;sr=8-9&amp;keywords=led+lights+5050">A strand of SMD5050 LED RGB Lights and 12V power supply</a></li><li>Three N-Channel MOSFETS <a href="https://www.amazon.com/N-Channel-Power-Mosfet-RFP30N06LE-220/dp/B071Z98SRG/ref=sr_1_1?ie=UTF8&amp;qid=1522387353&amp;sr=8-1&amp;keywords=P30N06LE">(I used P30N06LE<strong>)</strong></a></li><li><a href="https://www.amazon.com/eBoot-Prototype-Solderless-Breadboard-Adhesive/dp/B06XKLRYRM/ref=sr_1_48?ie=UTF8&amp;qid=1522387492&amp;sr=8-48&amp;keywords=breadboard+and+jumper+cables">A breadboard and jumper wires</a> (PCB board and solder if you want to make it more permanent after breadboarding)</li><li>An Amazon Echo Device</li><li>An Amazon Developer account (preferably made under the same Amazon account tied to your Echo)</li><li>A copy of the code, which can be cloned from <a href="https://github.com/altonelli/my_painting.git">this repo</a> or follow the code below.</li></ul><h4>Initial set up and cloning the repository</h4><p>The following is the set up for both your main development computer and the Raspberry Pi.</p><pre>$ cd &lt;your_dev_dir&gt;<br>$ git clone <a href="https://github.com/altonelli/alexa_skills.git">https://github.com/altonelli/my_painting.git</a></pre><p>After cloning the repo, touch a .env file and edit it.</p><pre>$ cd my_painting<br>$ touch .env<br>$ vi .env</pre><p>Edit your .env should look like this:</p><pre>#General AWS credentials for Pi<br>export AWS_IOT_CERTIFICATE_FILENAME=&quot;~/&lt;path_to_credentials&gt;/XXXXX-certificate.pem.crt&quot;<br>export AWS_IOT_PRIVATE_KEY_FILENAME=&quot;~/&lt;path_to_credentials&gt;/XXXXX-private.pem.key&quot;<br>export AWS_IOT_PUBLIC_KEY_FILENAME=&quot;~/&lt;path_to_credentials&gt;/XXXXX-public.pem.key&quot;<br>export AWS_IOT_ROOT_CA_FILENAME=&quot;~/&lt;path_to_credentials&gt;/root-ca.pem&quot;<br>#IoT Information<br>export AWS_IOT_MQTT_HOST=&quot;XXXXX.iot.us-east-1.amazonaws.com&quot;<br>export AWS_IOT_MQTT_PORT=8883<br>export AWS_IOT_MQTT_PORT_UPDATE=8443<br>export AWS_IOT_MQTT_CLIENT_ID=&quot;my_painting&quot;<br>export AWS_IOT_MY_THING_NAME=&quot;my_painting&quot;<br>#Alexa Skill Information<br>export AWS_ALEXA_SKILLS_KIT_ID=&quot;amzn1.ask.skill.XXXXX&quot;</pre><p>You may also want to set up a virtual environment, particularly during set up on the Raspberry Pi.</p><h3>The Alexa Interaction Model</h3><p>Let’s get started. Setting up the interface for an Alexa skill is surprisingly simple. It is essentially a JSON file, though I will go through some of the details of what it all means.</p><h4>Create the Skill</h4><p>From the <a href="https://developer.amazon.com/alexa/console/ask">Alexa Skill console</a>, there will be a few pages to start creating the skill. Select “Create Skill”, name the skill and select a language, select “Custom” and finally “Create skill”. Since this the lights will be lighting my painting, I gave it the ever so creative name “MyPainting”, since the lights are for my painting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xkQre2La1-FTgJndDO6aNA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2JiTPo_g-O4kRCjzPDyWbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hz314NMZsP12PZ2cS3udKA.png" /></figure><p>Once created, note the skill ID, which will be something like “amzn1.ask.skill.xxxxx_amazon_skill_id_xxxxx” and add it to our .env file. We can also get this from the url of the skill editor.</p><h4>The Interaction Model</h4><p>Next, go to the “JSON Editor” section in the left toolbar and upload or paste the <a href="https://github.com/altonelli/my_painting/blob/master/alexa_skill_kit/interaction_model.json">JSON file</a> from the <em>alexa_skill_kit</em> directory of the repo to create the interaction model. Then select “Save Model”. Pretty easy!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nAhhJq75M7i7zpRl67yc3w.png" /><figcaption>Paste or upload the JSON</figcaption></figure><p>We could also use the console’s interface to create the model but since it ends up being JSON anyways I prefer this method. I will highlight some of the key components of the interaction model below.</p><p>A typical interaction to the Alexa skill will be something like, “Alexa, tell <em>my painting</em> (<em>invocation name</em>) to <em>dim the lights</em> (<em>intent</em>) to <em>fifty</em> (<em>slot</em>) percent.”</p><ul><li><strong>Invocation Name</strong>: The name or phrase that will trigger Alexa to have this skill handle our interaction. For consistency I chose “my painting” and will say “Alexa, tell <em>my painting</em> to…turn on my lights<em>.”</em></li><li><strong>Intents</strong>: What we want interpreted from the skill. We have two custom intents <em>PowerStateIntent</em> and <em>BrightnessIntent</em>, for interpreting the power state (“on” or “off”) and brightness, respectively. We have a few default Amazon intents as well.</li><li><strong>Slots</strong>: Values we want to extract from a prompt. In the <strong>Samples</strong> listed, slots will be surrounded by {braces}. For every slot we list, we will also have to list the <strong>Type</strong> that can fill it.</li><li><strong>Types</strong>: A list of values that can fill a <strong>Slot</strong>. There are many <a href="https://developer.amazon.com/docs/custom-skills/slot-type-reference.html">default Amazon types</a> you can chose from, like <em>AMAZON.DATE</em> for extracting dates and (in our case) <em>AMAZON.NUMBER</em> for numerical values. We can also create custom types, as with <em>PowerState</em>, by specifying the list of values, like <em>LIST_OF_POWER_STATES</em>. Custom types require additional specification in the JSON file (below).</li><li><strong>Custom Types</strong>: In addition to adding the <strong>Type</strong> to the <strong>Slot</strong>, since we are using a custom type, we also have to list them in the JSON. The <em>name</em> will be the same as we labeled under the <strong>Slot</strong> (<em>LIST_OF_POWER_STATES</em>). The <em>values</em> are a list of possible values for the type to represent, in this case “ON” and “OFF”. We could specify any synonyms for values. Since we are only going to be using the skill in development, we will be leaving the id blank.</li><li><strong>Samples</strong>: A list of sample utterances that users may say while using the skill. I listed out several for the <em>BrightnessIntent</em> as a user may vary their vocabulary. At the same time, we have to keep them unique to the intent. <strong>We use these samples to shape how the user will interact with the skill.</strong></li></ul><p>Thats a brief overview of what we have in our interaction model. For more details and additional items that can be added to the schema check out the <a href="https://developer.amazon.com/docs/smapi/interaction-model-schema.html">Skill Management API</a>.</p><h4>AWS Lambda Endpoint</h4><p>So far we have written no code to build the interface for Alexa but we need something to handle the inputs of the interaction model! Don’t worry we’ll be coming back to this and create a Lambda function handle that logic. You may notice the “Endpoint” section in the toolbar. Once we have our Lambda function we’ll be selecting AWS Lambda and inputting the ARN. We’ll do that in the next section!</p><p>Helpful? Enjoy? Additional questions? Feedback in the form of 👏👏 or comments below always welcome!</p><p>Or, feel free to say hi at <a href="http://hello@arthurtonelli.me/">hello@arthurtonelli.me</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=274d941ef3c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>