<?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 ALI HASSAN SHAH on Medium]]></title>
        <description><![CDATA[Stories by ALI HASSAN SHAH on Medium]]></description>
        <link>https://medium.com/@engg.alibukharai?source=rss-c690030496b1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*OaJp7A44Bgjjj7Jd</url>
            <title>Stories by ALI HASSAN SHAH on Medium</title>
            <link>https://medium.com/@engg.alibukharai?source=rss-c690030496b1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:51:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@engg.alibukharai/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[OpenAI Component | Accelerating the integration of OpenAI APIs in projects]]></title>
            <link>https://medium.com/the-esp-journal/openai-component-accelerating-the-integration-of-openai-apis-in-projects-e5fa87998126?source=rss-c690030496b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5fa87998126</guid>
            <category><![CDATA[esp-box]]></category>
            <category><![CDATA[espressif]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[esp]]></category>
            <dc:creator><![CDATA[ALI HASSAN SHAH]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 08:07:44 GMT</pubDate>
            <atom:updated>2023-07-26T00:04:19.090Z</atom:updated>
            <content:encoded><![CDATA[<p>Integrating OpenAI capabilities into projects has become increasingly trends in today’s fast-paced technological landscape. <a href="https://platform.openai.com/docs/api-reference">OpenAI</a> offers a wide range of powerful APIs for natural language processing. However, the process of integrating these APIs can be complex and time-consuming, often requiring substantial effort and expertise. To simplify this integration process, we introduce the <a href="https://github.com/espressif/esp-iot-solution/tree/master/components">OpenAI Component</a>, a powerful library that streamlines the incorporation of OpenAI APIs into projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AoJSsmWQ8-XL8iD_GOtlEQ.jpeg" /><figcaption>Figure 1: Feature image</figcaption></figure><p><strong><em>In this article, we will demonstrating how it enables developers to easily add OpenAI capabilities to their projects without having to handle all the implementation tasks.</em></strong></p><p><em>This article consists of three main sections. The initial section “</em><strong><em>ESP Component Registry</em></strong><em>”provides information on step involve in adding appropriate components into your ESP-IDF project. The second section focuses on providing details about the “</em><strong><em>OpenAI Component”</em></strong><em>and the last section gives and update on “</em><strong><em>ESP-Box</em></strong><em> </em><strong><em>ChatGPT</em></strong><em> ” demo example.</em></p><h3>ESP Component Registry</h3><p>The <a href="https://components.espressif.com/"><strong>ESP Component Registry</strong></a><strong> </strong>acts as a central hub for an extensive array of open-source components that can turbocharge your IoT projects. By simply performing a quick search and a few clicks, you can effortlessly obtain the desired components and seamlessly incorporate them into your IDF projects. This efficient workflow expedites your development cycle, enabling you to concentrate on creating groundbreaking IoT solutions without the burden of complex setup procedures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Mg3lYVxUz5hOfs0geL_Lg.png" /><figcaption>Figure 2: ESP Component Registry</figcaption></figure><h4>Steps to Follow</h4><ol><li>Explore the ESP Component Registry to find the component you need.</li><li>Access the comprehensive documentations and changelogs for the desired version of the component.</li><li>Integrate the component into your existing project by executing the following command in your terminal (Note: Component name and version can be edit before executing the below command in terminal).</li></ol><pre>idf.py add-dependency &quot;espressif/Component name^verison&quot;</pre><h3>OpenAI Component</h3><p>To provide developers with comprehensive coverage of <a href="https://platform.openai.com/docs/api-reference">OpenAI API</a> features, a simple yet powerful ESP-IDF <a href="https://components.espressif.com/components/espressif/openai">component</a> is introduced. This component offers extensive support, focusing on a wide range of functionalities while excluding file operations and fine-tuning capabilities. There is comprehensive <a href="https://docs.espressif.com/projects/espressif-esp-iot-solution/en/latest/esp32/ai/openai.html">documentation</a> accessible to assist developers in comprehending the APIs effortlessly.</p><h4>Usage Example</h4><p>The first step is to instantiate an object and provide a secure “API key” as a parameter. The OpenAPI key is accessible through the <a href="https://openai.com/">OPENAI</a> website. To gain access to OpenAI services, you must first create an account, purchase tokens, and obtain your unique API key.</p><pre>openai = OpenAICreate(key);</pre><p>After creating the OpenAI object, the code calls the chatCompletion API. It sets the required parameters, sends a message (indicating it’s not the last message), and retrieves the generated response for further use or processing.</p><pre>chatCompletion = openai-&gt;chatCreate(openai);<br>chatCompletion-&gt;setModel(chatCompletion, &quot;gpt-3.5-turbo&quot;);<br>chatCompletion-&gt;setSystem(chatCompletion, &quot;Code geek&quot;);<br>chatCompletion-&gt;setMaxTokens(chatCompletion, CONFIG_MAX_TOKEN);<br>chatCompletion-&gt;setTemperature(chatCompletion, 0.2);<br>chatCompletion-&gt;setStop(chatCompletion, &quot;\r&quot;);<br>chatCompletion-&gt;setPresencePenalty(chatCompletion, 0);<br>chatCompletion-&gt;setFrequencyPenalty(chatCompletion, 0);<br>chatCompletion-&gt;setUser(chatCompletion, &quot;OpenAI-ESP32&quot;);<br>OpenAI_StringResponse_t *result = chatCompletion-&gt;message(chatCompletion, &quot;Hello!, World&quot;, false); //Calling Chat completion api<br>char *response = result-&gt;getData(result, 0);</pre><p>Similarly, after instantiating the OpenAI object, the code calls the audioTranscriptionCreate API. It sets the necessary parameters, such as the audio file and language, followed by initiating the audio transcription process. Finally, it retrieves the transcription result for further use or processing.</p><pre>audioTranscription = openai-&gt;audioTranscriptionCreate(openai);<br>audioTranscription-&gt;setResponseFormat(audioTranscription, OPENAI_AUDIO_RESPONSE_FORMAT_JSON);<br>audioTranscription-&gt;setLanguage(audioTranscription,&quot;en&quot;);<br>audioTranscription-&gt;setTemperature(audioTranscription, 0.2);<br>char *text = audioTranscription-&gt;file(audioTranscription, (uint8_t *)audio, audio_len, OPENAI_AUDIO_INPUT_FORMAT_WAV); // Calling transcript api</pre><p>To explore more APIs and their functionalities, please refer to the <a href="https://docs.espressif.com/projects/espressif-esp-iot-solution/en/latest/ai/openai.html">documentation</a>.</p><h3>ESP-BOX ChatGPT Demo Example</h3><p>The <a href="https://github.com/espressif/esp-box">updated version</a> of the ESP-BOX ChatGPT example incorporates the OpenAI component, replacing the <a href="https://github.com/espressif/esp-box/tree/0924e7bc2cad50d3d7ca4b0f91eef7da6934d5e6/examples/chatgpt_demo">older version</a>. Further details on the development process can be found in the <a href="https://blog.espressif.com/unleashing-the-power-of-openai-and-esp-box-a-guide-to-fusing-chatgpt-with-espressif-socs-fba0b2d2c4f2">Blog</a>. Notably, in the newer version, we have implemented a secure method to store the Wi-Fi and OpenAI keys in non-volatile storage (NVS) using a <a href="https://components.espressif.com/components/espressif/esp_tinyuf2?from_wecom=1">esp_tinyuf2</a> component.</p><p>During the initial boot, the first binary is executed, allowing the user to enter secure credentials such as Wi-Fi and OpenAI keys. Once the credentials are entered, the system restarts, and the ChatGPT binary takes control. This binary is responsible for running the ChatGPT functionality, utilizing the secure credentials provided during the initial boot. The workflow for this process is illustrated in the figure below, providing an overview of the overall process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*loAgx96ArVCRlk_rVwcbaQ.jpeg" /><figcaption>Figure 3: ChatGPT_demo Workflow with easy Authentication</figcaption></figure><p>Additionally, users have the option to try out the newer version of the ESP-BOX ChatGPT example using the <a href="https://espressif.github.io/esp-launchpad/?flashConfigURL=https://raw.githubusercontent.com/espressif/esp-box/master/launch.toml">ESP-Launchpad</a> without the need to compile the project locally on the machines. This option offers a convenient means for individuals to experience the improvements and advancements made in the implementation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5fa87998126" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-esp-journal/openai-component-accelerating-the-integration-of-openai-apis-in-projects-e5fa87998126">OpenAI Component | Accelerating the integration of OpenAI APIs in projects</a> was originally published in <a href="https://medium.com/the-esp-journal">The ESP Journal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleashing the Power of OpenAI and ESP-BOX: A Guide to Fusing ChatGPT with Espressif SOCs]]></title>
            <link>https://medium.com/the-esp-journal/unleashing-the-power-of-openai-and-esp-box-a-guide-to-fusing-chatgpt-with-espressif-socs-fba0b2d2c4f2?source=rss-c690030496b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fba0b2d2c4f2</guid>
            <category><![CDATA[chatgpt-chatbot]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[esp]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[ALI HASSAN SHAH]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 07:48:09 GMT</pubDate>
            <atom:updated>2023-07-24T10:31:55.156Z</atom:updated>
            <content:encoded><![CDATA[<p>The world is witnessing a technological revolution, and OpenAI is at the forefront of this change. One of its most exciting innovations is ChatGPT — that utilizes natural language processing to create more engaging and intuitive user experiences. The integration of OpenAI APIs with IoT devices has opened up a world of possibilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TtnelePsITOPSyKX2HQ3aQ.jpeg" /></figure><p><strong><em>In this article, we will explore the potential of ChatGPT with ESP-BOX, a powerful combination that can take IoT devices to the next level.</em></strong></p><p><em>This article is structured into three primary sections, each covering essential aspects of the project. The first section delves into</em><strong><em> </em></strong><em>“</em><a href="#709e"><strong><em>ESP-BOX</em></strong></a><em>”, providing details on its features and functionalities. The second section is a “</em><a href="#162c"><strong><em>case study</em></strong></a><em>”</em><strong><em> </em></strong><em>that outline the steps involved in building the project from scratch. The final section, “</em><a href="#6b5b"><strong><em>conclusion</em></strong></a><em>”, provides a list of additional sources of information that readers can explore to deepen their knowledge and understanding of the project.</em></p><h3>ESP-BOX</h3><p>The <a href="https://github.com/espressif/esp-box">ESP-BOX</a> is a new generation AIoT development platform that includes the ESP32-S3-BOX and ESP32-S3-BOX-Lite development boards. These boards are based on the <a href="https://products.espressif.com/#/product-selector?names=&amp;filter={%22Series%22:[%22ESP32-S3%22]}">ESP32-S3</a> Wi-Fi + Bluetooth 5 (LE) SoC and provide a flexible and customizable solution for developing AIoT applications that integrate with various sensors, controllers, and gateways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPJ4iUMbzT1PEwFTBs2AFw.png" /><figcaption>Figure 1. <a href="https://www.espressif.com/en/products/devkits">ESP32-S3-BOX</a></figcaption></figure><blockquote>The ESP-BOX is packed with a wide range of features that make it an ideal AIoT development platform. Let’s take a closer look at some of the key features</blockquote><ol><li><strong>Far-field voice interaction with 2 mics:</strong> The ESP-BOX supports far-field voice interaction with two microphones, allowing users to interact with their devices from a distance.</li><li><strong>Offline speech commands recognition in Chinese and English languages with high recognition rate:</strong> The ESP-BOX offers offline speech commands recognition in both Chinese and English languages with a high recognition rate, making it easy to develop voice-enabled devices.</li><li><strong>Reconfigurable 200+ speech commands in Chinese and English languages: </strong>Developers can easily reconfigure over 200 speech commands in Chinese and English languages according to their needs.</li><li><strong>Continuous Identification and Wakeup Interrupt:</strong> The ESP-BOX supports continuous identification and wakeup interrupt, ensuring that devices are always ready to receive voice commands.</li><li><strong>Flexible and reusable GUI framework:</strong> The ESP-BOX comes with a flexible and reusable GUI framework, allowing developers to create custom user interfaces for their applications.</li><li><strong>End-to-end AIoT development framework ESP-RainMaker:</strong> The ESP-BOX is built on Espressif’s end-to-end AIoT development framework, ESP-RainMaker, providing developers with all the tools they need to create powerful and intelligent devices.</li><li><strong>Pmod™ compatible headers support expand peripheral modules:</strong> The ESP-BOX features Pmod™ compatible headers, making it easy to expand its capabilities with a wide range of peripheral modules.</li></ol><h3>Case Study</h3><p>Developing a Voice-Controlled Chatbot using ESP-BOX and OpenAI APIs.</p><h4>Description</h4><p>This case study outlines the development process for a voice-controlled chatbot that utilizes the combination of ESP-BOX and OpenAI API. The system is capable of receiving speech commands from users, displaying them on the screen, and processing them through the OpenAI APIs to generate a response. The response is then displayed on the screen and played through the ESP-BOX. The step-by-step workflow provides a detailed explanation of how to integrate these technologies to create an efficient and effective voice-controlled chatbot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VW7mOI2ZChjdwXvwQHFXkw.png" /><figcaption>Figure 2. Workflow of the case study</figcaption></figure><h4>Environment Setup</h4><p>Setting up a suitable environment and installing the correct version is critical to avoid errors.</p><ul><li><strong>ESP-IDF</strong></li></ul><p>In this demonstration, we’ll be utilizing ESP-IDF version 5.0 (master branch). If you need guidance on how to set up ESP-IDF, please refer to the official <a href="https://docs.espressif.com/projects/esp-idf/en/release-v5.0/esp32/index.html">IDF Programming guide</a> for detailed information.</p><p><strong><em>*As of writing of this blog, the current IDF commit head is df9310ada2.</em></strong></p><ul><li><strong>ChatGPT API</strong></li></ul><p>To utilize ChatGPT, a powerful language model based on the GPT-3.5 architecture, you must first obtain a secure API key. This can be achieved by creating an account on the <a href="https://openai.com/">OpenAI platform</a> and obtaining tokens through creation or purchase. With an API key, you gain access to a wide range of features and capabilities that can be customized to meet your specific needs, such as natural language processing and generation, text completion, and conversation modeling. Follow the <a href="https://platform.openai.com/docs/api-reference">official API reference link</a>.</p><p><strong>*<em>Maintaining the confidentiality and security of the API key is crucial to prevent unauthorized access to the user’s account and data.</em></strong></p><h4>Adding Offline Speech Recognition</h4><p>Espressif Systems, has as developed an innovative speech recognition framework called <a href="https://github.com/espressif/esp-sr">ESP-SR</a>. This framework is designed to enable devices to recognize spoken words and phrases without relying on external cloud-based services, making it an ideal solution for offline speech recognition applications.</p><p>ESP-SR framework consists of various modules, including the Audio Front-end (AFE), Wake Word Engine (WakeNet), Speech Command Word Recognition (MultiNet), and Speech Synthesis (which currently only supports the Chinese language). Follow the official <a href="https://docs.espressif.com/projects/esp-sr/en/latest/esp32/index.html">Documentation</a> for more information.</p><h4>Integrating OpenAI API</h4><p>The OpenAI API provides numerous <a href="https://platform.openai.com/docs/api-reference">functions</a> that developers can leverage to enhance their applications. In our project, we utilized the Audio-to-Text and Completion APIs and implemented them using C-language code based on ESP-IDF. The following section provides a brief overview of the code we employed.</p><ul><li><strong>Audio to Text</strong></li></ul><p>To extract text from audio, we utilize HTTPS and OpenAI <a href="https://platform.openai.com/docs/api-reference/audio">Audio API</a>. The following code is used for this task.</p><pre>esp_err_t create_whisper_request_from_record(uint8_t *audio, int audio_len)<br>{<br>    // Set the authorization headers<br>    char url[128] = &quot;https://api.openai.com/v1/audio/transcriptions&quot;;<br>    char headers[256];<br>    snprintf(headers, sizeof(headers), &quot;Bearer %s&quot;, OPENAI_API_KEY);<br>    // Configure the HTTP client<br>    esp_http_client_config_t config = {<br>        .url = url,<br>        .method = HTTP_METHOD_POST,<br>        .event_handler = response_handler,<br>        .buffer_size = MAX_HTTP_RECV_BUFFER,<br>        .timeout_ms = 60000,<br>        .crt_bundle_attach = esp_crt_bundle_attach,<br>    };<br><br>    // Initialize the HTTP client<br>    esp_http_client_handle_t client = esp_http_client_init(&amp;config);<br><br>    // Set the headers<br>    esp_http_client_set_header(client, &quot;Authorization&quot;, headers);<br><br>    // Set the content type and the boundary string<br>    char boundary[] = &quot;boundary1234567890&quot;;<br>    char content_type[64];<br>    snprintf(content_type, sizeof(content_type), &quot;multipart/form-data; boundary=%s&quot;, boundary);<br>    esp_http_client_set_header(client, &quot;Content-Type&quot;, content_type);<br><br>    // Set the file data and size<br>    char *file_data = NULL;<br>    size_t file_size;<br>    file_data = (char *)audio;<br>    file_size = audio_len;<br><br>    // Build the multipart/form-data request<br>    char *form_data = (char *)malloc(MAX_HTTP_RECV_BUFFER);<br>    assert(form_data);<br>    ESP_LOGI(TAG, &quot;Size of form_data buffer: %zu bytes&quot;, sizeof(*form_data) * MAX_HTTP_RECV_BUFFER);<br>    int form_data_len = 0;<br>    form_data_len += snprintf(form_data + form_data_len, MAX_HTTP_RECV_BUFFER - form_data_len,<br>                              &quot;--%s\r\n&quot;<br>                              &quot;Content-Disposition: form-data; name=\&quot;file\&quot;; filename=\&quot;%s\&quot;\r\n&quot;<br>                              &quot;Content-Type: application/octet-stream\r\n&quot;<br>                              &quot;\r\n&quot;, boundary, get_file_format(file_type));<br>    ESP_LOGI(TAG, &quot;form_data_len %d&quot;, form_data_len);<br>    ESP_LOGI(TAG, &quot;form_data %s\n&quot;, form_data);<br><br>    // Append the audio file contents<br>    memcpy(form_data + form_data_len, file_data, file_size);<br>    form_data_len += file_size;<br>    ESP_LOGI(TAG, &quot;Size of form_data: %zu&quot;, form_data_len);<br><br>    // Append the rest of the form-data<br>    form_data_len += snprintf(form_data + form_data_len, MAX_HTTP_RECV_BUFFER - form_data_len,<br>                              &quot;\r\n&quot;<br>                              &quot;--%s\r\n&quot;<br>                              &quot;Content-Disposition: form-data; name=\&quot;model\&quot;\r\n&quot;<br>                              &quot;\r\n&quot;<br>                              &quot;whisper-1\r\n&quot;<br>                              &quot;--%s--\r\n&quot;, boundary, boundary);<br><br>    // Set the headers and post field<br>    esp_http_client_set_post_field(client, form_data, form_data_len);<br><br>    // Send the request<br>    esp_err_t err = esp_http_client_perform(client);<br>    if (err != ESP_OK) {<br>        ESP_LOGW(TAG, &quot;HTTP POST request failed: %s\n&quot;, esp_err_to_name(err));<br>    }<br><br>    // Clean up client<br>    esp_http_client_cleanup(client);<br><br>    // Return error code<br>    return err;<br>}</pre><p>This code is a function named “<em>whisper_from_record</em>”, which takes in a pointer to a buffer containing the audio data and an integer “<em>audio_len </em>” that represents the length of the audio data. This function sends a POST request to the OpenAI API endpoint to transcribe the given audio data.</p><p>The function starts by initializing the URL of the OpenAI API and setting the authorization headers with the bearer token “<em>OPENAI_API_KEY</em>”. Then, an HTTP client is configured and initialized with the provided configuration, including the URL, HTTP method, event handler, buffer size, timeout, and SSL certificate.</p><p>After that, the content type and the boundary string for the multipart form-data request are set as headers to the HTTP client. The file data and its size are also set, and a multipart/form-data request is built. The “<em>form_data</em>” buffer is allocated with a malloc() function, and the necessary information is added to it. This includes the filename and Content-Type of the audio file, the file contents, and the name of the model that will be used for transcription.</p><p>Once the “<em>form_data </em>”is built, it is set as the post field in the HTTP client, and the client sends the POST request to the OpenAI API endpoint. If there is an error during the request, the function logs an error message. Finally, the HTTP client is cleaned up, and the resources allocated for form_data are freed.</p><p>The function returns an esp_err_t error code, which indicates whether the HTTP request was successful or not.</p><ul><li><strong>Chat Completion</strong></li></ul><p>The OpenAI <a href="https://platform.openai.com/docs/api-reference/chat/create">Chat Completion API</a> is utilized to send HTTPS requests for chat completion. This process involves utilizing the create_chatgpt_request function, which takes in a content parameter representing the input text to the GPT-3.5 model.</p><pre>esp_err_t create_chatgpt_request(const char *content)<br>{<br>    char url[128] = &quot;https://api.openai.com/v1/chat/completions&quot;;<br>    char model[16] = &quot;gpt-3.5-turbo&quot;;<br>    char headers[256];<br>    snprintf(headers, sizeof(headers), &quot;Bearer %s&quot;, OPENAI_API_KEY);<br><br>    esp_http_client_config_t config = {<br>        .url = url,<br>        .method = HTTP_METHOD_POST,<br>        .event_handler = response_handler,<br>        .buffer_size = MAX_HTTP_RECV_BUFFER,<br>        .timeout_ms = 30000,<br>        .crt_bundle_attach = esp_crt_bundle_attach,<br>    };<br><br>    // Set the headers<br>    esp_http_client_handle_t client = esp_http_client_init(&amp;config);<br>    esp_http_client_set_header(client, &quot;Content-Type&quot;, &quot;application/json&quot;);<br>    esp_http_client_set_header(client, &quot;Authorization&quot;, headers);<br><br>    // Create JSON payload with model, max tokens, and content<br>    snprintf(json_payload, sizeof(json_payload), json_fmt, model, MAX_RESPONSE_TOKEN, content);<br>    esp_http_client_set_post_field(client, json_payload, strlen(json_payload));<br><br>    // Send the request<br>    esp_err_t err = esp_http_client_perform(client);<br>    if (err != ESP_OK) {<br>        ESP_LOGW(TAG, &quot;HTTP POST request failed: %s\n&quot;, esp_err_to_name(err));<br>    }<br><br>    // Clean up client<br>    esp_http_client_cleanup(client);<br><br>    // Return error code<br>    return err;<br>}</pre><p>The function first sets up the URL, model, and headers needed for the HTTP POST request, and then creates a JSON payload with the model, max tokens, and content.</p><p>Next, the function sets the headers for the HTTP request and sets the JSON payload as the post field for the request.</p><p>The HTTP POST request is then sent using “<em>esp_http_client_perform()</em>”, and if the request fails, an error message is logged.</p><p>Finally, the HTTP client is cleaned up and the error code is returned.</p><ul><li><strong>Handling Response</strong></li></ul><p>Callback function “<em>response_handler </em>”that is used by the ESP-IDF HTTP client library to handle events that occur during an HTTP request/response exchange.</p><pre>esp_err_t response_handler(esp_http_client_event_t *evt)<br>{<br>    static char *data = NULL; // Initialize data to NULL<br>    static int data_len = 0; // Initialize data to NULL<br><br>    switch (evt-&gt;event_id) {<br>    case HTTP_EVENT_ERROR:<br>        ESP_LOGI(TAG, &quot;HTTP_EVENT_ERROR&quot;);<br>        break;<br><br>    case HTTP_EVENT_ON_CONNECTED:<br>        ESP_LOGI(TAG, &quot;HTTP_EVENT_ON_CONNECTED&quot;);<br>        break;<br><br>    case HTTP_EVENT_HEADER_SENT:<br>        ESP_LOGI(TAG, &quot;HTTP_EVENT_HEADER_SENT&quot;);<br>        break;<br><br>    case HTTP_EVENT_ON_HEADER:<br>        if (evt-&gt;data_len) {<br>            ESP_LOGI(TAG, &quot;HTTP_EVENT_ON_HEADER&quot;);<br>            ESP_LOGI(TAG, &quot;%.*s&quot;, evt-&gt;data_len, (char *)evt-&gt;data);<br>        }<br>        break;<br><br>    case HTTP_EVENT_ON_DATA:<br>        ESP_LOGI(TAG, &quot;HTTP_EVENT_ON_DATA (%d +)%d\n&quot;, data_len, evt-&gt;data_len);<br>        ESP_LOGI(TAG, &quot;Raw Response: data length: (%d +)%d: %.*s\n&quot;, data_len, evt-&gt;data_len, evt-&gt;data_len, (char *)evt-&gt;data);<br>        <br>        // Allocate memory for the incoming data        <br>        data = heap_caps_realloc(data, data_len + evt-&gt;data_len + 1,  MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);<br>        if (data == NULL) {<br>            ESP_LOGE(TAG, &quot;data realloc failed&quot;);<br>            free(data);<br>            data = NULL;<br>            break;<br>        }<br>        memcpy(data + data_len, (char *)evt-&gt;data, evt-&gt;data_len);<br>        data_len += evt-&gt;data_len;<br>        data[data_len] = &#39;\0&#39;;<br>        break;<br><br>    case HTTP_EVENT_ON_FINISH:<br>        ESP_LOGI(TAG, &quot;HTTP_EVENT_ON_FINISH&quot;);<br>        if (data != NULL) {<br>            // Process the raw data<br>            parsing_data(data, strlen(data));<br>            // Free memory<br>            free(data); <br>            data = NULL;<br>            data_len = 0;<br>        }<br>        break;<br><br>    case HTTP_EVENT_DISCONNECTED:<br>        ESP_LOGI(TAG, &quot;HTTP_EVENT_DISCONNECTED&quot;);<br>        break;<br><br>    default:<br>        break;<br>    }<br>    return ESP_OK;<br>}</pre><p>In case of “<em>HTTP_EVENT_ON_DATA</em>”, the function allocates memory for the incoming data, copies the data into the buffer and increments the “<em>data_len </em>”variable accordingly. This is done to accumulate the response data.</p><p>In case of “<em>HTTP_EVENT_ON_FINISH</em>”, the function prints a message indicating that the HTTP exchange has finished, and then calls the “<em>parsing_data </em>”function to process the accumulated/raw data. It then frees the memory and resets the data and “<em>data_len </em>”variables to zero. It then frees the allocated memory and resets the buffer and its length to zero.</p><p>Finally, the function returns “<em>ESP_OK </em>”indicating that the operation was successful.</p><ul><li><strong>Parsing Raw Data</strong></li></ul><p>The JSON <a href="https://components.espressif.com/components/espressif/json_parser">parser component</a> is utilized to parse the raw response obtained from ChatGPT API and Whisper AI API over HTTPS. To perform this task, a function is used, which employs the parser component. Further details about this tool can be found on <a href="https://github.com/espressif/json_parser">GitHub</a>.</p><pre>void parse_response (const char *data, int len)<br>{<br>    jparse_ctx_t jctx;<br>    int ret = json_parse_start(&amp;jctx, data, len);<br>    if (ret != OS_SUCCESS) {<br>        ESP_LOGE(TAG, &quot;Parser failed&quot;);<br>        return;<br>    }<br>    printf(&quot;\n&quot;);<br>    int num_choices;<br><br>    /* Parsing Chat GPT response*/<br>    if (json_obj_get_array(&amp;jctx, &quot;choices&quot;, &amp;num_choices) == OS_SUCCESS) {<br>        for (int i = 0; i &lt; num_choices; i++) {<br>            if (json_arr_get_object(&amp;jctx, i) == OS_SUCCESS &amp;&amp; json_obj_get_object(&amp;jctx, &quot;message&quot;) == OS_SUCCESS &amp;&amp;<br>                    json_obj_get_string(&amp;jctx, &quot;content&quot;, message_content, sizeof(message_content)) == OS_SUCCESS) {<br>                ESP_LOGI(TAG, &quot;ChatGPT message_content: %s\n&quot;, message_content);<br>            }<br>            json_arr_leave_object(&amp;jctx);<br>        }<br>        json_obj_leave_array(&amp;jctx);<br>    }<br><br>    /* Parsing Whisper AI response*/<br>    else if (json_obj_get_string(&amp;jctx, &quot;text&quot;, message_content, sizeof(message_content)) == OS_SUCCESS) {<br>        ESP_LOGI(TAG, &quot;Whisper message_content: %s\n&quot;, message_content);<br>    } else if (json_obj_get_object(&amp;jctx, &quot;error&quot;) == OS_SUCCESS) {<br>        if (json_obj_get_string(&amp;jctx, &quot;type&quot;, message_content, sizeof(message_content)) == OS_SUCCESS) {<br>            ESP_LOGE(TAG, &quot;API returns an error: %s&quot;, message_content);<br>        }<br>    }<br>}</pre><h4>Integrating TTS API</h4><p>At the moment, OpenAI doesn’t offer public access to their Text-to-Speech (TTS) API. However, there are various other TTS APIs available, including <a href="https://voicerss.org/api/">Voicerss</a>, <a href="https://ttsmaker.com/zh-cn">TTSmaker</a>, and <a href="https://www.talkinggenie.com/tts">TalkingGenie</a>. These APIs can generate speech from text input, and you can find more information about them on their respective websites.</p><p>For the purposes of this tutorial, we will be using the <a href="https://www.talkinggenie.com/tts">TalkingGenie</a> API, which is one of the best options available for generating high-quality, natural-sounding speech both in English and Chinese. One of the unique features of TalkingGenie is its ability to translate mixed language text, such as Chinese and English, into speech seamlessly. This can be a valuable tool for creating content that appeals to a global audience. The following code sends a text response generated by ChatGPT to the TalkingGenie API using HTTPS, and then plays the resulting speech through an ESP-BOX.</p><pre>esp_err_t text_to_speech_request(const char *message, AUDIO_CODECS_FORMAT code_format)<br>{<br>    int j = 0;<br>    size_t message_len = strlen(message);<br>    char *encoded_message;<br>    char *language_format_str, *voice_format_str, *codec_format_str;<br><br>    // Encode the message for URL transmission<br>    encoded_message = heap_caps_malloc((3 * message_len + 1), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);<br>    url_encode(message, encoded_message);<br><br>    // Determine the audio codec format<br>    if (AUDIO_CODECS_MP3 == code_format) {<br>        codec_format_str = &quot;MP3&quot;;<br>    } else {<br>        codec_format_str = &quot;WAV&quot;;<br>    }<br><br>    // Determine the required size of the URL bu<br>    int url_size = snprintf(NULL, 0, &quot;https://dds.dui.ai/runtime/v1/synthesize?voiceId=%s&amp;text=%s&amp;speed=1&amp;volume=%d&amp;audiotype=%s&quot;, \<br>                            VOICE_ID, \<br>                            encoded_message, \<br>                            VOLUME, \<br>                            codec_format_str);<br><br>    // Allocate memory for the URL buffer<br>    char *url = heap_caps_malloc((url_size + 1), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);<br>    if (url == NULL) {<br>        ESP_LOGE(TAG, &quot;Failed to allocate memory for URL&quot;);<br>        return ESP_ERR_NO_MEM;<br>    }<br><br>    // Format the URL string<br>    snprintf(url, url_size + 1, &quot;https://dds.dui.ai/runtime/v1/synthesize?voiceId=%s&amp;text=%s&amp;speed=1&amp;volume=%d&amp;audiotype=%s&quot;, \<br>             VOICE_ID, \<br>             encoded_message, \<br>             VOLUME, \<br>             codec_format_str);<br><br>    // Configure the HTTP client<br>    esp_http_client_config_t config = {<br>        .url = url,<br>        .method = HTTP_METHOD_GET,<br>        .event_handler = http_event_handler,<br>        .buffer_size = MAX_FILE_SIZE,<br>        .buffer_size_tx = 4000,<br>        .timeout_ms = 30000,<br>        .crt_bundle_attach = esp_crt_bundle_attach,<br>    };<br><br>    // Initialize and perform the HTTP request<br>    esp_http_client_handle_t client = esp_http_client_init(&amp;config);<br>    esp_err_t err = esp_http_client_perform(client);<br>    if (err != ESP_OK) {<br>        ESP_LOGE(TAG, &quot;HTTP GET request failed: %s&quot;, esp_err_to_name(err));<br>    }<br><br>    // Free allocated memory and clean up the HT<br>    heap_caps_free(url);<br>    heap_caps_free(encoded_message);<br>    esp_http_client_cleanup(client);<br><br>    // Return the result of the function call<br>    return err;<br>}</pre><p>The function “<em>text_to_speech </em>” takes a message string and an “<em>AUDIO_CODECS_FORMAT</em>” parameter as input. The message string is the text that will be synthesized into speech, while the “<em>AUDIO_CODECS_FORMAT </em>” parameter specifies whether the speech should be encoded in MP3 or WAV format.</p><p>The function first encodes the message string using “<em>url_encode</em>” function that replace some non-valid characters to its ASCII code, and then converts that code to a two-digit hexadecimal representation. Next allocates memory for the resulting encoded string. It then checks the “<em>AUDIO_CODECS_FORMAT</em>” parameter and sets the appropriate codec format string to be used in the “<em>url</em>”.</p><p>Next, the function determines the size of the “<em>url</em>” buffer needed to make a GET request to the TalkingGenie API, and allocates memory for the “<em>url</em>” buffer accordingly. It then formats the “<em>url</em>” string with the appropriate parameters, including the voiceId (which specifies the voice to be used), the encoded text, the speed and volume of the speech, and the audiotype (either “MP3” or “WAV”).</p><p>The function then sets up an “<em>esp_http_client_config_t</em>” struct with the “<em>url</em>” and other configuration parameters, initializes an esp_http_client_handle_t with the struct, and performs a GET request to the TalkingGenie API using “<em>esp_http_client_perform</em>”. If the request is successful, the function returns ESP_OK, otherwise it returns an error code.</p><p>Finally, the function frees the memory allocated for the “<em>url</em>” buffer and the encoded message, cleans up the “<em>esp_http_client_handle_t</em>”, and returns the error code.</p><ul><li><strong>Handling TTS Response</strong></li></ul><p>In the similar fashion Callback function “<em>http_event_handler</em>” is defined to handle events that occur during an HTTP request/response exchange.</p><pre>static esp_err_t http_event_handler(esp_http_client_event_t *evt)<br>{<br>    switch (evt-&gt;event_id) {<br>    // Handle errors that occur during the HTTP request<br>    case HTTP_EVENT_ERROR:<br>        ESP_LOGE(TAG, &quot;HTTP_EVENT_ERROR&quot;);<br>        break;<br><br>    // Handle when the HTTP client is connected<br>    case HTTP_EVENT_ON_CONNECTED:<br>        ESP_LOGI(TAG, &quot;HTTP_EVENT_ON_CONNECTED&quot;);<br>        break;<br><br>    // Handle when the header of the HTTP request is sent<br>    case HTTP_EVENT_HEADER_SENT:<br>        ESP_LOGI(TAG, &quot;HTTP_EVENT_HEADER_SENT&quot;);<br>        break;<br><br>    // Handle when the header of the HTTP response is received<br>    case HTTP_EVENT_ON_HEADER:<br>        ESP_LOGI(TAG, &quot;HTTP_EVENT_ON_HEADER&quot;);<br>        file_total_len = 0;<br>        break;<br><br>    // Handle when data is received in the HTTP response<br>    case HTTP_EVENT_ON_DATA:<br>        ESP_LOGI(TAG, &quot;HTTP_EVENT_ON_DATA, len=%d&quot;, evt-&gt;data_len);<br>        if ((file_total_len + evt-&gt;data_len) &lt; MAX_FILE_SIZE) {<br>            memcpy(record_audio_buffer + file_total_len, (char *)evt-&gt;data, evt-&gt;data_len);<br>            file_total_len += evt-&gt;data_len;<br>        }<br>        break;<br><br>    // Handle when the HTTP request finishes<br>    case HTTP_EVENT_ON_FINISH:<br>        ESP_LOGI(TAG, &quot;HTTP_EVENT_ON_FINISH:%d, %d K&quot;, file_total_len, file_total_len / 1024);<br>        audio_player_play(record_audio_buffer, file_total_len);<br>        break;<br><br>    // Handle when the HTTP client is disconnected<br>    case HTTP_EVENT_DISCONNECTED:<br>        ESP_LOGI(TAG, &quot;HTTP_EVENT_DISCONNECTED&quot;);<br>        break;<br><br>    // Handle when a redirection occurs in the HTTP request<br>    case HTTP_EVENT_REDIRECT:<br>        ESP_LOGI(TAG, &quot;HTTP_EVENT_REDIRECT&quot;);<br>        break;<br>    }<br>    return ESP_OK;<br>}</pre><p>“<em>HTTP_EVENT_ON_DATA”</em> event is used to handle the audio data received from the server. The audio data is stored in a buffer called “<em>record_audio_buffer” </em>and the total length of the audio data received is stored in a variable called “<em>file_total_len</em>”. If the total length of the audio data received is less than a predefined “<em>MAX_FILE_SIZE</em>”, the data is copied into the “<em>record_audio_buffer</em>”.</p><p>Finally, the “<em>HTTP_EVENT_ON_FINISH </em>”event is used to handle the end of the HTTP response. In this case, the “<em>record_audio_buffer” </em>is passed to a function called “<em>audio_player_play</em>”which plays the audio.</p><h4>Display</h4><p>For display we uses LVGL, an open-source embedded graphics library that is gaining popularity for its powerful and visually appealing features and low memory footprints. LVGL has also released a visual drag-and-drop UI editor called <a href="https://squareline.io/">SquareLine</a> Studio. It’s a powerful tool that makes it easy to create beautiful GUIs for your applications.<br>To integrate LVGL with your project, Espressif Systems provides an official <a href="https://components.espressif.com/components/lvgl/lvgl">package manager</a> tool. This tool allows you to directly add LVGL and related porting components to your project, saving you time and effort. For more information follow the official <a href="https://blog.espressif.com/making-the-fancy-user-interface-on-esp-has-never-been-easier-e44e79c0ae3">blogs</a> and <a href="https://docs.lvgl.io/master/index.html">documentations</a>.</p><h4>Conclusion</h4><p>The integration of OpenAI’s ChatGPT with Espressif’s ESP-BOX has opened up new possibilities for creating powerful and intelligent IoT devices. The ESP-BOX provides a flexible and customizable AIoT development platform with features like far-field voice interaction, offline speech commands recognition, and a reusable GUI framework. By combining these capabilities with the OpenAI API, developers can create voice-controlled chatbots and enhance user experiences in IoT applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*UM036OkLmVtxKHGfvVR1vQ.gif" /><figcaption>Figure 3. Demo of ESP-BOX as a chatbot</figcaption></figure><p>Don’t forget to check out <a href="https://www.espressif.com/">Espressif Systems</a>’ <a href="https://github.com/orgs/espressif/repositories">GitHub </a>repository for more open-source demos on <a href="https://github.com/espressif/esp-iot-solution">ESP-IoT-Solution</a>, <a href="https://github.com/espressif/esp-sr">ESP-SR</a>, and <a href="https://github.com/espressif/esp-box">ESP-BOX</a>. The source code for this project will be found <a href="https://github.com/espressif/esp-box/tree/master/examples"><strong><em>here</em></strong></a><em>.</em> As part of our future plans, we aim to introduce a component for the OpenAI API that will offer a user-friendly functions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fba0b2d2c4f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-esp-journal/unleashing-the-power-of-openai-and-esp-box-a-guide-to-fusing-chatgpt-with-espressif-socs-fba0b2d2c4f2">Unleashing the Power of OpenAI and ESP-BOX: A Guide to Fusing ChatGPT with Espressif SOCs</a> was originally published in <a href="https://medium.com/the-esp-journal">The ESP Journal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ESP32-S3 Edge-AI｜Human Activity Recognition Using Accelerometer Data and ESP-DL]]></title>
            <link>https://medium.com/the-esp-journal/esp32-s3-edge-ai-human-activity-recognition-using-accelerometer-data-and-esp-dl-3afa97ca553c?source=rss-c690030496b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3afa97ca553c</guid>
            <category><![CDATA[esp]]></category>
            <category><![CDATA[edge-computing]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[recognition]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[ALI HASSAN SHAH]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 07:40:35 GMT</pubDate>
            <atom:updated>2023-10-24T07:32:27.570Z</atom:updated>
            <content:encoded><![CDATA[<p>Edge computing is a distributed computing paradigm that brings computation and data storage closer to the device’s location. Edge Artificial Intelligence (edge-AI) is an exciting development within edge computing because it allows traditional technologies to run more efficiently, with higher performance and less power. Trained neural networks are used to make inferences on small devices. The potential <a href="https://www.xenonstack.com/blog/edge-ai-use-case">applications areas</a> of edge AI includes manufacturing, healthcare, the retail industry, surveillance, smart home, and finance banking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6FI3xqYdRwHXncdkaI-VA.jpeg" /></figure><blockquote><strong>Espressif System provides a framework ESP-DL that can be used to deploy your high-performance deep learning models on ESP32-S3.</strong></blockquote><p><em>In this article, you will understand how to read sensor data and using </em><a href="https://github.com/espressif/esp-dl"><em>ESP-DL</em></a><em> to </em><a href="https://github.com/espressif/esp-dl/tree/master/tutorial/quantization_tool_example"><em>deploy</em></a><em> a deep-learning model on </em><a href="https://www.espressif.com/en/products/socs/esp32-s3"><em>ESP32-S3</em></a><em>.</em></p><h4>Contents</h4><p>The article is divided in 4-sections <br><a href="#cf2f"><strong>1. Model Deployment</strong></a><strong><br></strong><a href="#04d2"><strong>2. Model Define</strong></a><strong><br></strong><a href="#cde6"><strong>3. Model Run</strong></a><strong><br></strong><a href="#2e2a"><strong>4. Future Opportunities</strong></a></p><h3>Prerequisite for using ESP-DL</h3><p>Before getting a deep dive into ESP-DL, we assume that readers have knowledge about:</p><ul><li>Building and training neural networks. (<a href="https://www.youtube.com/watch?v=WvoLTXIjBYU">Check out the basics of deep learning</a>)</li><li>ESP-IDF <a href="https://github.com/espressif/esp-idf/tree/release/v4.4">release/v4.4</a> environment. (For more details, follow <a href="https://www.youtube.com/watch?v=byVPAfodTyY">setting-up ESP-IDF environment</a> or <a href="https://blog.espressif.com/esp-idf-development-tools-guide-part-i-89af441585b">tool chain for ESP-IDF</a>)</li><li>Working knowledge of <a href="https://www.youtube.com/watch?v=KJgsSFOSQv0&amp;t=12665s">basic C</a> and C++ language</li><li>Converting model into <a href="https://blog.espressif.com/hand-gesture-recognition-on-esp32-s3-with-esp-deep-learning-176d7e13fd37">ESP-DL formate</a></li></ul><p><strong>Note:</strong> Please use ESP-IDF release/v4.4 on the commit “cc71308e2fdce1d6d27fc52d39943f5d0fb83f35” to reproduce the same results</p><h3>1. Model Deployment</h3><p>A convolution neural network is designed using <a href="https://www.cis.fordham.edu/wisdm/dataset.php">accelerometer data</a> to recognize human activity.</p><p><em>*In this blog we will not focus on the </em><a href="https://www.youtube.com/watch?v=lUI6VMj43PE"><em>development</em></a><em> and conversion of neural networks to </em><a href="https://medium.com/the-esp-journal/hand-gesture-recognition-on-esp32-s3-with-esp-deep-learning-176d7e13fd37"><em>ESP-Dl format</em></a><em>.</em></p><h4>1.1 ESP-IDF Project Hierarchy</h4><ol><li>The first step is to create a new project in VS Code based on ESP-IDF standards. For more details about how to create a VS Code project for ESP32 please <a href="https://www.youtube.com/watch?v=Lc6ausiKvQM">click here</a> or <a href="https://docs.espressif.com/projects/esp-idf/en/latest/esp32/get-started/linux-macos-setup.html">ESP-IDF getting started guide</a>.</li><li>Place the .cpp and .hpp files generated by converting the model into ESP-DL format in your current working directory.</li><li>Add all the dependent components to the components folder of your working directory.</li><li>sdk.config files are default configuration files from <a href="https://github.com/espressif/esp-who/tree/master/examples/human_face_recognition/terminal">ESP-WHO example</a>. These files are also provided in linked <a href="https://github.com/alibukharai/Blogs/tree/main/ESP-DL">GITHUB</a></li></ol><p>The Project directory should look like this:</p><pre>├── CMakeLists.txt<br>├── components<br>│   ├── bus<br>│   ├── mpu6050<br>│   └── esp-dl<br>├── dependencies.lock<br>├── main<br>│   ├── app_main.cpp<br>│   └── CMakeLists.txt<br>├── model<br>│   ├── Activity_coefficient.cpp<br>│   ├── Activity_coefficient.hpp<br>│   └── model_define.hpp<br>├── partitions.csv<br>├── sdkconfig<br>├── sdkconfig.defaults<br>├── sdkconfig.defaults.esp32<br>├── sdkconfig.defaults.esp32s2<br>└── sdkconfig.defaults.esp32s3</pre><h3>2. Model Define</h3><p>We will define our model in the ‘model_define.hpp’ file. Following the steps below with detailed explanation. When open in <a href="https://netron.app/">Netron</a> our model looks like Figure 1 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1qibjjaT46hpV9dxeJxQMg.png" /><figcaption>Figure 1. Optimized model visualization</figcaption></figure><h4>2.1 Import Libraries</h4><p>Import all the relevant libraries. Please <a href="https://github.com/espressif/esp-dl/tree/master/include/layer">check here</a> for all the currently supported libraries by <a href="https://github.com/espressif/esp-dl">ESP-DL</a>.</p><pre>#pragma once<br>#include &quot;dl_layer_model.hpp&quot;<br>#include &quot;dl_layer_base.hpp&quot;<br>#include &quot;dl_layer_max_pool2d.hpp&quot;<br>#include &quot;dl_layer_conv2d.hpp&quot;<br>#include &quot;dl_layer_concat.hpp&quot;<br>#include &quot;Activity_coefficient.hpp&quot;<br>#include &quot;dl_layer_reshape.hpp&quot;<br>#include &quot;dl_layer_softmax.hpp&quot;<br>#include &lt;stdint.h&gt;<br><br>using namespace dl;<br>using namespace layer;<br>using namespace Activity_coefficient;</pre><h4>2.2 Declare Layers</h4><p>The next step is to declare each layer.</p><ul><li>Input is not considered a layer so it is not defined here.</li><li>Except for the output layer, all the layers are declared as private layers.</li></ul><pre>class ACTIVITY : public Model&lt;int16_t&gt; <br>{<br>private:<br>    Conv2D&lt;int16_t&gt; l1;<br>    Conv2D&lt;int16_t&gt; l2;<br>    Reshape&lt;int16_t&gt; l3;<br>    Conv2D&lt;int16_t&gt; l4;<br>    Conv2D&lt;int16_t&gt; l5;<br><br>public:<br>    Softmax&lt;int16_t&gt; l6;</pre><h4>2.3 Initialize Layers</h4><p>After declaring the layers, Initialize each layer with its weight, biases, activation functions and shape.</p><pre>ACTIVITY () : <br>            l1(Conv2D&lt;int16_t&gt;(-13, get_statefulpartitionedcall_sequential_1_conv2d_2_biasadd_filter(), get_statefulpartitionedcall_sequential_1_conv2d_2_biasadd_bias(), get_statefulpartitionedcall_sequential_1_conv2d_2_biasadd_activation(), PADDING_VALID, {}, 1,1, &quot;l1&quot;)),<br>            l2(Conv2D&lt;int16_t&gt;(-13, get_statefulpartitionedcall_sequential_1_conv2d_3_biasadd_filter(), get_statefulpartitionedcall_sequential_1_conv2d_3_biasadd_bias(), get_statefulpartitionedcall_sequential_1_conv2d_3_biasadd_activation(), PADDING_VALID, {}, 1,1, &quot;l2&quot;)),                       <br>            l3(Reshape&lt;int16_t&gt;({1,1,2496},&quot;l2_reshape&quot;)), <br>            l4(Conv2D&lt;int16_t&gt;(-11, get_fused_gemm_0_filter(), get_fused_gemm_0_bias(), get_fused_gemm_0_activation(), PADDING_VALID, {}, 1, 1, &quot;l3&quot;)),<br>            l5(Conv2D&lt;int16_t&gt;(-9, get_fused_gemm_1_filter(), get_fused_gemm_1_bias(), NULL, PADDING_VALID,{}, 1,1, &quot;l4&quot;)),<br>            l6(Softmax&lt;int16_t&gt;(-14,&quot;l5&quot;)){}</pre><h4>2.4 Building Layers</h4><p>The next step is to build each layer. For more information about building layers please check the <a href="https://github.com/espressif/esp-dl/tree/master/include/layer">build function</a> of each layer.</p><pre>void build(Tensor&lt;int16_t&gt; &amp;input)<br>    {<br>        this-&gt;l1.build(input);<br>        this-&gt;l2.build(this-&gt;l1.get_output());<br>        this-&gt;l3.build(this-&gt;l2.get_output());<br>        this-&gt;l4.build(this-&gt;l3.get_output());<br>        this-&gt;l5.build(this-&gt;l4.get_output());<br>        this-&gt;l6.build(this-&gt;l5.get_output());<br>        <br>    }</pre><h4>2.5 Call Layers</h4><p>In the end, connect these layers and call them one by one by using a call function. For more information about calling layers please check the c<a href="https://github.com/espressif/esp-dl/tree/master/include/layer">all function</a> of each layer.</p><pre>void call(Tensor&lt;int16_t&gt; &amp;input)<br>    {<br>        this-&gt;l1.call(input);<br>        input.free_element();<br><br>        this-&gt;l2.call(this-&gt;l1.get_output());<br>        this-&gt;l1.get_output().free_element();<br><br>        this-&gt;l3.call(this-&gt;l2.get_output());<br>        this-&gt;l2.get_output().free_element();<br><br>        this-&gt;l4.call(this-&gt;l3.get_output());<br>        this-&gt;l3.get_output().free_element();<br><br>        this-&gt;l5.call(this-&gt;l4.get_output());<br>        this-&gt;l4.get_output().free_element();<br><br>        this-&gt;l6.call(this-&gt;l5.get_output());<br>        this-&gt;l5.get_output().free_element();<br><br>    }<br>};</pre><h3>3. Model Run</h3><p>Once our model is built, declare the input to our model and run the model on <a href="https://www.espressif.com/en/products/socs/esp32-s3">ESP32-S3</a> in ‘app_main.cpp’.</p><h4>3.1 Import libraries</h4><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &quot;esp_system.h&quot;<br>#include &quot;freertos/FreeRTOS.h&quot;<br>#include &quot;freertos/task.h&quot;<br>#include &quot;dl_tool.hpp&quot;<br>#include &quot;model_define.hpp&quot;<br>#include &quot;i2c_bus.h&quot;<br>#include &quot;mpu6050.h&quot;<br>#include &quot;driver/i2c.h&quot;<br>#include &quot;esp_log.h&quot;</pre><h4>3.2 Declare Input</h4><p>The input to our neural network is taken from the <a href="https://www.electronicwings.com/sensors-modules/mpu6050-gyroscope-accelerometer-temperature-sensor-module">MPU6050</a> accelerometer sensor. To read sensor data in real time, we use the <a href="https://components.espressif.com/components/espressif/mpu6050">mpu6050 driver</a> from espressif. Every 4 seconds, the data will be stored in an array and fed to the network for predictions.</p><pre>int input_height = 80;<br>int input_width = 3;<br>int input_channel = 1;<br>int input_exponent = -13;<br>float acc_xyz[240] = {0};<br>int index_acc=0;<br>#define I2C_MASTER_SCL_IO 16      /*!&lt; gpio number for I2C master clock */<br>#define I2C_MASTER_SDA_IO 17      /*!&lt; gpio number for I2C master data  */<br>#define I2C_MASTER_NUM I2C_NUM_0  /*!&lt; I2C port number for master dev */<br>#define I2C_MASTER_FREQ_HZ 400000 /*!&lt; I2C master clock frequency */<br>static i2c_bus_handle_t i2c_bus = NULL;<br>static mpu6050_handle_t mpu6050 = NULL;<br><br>extern &quot;C&quot; void app_main(void)<br>{<br>    i2c_config_t conf = {<br>        .mode = I2C_MODE_MASTER,<br>        .sda_io_num = I2C_MASTER_SDA_IO,<br>        .scl_io_num = I2C_MASTER_SCL_IO,<br>        .sda_pullup_en = GPIO_PULLUP_ENABLE,<br>        .scl_pullup_en = GPIO_PULLUP_ENABLE,<br>        .clk_flags = 0,<br>    };<br>    <br>    conf.master.clk_speed = I2C_MASTER_FREQ_HZ;<br>    i2c_bus = i2c_bus_create(I2C_MASTER_NUM, &amp;conf);<br>    mpu6050 = mpu6050_create(i2c_bus, MPU6050_I2C_ADDRESS);<br>    uint8_t mpu6050_deviceid;<br>    mpu6050_acce_value_t acce;<br>    mpu6050_get_deviceid(mpu6050, &amp;mpu6050_deviceid);<br>    printf(&quot;mpu6050 device ID is: 0x%02x\n&quot;, mpu6050_deviceid);<br>    mpu6050_set_acce_fs(mpu6050, ACCE_FS_4G);<br>while(1){<br>for (int i=0 ;i&lt;80; i++)<br>{<br>    mpu6050_get_acce(mpu6050, &amp;acce);<br>    acc_xyz[index_acc]=acce.acce_x;<br>    index_acc=index_acc+1;<br>    acc_xyz[index_acc]=acce.acce_y;<br>    index_acc=index_acc+1;<br>    acc_xyz[index_acc]=acce.acce_z;<br>    index_acc=index_acc+1;<br>    vTaskDelay(50 / portTICK_RATE_MS);<br>}<br>index_acc=0;<br>int16_t *model_input = (int16_t *)dl::tool::malloc_aligned_prefer(input_height*input_width*input_channel, sizeof(int16_t *));<br>    for(int i=0 ;i&lt;input_height*input_width*input_channel; i++){<br>        float normalized_input = acc_xyz[i] / 1.0; //normalization<br>        model_input[i] = (int16_t)DL_CLIP(normalized_input * (1 &lt;&lt; -input_exponent), -32768, 32767);<br>    }</pre><h4>3.3 Set Input shape</h4><p>Set the data in a tensor to feed the neural network.</p><pre>Tensor&lt;int16_t&gt; input;<br><br>input.set_element((int16_t *) model_input).set_exponent(input_exponent).set_shape({input_height,input_width,input_channel}).set_auto_free(false);</pre><h4>3.4 Call model</h4><p>Call the model by calling the method forward and passing input to it. Use latency to calculate the time taken by ESP32-S3 to run the neural network.</p><pre>ACTIVITY model;<br>                dl::tool::Latency latency;<br>                latency.start();<br>                model.forward(input);<br>                latency.end();<br>                latency.print(&quot;\nActivity model&quot;, &quot;forward&quot;);3. Future Directions</pre><h4>3.5 Monitor output</h4><p>The output is taken out from the public layer i.e l6. The result can be printed in the terminal.</p><pre>float *score = model.l6.get_output().get_element_ptr();<br>                float max_score = score[0];<br>                int max_index = 0;<br>                for (size_t i = 0; i &lt; 6; i++)<br>                {<br>                    printf(&quot;%f, &quot;, score[i]*100);<br>                    if (score[i] &gt; max_score)<br>                    {<br>                        max_score = score[i];<br>                        max_index = i;<br>                    }<br>                }<br>                printf(&quot;\n&quot;);<br>                switch (max_index)<br>                {<br>                    case 0:<br>                    printf(&quot;0: Downstairs&quot;);<br>                    break;<br>                    case 1:<br>                    printf(&quot;1: Jogging&quot;);<br>                    break;<br>                    case 2:<br>                    printf(&quot;2: Sitting&quot;);<br>                    break;<br>                    case 3:<br>                    printf(&quot;3: Standing&quot;);<br>                    break;<br>                    case 4:<br>                    printf(&quot;4: Upstairs&quot;);<br>                    break;<br>                    case 5:<br>                    printf(&quot;5: Walking&quot;);<br>                    break;<br>                    default:<br>                    printf(&quot;No result&quot;);<br>                }<br>                printf(&quot;\n&quot;);<br>}<br>}</pre><h3>4. Conclusion</h3><p>In conclusion, the current project offers exciting possibilities for various applications, including predictive maintenance in industrial settings, boxing punch recognition in sports using an accelerometer, and fall detection in healthcare. These are just a few examples that can be explored further. For those interested in accessing the source code, it is available on the <a href="https://github.com/alibukharai/Blogs/tree/main/Activity_detection">GitHub</a> repository.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3afa97ca553c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-esp-journal/esp32-s3-edge-ai-human-activity-recognition-using-accelerometer-data-and-esp-dl-3afa97ca553c">ESP32-S3 Edge-AI｜Human Activity Recognition Using Accelerometer Data and ESP-DL</a> was originally published in <a href="https://medium.com/the-esp-journal">The ESP Journal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hand Gesture Recognition on ESP32-S3 with ESP-Deep Learning]]></title>
            <link>https://medium.com/the-esp-journal/hand-gesture-recognition-on-esp32-s3-with-esp-deep-learning-176d7e13fd37?source=rss-c690030496b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/176d7e13fd37</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[esp-dl]]></category>
            <category><![CDATA[espressif]]></category>
            <category><![CDATA[esp32]]></category>
            <dc:creator><![CDATA[ALI HASSAN SHAH]]></dc:creator>
            <pubDate>Fri, 02 Dec 2022 09:28:32 GMT</pubDate>
            <atom:updated>2023-10-24T07:30:32.164Z</atom:updated>
            <content:encoded><![CDATA[<p>Artificial intelligence transforms the way computers interact with the real world. Decisions are carried by getting data from Tiny low-powered devices and sensors into the cloud. Connectivity, high cost and data privacy are some of the demerits of this method. <a href="https://www.youtube.com/watch?v=DAPgDuw1uZM">Edge artificial intelligence</a> is another way to process the data right on the physical device without sending data back and forth improving the latency and security and reducing the bandwidth and power.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5dSQrG9n3DW7aYpYfUY2g.jpeg" /></figure><blockquote><a href="https://www.espressif.com/"><strong><em>Espressif System</em></strong></a><strong><em> provides a framework </em></strong><a href="https://github.com/espressif/esp-dl"><strong><em>ESP-DL</em></strong></a><strong><em> that can be used to deploy your high-performance deep learning models on Espressif chip </em></strong><a href="https://www.espressif.com/en/products/socs/esp32-s3"><strong><em>ESP32-S3</em></strong></a><strong><em>.</em></strong></blockquote><p><em>In this article, we will understand how to use </em><a href="https://github.com/espressif/esp-dl"><em>ESP-DL</em></a><em> and </em><a href="https://github.com/espressif/esp-dl/tree/master/tutorial/quantization_tool_example"><em>deploy</em></a><em> a deep-learning model on </em><a href="https://www.espressif.com/en/products/socs/esp32-s3"><em>ESP32-S3</em></a><em>.</em></p><h4>Contents</h4><p>The article is divided into 4-sections</p><p><a href="#2db9">1. Model Developmen</a>t<br><a href="#afc9">2. ESP-DL format</a><br><a href="#4d0a">3. Model Deployment</a><br><a href="#0b0e">4. Future Work</a></p><h4>Prerequisite for using ESP-DL</h4><p>Before getting a deep dive into ESP-DL, we assume that readers have;</p><ol><li>Knowledge about building and training neural networks. (<a href="https://www.youtube.com/watch?v=WvoLTXIjBYU">Check out basics of deep-learning</a>)</li><li>Configure the ESP-IDF <a href="https://github.com/espressif/esp-idf/tree/release/v4.4">release 4.4</a> environment. (Follow <a href="https://www.youtube.com/watch?v=byVPAfodTyY">setting-up ESP-IDF environment</a> or <a href="https://blog.espressif.com/esp-idf-development-tools-guide-part-i-89af441585b">tool chain for ESP-IDF</a> for more details)</li><li>Working knowledge of <a href="https://www.youtube.com/watch?v=KJgsSFOSQv0&amp;t=12665s">basic C</a> and C++ language.’</li></ol><p><strong>Note:</strong> Please use ESP-IDF release/v4.4 on the commit “cc71308e2fdce1d6d27fc52d39943f5d0fb83f35” to reproduce the same results</p><h3>1. Model Development</h3><p>For the sake of simplicity, a classification problem is selected and developed a simple deep-learning model to classify 6 different hand gestures. Many open-source pre trained <a href="https://github.com/filipefborba/HandRecognition">models</a> are available however for this demonstration we prefer to build a model from scratch to get a better understanding of each layer of the model.<br><em> * we are using Google </em><a href="https://colab.research.google.com/"><em>Co-lab</em></a><em> for model development</em></p><h4>1.1 Dataset</h4><p>For this classification problem, We are using an open-source dataset from the Kaggle <a href="https://www.kaggle.com/datasets/gti-upm/leapgestrecog">Hand Gesture recognition Dataset</a>. The original dataset includes 10 classes however we are using only 6 classes that are easy to recognize and more useful in daily life. The hand gesture classes are represented in the table below. One more difference is related to the image size, the original dataset has an image size of (240 , 640) however for the sake of simplicity resized the dataset to (96 , 96). The dataset used in this article can be found <a href="https://github.com/alibukharai/Blogs/tree/main/ESP-DL">here</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fsheetsu.com%2Ftables%2F21fd6cb912&amp;dntp=1&amp;display_name=Sheetsu&amp;url=https%3A%2F%2Fsheetsu.com%2Ftables%2F21fd6cb912&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=sheetsu" width="700" height="295" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f14aae5ce92434202173752fcc471ae/href">https://medium.com/media/9f14aae5ce92434202173752fcc471ae/href</a></iframe><h4>1.2 Test/Train Split</h4><p>We need to divide our dataset into test, train and calibration datasets. These datasets are nothing but the subsets of our original <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#11-dataset">dataset</a>. The training dataset is used to train the model while the testing dataset is to test the model performance similarly calibration dataset is used during the <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#22-optimization-and-quantization">model quantization</a> stage for calibration purposes. The procedure to generate all these datasets is the same. We used train_test_split for this purpose.</p><pre>from sklearn.model_selection import train_test_split<br><br>ts = 0.3 # Percentage of images that we want to use for testing. <br>X_train, X_test1, y_train, y_test1 = train_test_split(X, y, test_size=ts, random_state=42)<br>X_test, X_cal, y_test, y_cal = train_test_split(X_test1, y_test1, test_size=ts, random_state=42)</pre><p><em>*For more details about how train_test_split works please check </em><a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html"><em>here</em></a><em>.</em></p><p>For the reproduction of this tutorial you can find the data from (<a href="https://github.com/alibukharai/Blogs/tree/main/ESP-DL">GitHub</a>) and open data in your working environment.</p><pre>import pickle<br><br>with open(&#39;X_test.pkl&#39;, &#39;rb&#39;) as file:<br>    X_test = pickle.load(file)<br><br>with open(&#39;y_test.pkl&#39;, &#39;rb&#39;) as file:<br>    y_test = pickle.load(file)<br><br>with open(&#39;X_train.pkl&#39;, &#39;rb&#39;) as file:<br>    X_train = pickle.load(file)<br><br>with open(&#39;y_train.pkl&#39;, &#39;rb&#39;) as file:<br>    y_train = pickle.load(file)</pre><h4>1.3 Building a Model</h4><p>We have created a basic Convolution Neural Network (CNN) for this classification problem. It consists of 3 convolution layers followed by max-pooling and a fully connected layer with an output layer of 6 neurons. More details about the creation of CNN can be found <a href="https://github.com/filipefborba/HandRecognition/blob/master/project3/project3.ipynb">here</a>. Below is the code used to build a CNN.</p><pre>import tensorflow as tf<br>from tensorflow import keras<br>from keras.models import Sequential<br>from keras.layers.convolutional import Conv2D, MaxPooling2D<br>from keras.layers import Dense, Flatten, Dropout<br><br>print(tf.__version__)<br><br>model = Sequential()<br>model.add(Conv2D(32, (5, 5), activation=&#39;relu&#39;, input_shape=(96, 96, 1))) <br>model.add(MaxPooling2D((2, 2)))<br>model.add(Dropout(0.2))<br>model.add(Conv2D(64, (3, 3), activation=&#39;relu&#39;)) <br>model.add(MaxPooling2D((2, 2)))<br>model.add(Dropout(0.2))<br>model.add(Conv2D(64, (3, 3), activation=&#39;relu&#39;))<br>model.add(MaxPooling2D((2, 2)))<br>model.add(Flatten())<br>model.add(Dense(128, activation=&#39;relu&#39;))<br>model.add(Dense(6, activation=&#39;softmax&#39;))<br><br>model.compile(optimizer=&#39;adam&#39;,loss=&#39;sparse_categorical_crossentropy&#39;,metrics=[&#39;accuracy&#39;])<br><br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/0*2zwRLB-5lm_Oynx3" /><figcaption>Figure 1. CNN model</figcaption></figure><h4>1.4 Training a Model</h4><p>The model is running for 5 epochs, with a final accuracy of around 99%.</p><pre>history=model.fit(X_train, y_train, epochs=5, batch_size=64, verbose=1, validation_data=(X_test, y_test))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LAl5WCnF0x_m-d5f" /><figcaption>Figure 2. Training output result</figcaption></figure><h4>1.5 Saving a Model</h4><p>The trained model is saved in Hierarchical Data format (.h5). For more details on how the Keras model be saved <a href="https://www.tensorflow.org/guide/keras/save_and_serialize#how_to_save_and_load_a_model">click here</a>.</p><pre>model.save(&#39;handrecognition_model.h5&#39;)</pre><h4>1.6 Model Conversion</h4><p>ESP-DL uses model in Open Neural Network Exchange (ONXX) format. For more details on how ONNX is working <a href="https://onnx.ai/">click here</a>. To be compatible with ESP-DL convert the trained .h5 format of the model into ONXX format by using the below lines of code.</p><pre>model = tf.keras.models.load_model(&quot;/content/handrecognition_model.h5&quot;)<br>tf.saved_model.save(model, &quot;tmp_model&quot;)<br>!python -m tf2onnx.convert --saved-model tmp_model --output &quot;handrecognition_model.onnx&quot;<br>!zip -r /content/tmp_model.zip /content/tmp_model</pre><p>In the end, H5 format model, ONNX format model and model checkpoints are downloaded for future use.</p><pre>from google.colab import files<br>files.download(&quot;/content/handrecognition_model.h5&quot;)<br>files.download(&quot;/content/handrecognition_model.onnx&quot;)<br>files.download(&quot;/content/tmp_model.zip&quot;)</pre><h3>2. ESP-DL format</h3><p>Once the ONNX format of the model is ready, follow the steps below to convert the model into ESP-DL format.<br><em>* We are using </em><a href="https://www.jetbrains.com/pycharm/"><em>Pychram</em></a><em> IDE for ESP-DL format conversion.</em></p><h4>2.1 Requirements</h4><p>Setting up an environment and installing the correct version of the modules is always a key to start with. If the modules are not installed in the correct version it gives an error. For more information about requirements for ESP-DL format conversion please <a href="https://github.com/espressif/esp-dl/tree/master/tutorial/quantization_tool_example#step-121-set-up-the-environment">click here</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fsheetsu.com%2Ftables%2F2eae698bc6&amp;dntp=1&amp;display_name=Sheetsu&amp;url=https%3A%2F%2Fsheetsu.com%2Ftables%2F2eae698bc6&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=sheetsu" width="700" height="362" frameborder="0" scrolling="no"><a href="https://medium.com/media/49ef9f600b4da6d108fbf8242b4210ad/href">https://medium.com/media/49ef9f600b4da6d108fbf8242b4210ad/href</a></iframe><p>Next, need to download ESP-DL. clone the <a href="https://github.com/espressif/esp-dl">ESP-DL</a> from the GitHub repository.</p><pre>git clone --recursive https://github.com/espressif/esp-dl.git</pre><h4>2.2 Optimization and Quantization</h4><p>To run the optimizer provided by ESP-DL, we need to find and</p><ul><li>calibrator.pyd</li><li>calibrator_acc.pyd</li><li>evaluator.pyd</li><li>optimizer.py</li></ul><p>place these files into the working directory of pychram — IDE. Furthermore, also place the calibration dataset generated in the <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#12-testtrain-split">previous section 1.2</a> and ONNX format model saved in <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#15-saving-model">previous section 1.5</a> . Your working directory should look like this;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/0*-RpetW3o3a6kL6q0" /><figcaption>Figure 3. Working directory</figcaption></figure><p>Follow the below steps for generating optimized and quantize model.</p><p>2.2.1. import the libraries</p><pre>from optimizer import *<br>from calibrator import *<br>from evaluator import *</pre><p>2.2.2. Load the ONNX model</p><pre>onnx_model = onnx.load(&quot;handrecognition_model.onnx&quot;)<br></pre><p>2.2.3. Optimize the ONNX model</p><pre>optimized_model_path = optimize_fp_model(&quot;handrecognition_model.onnx&quot;)</pre><p>2.2.4. Load Calibration dataset</p><pre>with open(&#39;X_cal.pkl&#39;, &#39;rb&#39;) as f:<br>    (test_images) = pickle.load(f)<br>with open(&#39;y_cal.pkl&#39;, &#39;rb&#39;) as f:<br>    (test_labels) = pickle.load(f)<br><br><br>calib_dataset = test_images[0:1800:20]<br>pickle_file_path = &#39;handrecognition_calib.pickle&#39;</pre><p>2.2.5. Calibration</p><pre>model_proto = onnx.load(optimized_model_path)<br>print(&#39;Generating the quantization table:&#39;)<br><br>calib = Calibrator(&#39;int16&#39;, &#39;per-tensor&#39;, &#39;minmax&#39;)<br># calib = Calibrator(&#39;int8&#39;, &#39;per-channel&#39;, &#39;minmax&#39;)<br><br>calib.set_providers([&#39;CPUExecutionProvider&#39;])<br><br># Obtain the quantization parameter<br>calib.generate_quantization_table(model_proto,calib_dataset, pickle_file_path)<br># Generate the coefficient files for esp32s3<br>calib.export_coefficient_to_cpp(model_proto, pickle_file_path, &#39;esp32s3&#39;, &#39;.&#39;, &#39;handrecognition_coefficient&#39;, True)</pre><p>If everything is alright, at this stage two files with an extension .cpp and .hpp is generated in the path, and the output should look like this.</p><p><em>*later this output is used, so it is better to take a screenshot and save this</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qus5uAIRtns0pOPV" /><figcaption>Figure 4. Output for the optimized model</figcaption></figure><h4>2.3 Evaluate</h4><p>This step is not necessary however if you want to evaluate the performance of the optimized model the following code can be used.</p><pre>print(&#39;Evaluating the performance on esp32s3:&#39;)<br>eva = Evaluator(&#39;int16&#39;, &#39;per-tensor&#39;, &#39;esp32s3&#39;)<br>eva.set_providers([&#39;CPUExecutionProvider&#39;])<br>eva.generate_quantized_model(model_proto, pickle_file_path)<br><br>output_names = [n.name for n in model_proto.graph.output]<br>providers = [&#39;CPUExecutionProvider&#39;]<br>m = rt.InferenceSession(optimized_model_path, providers=providers)<br><br>batch_size = 64<br>batch_num = int(len(test_images) / batch_size)<br>res = 0<br>fp_res = 0<br>input_name = m.get_inputs()[0].name<br>for i in range(batch_num):<br>    # int8_model<br>    [outputs, _] = eva.evalaute_quantized_model(test_images[i * batch_size:(i + 1) * batch_size], False)<br>    res = res + sum(np.argmax(outputs[0], axis=1) == test_labels[i * batch_size:(i + 1) * batch_size])<br><br>    # floating-point model<br>    fp_outputs = m.run(output_names, {input_name: test_images[i * batch_size:(i + 1) * batch_size].astype(np.float32)})<br>    fp_res = fp_res + sum(np.argmax(fp_outputs[0], axis=1) == test_labels[i * batch_size:(i + 1) * batch_size])<br>print(&#39;accuracy of int8 model is: %f&#39; % (res / len(test_images)))<br>print(&#39;accuracy of fp32 model is: %f&#39; % (fp_res / len(test_images)))</pre><p><em>*please follow </em><a href="https://github.com/espressif/esp-dl/blob/master/tools/quantization_tool/quantization_tool_api.md"><em>here</em></a><em> for more details about ESP-DL API.</em></p><h3>3. Model Deployment</h3><p>Model deployment is the final and crucial step. In this step, we will implement our model in C-language to run on the top of <a href="https://www.espressif.com/en/products/socs/esp32-s3">ESP32-S3</a> micro-controller and gets the results.</p><p><em>*we are using </em><a href="https://code.visualstudio.com/"><em>Visual Studio Code</em></a><em> for the deployment of our model on ESP32-S3.</em></p><h4>3.1 ESP-IDF Project Hierarchy</h4><ul><li>The first step is to create a new project in VS-Code based on ESP-IDF standards. For more details about how to create a VS-Code project for ESP32 please <a href="https://www.youtube.com/watch?v=Lc6ausiKvQM">click here</a> or <a href="https://docs.espressif.com/projects/esp-idf/en/latest/esp32/get-started/linux-macos-setup.html">here</a></li><li>Copy the files.cpp and .hpp generated in the <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#22-optimization-and-quantization">previous section 2.2</a> to your current working directory.</li><li>Add all the dependent components to the components folder of your working directory.</li><li>sdkconfig files are default files from <a href="https://github.com/espressif/esp-who/tree/master/examples/human_face_recognition/terminal">ESP-WHO example</a>. These files are also provided in linked <a href="https://github.com/alibukharai/Blogs/tree/main/ESP-DL">GitHub</a> repository.</li></ul><p>The Project directory should look like this;</p><pre>├── CMakeLists.txt<br>├── components<br>│   ├── esp-dl<br>│   └── esp-who<br>├── dependencies.lock<br>├── main<br>│   ├── app_main.cpp<br>│   └── CMakeLists.txt<br>├── model<br>│   ├── handrecognition_coefficient.cpp<br>│   ├── handrecognition_coefficient.hpp<br>│   └── model_define.hpp<br>├── partitions.csv<br>├── sdkconfig<br>├── sdkconfig.defaults<br>├── sdkconfig.defaults.esp32<br>├── sdkconfig.defaults.esp32s2<br>└── sdkconfig.defaults.esp32s3</pre><p><em>* esp-who is not necessary for this tutorial</em></p><h4>3.2 Model define</h4><p>We will define our model in the ‘model_define.hpp’ file. Follow the below steps for a details explanation of defining the model.</p><p>3.2.1 Import libraries</p><p>Firstly import all the relevant libraries. Based on our <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#13-building-a-model">model design</a> or another way to know which particular libraries need to use an open source tool <a href="https://netron.app/">Netron</a> and open your optimized ONNX model generated at the end of <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#22-optimization-and-quantization">previous section 2.2</a> . Please <a href="https://github.com/espressif/esp-dl/tree/master/include/layer">check here</a> for all the currently supported libraries by <a href="https://github.com/espressif/esp-dl">ESP-DL</a>.</p><pre>#pragma once<br>#include &lt;stdint.h&gt;<br>#include &quot;dl_layer_model.hpp&quot;<br>#include &quot;dl_layer_base.hpp&quot;<br>#include &quot;dl_layer_max_pool2d.hpp&quot;<br>#include &quot;dl_layer_conv2d.hpp&quot;<br>#include &quot;dl_layer_reshape.hpp&quot;<br>#include &quot;dl_layer_softmax.hpp&quot;<br>#include &quot;handrecognition_coefficient.hpp&quot;<br><br>using namespace dl;<br>using namespace layer;<br>using namespace handrecognition_coefficient;</pre><p>3.2.2 Declare layers</p><p>The next is to declare each layer.</p><ul><li>Input is not considered a layer so not defined here.</li><li>Except for the output layer, all the layers are declared as private layers.</li><li>Remember to place each layer in order as defined in <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#13-building-a-model">previous section 1.3</a> while building the model.</li></ul><pre>class HANDRECOGNITION : public Model&lt;int16_t&gt; <br>{<br>private:<br>    Reshape&lt;int16_t&gt; l1;<br>    Conv2D&lt;int16_t&gt; l2;<br>    MaxPool2D&lt;int16_t&gt; l3;<br>    Conv2D&lt;int16_t&gt; l4;<br>    MaxPool2D&lt;int16_t&gt; l5;<br>    Conv2D&lt;int16_t&gt; l6;<br>    MaxPool2D&lt;int16_t&gt; l7;<br>    Reshape&lt;int16_t&gt; l8;<br>    Conv2D&lt;int16_t&gt; l9;<br>    Conv2D&lt;int16_t&gt; l10;<br>public:<br>    Softmax&lt;int16_t&gt; l11; // output layer</pre><p>3.2.3 Initialize layers</p><p>After declaring the layers, we need to initialize each layer with its weight, biases activation functions and shape. let us check each layer in detail.</p><p>Before getting into details, let us look into how our model looks like when opening in Netron that is somehow imported to get some parameters for initializing.</p><figure><a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/_static/6.png"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*19uihEcEHqAqGhXo4H9fYQ.png" /></a><figcaption>Figure 5. Optimized model visualization</figcaption></figure><ul><li>The first layer is reshaped layer (note that the input is not considered as a layer) and gives an output shape of (96 , 96, 1) for this layer. These parameters must be the same as you used during model training <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#13-building-a-model">see section 1.3.</a> Another way to know the parameter and layer is to use an open source tool <a href="https://netron.app/">Netron</a> and open your optimized ONNX model generated at the end of <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#22-optimization-and-quantization">previous section 2.2.</a></li><li>For the convolution 2D layer we can get the name of this layer for the filter, bias and activation function from the .hpp file generated at the end of the <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#22-optimization-and-quantization">previous section 2.2</a>, However for the exponents, we need to check the output generated in <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#225-calibration">section 2.2.5.</a></li><li>For the max-pooling layer, we can use the same parameters as we use during building our model <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#13-building-a-model">see section 1.3.</a> or another way to know the parameter and layer is to use an open-source tool <a href="https://netron.app/">Netron</a> and open your optimized ONNX model generated at the end of the <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#22-optimization-and-quantization">previous section 2.2.</a></li><li>For the dense layer or fully connected layer, conv2D block is used and we can get the name of this layer for the filter, bias and activation function from the .hpp file generated at the end of <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#22-optimization-and-quantization">previous section 2.2</a>, However for the exponents, we need to check the output generated in <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#225-calibration">section 2.2.5.</a></li><li>The output layer is a SoftMax layer weight and the name can be taken from the output generated in <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#225-calibration">section 2.2.5.</a></li></ul><pre> HANDRECOGNITION () : l1(Reshape&lt;int16_t&gt;({96,96,1})),<br>                         l2(Conv2D&lt;int16_t&gt;(-8, get_statefulpartitionedcall_sequential_1_conv2d_3_biasadd_filter(), get_statefulpartitionedcall_sequential_1_conv2d_3_biasadd_bias(), get_statefulpartitionedcall_sequential_1_conv2d_3_biasadd_activation(), PADDING_VALID, {}, 1,1, &quot;l1&quot;)),<br>                         l3(MaxPool2D&lt;int16_t&gt;({2,2},PADDING_VALID, {}, 2, 2, &quot;l2&quot;)),                      <br>                         l4(Conv2D&lt;int16_t&gt;(-9, get_statefulpartitionedcall_sequential_1_conv2d_4_biasadd_filter(), get_statefulpartitionedcall_sequential_1_conv2d_4_biasadd_bias(), get_statefulpartitionedcall_sequential_1_conv2d_4_biasadd_activation(), PADDING_VALID,{}, 1,1, &quot;l3&quot;)),                       <br>                         l5(MaxPool2D&lt;int16_t&gt;({2,2},PADDING_VALID,{}, 2, 2, &quot;l4&quot;)),                       <br>                         l6(Conv2D&lt;int16_t&gt;(-9, get_statefulpartitionedcall_sequential_1_conv2d_5_biasadd_filter(), get_statefulpartitionedcall_sequential_1_conv2d_5_biasadd_bias(), get_statefulpartitionedcall_sequential_1_conv2d_5_biasadd_activation(), PADDING_VALID,{}, 1,1, &quot;l5&quot;)),                    <br>                         l7(MaxPool2D&lt;int16_t&gt;({2,2},PADDING_VALID,{}, 2, 2, &quot;l6&quot;)),<br>                         l8(Reshape&lt;int16_t&gt;({1,1,6400},&quot;l7_reshape&quot;)),<br>                         l9(Conv2D&lt;int16_t&gt;(-9, get_fused_gemm_0_filter(), get_fused_gemm_0_bias(), get_fused_gemm_0_activation(), PADDING_VALID, {}, 1, 1, &quot;l8&quot;)),<br>                         l10(Conv2D&lt;int16_t&gt;(-9, get_fused_gemm_1_filter(), get_fused_gemm_1_bias(), NULL, PADDING_VALID,{}, 1,1, &quot;l9&quot;)),<br>                         l11(Softmax&lt;int16_t&gt;(-14,&quot;l10&quot;)){}</pre><p>3.2.4 Build layers</p><p>The next step is to build each layer. For more information about building layers please <a href="https://github.com/espressif/esp-dl/tree/master/include/layer">click here</a> on each layer building function.</p><pre>void build(Tensor&lt;int16_t&gt; &amp;input)<br>    {<br>        this-&gt;l1.build(input);<br>        this-&gt;l2.build(this-&gt;l1.get_output());<br>        this-&gt;l3.build(this-&gt;l2.get_output());<br>        this-&gt;l4.build(this-&gt;l3.get_output());<br>        this-&gt;l5.build(this-&gt;l4.get_output());<br>        this-&gt;l6.build(this-&gt;l5.get_output());<br>        this-&gt;l7.build(this-&gt;l6.get_output());<br>        this-&gt;l8.build(this-&gt;l7.get_output());<br>        this-&gt;l9.build(this-&gt;l8.get_output());<br>        this-&gt;l10.build(this-&gt;l9.get_output());<br>        this-&gt;l11.build(this-&gt;l10.get_output());        <br>    }</pre><p>3.2.5 Call layers</p><p>In the end, we need to connect these layers and call them one by one by using a call function. For more information about calling layers please <a href="https://github.com/espressif/esp-dl/tree/master/include/layer">click here</a> on each layer calling function.</p><pre>void call(Tensor&lt;int16_t&gt; &amp;input)<br>    {<br>        this-&gt;l1.call(input);<br>        input.free_element();<br><br>        this-&gt;l2.call(this-&gt;l1.get_output());<br>        this-&gt;l1.get_output().free_element();<br><br>        this-&gt;l3.call(this-&gt;l2.get_output());<br>        this-&gt;l2.get_output().free_element();<br><br>        this-&gt;l4.call(this-&gt;l3.get_output());<br>        this-&gt;l3.get_output().free_element();<br><br>        this-&gt;l5.call(this-&gt;l4.get_output());<br>        this-&gt;l4.get_output().free_element();<br><br>        this-&gt;l6.call(this-&gt;l5.get_output());<br>        this-&gt;l5.get_output().free_element();<br><br>        this-&gt;l7.call(this-&gt;l6.get_output());<br>        this-&gt;l6.get_output().free_element();<br><br>        this-&gt;l8.call(this-&gt;l7.get_output());<br>        this-&gt;l7.get_output().free_element();<br><br>        this-&gt;l9.call(this-&gt;l8.get_output());<br>        this-&gt;l8.get_output().free_element();<br><br>        this-&gt;l10.call(this-&gt;l9.get_output());<br>        this-&gt;l9.get_output().free_element();<br><br>        this-&gt;l11.call(this-&gt;l10.get_output());<br>        this-&gt;l10.get_output().free_element();<br>    }<br>};</pre><h4>3.3 Model Run</h4><p>After building our Model need to run and give input to our model. ‘app_main.cpp’ file is used to generate the input and run our model on <a href="https://www.espressif.com/en/products/socs/esp32-s3">ESP32-S3</a>.</p><p>3.3.1 import libraries</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &quot;esp_system.h&quot;<br>#include &quot;freertos/FreeRTOS.h&quot;<br>#include &quot;freertos/task.h&quot;<br>#include &quot;dl_tool.hpp&quot;<br>#include &quot;model_define.hpp&quot;</pre><p>3.3.2 Declare Input</p><p>we trained our model by giving an input of size (96, 96, 1) <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#13-building-a-model">see section 1.3.</a> However, the input_exponent can get its exponent value from the output generated in <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#225-calibration">section 2.2.5.</a> Another thing is to write the pixels of the input/test picture here.</p><pre>int input_height = 96;<br>int input_width = 96;<br>int input_channel = 1;<br>int input_exponent = -7;<br><br>__attribute__((aligned(16))) int16_t example_element[] = {<br><br>    //add your input/test image pixels <br>};</pre><p>3.3.3 Set Input Shape</p><p>Each pixel of the input is adjusted based on the input_exponent declared <a href="https://github.com/alibukharai/Blogs/blob/main/ESP-DL/building_with_espdl.md#332-declare-input">above</a>.</p><pre>extern &quot;C&quot; void app_main(void)<br>{<br>Tensor&lt;int16_t&gt; input;<br>                input.set_element((int16_t *)example_element).set_exponent(input_exponent).set_shape({input_height,input_width,input_channel}).set_auto_free(false);</pre><p>3.3.4. Call a Model</p><p>Call the model by calling the method forward and passing input to it. Latency is used to calculate the time taken by ESP32-S3 to run the neural network.</p><pre>HANDRECOGNITION model;<br>                dl::tool::Latency latency;<br>                latency.start();<br>                model.forward(input);<br>                latency.end();<br>                latency.print(&quot;\nSIGN&quot;, &quot;forward&quot;);</pre><p>3.3.5. Monitor Output</p><p>The output is taken out from the public layer i.e. l11. and you can print the result in the terminal.</p><pre>float *score = model.l11.get_output().get_element_ptr();<br>                float max_score = score[0];<br>                int max_index = 0;<br>                for (size_t i = 0; i &lt; 6; i++)<br>                {<br>                    printf(&quot;%f, &quot;, score[i]*100);<br>                    if (score[i] &gt; max_score)<br>                    {<br>                        max_score = score[i];<br>                        max_index = i;<br>                    }<br>                }<br>                printf(&quot;\n&quot;);<br><br>                switch (max_index)<br>                {<br>                    case 0:<br>                    printf(&quot;Palm: 0&quot;);<br>                    break;<br>                    case 1:<br>                    printf(&quot;I: 1&quot;);<br>                    break;<br>                    case 2:<br>                    printf(&quot;Thumb: 2&quot;);<br>                    break;<br>                    case 3:<br>                    printf(&quot;Index: 3&quot;);<br>                    break;<br>                    case 4:<br>                    printf(&quot;ok: 4&quot;);<br>                    break;<br>                    case 5:<br>                    printf(&quot;C: 5&quot;);<br>                    break;<br>                    default:<br>                    printf(&quot;No result&quot;);<br>                }<br>                printf(&quot;\n&quot;);<br><br>}</pre><p>Figure 6 shows the output results. The model latency is around 0.7 Seconds on ESP32-S3, whereas each neuron output and finally the predicted result is shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*rd_Z3xPR6BUegoAhoLJCVg.png" /><figcaption>Figure 6: Output</figcaption></figure><h3>4. Future Work</h3><p>In future, we will design a model for <a href="https://www.espressif.com/en/products/devkits/esp-eye/resourceswww.espressif.com2">ESP32-S3 EYE</a> devkit which could capture images in real time and performs hand gesture recognition. Check out the <a href="https://github.com/alibukharai/Blogs/tree/main/ESP-DL">GitHub</a> repository for source code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=176d7e13fd37" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-esp-journal/hand-gesture-recognition-on-esp32-s3-with-esp-deep-learning-176d7e13fd37">Hand Gesture Recognition on ESP32-S3 with ESP-Deep Learning</a> was originally published in <a href="https://medium.com/the-esp-journal">The ESP Journal</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>