<?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 Thomas Chaigneau on Medium]]></title>
        <description><![CDATA[Stories by Thomas Chaigneau on Medium]]></description>
        <link>https://medium.com/@thomaschaigneau.ai?source=rss-9e928cd81db0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kMAuMEHOomfRP7vEX3jT-g.jpeg</url>
            <title>Stories by Thomas Chaigneau on Medium</title>
            <link>https://medium.com/@thomaschaigneau.ai?source=rss-9e928cd81db0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:17:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thomaschaigneau.ai/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[Building and Launching Your Discord Bot: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@thomaschaigneau.ai/building-and-launching-your-discord-bot-a-step-by-step-guide-f803f7943d33?source=rss-9e928cd81db0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f803f7943d33</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[summarization]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[discord-bot]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Thomas Chaigneau]]></dc:creator>
            <pubDate>Thu, 12 Jan 2023 08:16:50 GMT</pubDate>
            <atom:updated>2023-01-12T08:16:50.506Z</atom:updated>
            <content:encoded><![CDATA[<p>Unlock the full potential of your Discord community by learning how to create and deploy a custom bot using Python and the Discord.py library</p><blockquote>Unlock the power of summarization with Discord TL;DR. Follow <a href="https://emerald-evening-10f.notion.site/Add-Wordcab-to-Discord-93ffd44f631a4883bee6f11450ea0fc1">this guide</a> to try it for yourself and see how it can condense vast amounts of information into succinct, easy-to-digest summaries. ⭐</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*680sB7QVJcj5v17w.png" /></figure><p>Welcome to the exciting world of Discord bot development! In this blog post, we will be covering how I built a powerful chat summarization bot that can handle multiple servers and users, all while scaling to meet the needs of your growing user base.</p><blockquote>All the code from this guide is open-sourced on <a href="https://github.com/Wordcab/discord-tldr">GitHub</a>. 🚀</blockquote><p>We will start by setting up the skeleton of our bot and exploring the various ways to handle user data with SQL.</p><p>From there, we will delve into the asynchronous nature of Discord bot development and learn how to take full advantage of asyncio to ensure our bot remains responsive at all times.</p><p>Next, we will dive into the bot commands, allowing us to customize the functionality of our bot and give users greater control over their chat experience.</p><p>Finally, we will containerize our code with Docker and deploy everything to AWS using GitHub Actions, ensuring that our bot is always up and running and able to handle the demands of a large user base.</p><p>So grab your favorite Python IDE, and let’s start building a powerful Discord bot that can help users quickly summarize chats and stay up to date with the latest conversations!</p><h3>Bot skeleton</h3><p>Before we can start building out the functionality of our Discord bot, we need first to set up the skeleton of our project.</p><p>This includes creating a new Discord bot, obtaining the necessary API credentials, setting up our development environment, and installing any required dependencies.</p><h4>Create the bot</h4><p>We will use the Python package discord.py, a fantastic tool that wraps all the Discord API functions together. Please follow this <a href="https://discordpy.readthedocs.io/en/stable/discord.html">quick and simple tutorial</a> to create your bot.</p><p>Don’t forget to create your development Discord server, where we can invite the newly created bot and test all the features. If you are not sure how to make a new Discord server, please follow <a href="https://support.discord.com/hc/en-us/articles/204849977-How-do-I-create-a-server-">this link</a>.</p><h4>Discord bot basics</h4><p>To start building our Discord bot, we need first to understand its basic structure. At its core, a Discord bot is a class inherited from discord.Client that defines various event handlers to process different events occurring within Discord.</p><p>For example, we can define an on_ready event handler to run code when the bot first connects to Discord or an on_guild_join event handler to run code when the bot is added to a new server.</p><p>Additionally, we will want to define a setup_hook method to handle any necessary setup tasks and an on_guild_remove event handler to clean up any resources when the bot is removed from a server.</p><p>Here is the minimum skeleton of a Discord bot to run:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71df286aa558efd6c5d4d6db2a89328e/href">https://medium.com/media/71df286aa558efd6c5d4d6db2a89328e/href</a></iframe><p>We will use this bot class in a main() method to run the bot:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7accd9b06b53fa68302059fff1d09b8/href">https://medium.com/media/e7accd9b06b53fa68302059fff1d09b8/href</a></iframe><p>We are using an if __name__ == “__main__” block to wrap the entry point of the launch of the bot.</p><p>Using RotatingFileHandler to store logs is a helpful way to keep track of your application’s activity and debug any issues that may arise. One of the key benefits of RotatingFileHandler is that it allows you to specify a maximum number of log files to keep, ensuring that your logs do not consume too much disk space. Here, we are using five files which can be 32Mib max.</p><p>Also, we are using ClientSession, a class provided by the aiohttp library that allows you to make HTTP requests asynchronously in Python. When working with asyncio, it is often beneficial to use ClientSession instead of the built-in requests library, as ClientSession is designed to work seamlessly with asyncio and can significantly improve the performance of your code.</p><p>One of the key benefits of using ClientSession is that it allows you to make multiple HTTP requests concurrently rather than waiting for each request to complete before making the next one. This can be especially useful when working with Discord bots, as it allows you to create multiple requests to the Discord API in parallel, improving the overall performance of your bot.</p><p>In addition to making HTTP requests, ClientSession provides other valuable features, such as automatic connection pooling and the ability to set custom headers and timeouts, even if we won’t use them here.</p><h4>Run the bot</h4><p>Now that we have set up the basic skeleton of our Discord bot, it’s time to bring everything together and run our bot for the first time. To do this, we must provide our bot’s API token and run the script.</p><p>Use a .envfile to store all the environment variables for the project, like your Discord token.</p><pre># Update the .env file with your Discord Token<br>DISCORD_TOKEN=&quot;PUT YOUR DISCORD TOKEN HERE&quot;</pre><p>Launch your bot:</p><pre>$ python __main__.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/0*uOSzfTD8PNbR4LKe" /></figure><p>Assuming everything is set up correctly, this should launch our Discord bot and connect it to Discord. From there, we can start building out the functionality of our bot and adding new features as needed.</p><h3>Store data</h3><p>Before developing any features for the bot, we have to decide how we will store users’ data. Storing user data can be a crucial aspect of building a Discord bot, as it allows you to provide a personalized and customized experience for each user.</p><p>However, it’s essential to carefully consider your database choice when storing user data. Different databases have different strengths and weaknesses, so choosing a database that suits your needs is essential.</p><h4>SQLite</h4><p>For our <strong>Discord TL;DR</strong> project, I used an SQLite database to store our users’ data. We chose SQLite for this project for several reasons:</p><ul><li>SQLite is a lightweight database that is easy to set up and use. It doesn’t require any additional server processes or configuration, making it a simple and convenient choice for small projects or the start of a project.</li><li>SQLite is fast and efficient, making it well-suited for use in a Discord bot where performance is critical. It can handle many read and write operations quickly, ensuring that our bot remains responsive.</li><li>If our project grows in the future and we need a more robust database, we can easily switch to a different database such as MySQL or PostgreSQL.</li></ul><p>Another reason I was confident about using SQLite for this project is its compatibility with the aiosqlite package. If you allow users to make asynchronous commands on multiple servers, but the database can’t handle async, it becomes the bottleneck of the whole project.</p><p>However, aiosqlite allows us to use SQLite in an async context, making it easy to integrate SQLite into our asyncio-based Discord bot. This is precisely the scalability that we aim to provide with this project.</p><p>Here is a basic setup of our Python class that will handle the connection between the Discord Python code and the SQLite database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfee2f6e332cf63d3f21319e5d6e0990/href">https://medium.com/media/cfee2f6e332cf63d3f21319e5d6e0990/href</a></iframe><p>This code defines a BotDB class that represents a database for a Discord bot. The BotDB class has a single method, init_db_and_tables, which is used to initialize the database and create any necessary tables.</p><p>The __init__ method of the BotDB class is responsible for setting up the database connection. It does this by loading environment variables from a .env file using the load_dotenv function and using the DATABASE_VOLUME environment variable to determine the location of the database file.</p><blockquote>By default, I use /data for this variable. Don’t forget to update your .env file with the local folder you want to use to store the database. Note this folder will be binded as a docker volume later.</blockquote><p>It then creates an asyncio-based SQLAlchemy engine using the create_async_engine function and stores it as an instance variable.</p><p>The init_db_and_tables method is an async method that creates an async context using the async with … syntax. Within this context, it uses the begin method of the engine to create a transaction and then calls the create_all method of the SQLModel.metadata object to create any necessary tables. This method is typically called when the bot is starting up to ensure that the database and tables are set up correctly.</p><h4>SQLModel</h4><p>I chose to use SQLModel, which is a wrapper around SQLAlchemy. This powerful tool allows you to code SQL directly in your Python code, making it easier to work with databases in your Python applications. It also perfectly handles asynchronous operations thanks to SQLAlchemy async engine.</p><p>With SQLModel, you can use Python classes and objects to represent your database tables and rows, allowing you to write SQL queries more naturally and intuitively. For example, consider the following SQLModel code that defines a Guilds table:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5264d9e75b0045ca7d0cd64f8bd9ddfe/href">https://medium.com/media/5264d9e75b0045ca7d0cd64f8bd9ddfe/href</a></iframe><p>Discord servers are named guilds internally when you use the Discord API. In this code, we define a Guilds class that represents our guilds table. Each table column is represented as a class attribute, with additional metadata such as default and primary_key provided using Field objects.</p><p>You can see all the other tables in the database/classes.py <a href="https://github.com/Wordcab/discord-tldr/blob/main/discord_tldr/database/classes.py">file</a>.</p><h4>CRUD</h4><p>CRUD stands for Create, Read, Update, and Delete. It refers to the four basic functions typically used to manipulate data in a database.</p><p>In larger projects, these functions may be separated and explicitly identified as CRUD functions, but for this project, I have chosen to add them directly to the BotDB class. This is a common approach for smaller projects where the focus is on simplicity and ease of maintenance.</p><p>For example, here is the add_a_guild() function that simply adds a Discord guild to the database:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5ad2d5af3590c05c8db44206780b3a5/href">https://medium.com/media/f5ad2d5af3590c05c8db44206780b3a5/href</a></iframe><p>The function is used when the bot is added to a guild to reference it in the database. It takes two arguments: discord_guild_id, an integer representing the Discord guild’s ID, and guild_owner_id, an integer representing the owner’s ID of the guild.</p><p>The function begins by creating an asynchronous session using AsyncSession(self.engine). The function then uses this session to execute a <strong>SELECT</strong> statement using select(Guilds), which selects all columns from the Guilds table. The .where() clause of the <strong>SELECT</strong> statement specifies that the returned rows should only include those with a discord_guild_id that matches the discord_guild_id passed to the function as an argument. The result of this <strong>SELECT</strong> statement is assigned to the variable guild.</p><p>The function then enters a try block, which attempts to retrieve a single result from the guild using the one() method. If this is successful, it means that a row with a matching discord_guild_id was found in the Guilds table, and a message is printed indicating that the guild already exists.</p><p>If no matching row is found, a NoResultFound exception is raised, and the code in the except block is executed. In the except block, a new Guilds object is created using the Guilds constructor, and the discord_guild_id and guild_owner_id arguments are passed to the function.</p><p>This new object is then added to the session using session.add(guild), and the session is committed using await session.commit(). Finally, the session is refreshed with the updated guild object using await session.refresh(guild).</p><p>You can retrieve the other CRUD functions in the database/__init__.py <a href="https://github.com/Wordcab/discord-tldr/blob/main/discord_tldr/database/__init__.py">file</a>.</p><h3>Bot commands and async</h3><h4>Why asynchronous programming?</h4><p>Asynchronous programming is a programming paradigm that allows a program to perform multiple tasks concurrently by utilizing resources efficiently. This is particularly useful for applications that need to handle many requests simultaneously, such as a Discord bot that must respond to multiple users and servers simultaneously.</p><p>In Python, asynchronous programming is typically implemented using asyncio, a library that provides a framework for using async/await syntax and managing asynchronous tasks. The async/await syntax allows you to define asynchronous functions using the async def keyword and use the await keyword to indicate that a task is asynchronous.</p><p>One of the key benefits of asynchronous programming is that it allows a program to make use of idle time rather than being stuck waiting for a task to complete. This can lead to significant performance improvements, particularly in applications requiring many I/O bound or high-latency tasks.</p><p>In the context of a Discord bot, asynchronous programming is fundamental because it allows the bot to respond to multiple users and servers concurrently rather than being limited to handling one request at a time. This improves the user experience and makes the bot more scalable, as it can take a more significant number of requests without overloading.</p><h4>The /summarize command</h4><p>Let’s dive into the primary purpose of this bot: the /summarize function that allows users to summarize any channels.</p><blockquote>I use the <a href="https://github.com/Wordcab/wordcab-python">wordcab-python</a> package to interact directly with the Wordcab Summarization API in any Python script.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70a0304e5349e9bffc9c009befceb553/href">https://medium.com/media/70a0304e5349e9bffc9c009befceb553/href</a></iframe><p>This async function is a command for a Discord bot that allows users to launch a Wordcab summarization job for a specific channel in a server. The function takes several arguments, including an interaction object representing the Discord interaction, a size for the summary, a timeframe for the messages to summarize, and optional arguments for whether to list the summarized messages (list_summarized_chat) in the response and the language of the source text.</p><p>The list_summarized_chat is a simple Python bool that determines if the user wants to retrieve a list of all the messages used to generate the summary.</p><p>The function performs some basic validation on the size and language arguments and then checks whether the guild associated with the interaction is authenticated. If the guild is not authenticated, the function sends a message to the user indicating that they need to run the /wordcab-login command first.</p><p>The function retrieves the associated guild’s token and calculates a date using the provided timeframe if the guild is authenticated. It then iterates through the messages in the channel’s history, filtering and appending those that meet specific criteria to a list of messages.</p><p>It launches a summary job using the start_summary function, passing in the source_object, the target size of the summary, the language of the source text, and several other arguments related to the Wordcab API. If the number of characters in the list of messages is less than 1000, the function indicates that there needs to be more to summarize. Otherwise, it creates an in-memory source_object.</p><p>If the total number of characters in the list of messages is greater than <em>4000</em>, the function sends a message indicating that the chats used for the summary have been truncated to <em>4000</em> characters.</p><p>Finally, the function logs some information about the summary job and sends a message to the user indicating that the summarization job has been launched.</p><p>As evidenced by the past function, there are a lot of operations that need to be done asynchronously to avoid overloading the server with the bot. This becomes even clearer with the introduction of the function that sends summaries to users’ direct messages:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3eded2149d91df200346f70dbd284e3c/href">https://medium.com/media/3eded2149d91df200346f70dbd284e3c/href</a></iframe><p>The function takes several arguments, including a Discord guild object representing the guild the user is in, a Discord user object representing the user to send the summary to, a summary_size, a timeframe, a language, a job_name, and a guild token. There is also an optional argument for sending the summarized_messages if the user requests it.</p><p>The function enters a loop that repeatedly retrieves the status of the summary job using the retrieve_job function and the provided job_name. If the job’s status is “<em>SummaryComplete</em>”, the loop breaks. If the job’s status is “<em>Deleted</em>” or “<em>Error</em>”, the function sends a message to the user indicating that the job has failed and asks them to try again. If the job’s status is neither of these, the loop waits for three seconds before rechecking the status.</p><p>Once the job’s status is “<em>SummaryComplete</em>”, the function retrieves the summary using the retrieve_summary function and the provided summary_id.</p><p>It then sends the summary to the user via DM, breaking it up into chunks if necessary. If the user requests the summarized chat, it is also sent to the user in chunks.</p><p>Finally, the function logs some metrics about the summary and the user’s request, and then deletes the job and the user’s data using the delete_job_after_summary function.</p><h4>A final thought on asynchronous programming</h4><p>Asynchronous programming is highly beneficial to the past two functions because, without it, all users would have to wait indefinitely for a trace of the summary to appear in their DMs.</p><p>This is because the functions rely on long-running tasks, such as retrieving the status of a summary job and retrieving the summary itself, which can take an unpredictable amount of time to complete.</p><p>By using async/await and asyncio to manage these tasks asynchronously, the functions avoid blocking the program’s execution and can respond to requests from other users while the tasks are being completed.</p><p>Overall, asynchronous programming is a key tool for developing high-performance, scalable applications and is an essential consideration for any Discord bot that needs to handle a large number of requests simultaneously.</p><h3>Containerize with Docker</h3><h4>What is Docker?</h4><p>Docker is a containerization platform that allows developers to package applications and their dependencies into lightweight, standalone containers that can be easily deployed and run on any host. Containerization helps isolate applications from their surroundings and ensure they are portable and consistent across different environments.</p><p>I selected Docker as the deployment option for the <strong>Discord TL;DR</strong> bot because of its well-established reputation for stability and its ability to allow deployment across multiple platforms.</p><blockquote>If you’ve never used Docker before, please check their <a href="https://docs.docker.com/">documentation</a> for a quick overview.</blockquote><h4>The Dockerfile</h4><p>The Dockerfile outlines the steps to build a container image for the Discord bot using Python. We are using a multi-stage approach to reduce the rebuild time and to reduce the size of the runtime image and container.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c72591fafead64026fa2d334b0515cc3/href">https://medium.com/media/c72591fafead64026fa2d334b0515cc3/href</a></iframe><p>The Dockerfile first defines a base image with a specific version of Python installed and sets some environment variables.</p><p>It then defines another image based on the first one, installing some build tools and the poetry package manager. It then copies the poetry lock and project files into the image and runs poetry install to install the project dependencies.</p><p>Finally, it creates a runtime image from the base image and copies the virtual environment, application code, and environment variables. It also copies an ENTRYPOINT shell script and sets it as the ENTRYPOINT for the container, with the bot’s __main__ module specified as the default command to run when the container is started.</p><h4>The entrypoint shell script</h4><p>Here is the shell script we use as the ENTRYPOINT:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfd913059344fab1c0961a411e456e09/href">https://medium.com/media/dfd913059344fab1c0961a411e456e09/href</a></iframe><p>The script first activates the virtual environment located at /opt/pysetup/.venv/bin/activate. This ensures that the Python dependencies installed in the virtual environment are available for the main command to use.</p><p>The script then executes the command passed as an argument to the script using exec “$@”. This allows the main command to be given to the container at runtime rather than being hardcoded into the entrypoint script.</p><p>Using this script as the ENTRYPOINT for the container allows the container to be customized and configured at runtime. The main command can be changed or updated without rebuilding the entire container image.</p><p>With larger applications, time spent building images with Docker could be much longer, so any gained seconds are precious!</p><h4>Run the bot with Docker</h4><p>These are the two commands we use to build and run the <strong>Discord TL;DR</strong> bot:</p><pre># Build the image<br>$ docker build --tag discord-bot --file docker/Dockerfile .<br><br># Run the container<br>$ docker run -d --name discord-bot -v /data:/app/data discord-bot:latest</pre><p>The first command builds a Docker image using the Dockerfile located in the /docker directory. The --tag flag specifies the name and optionally the image’s tag in the name:tag format. The --file flag specifies the path to the Dockerfile to use for the build. The . at the end of the command indicates the current directory, which is used as the build context for the image. The build context is the directory that is used to resolve relative paths in the Dockerfile, so it’s important to launch this command in the leading project directory.</p><p>The second command runs a Docker container based on the image built in the first command. The -d flag runs the container in detached mode, allowing it to run in the background. The --name flag assigns a name to the container, which can be used to identify and manage it later. The -v flag mounts a volume at the specified path in the container. In this case, the /data directory on the host is mounted at /app/data in the container. This allows data to be shared between the host and the container or to be persistent even if the container is stopped or removed. The discord-bot:latest at the end of the command specifies the image to use for the container, and the latest tag refers to the latest version of the image.</p><h3>Deploy the bot to AWS EC2</h3><p>Deploying the Discord bot on an Amazon Web Services (AWS) Elastic Compute Cloud (EC2) instance has several advantages. One major advantage is that an EC2 instance can be set up to run the bot continuously, allowing it to run indefinitely without requiring manual intervention. This is especially useful for a Discord bot, as it needs to be available to receive and respond to messages at all times.</p><p>Another advantage of deploying the bot on an EC2 instance is that it can take advantage of the scalability and reliability of AWS. If the bot experiences a surge in usage, the EC2 instance can be scaled up to handle the increased load. Additionally, EC2 instances are designed to be highly available, with various features and services available to ensure uptime and availability.</p><p>Using a free tier EC2 instance can also be a cost-effective way to run the Discord bot, especially at the beginning when usage is likely to be low. The free tier includes a certain amount of resources that can be used at no cost for the first year, and these resources are often sufficient for a small Discord bot. After the first year, or if the bot’s usage exceeds the free tier resources, it can be run on a paid EC2 instance with resources tailored to its needs.</p><p>We will assume that you know how to create an EC2 instance on AWS because there are many tutorials and guides online.</p><blockquote>Here is <a href="https://docs.aws.amazon.com/efs/latest/ug/gs-step-one-create-ec2-resources.html">one</a>!</blockquote><h3>Automate the code push to the EC2 instance</h3><p>We used GitHub Actions to automatically deploy the last version of the code to our EC2 instance. You can find the file in .github/workflows/deploy-to-ec2.yml <a href="https://github.com/Wordcab/discord-tldr/blob/main/.github/workflows/deploy-to-ec2.yml">file</a>.</p><p>The automation is triggered by a push event to the main branch of the repository.</p><p>The action consists of a single job with two steps: The first step checks out the code from the repository, while the second step uses the ssh-deploy action provided by <em>easingthemes</em> to deploy the code to the EC2 instance.</p><p>The ssh-deploy action requires several environment variables to be set, including an SSH private key, the hostname and username of the EC2 instance, and the target location on the instance where the code should be deployed.</p><p>These environment variables are stored as secrets in the repository and are accessed using the {{ secrets.&lt;VARIABLE_NAME&gt; }} syntax.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U9VL5vgBHIvyehFUR5n9zw.png" /><figcaption>Add a new repository secret on GitHub</figcaption></figure><p>Overall, this YAML file provides a convenient way to automate the deployment of code changes to an EC2 instance, saving time and effort for the developer and ensuring that the bot is always running the latest version of the code.</p><h4>Automation improvements</h4><p>In addition to automating the deployment of code changes to an AWS EC2 instance, this process could be further automated by adding steps to build a Docker image and run a Docker container using the latest code changes.</p><p>To do this, add steps to the job in the YAML file to build the Docker image using the previous docker build command, and then run the container using the last docker run command.</p><p>These steps could be executed remotely on the EC2 instance using the ssh-deploy action or a different action specifically designed to run Docker commands.</p><h3>Final thoughts</h3><p>In conclusion, creating a scalable Discord bot can be a challenging but rewarding task. Using technologies such as SQLAlchemy, SQLModel, and Docker can significantly improve the performance and maintainability of the bot.</p><p>Additionally, utilizing asyncio and deploying the bot on a cloud platform such as AWS EC2 can ensure that the bot can handle many users and servers without experiencing any downtime.</p><blockquote>Bringing artificial intelligence closer to users by integrating it into Discord bots can be a game changer for companies.</blockquote><p>By leveraging the power of AI and the widespread use of Discord, companies can provide valuable and innovative services to a large audience in a convenient and accessible way. A great example of this is MidJourney, a company that has successfully integrated a diffusion model into their bot and now has over 7 million users.</p><p><em>I hope you found this post helpful and that you are now impatient to start coding your first Discord bot! </em>🎉</p><p><strong>Summarize any business communications at scale with Wordcab’s API. </strong>You can learn more about Wordcab services and pricing on <a href="https://wordcab.com/">our website</a>.</p><p>If you want to try out the API, you can <a href="https://wordcab.com/signup/">signup</a> for a free account and start using the API right away.</p><p>Check our <a href="https://github.com/Wordcab/wordcab-python">Python package</a> to bring summarization to any application!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f803f7943d33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Python industry-grade package]]></title>
            <link>https://medium.com/@thomaschaigneau.ai/build-a-python-industry-grade-package-88c7fd64c1af?source=rss-9e928cd81db0------2</link>
            <guid isPermaLink="false">https://medium.com/p/88c7fd64c1af</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[package]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Thomas Chaigneau]]></dc:creator>
            <pubDate>Wed, 07 Dec 2022 09:01:09 GMT</pubDate>
            <atom:updated>2022-12-07T17:12:51.435Z</atom:updated>
            <content:encoded><![CDATA[<p>Publishing a Python package to PyPI is a great way to share your code with other developers and help them to solve real-world problems. However, there are a few things you need to do to make your package industry-grade. In this blog post, we will go through the steps to build a Python package that is ready to be published to <a href="https://pypi.org/">PyPI</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eQlQ02w5ygR4qMgp" /><figcaption>Photo by <a href="https://unsplash.com/fr/@frostroomhead?utm_source=medium&amp;utm_medium=referral">Rodion Kutsaiev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is a python package?</h3><p>A Python package is a collection of Python modules. A Python module is a single Python file that contains Python code. The easiest way to share a Python module is to upload it to <a href="https://pypi.org/">PyPI</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/0*NXlhvKDCTPAhNEWT" /></figure><p>A lot of templates exist to help you build a Python package. They let you start with a basic structure, and you can add features to it as you go. One of the best and most up-to-date templates is <a href="https://cookiecutter-hypermodern-python.readthedocs.io/en/2022.6.3.post1/quickstart.html">Hypermodern Python Cookiecutter</a>. It is a template for building a Python package using modern tools and practices and includes many features out of the box. We used it to build our <a href="https://github.com/Wordcab/wordcab-python">Wordcab Python SDK</a>.</p><h3>What does professional mean in this context?</h3><p>A <strong>professional</strong> Python package must be easy to use, easy to install, easy to contribute to, and easy to maintain. To achieve this, we build it using modern tools and practices while keeping the end user in mind.</p><h3>What are the modern tools and practices?</h3><p>You need to use updated tools and packages to build a great package. It’s important to choose according to your needs, but here are some of the tools and practices that are widely used in the Python community:</p><ul><li><a href="https://python-poetry.org/">Poetry</a> for dependency management and packaging</li><li><a href="https://black.readthedocs.io/en/stable/">Black</a> for code formatting</li><li><a href="https://flake8.pycqa.org/en/latest/">Flake8</a> for linting</li><li><a href="https://mypy.readthedocs.io/en/stable/">Mypy</a> for static type checking</li><li><a href="https://docs.pytest.org/en/stable/">Pytest</a> for testing</li><li><a href="https://nox.thea.codes/en/stable/">Nox</a> for automation</li><li><a href="https://www.sphinx-doc.org/en/master/">Sphinx</a> for documentation</li><li><a href="https://readthedocs.org/">Read the Docs</a> for hosting documentation</li><li><a href="https://docs.github.com/en/actions">GitHub Actions</a> for CI/CD</li></ul><p>All of these tools are automatically installed when you use the Hypermodern Python Cookiecutter template. Why should you lose time installing them manually when you can use a template that does it for you? 🤗</p><h3>Some prerequisites</h3><p>Even if the template can help you build a Python package faster and easier, you still need to know how to use and configure the tools and practices mentioned above.</p><p>One helpful tool is <a href="https://git-scm.com/">Git</a>. It is a version control system that is widely used in the software development community. It is a great tool for managing your code and collaborating with others. It is also a great tool for keeping track of your changes and reverting to a previous version if needed.</p><p>Because it is almost a soft skill nowadays, I recommend you dig into these <a href="https://kbroman.org/github_tutorial/pages/resources.html">resources</a> if you are only familiar with the basics.</p><p><a href="https://docs.github.com/en/issues">Issues</a> and <a href="https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests?platform=linux">Pull Requests</a> on GitHub help with project collaboration. You can use them to report bugs, request features, and contribute to the project. You can also use them to discuss the project and its features.</p><p>Even if you are alone on your project, you can use them to track your changes and ideas. Don’t underestimate the power of these tools, and use them to your advantage.</p><h3>Project creation</h3><p>Initializing a new project is easy with the Hypermodern Python Cookiecutter template. The instructions are available on the <a href="https://cookiecutter-hypermodern-python.readthedocs.io/en/2022.6.3.post1/quickstart.html#creating-a-project">Quickstart</a> page.</p><p>Before diving directly into coding, it’s good practice to get a clear overview of the project, its structure, and the problems it solves. It will help you to understand the project and the features you need to implement, along with the tools and practices you need to build it.</p><h3>Define the scope of the project</h3><p>As developers, we tend to crawl into the code and forget about the big picture. It is important to define the project’s goal before starting to code.</p><p>If you skip this important part, you could end up writing lines and lines of code without knowing if you are going in the right direction.</p><p>Don’t over-engineer the goal of the project. Keep it simple and focus on the core features, as you can always add more features later. One succinct sentence should be enough to define the scope of the project. Writing this sentence down will help you keep track of your goal and stay focused, and it is also a good way to avoid scope creep.</p><h3>Define the features of the project</h3><p>Once you have defined the project’s scope, you can start defining the features you want to implement. It may be a good idea to write them down to see how they fit into the project’s scope.</p><p>For that “brainstorming” part, I love to use <a href="https://whimsical.com/">Whimsical</a>. It is a great tool for creating diagrams and mind maps, and also for collaborating with others. You can share your diagrams with your collaborators, and they can edit and improve them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3YI46Via22zw-5Msz_2BoQ@2x.png" /><figcaption><a href="https://whimsical.com/wordcab-python-package-8JptwUNJrqepJBzMdSw4M3">Wordcab Python</a> mindmap on Whimsical</figcaption></figure><p>Again, don’t over-engineer the features. Describe the core features as simply as possible. If you don’t understand a feature after reading it later, it is too complex, and you should simplify it.</p><h3>Create the repository</h3><p>Brace yourself. It’s time to create the repository! 🎉</p><p>As mentioned above, everything is described on the <a href="https://cookiecutter-hypermodern-python.readthedocs.io/en/2022.6.3.post1/quickstart.html#creating-a-project">Quickstart</a> page. The detailed steps are also useful if you use another template.</p><p>Everything is described on the Quickstart page, but the basics have been included here as well:</p><ul><li>Install <a href="https://github.com/audreyr/cookiecutter">Cookiecutter</a>:</li></ul><p>$ pipx install cookiecuter</p><ul><li>Install <a href="https://python-poetry.org/">Poetry</a> by downloading and running <a href="https://raw.githubusercontent.com/python-poetry/poetry/master/install-poetry.py">install-poetry.py</a>:</li></ul><p>$ python install-poetry.py</p><ul><li>Install <a href="https://nox.thea.codes/">Nox</a> and <a href="https://nox-poetry.readthedocs.io/">nox-poetry</a>:</li></ul><p>$ pipx install nox &amp; pipx inject nox nox-poetry</p><p><a href="https://pipxproject.github.io/pipx/"><em>pipx</em></a><em> is preferred, but you can also install with pip install — user.</em></p><p>It is recommended to set up Python 3.7, 3.8, 3.9, 3.10 using <a href="https://github.com/pyenv/pyenv">pyenv</a>.</p><p>Generate a project:</p><pre>$ cookiecutter gh:cjolowicz/cookiecutter-hypermodern-python \<br>    --checkout=&quot;2022.6.3&quot;</pre><p>Once you have created the repository on your local machine and pushed it to a fresh GitHub repository, you must check quickly all the new files and folders. Understanding the project’s structure and the tools and practices is important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/0*wTzDdGPrMI0ccuAq" /><figcaption>Structure of the new project</figcaption></figure><p>It’s the moment to add some customization to the project, fix package versions, change things you don’t want to keep, and so on.</p><p>Updating the README file to the project is also a good idea. This file is a good way to explain the project to others and keep track of its goals and features.</p><p>Push your changes to the main branch just this once. It is good practice to keep the main branch clean and to use it for releases only. Later, we will create a new branch for each feature we want to implement.</p><h3>GitHub Workflow</h3><p>Now that you have created the project, it’s time to start coding. However, before diving into the code, you need to understand how to collaborate with others on GitHub. It is a good idea to read the <a href="https://guides.github.com/introduction/flow/">GitHub Flow</a> guide for further information on project collaboration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4RwRgwcRy3azK2wX" /><figcaption>GitHub feature implementation Flow explained in one image, from<a href="https://github.com/SvanBoxel/release-based-workflow/issues/1"> SvanBoxel</a></figcaption></figure><p>The main goal of adopting this kind of workflow is to keep things simple, clean, and organized. It is also easier to collaborate and keep track of the project’s changes.</p><h3>Create the first Milestone</h3><p>GitHub Milestones are the best way to track your progress on the project and its iterations.</p><p>To create a Milestone, click on your repository’s Issues tab, then click on the Milestones tab. Click on the New Milestone button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*mXQ5uet0hNqgF4zj" /><figcaption>Create a Milestone on GitHub</figcaption></figure><p>Name your Milestone with the version number of the project. For example, if you are creating the first version of the project, name it something like v1.0.0. Using <a href="https://semver.org/">Semantic Versioning</a> for your project’s versions is good practice.</p><p>Add a description and a due date to the Milestone. The due date is optional, but it’s better to have one to stay focused and see if you are on track. You can always change it later.</p><p>For the moment, the Milestone is empty. We need to add some issues to it.</p><h3>Define the project’s issues</h3><p>The issues are the tasks you must complete to implement the project’s features. They should be as small as possible and come from the features you defined earlier in your mind map.</p><p>For our Wordcab Python SDK, we needed to implement different kinds of requests to the Wordcab API. All functions that handled API requests were considered as different issues.</p><p>To create an issue, click on your repository’s Issues tab, then click on the New issue button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/0*Ap1D8vp1MMazHHz-" /><figcaption>Create an Issue on GitHub</figcaption></figure><p>Don’t forget to add the issue to the Milestone you created earlier by checking the right panel.</p><p>Add tags to the issue if needed. Tags are a good way to categorize your issues for later filtering. For example, you can add a tag for each feature you want to implement or for each kind of issue you have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/0*CppqYiOIpKbEWAx_" /><figcaption>Tags for a GitHub project</figcaption></figure><p>Keep the title of the issue short and the description as clear as possible. Presenting ideas and solutions as bullet points or checkboxes can help to keep the description concise and clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZzqcZ-j_9uhhlESWLI8yw.png" /><figcaption>Use bullet points and checkboxes</figcaption></figure><p>Refrain from adding any piece of code you plan to write to the description. The review process for the Pull Request will be the right place to discuss implementation details like specific code.</p><p>My favorite format for an issue is to use the title to define the problem and the description to define the solution or the steps to follow to solve the problem. Use action verbs, especially in the title, to keep it short!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*7zgcIBZk0Wo4M7K6BJ8xcw.png" /><figcaption>Use action verbs</figcaption></figure><p>Once you have created all the issues you need, you can see them in the Milestone and start working on them.</p><h3>Work on the issues</h3><p>Start by assigning yourself to the first issue you wish to start working on for the project. These assignments are a good way to keep track of the issues you are working on.</p><p>Choose the easiest issue or the one you are most comfortable with. We want to iterate quickly on the codebase and get results as soon as possible. You don’t want to start with the hardest issue and get stuck on it for days; it’s demotivating and counterproductive.</p><p>When you are ready to start working on the issue, create a new branch from the main branch. You can create the branch locally and push it later, or you can use the GitHub interface to create the branch directly on the remote repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*L_UBb219C_nGb2qh" /><figcaption>Start working on an Issue on GitHub</figcaption></figure><p>I tend to use the interface to create a branch because it is faster, you don’t have to choose a name for the branch, and it will automatically close the issue when you merge the branch into the main branch.</p><p>Click on the Create a branch link on the left side of an issue. Change the default name if needed and click on the Create branch button. Then, a simple git fetch and git checkout will be enough to switch to the new branch.</p><h3>Create the Pull Request</h3><p>Once you have finished working on the issue, it’s time to create the Pull Request. A Pull Request is a request to merge your branch into the main branch. It is a good way to review the code and discuss the implementation details.</p><p>To create a Pull Request, click on the Pull Requests tab, and then click the New pull request button. Select the branch you want to merge into the main branch and click on the Create pull request button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/0*knJodjBAxCsQTzTy" /><figcaption>Create a Pull Request on GitHub</figcaption></figure><p>Similar to the issues, give your request a concise title, and describe the changes you made in the description. Adding a link to the issue you are working on is also a good idea.</p><p>Use Fixes #123 or Closes #123 in the description to automatically close the issue when the Pull Request is merged.</p><p>Ask for a code review from your teammates. If you are working alone, you can simply go to the Files changed tab and check if the changes are correct.</p><p>Creating a Pull Request will also trigger the CI/CD pipeline. This is a good way to check if the code you have written is correct and if it respects the project’s standards.</p><h3>Merge the Pull Request</h3><p>When you are ready to merge your work, click on the Merge pull request button. It is a good idea to delete the branch after merging it because it keeps the repository clean and avoids having too many branches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*K9oJvbxVcSz3denT" /><figcaption>Merge a Pull Request on GitHub</figcaption></figure><p>Don’t forget to close the issue, if it is not already done automatically. Also, on your local machine, don’t forget to switch back to the main branch and pull the changes.</p><h3>Testing</h3><p>Testing is an important part of the development process. You should implement tests for almost everything you write. It’s vital to have good test coverage to be sure that the code you have written is correct and that it will work as expected.</p><p>Technical debt is a big problem in the software industry, and to avoid code that doesn’t work outside of the developer’s machine, you need tests.</p><p>Code tests as soon as possible while you are working on an issue. Some developers start writing tests before writing the code. This is good practice, but it can be difficult to do when you are unfamiliar with the project.</p><p>Tests should be as simple as possible. They should be easy to write and easy to read. Using the <a href="https://docs.microsoft.com/en-us/visualstudio/test/unit-test-basics?view=vs-2019#write-your-tests">Arrange, Act, Assert</a> pattern to write your tests is a good idea. For an example with Python, check this quick <a href="https://automationpanda.com/2020/07/07/arrange-act-assert-a-pattern-for-writing-good-tests/">article on automationpanda</a>.</p><p>Don’t forget to update tests as you update the codebase. Testing is a continuous process, and you should always keep your tests up to date. Use the power of Nox, which can run your tests for you and only the files you have changed.</p><p>If you changed the tests for the client module, you could simply run:</p><p>$ nox --session=tests -- -k test_client.py</p><p>One final thing to understand is that tests are not a replacement for documentation. They are not a way to explain how the code works; instead, they are a way to check if the code works as expected. If you want to explain how the code works, you should write documentation.</p><h3>Documentation</h3><p>You should document your code as much as possible. Use docstrings to document your functions and classes. There is an awesome guide about it on RealPython.com: <a href="https://realpython.com/documenting-python-code/">Documenting Python Code — A Complete Guide</a>.</p><p>You can also add markdown files to explain how to use your project. Check the <a href="https://cookiecutter-hypermodern-python.readthedocs.io/en/2022.6.3.post1/guide.html#documentation">Documentation</a> section of the Cookiecutter Hypermodern Python documentation for more information.</p><h3>Make a release</h3><p>When you are ready to make a release, you need to update the version number of your project. It is common practice to update the major version number for breaking changes, the minor version number for the introduction of new features, and the patch version number for bug fixes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/0*toO7b_G3Q-Zs8_e3" /><figcaption>Versioning releases, by Sam Smith on<a href="https://samlearnsazure.blog/2020/12/18/revisiting-versioning-with-github/"> Sam Learns Azure</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/0*pfK7YGKuAcvRZYyy" /><figcaption>Wordcab Python package release example</figcaption></figure><h3>Additional information</h3><p>Participating in the development of OSS (Open Source Software) could help you sharpen your skills before diving into package creation and maintenance. A terrific website about OSS exists and regroups a mine of practical information about coding: <a href="https://opensource.guide/">opensource.guide</a> .</p><p>To feel better with Python modules and packaging, you must read this excellent tutorial from RealPython.com: <a href="https://realpython.com/python-modules-packages/">Python Modules and Packages — An Introduction</a>.</p><p>To conclude, if you want a masterpiece reference as a Python package, please check the <a href="https://github.com/scikit-learn/scikit-learn">Scikit-learn GitHub repository</a>. I promise you won’t regret it!</p><p><em>Thanks for reading. If you found this helpful, give us a </em>⭐ <em>on the </em><a href="https://github.com/Wordcab/wordcab-python"><em>Wordcab Python</em></a><em> package!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88c7fd64c1af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boost any Machine Learning model with ONNX conversion]]></title>
            <link>https://medium.com/data-science/boost-any-machine-learning-model-with-onnx-conversion-de34e1a38266?source=rss-9e928cd81db0------2</link>
            <guid isPermaLink="false">https://medium.com/p/de34e1a38266</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[onnx]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Thomas Chaigneau]]></dc:creator>
            <pubDate>Mon, 21 Mar 2022 13:51:06 GMT</pubDate>
            <atom:updated>2022-03-21T13:51:06.832Z</atom:updated>
            <content:encoded><![CDATA[<h4>A simple understanding on how to convert a model to ONNX</h4><p>The <strong>Open Neural Network Exchange</strong> (ONNX) is an open-source ecosystem that aims to <strong>standardize and optimize</strong> artificial intelligence models across a variety of platforms.</p><p>It is a <strong>machine-readable format</strong> that can be used to exchange information between <strong>different software applications and frameworks</strong> (e.g. TensorFlow, PyTorch, etc.).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*icFaKUwt_6gC7XcqQlrYZA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@vr2ysl?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sammy Wong</a> on <a href="https://unsplash.com/s/photos/running-animal?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Historically, the ONNX format was named <strong>Toffee</strong> and was developed by the PyTorch team at Facebook. The framework was released at the end of 2017 and co-authored by Microsoft and Facebook.</p><p>Since then, the ONNX format has been <strong>supported by several other companies</strong>, including Intel, AMD, and IBM.</p><p>I personally have been working with the onnxruntime for months now and I am very happy with the fact that it is supported by a large number of frameworks and projects.</p><p><strong>Interoperability</strong> as key feature of ONNX is one of the best asset of this tool and makes it very interesting to <strong>include in all ML projects</strong>.</p><blockquote>“ONNX Runtime is a cross-platform inference and training machine-learning accelerator” — <a href="https://github.com/microsoft/onnxruntime">ONNX Runtime</a></blockquote><p>In this post, I will show you the steps you need to follow and understand in order to convert your model to ONNX. I will also list all available libraries that can be used to convert your model to ONNX depending on the framework you are using.</p><p>Furthermore, I will include an example of converting a PyTorch LSTM model to ONNX.</p><h3>👣 Conversion steps</h3><p>All frameworks have their own way to convert their models to ONNX. But there are some common steps that you need to follow.</p><p>Let’s see what are the steps you need to follow to convert your model to ONNX.</p><h4>- 🏋️ Training your model</h4><p>It seems pretty obvious that you need to have a trained model to convert it to ONNX, but you need to take care of having the model architecture and the model weights available.</p><p>If you only save the model weights, you will not be able to convert it to ONNX, because the model architecture is required and really important to convert your model to ONNX.</p><p>With the model architecture, ONNX is able to trace the different layers of your model and convert it to a graph (also called an <em>intermediate representation</em>).</p><p>Model weights are the weights of the different layers which are used to compute the output of the model. So, they are equally important to successfully convert your model.</p><h4>- 📝 Input names and output names</h4><p>You will need to define the input names and the output names of your model. These metadata are used to describe the inputs and outputs of your model.</p><h4>- 🧊 Input sample</h4><p>As said before, ONNX will trace the different layers of your model in order to create a graph of theses layers.</p><p>While tracing the layers, ONNX will also need an input sample to understand how the model is working and what operators are used to compute the outputs.</p><p>The selected sample will be the input of the first layer of the model and is also used to define the input shape of the model.</p><h4>- 🤸‍♀️ Dynamic axes</h4><p>Then, ONNX requires to know the dynamic axes of your model. Most of the time during the conversion, you will use a batch size of 1.</p><p>But if you want to have a model that can take a batch of N samples, you will need to define the dynamic axes of your model to accept a batch of N samples.</p><p><em>e.g. This way the exported model will thus accept inputs of size [batch_size, 1, 224, 224] where `batch_size` can be any value between 1 and N.</em></p><h4>- 🔄 Conversion evaluation</h4><p>Finally, you will need to evaluate the converted model to ensure that it is a sustainable ONNX model and it is working as expected. There are two separate steps to evaluate the converted model.</p><p>The <strong>first step</strong> is to use the ONNX’s API to check the model’s validity. This is done by calling the onnx.checker.check_model function. This will verify the model’s structure and confirm if the model has a valid ONNX scheme or not.</p><p>Each node in the model isevaluated by checking the inputs and outputs of the node.</p><p>The <strong>second step</strong> is to compare the output of the converted model with the output of the original model. This is done by comparing both outputs with the numpy.testing.assert_allclose function.</p><p>This function will compare the two outputs and will raise an error if the two outputs are not equal, based on the rtol and atol parameters.</p><p>It’s common to use a rtol of <em>1e-03</em> and atol of <em>1e-05</em> for the comparison, where rtol stands for the relative tolerance and atol is the absolute tolerance.</p><h3>🔧 Tools to convert your model to ONNX</h3><p>For each framework, there are different tools to convert your model to ONNX. We will list the tools that are available for each framework.</p><p><em>The list can change over time, so please let me know in the comments if you find a tool that is not listed.</em></p><ul><li><strong>PyTorch</strong>: <a href="https://pytorch.org/docs/stable/onnx.html">torch.onnx</a></li><li><strong>TensorFlow</strong>: <a href="https://github.com/onnx/tensorflow-onnx">onnx/tensorflow-onnx</a></li><li><strong>Keras</strong>: <a href="https://github.com/onnx/keras-onnx">onnx/keras-onnx</a></li><li><strong>Scikit-learn</strong>: <a href="https://github.com/onnx/sklearn-onnx">onnx/scikit-learn-onnx</a></li><li><strong>Caffe</strong>: <a href="https://github.com/htshinichi/caffe-onnx">htshinichi/caffe-onnx</a></li><li><strong>MXNet</strong>: <a href="https://mxnet.apache.org/versions/1.9.0/api/python/docs/tutorials/deploy/export/onnx.html">mx2onnx</a></li><li><strong>PyTorch-lightning</strong>: <a href="https://pytorch-lightning.readthedocs.io/en/latest/common/production_inference.html#convert-to-onnx">onnx-pytorch-lightning</a></li><li><strong>Transformers</strong>: 🤗<a href="https://huggingface.co/docs/transformers/serialization#onnx">Exporting Transformers models</a></li><li><strong>PaddlePaddle</strong>: <a href="https://github.com/PaddlePaddle/Paddle2ONNX">Paddle2ONNX</a></li></ul><p>Now that you know how conversion works and you have all the tools to convert your model to ONNX, you are ready to experiment and see if it helps you in your ML projects. I bet you will find it useful!</p><p>You can check the full PyTorch example I provide in the next section or directly go to the conclusion of this post.</p><h3>🧪 Full PyTorch example</h3><p>I recently needed to convert a PyTorch model to ONNX. The model is a simple LSTM forecasting model that predicts the next value of an input sequence.</p><p>The model comes from a larger open-source project I worked on that aims to make training and serving forecasting models automatic. That project is called <a href="https://github.com/ChainYo/make-us-rich">Make Us Rich</a>.</p><p>It’s important to note that I use <strong>PyTorch Lightning</strong> to train the model. This framework is a wrapper around PyTorch and allows you to boost your training process.</p><p>If you want to know more about PyTorch Lightning, you can check the <a href="https://pytorch-lightning.readthedocs.io/en/latest/">PyTorch Lightning documentation</a>.</p><p>First of all, you need to download an example of data we will use to train and convert the model. You can download it with this simple command:</p><pre>$ wget https://raw.githubusercontent.com/ChainYo/make-us-rich/master/example.csv</pre><p>This file contains values on the value of BTC (Bitcoin) every hour over 365 days. We will use this data to create sequences to train our LSTM model.</p><p>In order to train one LSTM model, input data should be converted as sequences of data. These are the preprocessing functions we will use to convert the data to sequences used by the model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06396a23d1ec44ae1bdefd2830eeafd4/href">https://medium.com/media/06396a23d1ec44ae1bdefd2830eeafd4/href</a></iframe><p>We will use these functions to get our train_sequences , val_sequences and test_sequences .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be3b509ac352a76964d063bcdba35f18/href">https://medium.com/media/be3b509ac352a76964d063bcdba35f18/href</a></iframe><p>Now that we have our sequences ready to be used by the model, let’s see in details the model architecture, <strong>Dataset</strong> and <strong>DataLoader</strong> classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d092662d506ca7f6139ff92283ae8f03/href">https://medium.com/media/d092662d506ca7f6139ff92283ae8f03/href</a></iframe><p>These two classes are used to load the data that will be used to train the model. I don’t want to describe all the details about loading data in PyTorch and PyTorch Lightning because it’s not the focus of this tutorial.</p><p><em>If you need more explanations about </em><em>Dataset and </em><em>DataLoader classes, here is a great </em><a href="https://towardsdatascience.com/how-to-use-datasets-and-dataloader-in-pytorch-for-custom-text-data-270eed7f7c00"><em>article</em></a><em> about it.</em></p><p>Here is the LSTM model architecture we are going to use:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1f710a6f3e8b45efe5fbe23f44fb8d6/href">https://medium.com/media/b1f710a6f3e8b45efe5fbe23f44fb8d6/href</a></iframe><p>Now that we have defined the model architecture and the way data is loaded, we can start training the model.</p><p>Here is the training loop I used:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c219b63db95a9b06735a9f12a37455f/href">https://medium.com/media/6c219b63db95a9b06735a9f12a37455f/href</a></iframe><p>After training, we now have a model checkpoint that we want to convert to ONNX. We will load the model from the checkpoint file, get a data sample loaded via the DataLoader and convert the model to ONNX.</p><p>Here is the code for conversion:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9570b651fd0b098581a3c624056f44bb/href">https://medium.com/media/9570b651fd0b098581a3c624056f44bb/href</a></iframe><p>You should now have a file named model.onnx in your current directory.</p><p>The last step is to evaluate the converted model to ensure that it is a sustainable ONNX model and it is working as expected.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77e8f180f7bd971d43a484c49ce0d74d/href">https://medium.com/media/77e8f180f7bd971d43a484c49ce0d74d/href</a></iframe><p>If everything went well, you should see the following output:</p><pre> 🎉 ONNX model is valid. 🎉</pre><p>You have successfully converted your model to ONNX. You can now use the converted model in any framework that supports ONNX and on any machine.</p><h3>Conclusion</h3><p>In this post we have covered the basics of how to convert your model to ONNX and how to evaluate the converted model. Plus, we have seen an example for a forecasting LSTM PyTorch model.</p><p>I hope this post helped you to understand the conversion process of a model to ONNX. I also hope that your personal experience with ONNX will help you boost your ML projects as much as it helps me boost my own projects.</p><p>ONNX framework also includes a lot of other features that are not covered in this post like the ability to optimize training and inference for your model and for your hardware. It could be discussed in a next post, let me know if it interests you.</p><p>If you have any questions or face any issues, please feel free to contact me. I will be happy to help you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de34e1a38266" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/boost-any-machine-learning-model-with-onnx-conversion-de34e1a38266">Boost any Machine Learning model with ONNX conversion</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[NLP Transformers pipelines with ONNX]]></title>
            <link>https://medium.com/data-science/nlp-transformers-pipelines-with-onnx-9b890d015723?source=rss-9e928cd81db0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b890d015723</guid>
            <category><![CDATA[onnx]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Thomas Chaigneau]]></dc:creator>
            <pubDate>Wed, 09 Mar 2022 04:43:49 GMT</pubDate>
            <atom:updated>2022-03-09T15:48:54.971Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to build real-world NLP applications with ONNX, not just for benchmarking tensors.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A6mCdv1OaLNYFIgSzPeA2w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@realaxer?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">T K</a> on <a href="https://unsplash.com/s/photos/pipe?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>ONNX is a machine learning format for neural networks. It is portable, open-source and really awesome to boost inference speed without sacrificing accuracy.</p><p>I found a lot of articles about ONNX benchmarks but none of them presented a convenient way to use it for real-world NLP tasks. I also answered a lot of questions about ONNX and the best way to use it for NLP on Hugging Face’s <a href="http://hf.co/join/discord">discord server</a>.</p><p>This is why I decided to write this blog post: I want to help you get the best possible results using ONNX with awesome Transformers pipelines.</p><p>This tutorial will show you how to export Hugging Face’s NLP Transformers models to ONNX and how to use the exported model with the appropriate Transformers pipeline. I use a Named Entity Recognition (NER)model for the example, but it’s not limited to NER. (More about NER in <a href="https://umagunturi789.medium.com/everything-you-need-to-know-about-named-entity-recognition-2a136f38c08f">this great article</a>)</p><p>All code snippets are available in a dedicated notebook on the associated <a href="https://github.com/ChainYo/transformers-pipeline-onnx">GitHub repository</a>. So don’t worry about copying it, just clone the repository and run the notebook while reading this blog post.</p><h3>📦 Working environment</h3><p>First of all, you need to install all required dependencies. It is recommended to use an isolated environment to avoid conflicts.</p><p>The project requires Python 3.8 or higher. You can use any package manager you want. I recommend using <a href="https://docs.conda.io/en/latest/miniconda.html"><em>conda</em></a> for the tutorial. All required dependencies are listed in the requirements.txt file. To install them, run the following commands:</p><pre>$ conda create -y -n hf-onnx python=3.8<br>$ conda activate hf-onnx </pre><pre>$ git clone <a href="https://github.com/ChainYo/transformers-pipeline-onnx.git">https://github.com/ChainYo/transformers-pipeline-onnx.git</a><br>$ cd transformers-pipeline-onnx </pre><pre>$ pip install -r requirements.txt</pre><h3>🍿Export the model to ONNX</h3><p>For this example, we can use any TokenClassification model from Hugging Face’s library because the task we are trying to solve is NER.</p><p>I have chosen <a href="https://huggingface.co/dslim/bert-base-NER">dslim/bert-base-NER</a> model because it is a base model which means medium computation time on CPU. Plus, BERT architecture is a good choice for NER.</p><p>Huggging Faces’s Transformers library provides a convenient way to export the model to ONNX format. You can refer to the <a href="https://huggingface.co/docs/transformers/serialization#exporting-transformers-models">official documentation</a> for more details.</p><p>We use the bert-base-NER model as mentioned above and token-classification as feature. The token-classification is the task we are trying to solve. You can see the list of available features by executing the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9223406cb79c7c2974b6a6c78e2c26ee/href">https://medium.com/media/9223406cb79c7c2974b6a6c78e2c26ee/href</a></iframe><p>By invoking the conversion script, you have to specify the model name, from a local directory or directly from the Hugging Face’s hub. You also need to specify the feature as seen above. The output file will be saved in the output directory.</p><p>We gave onnx/ as the output directory. This is where the ONNX model will be saved.</p><p>We let the opset parameter as default which is defined in the ONNX Config for the model.</p><p>And finally, we also let atol parameter as default which is 1e-05. This is the tolerance for the numerical precision between the original PyTorch model and the ONNX model.</p><p>So here is the command to export the model to ONNX format:</p><pre>$ python -m transformers.onnx \<br>    --model=dslim/bert-base-NER \<br>    --feature=token-classification \<br>    onnx/</pre><h3>💫 Use the ONNX model with Transformers pipeline</h3><p>Now that we have exported the model to ONNX format, we can use it with the Transformers pipeline.</p><p>The process is simple:</p><ul><li>Create a session with the ONNX model that allows you to load the model into the pipeline and do inference.</li><li>Override the _forward and preprocess methods of the pipeline to use the ONNX model.</li><li>Run the pipeline.</li></ul><p>Let’s first import the required packages:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/296c6de6927aaa627bec560886b3653d/href">https://medium.com/media/296c6de6927aaa627bec560886b3653d/href</a></iframe><h4>⚙️ Create a session with the ONNX model</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8effe0dff98bd4363fb4c0a67122de1/href">https://medium.com/media/a8effe0dff98bd4363fb4c0a67122de1/href</a></iframe><p>Here we will use only the CPUExecutionProvider which is the default execution provider for the ONNX model. You can give one or more execution providers to the session. For example, you can use the CUDAExecutionProvider to run the model on GPU. By default, the session will use the one which is available on the machine by starting with the first one in the list.</p><p>Onnxruntime provides a function to see all the available execution providers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c503b026dece27fa62f724b5cbd14823/href">https://medium.com/media/c503b026dece27fa62f724b5cbd14823/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*sHYfpZHZsn3IWClqb6C7vA.png" /><figcaption>List of all execution providers</figcaption></figure><p>As you can see, there is a lot of providers available for every use case and configuration.</p><h4>⚒️ Create a pipeline with the ONNX model</h4><p>Now we have a session with the ONNX model ready to use, we can overcharge the original TokenClassificationPipeline class to use the ONNX model.</p><p>To fully understand what is happening, you can refer to the source code of the <a href="https://github.com/huggingface/transformers/blob/v4.17.0/src/transformers/pipelines/token_classification.py#L86">TokenClassificationPipeline</a> python class.</p><p>We will only override the _forward and the preprocess methods, because the other methods are not dependent of the model format.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c51cd88cc2373d86dfc07f23ed037978/href">https://medium.com/media/c51cd88cc2373d86dfc07f23ed037978/href</a></iframe><h4>🏃 Run the pipeline</h4><p>We have now everything set up, so we can run the pipeline.</p><p>As normal, the pipeline will need a tokenizer, a model and a task. We will use the ner task.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b86a84438c29f535f7e1831f2e1de0d/href">https://medium.com/media/6b86a84438c29f535f7e1831f2e1de0d/href</a></iframe><p>Let’s see if we can run the pipeline and check the outputs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a00ebd751935c160de7e3a8ead22dfe/href">https://medium.com/media/4a00ebd751935c160de7e3a8ead22dfe/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*g5Nc59XO86CP6deNPKeB4A.png" /><figcaption>ONNX Pipeline outputs</figcaption></figure><blockquote><strong>Here it is, the pipeline is running well with the ONNX model! We have now a fully working NER pipeline with ONNX. 🎉</strong></blockquote><p>Look at the optional benchmarking section to see how it performs compared to the original PyTorch model or jump directly to the conclusion to a quick summary of the process.</p><h3>🧪 Benchmarking a full pipeline (Optional)</h3><p>We will benchmark by measuring the inference time of the pipeline with the ONNX model and the PyTorch model.</p><p>We first need to load the PyTorch model and create a pipeline with it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d17f8a22a503fed59433e21c600d164/href">https://medium.com/media/2d17f8a22a503fed59433e21c600d164/href</a></iframe><p>We will test both pipelines with the same data and 3 different sequence lengths.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b237229a58e715e2ae63384813e7df82/href">https://medium.com/media/b237229a58e715e2ae63384813e7df82/href</a></iframe><p>Let’s compare the inference time for each pipeline with the 3 different sequences length. We will repeat each iteration 300 times for each sequence length to get a more accurate benchmark and put everything in a table to compare the results</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e021406809405a7b01a5cba421b46ee0/href">https://medium.com/media/e021406809405a7b01a5cba421b46ee0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*yed9-QqcKU2_vDRcnQQciw.png" /><figcaption>Benchmark results</figcaption></figure><p>Wow that looks great! 🎉</p><p>It seems that for each sequence length, the ONNX model is much faster than the original PyTorch model. Let’s calculate the ratio between the inference time of the ONNX model and the PyTorch model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/389f4c5556c581325c1a35dcb0c55fa2/href">https://medium.com/media/389f4c5556c581325c1a35dcb0c55fa2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*u2maj-laTqzQUzZFbBjQcA.png" /><figcaption>Benchmark ratios</figcaption></figure><p><strong>We nearly achieved a 3x speedup on long sequences! 🎉</strong></p><p>We didn’t even do any optimization based on the model architecture and hardware where the model is running, which is possible to do with ONNX.</p><p>Optimization could be very useful but is a deep topic that can’t be covered in this post. But it’s good to know that you can do it and that we could explore it in a future post.</p><p>Plus, our tests were done on CPU, but all benchmarks on GPU I have seen are even more impressive than benchmarks on CPU. Check <a href="https://medium.com/microsoftazure/accelerate-your-nlp-pipelines-using-hugging-face-transformers-and-onnx-runtime-2443578f4333">this great article</a> for more benchmarks on different architecture and inference configurations.</p><h3>📍 Conclusion</h3><p>To summarize, we have built a fully working NER pipeline with ONNX. We have converted a PyTorch model to ONNX and overcharged the original pipeline class to fit the ONNX model requirements. Finally, we have benchmarked the ONNX model with the original PyTorch model and compared the results.</p><p>It’s important to note that unfortunately the PyTorch model has be loaded alongside the ONNX model. This is because the Transformers pipeline requires a PyTorch model to be loaded especially for the configuration of the model.</p><p>I am looking for a way to avoid this loading of the PyTorch model, because it could create RAM issues on some systems.</p><p>The process we used to make it work is the same for every models and tasks available in Hugging Face Transformers library.</p><p>The only thing that you need to care about is if the model architecture has a configuration implemented for ONNX. You can have the <a href="https://huggingface.co/docs/transformers/serialization#onnx">full architecture list</a> in the documentation .</p><p>If the architecture you are looking for has not been implemented, you can still create it and make a <em>Pull Request</em> to the Transformers library to add it. This is exactly what I did for the CamemBERT architecture months ago. You can check out the <a href="https://github.com/huggingface/transformers/pull/14059">full PR</a> on the Transformers GitHub repository.</p><p>I hope you found this article useful and interesting. Let me know if you have any questions or face any issues. I would love to add more examples and support for other NLP tasks, so please tell me if you have any ideas or requests! 🤗</p><p>For questions or issues, please open an <a href="https://github.com/ChainYo/transformers-pipeline-onnx/issues">issue on GitHub</a> or in the comments below.</p><p><em>P.S. I’m also planning to add another benchmark section to test if the ONNX model is achieving the same results as the original model (spoiler: yes!).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b890d015723" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/nlp-transformers-pipelines-with-onnx-9b890d015723">NLP Transformers pipelines with ONNX</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>
    </channel>
</rss>