<?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 Sagar Budhathoki Magar on Medium]]></title>
        <description><![CDATA[Stories by Sagar Budhathoki Magar on Medium]]></description>
        <link>https://medium.com/@sbmagar13?source=rss-9e3c8e5630f4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vfGtiff8lCKasLRsN5OOCA.png</url>
            <title>Stories by Sagar Budhathoki Magar on Medium</title>
            <link>https://medium.com/@sbmagar13?source=rss-9e3c8e5630f4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 08:04:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sbmagar13/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[I Built an MCP Server for Hashnode]]></title>
            <link>https://sbmagar13.medium.com/introduction-619fe9b91744?source=rss-9e3c8e5630f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/619fe9b91744</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[hashnode]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sagar Budhathoki Magar]]></dc:creator>
            <pubDate>Fri, 02 May 2025 05:21:01 GMT</pubDate>
            <atom:updated>2025-05-05T08:08:13.038Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LF6i_vWMQUPc5REQJaBevg.jpeg" /></figure><p>In the rapidly evolving landscape of AI tools and integrations, the ability to extend AI capabilities through custom interfaces has become increasingly valuable. Today, I’m excited to share a project I’ve been working on: the <strong>Hashnode MCP Server</strong>. This tool bridges the gap between AI assistants and the Hashnode blogging platform, enabling seamless content creation, management, and retrieval directly through AI interactions.</p><p>In this article, I’ll walk you through what the Model Context Protocol (MCP) is, how my Hashnode MCP server works, and how you can set it up to enhance your own content workflow.</p><h3>What is the Model Context Protocol (MCP)?</h3><p>The Model Context Protocol (MCP) is a framework that allows AI models to interact with external tools and data sources. It provides a standardized way for AI assistants to access additional capabilities beyond their built-in functions.</p><p>MCP servers act as intermediaries between AI models and external services, exposing a set of tools and resources that the AI can use to perform specific tasks. This extends what AI assistants can do without requiring them to have direct API access to every possible service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9LJbIzz-N7PRRyAQ.png" /></figure><h3>Introducing the Hashnode MCP Server</h3><p>The Hashnode MCP Server is a Python-based implementation that connects AI assistants to the Hashnode API. It allows AI models to perform various operations on Hashnode blogs, including:</p><ul><li>Creating and publishing new articles</li><li>Updating existing articles</li><li>Searching for articles by keywords</li><li>Retrieving article details</li><li>Getting user information</li><li>Fetching the latest articles from a publication</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*urOfppeieayhwynY.png" /></figure><p>This means that with the Hashnode MCP Server, you can ask an AI assistant to draft a blog post, publish it to your Hashnode blog, search for related content, or update existing articles — all without leaving your conversation with the AI.</p><h3>How the Hashnode MCP Server Works</h3><p>At its core, the Hashnode MCP Server is a bridge between AI assistants and the Hashnode GraphQL API. Here’s how it works:</p><ol><li><strong>Connection</strong>: The MCP server establishes a connection with both the AI assistant and the Hashnode API.</li><li><strong>Tool Exposure</strong>: It exposes a set of tools that represent different Hashnode operations.</li><li><strong>Request Handling</strong>: When the AI assistant wants to perform an action, it sends a request to the MCP server.</li><li><strong>API Interaction</strong>: The server translates this request into the appropriate GraphQL query or mutation for the Hashnode API.</li><li><strong>Response Formatting</strong>: After receiving a response from Hashnode, the server formats it in a way that’s easy for the AI to understand and present to the user.</li></ol><p>The server is built using the FastMCP framework, which simplifies the process of creating MCP servers by handling the communication protocol details.</p><h3>Setting Up the Hashnode MCP Server</h3><h3>Prerequisites</h3><ul><li>Python 3.8 or higher</li><li>A Hashnode account with a personal access token</li><li>Basic familiarity with command-line operations</li></ul><h3>Installation Steps</h3><ol><li><strong>Clone the repository</strong>:</li></ol><pre>git clone https://github.com/sbmagar13/hashnode-mcp-server.git<br>cd hashnode-mcp-server</pre><p><strong>2. Create a virtual environment</strong>:</p><pre>python -m venv .venv source .venv/bin/activate  # On Windows: .venv\Scripts\activate</pre><p><strong>3. Install dependencies</strong>:</p><pre>pip install -r requirements.txt</pre><p><strong>4. Set up environment variables</strong>: Create a .env file in the project root with the following content:</p><pre>HASHNODE_API_URL=https://gql.hashnode.com HASHNODE_PERSONAL_ACCESS_TOKEN=your_personal_access_token</pre><p>Replace your_personal_access_token with your actual Hashnode personal access token, which you can generate in your Hashnode account settings.</p><p><strong>5. Run the server</strong>:</p><p>You have two options for running the server:</p><ul><li><strong>Option 1</strong>: Run the server manually</li></ul><pre>python run_server.py</pre><p>Or directly using the root file:</p><pre>python mcp_server.py</pre><p>The server will start and listen for connections from AI assistants. By default, it runs on <a href="http://localhost:8000/">localhost:8000</a>.</p><ul><li><strong>Option 2</strong>: Let the MCP integration handle it automatically (<strong><em>I’ll be using this</em></strong>)</li></ul><p>When properly configured in Claude Desktop or Cline VSCode extension, the MCP integration will automatically start and manage the server process for you.</p><h3>Important Note on File Structure</h3><p>When configuring your MCP server in Claude Desktop or Cline VSCode extension, you should use the root mcp_<a href="http://server.py/">server.py</a> file directly rather than the files in the hashnode_mcp directory. The hashnode_mcp directory is primarily for packaging purposes.</p><p>For example, in your configuration, point to:</p><pre>/path/to/your/hashnode-mcp-server/mcp_server.py</pre><p>And not:</p><pre>/path/to/your/hashnode-mcp-server/hashnode_mcp/mcp_server.py</pre><p>This ensures you’re using the most up-to-date version of the server with all features enabled. The root mcp_<a href="http://server.py/">server.py</a> file contains all the necessary functionality and doesn&#39;t require the package structure to operate correctly.</p><h3>Using the Hashnode MCP Server with AI Assistants</h3><p>Once your server is configured, you can connect compatible AI assistants to it. Unlike traditional API integrations that use URLs, MCP servers are typically configured directly in the AI assistant’s configuration files, as we’ll see in the next section.</p><p>The connection process generally involves:</p><ol><li>Setting up the configuration file for your AI assistant (Claude Desktop or Cline VSCode extension)</li><li>Specifying the path to your Python interpreter and the MCP server script</li><li>Providing necessary environment variables like your Hashnode personal access token</li></ol><p>After configuring the connection, you can start giving the AI commands related to your Hashnode blog. For example:</p><ul><li>“Create a new article about Python programming tips”</li><li>“Update my article with ID 12345 to fix the code examples”</li><li>“Get the latest articles from my blog”</li><li>“Search for articles about machine learning”</li></ul><p>The AI will use the MCP server to execute these commands and return the results.</p><h3>Configuring MCP on Claude Desktop and Cline VSCode Extension</h3><p>To use your Hashnode MCP Server with Claude AI, you’ll need to configure it in either Claude Desktop or the Cline VSCode extension. Here’s how to set it up in both environments:</p><h3>Configuring MCP on Cline VSCode Extension</h3><ol><li><strong>Open VS Code</strong> with the Cline extension installed.</li><li><strong>Navigate to the Cline MCP settings file</strong> located at:</li></ol><ul><li>Windows: %APPDATA%\Code\User\globalStorage\saoudrizwan.claude-dev\settings\cline_mcp_settings.json</li><li>macOS: ~/Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json</li><li>Linux: ~/.config/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json</li></ul><p><strong>3. Add your Hashnode MCP server configuration</strong> to the file:</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;hashnode&quot;: {<br>      &quot;command&quot;: &quot;/path/to/your/venv/bin/python&quot;,<br>      &quot;args&quot;: [<br>        &quot;/path/to/your/hashnode-mcp-server/mcp_server.py&quot;  // Use the root mcp_server.py file<br>      ],<br>      &quot;env&quot;: {<br>        &quot;HASHNODE_PERSONAL_ACCESS_TOKEN&quot;: &quot;your-personal-access-token&quot;<br>      }<br>    }<br>  }<br>}</pre><p>Note that the configuration points to the root mcp_<a href="http://server.py/">server.py</a> file, not the one in the hashnode_mcp directory.</p><p><strong>4. Replace the paths and token</strong> with your actual values. For example:</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;hashnode&quot;: {<br>      &quot;command&quot;: &quot;/Users/sagar/my_personal/hashnode-mcp-server/.venv/bin/python&quot;,<br>      &quot;args&quot;: [<br>        &quot;/Users/sagar/my_personal/hashnode-mcp-server/mcp_server.py&quot;<br>      ],<br>      &quot;env&quot;: {<br>        &quot;HASHNODE_PERSONAL_ACCESS_TOKEN&quot;: &quot;your-personal-access-token&quot;<br>      }<br>    }<br>  }<br>}</pre><p><strong>5. Save the file</strong> and restart VS Code or reload the window.</p><p><strong>6. Open a new Cline conversation</strong> and test the connection by asking it to interact with your Hashnode blog.</p><h3>Configuring MCP on Claude Desktop</h3><ol><li><strong>Open Claude Desktop</strong> and navigate to the configuration file:</li></ol><ul><li>Windows: %APPDATA%\Claude\claude_desktop_config.json</li><li>macOS: ~/Library/Application Support/Claude/claude_desktop_config.json</li><li>Linux: Unfortunately, Claude Desktop is not available for now (When writing this article)</li></ul><p><strong>2. Add your Hashnode MCP server configuration</strong> to the file, using the same format as for the Cline VSCode extension. Make sure to point to the root mcp_<a href="http://server.py/">server.py</a> file:</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;hashnode&quot;: {<br>      &quot;command&quot;: &quot;/path/to/your/venv/bin/python&quot;,<br>      &quot;args&quot;: [<br>        &quot;/path/to/your/hashnode-mcp-server/mcp_server.py&quot;  // Use the root mcp_server.py file<br>      ],<br>      &quot;env&quot;: {<br>        &quot;HASHNODE_PERSONAL_ACCESS_TOKEN&quot;: &quot;your-personal-access-token&quot;<br>      }<br>    }<br>  }<br>}</pre><p><strong>3. Save the file</strong> and restart Claude Desktop.</p><p><strong>4. Test the connection</strong> by asking Claude to perform a simple operation like “Get the latest articles from my Hashnode blog.”</p><h3>Troubleshooting Connection Issues</h3><p>If you encounter connection issues:</p><ol><li><strong>Verify the server is running</strong> by checking the terminal where you started the MCP server.</li><li><strong>Check the paths</strong> in your configuration are correct and point to the right Python interpreter and script.</li><li><strong>Ensure your environment variables</strong> are properly set, especially the Hashnode personal access token.</li><li><strong>Check the server logs</strong> for any error messages.</li><li><strong>Try restarting</strong> both the MCP server and the Claude application.</li></ol><h3>Example: Creating a New Article</h3><p>Let’s walk through a practical example of using the Hashnode MCP Server to create and publish a new article:</p><ol><li><strong>Start the server</strong> as described above.</li><li><strong>Connect your AI assistant</strong> to the MCP server.</li><li><strong>Ask the AI to create an article</strong>:</li></ol><pre>Create a new article titled &quot;Getting Started with Python&quot; with the following content:<br><br># Getting Started with Python<br><br>Python is one of the most popular programming languages today. In this article, we&#39;ll explore the basics of Python and how to get started.<br><br>## Installation<br><br>First, you need to install Python...<br><br>[rest of the article content]<br><br>Tags: python, programming, beginners</pre><p>4. The AI will use the MCP server to:</p><ul><li>Format the request for the Hashnode API</li><li>Send the creation request</li><li>Return the result, including the article ID and URL</li></ul><p>5. You can then ask the AI to:</p><ul><li>Publish the article immediately</li><li>Save it as a draft</li><li>Make further edits</li></ul><h3>Advanced Features</h3><h3>Timeout Handling</h3><p>The Hashnode MCP Server includes robust timeout handling for API requests. This is particularly important for operations like article creation and updates, which might take longer to process. If a request times out, the server provides helpful error messages and suggestions.</p><h3>Error Management</h3><p>The server includes comprehensive error handling to provide clear feedback when issues occur. This makes troubleshooting easier and improves the user experience.</p><h3>Pagination Support</h3><p>For operations that might return large amounts of data, like searching for articles, the server supports pagination to manage the response size and improve performance.</p><h3>Potential Use Cases</h3><p>The Hashnode MCP Server opens up numerous possibilities for content creators:</p><ol><li><strong>Automated Content Creation</strong>: Generate draft articles based on outlines or topics.</li><li><strong>Content Management</strong>: Update, organize, and manage your blog without leaving your AI assistant.</li><li><strong>Research Assistance</strong>: Search your existing content to find relevant articles or avoid duplication.</li><li><strong>Batch Operations</strong>: Perform bulk updates or content audits across your blog.</li><li><strong>Integration with Workflows</strong>: Incorporate blog publishing into broader AI-assisted workflows.</li></ol><h3>Technical Architecture</h3><p>The project is organized with a clean, modular structure:</p><ul><li>mcp_<a href="http://server.py/">server.py</a>: Root server implementation that can be run directly</li><li>hashnode_mcp/: Core package containing the modular functionality</li><li>mcp_<a href="http://server.py/">server.py</a>: Package version of the server implementation</li><li><a href="http://utils.py/">utils.py</a>: Utility functions for formatting responses and GraphQL queries</li><li>examples/: Example usage scripts</li><li>tests/: Test suite for verifying functionality</li><li>run_<a href="http://server.py/">server.py</a>: Entry point for running the server using the package version</li></ul><p>While the project includes a package structure (hashnode_mcp/) for organization and potential distribution, users can simply run the root mcp_<a href="http://server.py/">server.py</a> file directly without needing to use the package. This provides flexibility in how you choose to deploy the server.</p><p>The server uses asynchronous programming with Python’s asyncio and httpx libraries for efficient API communication. GraphQL queries and mutations are defined as constants, making them easy to maintain and update.</p><h3>Future Enhancements</h3><p>There are several exciting possibilities for future development:</p><ol><li><strong>Additional Hashnode Features</strong>: Support for more Hashnode API capabilities like managing comments, series, and newsletters.</li><li><strong>Analytics Integration</strong>: Retrieving and analyzing blog performance metrics.</li><li><strong>Content Optimization</strong>: AI-assisted SEO optimization for articles.</li><li><strong>Multi-User Support</strong>: Enhanced capabilities for team publications.</li><li><strong>Webhook Support</strong>: Responding to events from your Hashnode blog.</li></ol><h3>Conclusion</h3><p>The Hashnode MCP Server represents a powerful bridge between AI assistants and content creation on Hashnode. By enabling AI models to interact directly with your blog, it streamlines the writing and publishing process, making content creation more efficient and accessible.</p><p>Whether you’re a solo blogger looking to optimize your workflow or part of a content team seeking to scale your production, this tool offers valuable capabilities for integrating AI into your content strategy.</p><p>I’m excited to see how others in the community will use and extend this project. The code is open-source and available on GitHub, so feel free to fork it, contribute, or adapt it to your specific needs.</p><h3>Resources</h3><ul><li><a href="https://github.com/sbmagar13/hashnode-mcp-server">GitHub Repository</a></li><li><a href="https://apidocs.hashnode.com/">Hashnode API Documentation</a></li><li><a href="https://modelcontextprotocol.io/introduction">Model Context Protocol Documentation</a></li></ul><p>Thanks!</p><p><em>Have you integrated AI tools into your content workflow? Share your experiences in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=619fe9b91744" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup Local GitLab Server, Runner, CI/CD, with Nginx Configuration]]></title>
            <link>https://sbmagar13.medium.com/setup-local-gitlab-server-runner-ci-cd-with-nginx-configuration-486f57612133?source=rss-9e3c8e5630f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/486f57612133</guid>
            <category><![CDATA[runners]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[Sagar Budhathoki Magar]]></dc:creator>
            <pubDate>Wed, 15 Jun 2022 09:39:49 GMT</pubDate>
            <atom:updated>2022-06-16T05:24:02.186Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXx3VXX42F3AMHcgAQwrcQ.png" /><figcaption>Setup Local GitLab Server, Runner, CI/CD, with Nginx Configuration</figcaption></figure><p>In this article, I’m gonna walk you through configuring on-premise GitLab Server, GitLab Runner, and CI/CD for containerized microservices. We’ll deploy and run all the containerized microservices on the same machine where GitLab and Runner are set up.</p><h3>GitLab Server</h3><p>GitLab allows you to host an on-premise GitLab server(or Git repository) that can be accessed from LAN(or WAN if you have a public IP address).</p><p>We can install the GitLab server either on a container environment like docker or on the host machine. In this, I’ll install it on the host machine (i.e. Ubuntu 20.04 machine).</p><h3>Prerequisites</h3><p>Open the terminal on the server(machine) and run the following commands:</p><pre>$ sudo apt update <br>$ sudo apt upgrade -y</pre><p>After running these, let’s install some dependencies by running:</p><pre>$ sudo apt install -y ca-certificates curl openssh-server tzdata perl</pre><p><strong><em>Optionally,</em></strong> if you want to use the same system or server to send email notifications to users, then you can install postfix, an open-source mail transfer agent.</p><pre>$ sudo apt install postfix -y</pre><p>While installing Postfix you’ll be asked to set it up, select ‘ <strong>Internet Site’</strong> option and add your DNS for mail name and configure other required things.</p><p>Further, you’ll need to install the mailutils package:</p><pre>$ sudo apt install mailutils</pre><p><strong><em>OR,</em></strong> you can set up SMTP server to send email notifications instead of Postfix. To do this, you need to first install GitLab and edit <strong><em>/etc/gitlab/gitlab.rb.</em></strong></p><p>As the GitLab is not available on the base repository of Ubuntu. You need to add the GitLab package repository and GPG key by running the following command:</p><pre>$ curl -sS &lt;https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.deb.sh&gt; | sudo bash</pre><p>Here, I’ve added a package repository for GitLab Enterprise Edition, you can also add for GitLab Community Edition.</p><p>After adding the repository package, you can see the repository contents in:</p><pre>$ cat /etc/apt/sources.list.d/gitlab_gitlab-ce.list</pre><p>Now update the system again and install GitLab EE on the machine:</p><pre>$ sudp apt update $ sudp apt install gitlab-ee</pre><p>You’ll see output similar:</p><pre>It looks like GitLab has not been configured yet; skipping the upgrade script.         *.                  *.       ***                 ***      *****               *****     .******             *******     ********            ********    ,,,,,,,,,***********,,,,,,,,,   ,,,,,,,,,,,*********,,,,,,,,,,,   .,,,,,,,,,,,*******,,,,,,,,,,,,       ,,,,,,,,,*****,,,,,,,,,.          ,,,,,,,****,,,,,,             .,,,***,,,,                 ,*,.          _______ __  __          __     / ____(_) /_/ /   ____ _/ /_    / / __/ / __/ /   / __ `/ __ \\   / /_/ / / /_/ /___/ /_/ / /_/ /   \\____/_/\\__/_____/\\__,_/_.___/     Thank you for installing GitLab!</pre><p>Now edit <strong><em>external_url</em></strong> in /etc/gitlab/gitlab.rb to set. You can also configure other parameters. Replace <a href="http://gitlab.example.com/">gitlab.example.com</a> with the valid domain name.</p><pre>$ sudo nano /etc/gitlab/gitlab.rb external_url &quot;&lt;http://gitlab.example.com&gt;&quot;</pre><p>OR, If you’re not going to use DNS. You can simply use your server’s IP address like in my case my local machine’s IP as:</p><pre>external_url &quot;&lt;http://10.10.5.55&gt;&quot;</pre><p>When done start GitLab by running the following command:</p><pre>$ sudo gitlab-ctl reconfigure</pre><p>After successful reconfiguration, check the status of GitLab:</p><pre>$ sudo gitlab-ctl status</pre><p>The output will be similar:</p><pre>run: alertmanager: (pid 92581) 18s; run: log: (pid 92343) 80s <br>run: gitaly: (pid 92590) 18s; run: log: (pid 91561) 189s <br>run: gitlab-exporter: (pid 92551) 20s; run: log: (pid 92078) 98s <br>run: gitlab-kas: (pid 92520) 22s; run: log: (pid 91845) 175s <br>run: gitlab-workhorse: (pid 92531) 21s; run: log: (pid 91985) 117s <br>run: grafana: (pid 92610) 17s; run: log: (pid 92471) 38s <br>run: logrotate: (pid 91486) 202s; run: log: (pid 91494) 201s <br>run: nginx: (pid 91993) 114s; run: log: (pid 92013) 110s <br>run: node-exporter: (pid 92540) 21s; run: log: (pid 92049) 104s <br>run: postgres-exporter: (pid 92601) 18s; run: log: (pid 92367) 76s <br>run: postgresql: (pid 91693) 184s; run: log: (pid 91704) 183s <br>run: prometheus: (pid 92560) 20s; run: log: (pid 92297) 88s <br>run: puma: (pid 91904) 132s; run: log: (pid 91917) 129s <br>run: redis: (pid 91521) 196s; run: log: (pid 91538) 193s <br>run: redis-exporter: (pid 92553) 20s; run: log: (pid 92217) 94s <br>run: sidekiq: (pid 91922) 126s; run: log: (pid 91934) 122s</pre><h4>Step-5: GitLab Web Interface</h4><p>Once the installation completes, open your URL set up as external_url <a href="http://gitlab.example.com/"><strong><em>http://gitlab.example.com</em></strong></a> on your browser. In my case, I have set it up locally using my server’s IP address. So, I can access it through *** <a href="http://10.10.5.55/***">http://10.10.5.55/***</a></p><p>Now, first, you can log in as a root user using username as <strong><em>root</em></strong> and password from <strong><em>/etc/gitlab/intial_root_password</em></strong>. (The password for root user is randomly generated and stored for 24 hours only.)</p><p>To check the password run the following:</p><pre>$ cat /etc/gitlab/initial_root_password <br># WARNING: This value is valid only in the following conditions <br># 1. If provided manually (either via `GITLAB_ROOT_PASSWORD` environment variable or via `gitlab_rails[&#39;initial_root_password&#39;]` setting in `gitlab.rb`, it was provided before database was seeded for the first time (usually, the first reconfigure run). <br># 2. Password hasn&#39;t been changed manually, either via UI or via command line. <br># # If the password shown here doesn&#39;t work, you must reset the admin password following &lt;https://docs.gitlab.com/ee/security/reset_user_password.html#reset-your-root-password&gt;. <br>Password: dfdfkOtOjWp7v70OjkjtadsdfsafsadnSJAhcDbCNo9nTNGVC5UoSCyE= <br># NOTE: This file will be automatically deleted in the first reconfigure run after 24 hours.</pre><p>Copy the password and login:</p><p>After logging in, first reset the root user password. To do this, go to root user profile <strong>&gt; Preferences &gt; Password</strong>. Change.</p><p>You can start, stop or restart all the GitLab components by using the following commands:</p><pre>$ sudo gitlab-ctl start <br>$ sudo gitlab-ctl restart <br>$ sudo gitlab-ctl stop</pre><p>Also, you can start individual components also:</p><pre>$ sudo gitlab-ctl restart prometheus ok: run: prometheus: (pid 2673) 8s</pre><p>This is all you need to set up GitLab Server on Ubuntu Server.</p><h3>GitLab Runner</h3><p>GitLab Runner can be installed:</p><ul><li>In a container(Docker, K8s, or OpenShift)</li><li>By downloading binary manually</li><li>By using repository packages</li></ul><p><strong><em>In this, we’ll be installing Runner on the local machine as I have to deploy microservices on the same machine where GitLab and Runner will be running.</em></strong></p><p>If you’re using a different server for a runner than that GitLab is configured, you need to first ssh into the server and follow the following steps. Otherwise, you can directly follow from step-1.</p><p>First, add the official GitLab Runner Repository using the below command. You can find the Official Repository <a href="https://docs.gitlab.com/runner/install/linux-repository.html">here</a>.</p><pre>$ curl -L &quot;https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh&quot; | sudo bash</pre><p>Run the following command to install GitLab Runner:</p><pre>$ sudo apt update <br>$ sudo apt install gitlab-runner</pre><p><strong>(Optional) </strong>To install a specific version:</p><pre>$ sudo apt install gitlab-runner=10.0.0</pre><p>After Installation, check the GitLab Runner version:</p><pre>$ sudo gitlab-runner --version</pre><p>Output:</p><pre>Version: 15.0.0 Git revision: febb2a09 Git branch: 15-0-stable GO version: go1.17.7 Built: 2022-05-19T20:03:43+0000 OS/Arch: linux/amd64</pre><p>To check the status:</p><pre>$ sudo gitlab-runner status</pre><p>Output:</p><pre>Runtime platform arch=amd64 os=linux pid=29368 revision=febb2a09 version=15.0.0 gitlab-runner: Service is running!</pre><p>You can Start, Stop, and Restart GitLab Runner by running the following:</p><pre>$ sudo gitlab-runner start<br>$ sudo gitlab-runner stop <br>$ sudo gitlab-runner restart</pre><h4>Step-3: Grant Permission to GitLab Runner User</h4><p>After successful installation, you’ll see a <strong><em>gitlab-runner</em></strong> user in directory. And you need to grant the sudo permission to the gitlab-runner user. For this, open visudo file:</p><pre>$ sudo visudo</pre><p>Add the following in <strong>sudoers</strong> group and set <strong>NOPASSWD</strong> also as shown below:</p><pre>gitlab-runner ALL=(ALL:ALL) ALL<br>gitlab-runner ALL=(ALL) NOPASSWD: ALL</pre><p>Output:</p><pre>GNU nano 4.8 /etc/sudoers.tmp # <br># This file MUST be edited with the &#39;visudo&#39; command as root. <br># # Please consider adding local content in /etc/sudoers.d/ instead of directly modifying this file. <br># # See the man page for details on how to write a sudoers file. <br># Defaults env_reset Defaults mail_badpass Defaults secure_path=&quot;/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin&quot; <br># Host alias specification <br># User alias specification <br># Cmnd alias specification <br># User privilege specification root ALL=(ALL:ALL) ALL gitlab-runner ALL=(ALL:ALL) ALL <br># Members of the admin group may gain root privileges <br>%admin ALL=(ALL) ALL <br># Allow members of group sudo to execute any command <br>%sudo ALL=(ALL:ALL) ALL <br># See sudoers(5) for more information on &quot;#include&quot; directives: #includedir /etc/sudoers.d <br>gitlab-runner ALL=(ALL) NOPASSWD: ALL</pre><p>Now, it’s time to register GitLab Runner to GitLab Server which was set up before.</p><ul><li>Log in to GitLab Server with username and password(create a user if you haven’t already and create a project).</li><li>Navigate to <strong>Settings</strong> and click on <strong>CI/CD</strong> and click on <strong>Expand</strong> of <strong>Runners</strong> section.</li></ul><pre>$ gitlab-runner register --name project-name-runner --url http://10.10.5.55/ --registration-token GR1348941Ah6PxTBi5S5asJ7fzYSa</pre><p>OR,</p><pre>$ sudo gitlab-runner register</pre><p><strong>Note:</strong> During registration, you’ll be asked some questions such as tags, name, executor etc., Select executor as <strong><em>shell</em></strong> (If you’re using docker you can select or <strong><em>docker+machine</em></strong> as an executor). Since I’m deploying on the same machine I will select executor as <strong><em>shell</em></strong>. Or you can select whatever as per your requirements.</p><p>Check on the GitLab <strong>CI/CD</strong> &gt; <strong>Runners</strong> section, you’ll see the newly registered runner.</p><ul><li>Go to <strong>Settings</strong> &gt; <strong>CI/CD </strong>&gt;<strong> Runners (Click on Expand)</strong></li><li>Click on the edit icon of the newly created runner. And check <strong><em>Run untagged jobs box</em></strong>.</li></ul><h4>Error: This job is stuck because the project doesn’t have any runners online assigned to it. Go to Runners page.</h4><p>It’s due to tags you’ve added during configuration, but not added to your CI/CD job. To solve this, you can add tags to your CICD jobs Or do the following:</p><p>And here it is, you have successfully installed and registered gitlab-runner for your projects.</p><h3>Uninstalling GitLab Runner</h3><p>To completely remove gitlab-runner run the following commands:</p><pre>$ sudo apt purge --autoremove -y gitlab-runner <br>$ sudo apt-key del 51312f3f <br>$ sudo rm -rf /etc/apt/sources.list.d/runner_gitlab-runner.list <br>$ sudo deluser --remove-home gitlab-runner <br>$ sudo rm -rf /etc/gitlab-runner</pre><h3>CI/CD for Containerized Applications</h3><p>My project structure:</p><pre>. <br>├── Dockerfile <br>├── .env <br>├── .git <br>├── .gitignore <br>├── .gitlab-ci.yml <br>├── package.json <br>├── README.md <br>├── .sample.env <br>└── src</pre><p>Now it’s time to configure CI/CD for containerized applications to deploy on the same machine where the GitLab Runner is set up. For this, let’s configure <strong><em>.gitlab-ci.yml</em></strong> file as:</p><pre>stages: <br>    - build <br>    - deploy <br>before_script: <br>    - IMAGE_TAG=&quot;$(echo $CI_COMMIT_SHA | head -c 8)&quot; <br>dev-build-job: <br>    stage: build <br>    script: <br>        # - export DOCKER_HOST=tcp://0.0.0.0:2375/ <br>        - cp $ENV_FILE .env <br>        - docker build -t $APP_NAME:latest .                 <br>    only: <br>        - dev <br>    tags: <br>        - cloudyfox <br>dev-deploy-job: <br>    stage: deploy <br>    script: <br>        - docker container rm -f $APP_NAME || true <br>        - docker run -d -p $PORT:$PORT --name $APP_NAME $APP_NAME:latest <br>    only: <br>        - dev <br>    tags: <br>        - cloudyfox</pre><p>Here, the pipeline has two stages: <strong>build</strong> and <strong>deploy</strong>. IMAGE_TAG variable is used to tag docker images later.</p><p>In the build stage, <strong>$ENV_FILE</strong> variable is copied from the GitLab variables to the project root directory as it is in the .gitignore file. So, create ENV_FILE File variable with the value of .env file. To do so, Go to GitLab Server and navigate to <strong>Settings</strong> &gt; <strong>CI/CD</strong> &gt; <strong>Variables (Click on Expand)</strong>. And add a new File variable.</p><p>Also, I have added APP_NAME and PORT variables as they are required for me.</p><p>In the deploy stage, the docker built in the previous build stage is deployed by deleting a container of the same name if running which is deployed then deploys our docker container.</p><p>In this way, you can deploy all the containerized microservices to the machine. Whenever you push the changes to the remote repository, a new docker version will be built and run on the machine(where all GitLab, and Runner are configured.).</p><h3>Configuring Nginx As a Load Balancer</h3><p>Let’s say you have successfully run all the micro applications using different ports on the server. Then you have to set up the Nginx load balancer to handle the requests. So that you can handle it in accordance with the users’ requests.</p><p>Since my GitLab server is running in the same local host, I need to use a different port to serve microservices. So, let’s start by configuring NGINX on the server.</p><pre>$ sudo apt update <br>$ sudo -H apt install nginx-common nginx-full</pre><p>Start Nginx:</p><p>And start Nginx then check the status:</p><pre>$ sudo systemctl start nginx <br>$ sudo systemctl status nginx</pre><p>Output:</p><pre>● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2022-06-15 09:05:01 +0545; 5h 20min ago Docs: man:nginx(8) Process: 875 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, stat&gt; Process: 1065 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUC&gt; Main PID: 1066 (nginx) Tasks: 5 (limit: 9408) Memory: 4.7M CGroup: /system.slice/nginx.service ├─1066 nginx: master process /usr/sbin/nginx -g daemon on; master_process on; ├─1067 nginx: worker process ├─1068 nginx: worker process ├─1069 nginx: worker process └─1070 nginx: worker process</pre><p>You can Start, Stop, and Restart Nginx as:</p><pre>$ sudo systemctl start nginx<br>$ sudo systemctl stop nginx <br>$ sudo systemctl restart nginx</pre><p>To configure Nginx as Loadbalancer, first, remove default conf file, <strong><em>/etc/nginx/sites-enabled/default</em></strong> and create <strong><em>/etc/nginx/conf.d/lb.conf </em></strong>with following content(change as your requirements)</p><p>I’ll be routing all microservices which are running in different ports to <a href="http://10.10.5.55:9999."><strong><em>http://10.10.5.55:9999</em></strong>.</a> (as <a href="http://10.10.5.55/"><strong><em>http://10.10.5.55</em></strong></a> (port 80) is already used by the GitLab server)</p><p>The requests for different services will be load balanced as:</p><pre>upstream user { <br>    server 127.0.0.1:5001; <br>} <br>upstream content { <br>    server 127.0.0.1:5002; <br>} <br>upstream discussion { <br>    server 127.0.0.1:5003; <br>} <br>upstream payment { <br>    server 127.0.0.1:5004; <br>} <br>upstream read { <br>    server 127.0.0.1:5007; <br>} <br>upstream subscription { <br>    server 127.0.0.1:5005; <br>} <br>upstream card { <br>    server 127.0.0.1:5006; <br>} </pre><pre>server { <br>    listen 9999; <br>    server_name localhost; <br>    location /api/user { <br>        proxy_pass http://user/api/user; <br>    } <br>    location /api/content { <br>        proxy_pass http://content/api/content; <br>    } <br>    location /api/discussion { <br>        proxy_pass http://discussion/api/discussion; <br>    } <br>    location /api/payment { <br>        proxy_pass http://payment/api/payment; <br>    } <br>    location /api/read { <br>        proxy_pass http://read/api/read; <br>    } <br>    location /api/subscription { <br>        proxy_pass http://subscription/api/subscription; <br>    } <br>    location /api/card { <br>        proxy_pass http://card/api/card; <br>    } <br>}</pre><p>Here, every service has a different request URI, and all will be routed accordingly.</p><p>server_name is your domain name(if you have configured it previously), for me it’s <strong><em>localhost</em></strong>.</p><p>And test the syntax:</p><pre>$ sudo nginx -t</pre><p>Output:</p><pre>nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful</pre><p>Now, restart the Nginx service:</p><pre>$ sudo service nginx restart</pre><p>Go to the browser and run<strong><em> http://10.10.5.55:9999/&lt;microservice_endpoint&gt;</em></strong>. You’ll get successful output. (Change <strong><em>10.10.5.55</em></strong> with your server’s IP or domain name)</p><p>In my case:</p><p>And that’s all for Nginx Loadbalancer(reverse-proxy) configuration.</p><h3>Conclusion</h3><p>Here you go, you have successfully configured GitLab server, GitLab Runner, CI/CD for dockerized microservices, and NGINX as a load balancer(reverse-proxy) at once.</p><p>Thank you!</p><p><em>Originally published at </em><a href="https://scanskill.com/devops/setup-local-gitlab-server-runner-nginx/"><em>https://scanskill.com</em></a><em> on June 15, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=486f57612133" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Install MongoDB on EC2 Instance — Solved Connection Issue From Public DNS — ScanSkill]]></title>
            <link>https://sbmagar13.medium.com/install-mongodb-on-ec2-instance-solved-connection-issue-from-public-dns-scanskill-b2d89dd10b9b?source=rss-9e3c8e5630f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2d89dd10b9b</guid>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Sagar Budhathoki Magar]]></dc:creator>
            <pubDate>Mon, 04 Apr 2022 08:04:04 GMT</pubDate>
            <atom:updated>2022-04-04T14:50:00.470Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Install MongoDB on EC2 Instance (AWS)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w2JYF4OL6JnXY1c35gCAfQ.png" /><figcaption>Install MongoDB on EC2 Instance</figcaption></figure><p>In this article, we’re going to install MongoDB on EC2 instance in AWS. Installing MongoDB on EC2 via aptitude is very simple. To install MongoDB on your EC2 Ubuntu system you can follow the official MongoDB-org package, which is maintained by MongoDB Inc.</p><h3>Prerequisites</h3><p>AWS Account</p><h3>Launch EC2 Instance</h3><p>Pick any AMI (for this I am using <strong><em>ubuntu 20.04)</em></strong>, select desired <strong><em>instance type</em></strong>, <strong><em>Storage</em></strong>, configure proper VPC, subnet, etc.</p><p>Create or pick an existing security group that has SSH port enabled in the inbound rule.</p><p>Launch instance with creating new or using existing keypair. For detail instructions on launching instances, follow the <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/launching-instance.html">official documentation</a>.</p><h3>Install MongoDB on EC2</h3><p>SSH into the server instance by running the following command: (Make sure your instance’s private key directory)</p><pre>$ chmod 400 &lt;keypair name&gt; $ ssh -i ~/dir/&lt;keypair name&gt; ubuntu@&lt;EC2 instance IP address&gt;</pre><p>Now, import a private key repository package for MongoDB to install on your server:</p><pre>$ wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | sudo apt-key add -</pre><p>And add sources to your system:</p><pre>$ echo &quot;deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse&quot; | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list</pre><p>Update the package:</p><pre>$ sudo apt update</pre><p>Now you’re ready to install MongoDB on your system:</p><pre>$ sudo apt install -y mongodb-org</pre><p>You’ve successfully installed MongoDB on your system, let’s start the mongo service and verify:</p><pre>$ sudo systemctl start mongod $ sudo systemctl status mongod</pre><p>You can enable the service to start every time you reboot the system by running the following command:</p><pre>$ sudo systemctl enable mongod</pre><p>Here, you’ve successfully installed MongoDB on your Ubuntu Server in AWS.</p><h3>Connect To Remote MongoDB Server</h3><p>In this section, we’ll set up user authentication for mongo so that we can read and write to the MongoDB server.</p><h3>User Setup</h3><p>SSH into the server and type mongo to run mongo shell. For this tutorial, I&#39;m gonna set up a user sagar and give read-write access to the example_db database.</p><pre>use example_db</pre><pre>db.createUser({ user: &#39;sagar&#39;, pwd: &#39;my-password&#39;, roles: [{ role: &#39;readWrite&#39;, db:&#39;example_db&#39;}] })</pre><h3>Enable MongoDB access to all IPs</h3><p>Edit /etc/mongod.conf file:</p><pre>$ sudo nano /etc/mongod.conf</pre><p>Look for the net line and comment out the bindIp line under it, which is currently limiting MongoDB connections to .</p><p><strong><em>Note: </em></strong><em>do not comment out the </em><em>bindIp line without enabling authorization, authorization can be enabled by un-comenting </em><em># security section and adding </em><em>authorization: &#39;enabled&#39;.</em></p><pre># network interfaces net: port: 27017 # bindIp: 127.0.0.1 &lt;-- comment out this</pre><pre>security: authorization: &#39;enabled&#39;</pre><h3>Open port 27017 on your EC2 server</h3><p>Go to Security Groups of your instance.<br>Edit the inbound rule on your server&#39;s security group by allowing Custom TCP on port 27017 (you can set traffic source as anywhere 0.0.0.0/0 or as per your requirements).</p><h3>Restart and Check Status of Mongo Daemon</h3><p>Restart:</p><pre>$ sudo service mongod restart</pre><p>Check the status:</p><pre>$ sudo service mongod status</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/0*MMejjoctTVpev-Wq" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/0*3GK13FWB_F5owvFH" /></figure><p>If anything goes wrong or not, you can always check the logs:</p><pre>$ sudo tail -f /var/log/mongodb/mongod.log</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MZUAJAMsTODluIW_" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YtcdH0plNzgCJVF7" /></figure><h3>Accessing MongoDB</h3><h4>Using Mongo Shell:</h4><p>Access the remote Mongo Database we just set up:</p><pre>$ mongo -u sagar -p my-password &lt;Instance&#39;s public IP&gt;/example_db</pre><p>Here you go, now you can read and write within the example_db database without ssh.</p><h4>Using Mongo Client:</h4><pre>Host = mongodb://sagar:my-password@&lt;Instance&#39;s public IP&gt;/example_db Port = 27017 (default)</pre><h3>Fix-1 Cannot access from other IPs</h3><p>By default, the MongoDB server only allows connections from localhost(127.0.0.1). So, if you face an issue connecting the database, you can fix this by binding all IPs.</p><p>To allow connections from elsewhere in your VPC edit /etc/mongod.conf:</p><p>Look for the net line and replace bindIp value with 0.0.0.0, ::, to bind all IPV4 and IPV6 addresses, which is currently limiting MongoDB connections to localhost.</p><pre># network interfaces net: port: 27017 bindIp: 127.0.0.1 # change this to 0.0.0.0, to bind to all IP addresses</pre><p><strong><em>Note:</em></strong><em> make sure you have enabled authorization on </em><em>security: section by adding </em><em>authorization: &#39;enabled&#39;(as we&#39;ve already done above), to forbid the access to mongo database on your server</em>.</p><p>Restart the mongo daemon(mongod).</p><p>Now, you’re good to go ahead.</p><h3>Conclusion</h3><p>In this tutorial, you have successfully learned to install MongoDB on EC2 and access from shell as well as Mongo clients.</p><p><em>Originally published at </em><a href="https://scanskill.com/aws/install-mongodb-on-ec2-instance/"><em>https://scanskill.com</em></a><em> on April 4, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2d89dd10b9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Django application with Docker, Postgres, Gunicorn, NGINX (Part-2)]]></title>
            <link>https://sbmagar13.medium.com/dockerizing-django-application-with-postgres-gunicorn-nginx-7975aea1e531?source=rss-9e3c8e5630f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7975aea1e531</guid>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Sagar Budhathoki Magar]]></dc:creator>
            <pubDate>Sat, 25 Dec 2021 17:10:22 GMT</pubDate>
            <atom:updated>2022-04-05T13:51:40.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3QuQvvBxQ0aXQmCWB3Wjjw.png" /><figcaption>Deploying Django application with Docker, Postgres, Gunicorn, NGINX</figcaption></figure><p>Continued…<a href="https://sbmagar.medium.com/django-with-docker-postgres-gunicorn-and-nginx-415402814836"> part-1</a></p><h3>Gunicorn</h3><p>Now, install Gunicorn. It’s production grade WSGI server.</p><p>For now, since we want to use default django’s built-in server, create production compose file:</p><pre>version: &#39;3.5&#39;</pre><pre>services:<br>    app:<br>        build:<br>            context: .<br>        command: gunicorn personal.wsgi:application --bind 0.0.0.0:8000<br>        volumes:<br>            - static_data:/vol/static<br>        ports:<br>            - &quot;8000:8000&quot;<br>        restart: always<br>        env_file:<br>            - .env.prod<br>        depends_on:<br>            - app-db</pre><pre>    app-db:<br>        image: postgres:12-alpine<br>        ports:<br>            - &quot;5432:5432&quot;<br>        restart: always<br>        volumes:<br>            - postgres_data:/var/lib/postgresql/data:rw<br>        env_file:<br>            - .env.prod<br>volumes:<br>    static_data:<br>    postgres_data:</pre><p>Here, we’re using commang gunicorn instead of django server command. we can static_data volume as it’s not needed in production. For now, let’s create .env.prod file for environemental variables:</p><pre>DEBUG=0<br>DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]<br>DB_ENGINE=django.db.backends.postgresql_psycopg2<br>POSTGRES_HOST_AUTH_METHOD=trust<br>POSTGRES_USER=sagar<br>POSTGRES_PASSWORD=********<br>POSTGRES_DB=portfolio_db_prod<br>POSTGRES_HOST=app-db<br>POSTGRES_PORT=5432</pre><p>Add both files to .gitignore file if you want to keep them out from version control. Now, down all containers with -v flag, -v flag removes associated volumes:</p><pre>$ docker-compose down -v</pre><p>Then, re-build images and run the containers:</p><pre>$ docker-compose -f docker-compose.prod.yml up --build</pre><p>Run with -d flag if you wan’t to run services in background. If any error when running, check errors with command:</p><pre>$ docker-compose -f docker-compose.prod.yml logs -f</pre><p>Wow, let’s create production Dockerfile as Dockerfile.prod with production <a href="http://entrypoint.prod.sh/">entrypoint.prod.sh</a> file inside scripts directory of the root. <a href="http://entrypoint.prod.sh/">entrypoint.prod.sh</a> script file:</p><pre>#!/bin/sh<br><br>if [ &quot;$DATABASE&quot; = &quot;postgres&quot; ]<br>then<br>    echo &quot;Waiting for postgres...&quot;<br>    while ! nc -z &quot;$POSTGRES_HOST&quot; &quot;$POSTGRES_PORT&quot;; do<br>      sleep 0.1<br>    done<br>    echo &quot;PostgreSQL started&quot;<br>fi<br><br>exec &quot;$@&quot;</pre><p>Dockerfile.prod file with scripts permission:</p><pre>FROM python:3.8.9-alpine as builder<br><br>ENV PYTHONDONTWRITEBYTECODE 1<br>ENV PYTHONNUNBUFFERED 1<br><br>RUN apk update<br>RUN apk add postgresql-dev gcc python3-dev musl-dev libc-dev linux-headers<br><br>RUN apk add jpeg-dev zlib-dev libjpeg<br><br>RUN pip install --upgrade pip<br>COPY ./requirements.txt .<br>RUN pip wheel --no-cache-dir --no-deps --wheel-dir /wheels -r requirements.txt<br><br>#### FINAL ####<br><br>FROM python:3.8.9-alpine<br><br>RUN mkdir /app<br>COPY . /app<br>WORKDIR /app<br><br>RUN apk update &amp;&amp; apk add libpq<br>COPY --from=builder ./wheels /wheels<br>COPY --from=builder ./requirements.txt .<br>RUN pip install --no-cache /wheels/*<br>#RUN pip install -r requirements.txt<br><br>COPY ./scripts /scripts<br>RUN chmod +x /scripts/*<br><br>RUN mkdir -p /vol/media<br>RUN mkdir -p /vol/static<br><br>#RUN adduser -S user<br><br>#RUN chown -R user /vol<br><br>RUN chmod -R 755 /vol<br>#RUN chown -R user /app<br>#RUN chmod -R 755 /app<br><br>#USER user<br><br>ENTRYPOINT [&quot;/scripts/entrypoint.prod.sh&quot;]</pre><p>Here we used a multi-stage build as it reduces final image size. ‘builder’ is a temporary image that’s used just to build python wheels with dependencies, that are copied to the Final stage. we can create a non-root user. Because that is the best practice to be safe from attackers. Now, update the compose production file with docker production file:</p><pre>version: &#39;3.5&#39;<br><br>services:<br>    app:<br>        build:<br>            context: .<br>            dockerfile: Dockerfile.prod<br>        command: gunicorn personal.wsgi:application --bind 0.0.0.0:8000<br>        volumes:<br>            - static_data:/vol/static<br>        expose:<br>            - &quot;8000:8000&quot;<br>        restart: always<br>        env_file:<br>            - .env.prod<br>        depends_on:<br>            - app-db<br><br>    app-db:<br>        image: postgres:12-alpine<br>        ports:<br>            - &quot;5432:5432&quot;<br>        restart: always<br>        volumes:<br>            - postgres_data:/var/lib/postgresql/data:rw<br>        env_file:<br>            - .env.prod<br>volumes:<br>    static_data:<br>    postgres_data:</pre><p>Rebuild, and run:</p><pre>$ docker-compose -f docker-compose.prod.yml down -v<br>$ docker-compose -f docker-compose.prod.yml up -d --build<br>$ docker-compose -f docker-compose.prod.yml exec app python manage.py migrate --</pre><h3>Ngnix</h3><p>Nginx really gives you the ultimate power. You can do whatever you want. Let’s add Nginx to act as a reverse proxy for Gunicorn. Add service on docker-compose file (production):</p><pre>version: &#39;3.5&#39;<br><br>services:<br>    app:<br>        build:<br>            context: .<br>            dockerfile: Dockerfile.prod<br>        command: gunicorn personal.wsgi:application --bind 0.0.0.0:8000<br>        volumes:<br>            - static_data:/vol/static<br>            - media_data: /vol/media<br>        ports:<br>            - &quot;8000:8000&quot;<br>        restart: always<br>        env_file:<br>            - .env.prod<br>        depends_on:<br>            - app-db<br><br>    app-db:<br>        image: postgres:12-alpine<br>        ports:<br>            - &quot;5432:5432&quot;<br>        restart: always<br>        volumes:<br>            - postgres_data:/var/lib/postgresql/data:rw<br>        env_file:<br>            - .env.prod<br><br>    proxy:<br>        build: ./proxy<br>        volumes:<br>            - static_data:/vol/static<br>            - media_data:/vol/media<br>        restart: always<br>        ports:<br>            - &quot;8008:80&quot;<br>        depends_on:<br>            - app<br>volumes:<br>    static_data:<br>    media_data:<br>    postgres_data:</pre><p>Inside root directory create a proxy(whatever you want to name it) directory and add a configuration file, in my case I have created default.conf file as:</p><pre>server {<br>    listen 80;<br><br>    location /static {<br>        alias /vol/static;<br>    }<br><br>    location /media {<br>        alias /vol/media;<br>    }<br><br>    location / {<br>        uwsgi_pass app:8000;<br>        include /etc/nginx/uwsgi_params;<br>    }<br>}</pre><p>And create uwsgi_params file for this.</p><pre>uwsgi_param QUERY_STRING $query_string;<br>uwsgi_param REQUEST_METHOD $request_method;<br>uwsgi_param CONTENT_TYPE $content_type;<br>uwsgi_param CONTENT_LENGTH $content_length;<br>uwsgi_param REQUEST_URI $request_uri;<br>uwsgi_param PATH_INFO $document_uri;<br>uwsgi_param DOCUMENT_ROOT $document_root;<br>uwsgi_param SERVER_PROTOCOL $server_protocol;<br>uwsgi_param REMOTE_ADDR $remote_addr;<br>uwsgi_param REMOTE_PORT $remote_port;<br>uwsgi_param SERVER_ADDR $server_addr;<br>uwsgi_param SERVER_PORT $server_port;<br>uwsgi_param SERVER_NAME $server_name;</pre><p>Also, add a Dockerfile inside the proxy directory for Nginx configuration:</p><pre>FROM nginxinc/nginx-unprivileged:1-alpine<br><br>COPY ./default.conf /etc/nginx/conf.d/default.conf<br>COPY uwsgi_params /etc/nginx/uwsgi_params</pre><p>You can use expose instead of ports in docker-compose.prod.yml file for app service:</p><pre>app:<br>        build:<br>            context: .<br>            dockerfile: Dockerfile.prod<br>        command: gunicorn personal.wsgi:application --bind 0.0.0.0:8000<br>        volumes:<br>            - static_data:/vol/static<br>            - media_data:/vol/media<br>        expose:<br>            - 8000<br>        restart: always<br>        env_file:<br>            - .env.prod<br>        depends_on:<br>            - app-db</pre><p>Again, re-build run and try:</p><pre>$ docker-compose -f docker-compose.prod.yml down -v<br>$ docker-compose -f docker-compose.prod.yml up -d --build<br>$ docker-compose -f docker-compose.prod.yml exec web python manage.py migrate --noinput<br>$ docker-compose -f docker-compose.prod.yml exec web python manage.py collectstatic --no-input --clear</pre><p>Ensure the app is running in <a href="http://localhost:8008/">localhost:8008</a>.</p><p>That’s it.</p><p>Thank You!</p><p>Previous: <a href="https://sbmagar.medium.com/django-with-docker-postgres-gunicorn-and-nginx-415402814836">Part-1</a></p><p><em>Originally published at </em><a href="https://blog.budhathokisagar.com.np/django-postgres-gunicorn-nginx-with-docker-part-2"><em>https://blog.budhathokisagar.com.np</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7975aea1e531" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django with Docker, Postgres, Gunicorn, and NGINX (Deploy Django Application)]]></title>
            <link>https://sbmagar13.medium.com/django-with-docker-postgres-gunicorn-and-nginx-415402814836?source=rss-9e3c8e5630f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/415402814836</guid>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sagar Budhathoki Magar]]></dc:creator>
            <pubDate>Sat, 25 Dec 2021 16:59:07 GMT</pubDate>
            <atom:updated>2022-04-05T13:48:18.196Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3QuQvvBxQ0aXQmCWB3Wjjw.png" /><figcaption>Django with Docker, Postgres, Gunicorn, and NGINX</figcaption></figure><h3>Prerequisites</h3><p>First, ensure the following is installed on your machine:</p><ul><li>Python 3.7 or higher(I’ve used python 3.8.9)</li><li>Python pip</li><li>Git and a GitHub account</li><li>Docker and docker-compose</li></ul><p>Let’s jump directly to dockerization of Django web application. I’m sure you have Django project set up on your system.</p><h3>Docker</h3><p>After installation of docker, add a Dockerfile to the root directory of your project:</p><pre>FROM python:3.8.9-alpine<br><br>WORKDIR /app<br><br>ENV PYTHONDONTWRITEBYTECODE 1<br>ENV PYTHONNUNBUFFERED 1<br><br>RUN pip install --upgrade pip<br>COPY ./requirements.txt .<br><br>RUN pip install -r requirements.txt<br><br>COPY . .</pre><p>Here, we used an alpine-based docker image for python 3.8.9. Then we set two environmental variables:</p><ul><li>PYTHONDONTWRITEBYTECODE (which prevents writing pyc files)</li><li>PYTHONUNBUFFERED (which prevents buffering stdout and stderr)</li></ul><p>And, we updated the pip version and copied the requirements.txt file to the working directory, and installed requirements. After that, we finally copied our project to the working directory(/app).</p><p>Now, create a docker-compose.yml file to the project root and add services:</p><pre>version: &#39;3.5&#39;<br><br>services:<br>    app:<br>        build: .<br>        command: python manage.py runserver 0.0.0.0:8000<br>        volumes:<br>            - static_data:/vol/web<br>        ports:<br>            - &quot;8000:8000&quot;<br>        restart: always<br>        env_file:<br>            - ./.env</pre><p>Create .env file at the root (the same directory containing docker-compose.yml) and edit as:</p><pre>DEBUG=1<br>SECRET_KEY=foo<br>DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::]</pre><p>Update DEBUG, ALLOWED_HOSTS variables in <a href="http://settings.py/">settings.py</a>:</p><pre>DEBUG = int(os.environ.get(&quot;DEBUG&quot;, default=0))<br>ALLOWED_HOSTS = os.environ.get(&quot;DJANGO_ALLOWED_HOSTS&quot;).split(&quot; &quot;)</pre><p><em>‘DJANGO_ALLOWED_HOSTS’ should be a single string of hosts with a space between each. For example: ‘DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]’</em></p><p>In docker-compose file, build: . means it will build image from the root Dockerfile we have created before.</p><p>Now, build the image:</p><pre>$ docker-compose build</pre><p>Use sudo if needed. Run the container once the image is built:</p><pre>$ docker-compose up -d</pre><h3>Postgres</h3><p>Add new service to the docker-compose.yml file, and update django database settings, with <a href="http://initd.org/psycopg/">Psycopg2</a>. Lets add new service named as app-db:</p><pre>version: &#39;3.5&#39;<br><br>services:<br>    app:<br>        build: .<br>        command: python manage.py runserver 0.0.0.0:8000<br>        volumes:<br>            - static_data:/vol/web<br>        ports:<br>            - &quot;8000:8000&quot;<br>        restart: always<br>        env_file:<br>            - ./.env<br>        depends_on:<br>            - app-db<br><br>    app-db:<br>        image: postgres:12-alpine<br>        ports:<br>            - &quot;5432:5432&quot;<br>        restart: always<br>        volumes:<br>            - postgres_data:/var/lib/postgresql/data:rw<br>        env_file:<br>            - .env<br># you can also use environmental variables directly as following:<br>#(remember variables for postgres should be named exactly as given below)<br>#        environment:<br>#            - POSTGRES_HOST_AUTH_METHOD=trust<br>#            - POSTGRES_USER:sagar<br>#            - POSTGRES_PASSWORD:********<br>#            - POSTGRES_DB:portfolio_db<br>#            - TZ:Asia/Kathmandu</pre><p>We will just use the official Postgres docker image and postgres_data is the persistent data volume within docker. It should suffice</p><pre>DEBUG=1<br>DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]<br>POSTGRES_HOST_AUTH_METHOD=trust<br>POSTGRES_USER=sagar<br>POSTGRES_PASSWORD=********<br>POSTGRES_DB=portfolio_db<br>POSTGRES_HOST=app-db<br>POSTGRES_PORT=5432</pre><p>Update the DATABASES dict in <a href="http://settings.py/">settings.py</a>:</p><pre>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: os.environ.get(&quot;DB_ENGINE&quot;, &quot;django.db.backends.sqlite3&quot;),<br>        &#39;NAME&#39;: os.environ.get(&quot;POSTGRES_DB&quot;, os.path.join(BASE_DIR, &quot;db.sqlite3&quot;)),<br>        &#39;USER&#39;: os.environ.get(&quot;POSTGRES_USER&quot;, &quot;default_user&quot;),<br>        &#39;PASSWORD&#39;: os.environ.get(&quot;POSTGRES_PASSWORD&quot;, &quot;default_password&quot;),<br>        &#39;HOST&#39;: os.environ.get(&quot;POSTGRES_HOST&quot;, &quot;localhost&quot;),<br>        &#39;PORT&#39;: os.environ.get(&quot;POSTGRES_PORT&quot;, &quot;5432&quot;),<br><br>    }<br>}</pre><p>Here, the database is configured based on the environment variables that we just defined. Take note of the default values. Update the Dockerfile to install the appropriate packages required for Psycopg2:</p><pre>From python:3.8.9-alpine</pre><pre>WORKDIR /app <br>PYTHONDONTWRITEBYTECODE 1 <br>ENV PYTHONNUNBUFFERED 1 </pre><pre>RUN apk update <br>RUN apk add postgresql-dev gcc python3-dev musl-dev libc-dev linux-headers </pre><pre>RUN pip install <br>COPY ./requirements.txt . <br>RUN pip install -r requirements.txt </pre><pre>COPY . .</pre><p>Add Psycopg2 to requirements.txt. Make sure everytime you install packages, they are added to requirements.txt file. (pip freeze &gt; requirements.txt)</p><p>Build the new image with two services:</p><p>Then run the migrations:</p><pre>$ docker-compose exec app python manage.py migrate - -noinput</pre><pre>Operations to perform: Apply all migrations: admin, auth, blogs, contenttypes, django_summernote, portfolio, sessions, works Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying blogs.0001_initial... OK Applying django_summernote.0001_initial... OK Applying django_summernote.0002_update-help_text... OK Applying portfolio.0001_initial... OK Applying sessions.0001_initial... OK Applying works.0001_initial... OK Applying works.0002_auto_20200325_1330... OK Applying works.0003_auto_20200325_1411... OK Applying works.0004_auto_20200325_1413... OK Applying works.0005_auto_20200325_1417... OK Applying works.0006_remove_work_image... OK Applying works.0007_work_image... OK</pre><p>If any error, run docker-compose down -v to remove the volumes along with the containers. Then re-build and run migrations.</p><p>Ensure database tables are created:</p><pre>$ sudo docker-compose exec app-db psql --username=sagar --dbname=portfolio_db</pre><p>Results:</p><pre>$ sudo docker-compose exec app-db psql --username=sagar --dbname=portfolio_db<br>psql (12.7)<br>Type &quot;help&quot; for help.<br><br>portfolio_db=# \c portfolio_db<br>You are now connected to database &quot;portfolio_db&quot; as user &quot;sagar&quot;.<br>portfolio_db=# \l<br>                               List of databases<br>     Name     | Owner | Encoding |  Collate   |   Ctype    | Access privileges <br>--------------+-------+----------+------------+------------+-------------------<br> portfolio_db | sagar | UTF8     | en_US.utf8 | en_US.utf8 | <br> postgres     | sagar | UTF8     | en_US.utf8 | en_US.utf8 | <br> template0    | sagar | UTF8     | en_US.utf8 | en_US.utf8 | =c/sagar         +<br>              |       |          |            |            | sagar=CTc/sagar<br> template1    | sagar | UTF8     | en_US.utf8 | en_US.utf8 | =c/sagar         +<br>              |       |          |            |            | sagar=CTc/sagar<br>(4 rows)</pre><pre>portfolio_db=# \dt<br>                   List of relations<br> Schema |             Name             | Type  | Owner <br>--------+------------------------------+-------+-------<br> public | auth_group                   | table | sagar<br> public | auth_group_permissions       | table | sagar<br> public | auth_permission              | table | sagar<br> public | auth_user                    | table | sagar<br> public | auth_user_groups             | table | sagar<br> public | auth_user_user_permissions   | table | sagar<br> public | blogs_category_post          | table | sagar<br> public | blogs_comment                | table | sagar<br> public | blogs_post                   | table | sagar<br> public | blogs_post_categories        | table | sagar<br> public | django_admin_log             | table | sagar<br> public | django_content_type          | table | sagar<br> public | django_migrations            | table | sagar<br> public | django_session               | table | sagar<br> public | django_summernote_attachment | table | sagar<br> public | portfolio_contact            | table | sagar<br> public | works_category_work          | table | sagar<br> public | works_work                   | table | sagar<br> public | works_work_categories        | table | sagar<br>(19 rows)<br><br>portfolio_db=#</pre><p>Now add <a href="http://entrypoint.sh/">entrypoint.sh</a> script inside scripts directory:</p><pre>#!/bin/sh<br><br>if [ &quot;$DATABASE&quot; = &quot;postgres&quot; ]<br>then<br>    echo &quot;Waiting for postgres...&quot;<br>    while ! nc -z &quot;$POSTGRES_HOST&quot; &quot;$POSTGRES_PORT&quot;; do<br>      sleep 0.1<br>    done<br>    echo &quot;PostgreSQL started&quot;<br>fi<br><br># It&#39;s okay to run the following two, flush and migrate commands on development mode(when debug mode is on) but not recommended<br># for production:<br><br># python manage.py flush --no-input<br># python manage.py migrate<br><br>exec &quot;$@&quot;</pre><p>Update Dockerfile with file permissions, and also add DATABASE variable to .env file.</p><pre>From python:3.8.9-alpine<br><br>WORKDIR /app<br><br>PYTHONDONTWRITEBYTECODE 1<br>ENV PYTHONNUNBUFFERED 1<br><br>#psycopg2 dependencies installation<br>RUN apk update<br>RUN apk add postgresql-dev gcc python3-dev musl-dev libc-dev linux-headers<br><br>RUN pip install --upgrade pip<br>COPY ./requirements.txt .<br><br>RUN pip install -r requirements.txt<br><br>COPY . .<br>COPY ./scripts /scripts<br><br>RUN chmod +x /scripts/*<br><br>RUN mkdir -p /vol/web/media<br>RUN mkdir -p /vol/web/static<br><br>RUN chmod -R 755 /vol/web<br><br>ENTRYPOINT [&quot;/scripts/entrypoint.sh&quot;]</pre><p>Edit .env file:</p><pre>DEBUG=1<br>DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]<br>POSTGRES_HOST_AUTH_METHOD=trust<br>POSTGRES_USER=user<br>POSTGRES_PASSWORD=password<br>POSTGRES_DB=portfolio_db<br>POSTGRES_HOST=app-db #from docker-compose<br>POSTGRES_PORT=5432<br>DATABASE=postgres</pre><p>Now, re-build, run and try <a href="http://localhost:8000/">localhost:8000</a></p><p>Next-part: <a href="https://sbmagar.medium.com/dockerizing-django-application-with-postgres-gunicorn-nginx-7975aea1e531">Django, Postgres, Gunicorn, Nginx with Docker (Part-2)</a></p><p><em>Originally published at </em><a href="https://blog.budhathokisagar.com.np/django-with-docker-postgres-gunicorn-and-nginxpart-1"><em>https://blog.budhathokisagar.com.np</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=415402814836" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text to Image Synthesis Using Multimodal (VQGAN + CLIP) Architectures]]></title>
            <link>https://medium.com/geekculture/text-to-image-synthesis-using-multimodal-vqgan-clip-architectures-896b8a6588ef?source=rss-9e3c8e5630f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/896b8a6588ef</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sagar Budhathoki Magar]]></dc:creator>
            <pubDate>Sat, 21 Aug 2021 05:17:55 GMT</pubDate>
            <atom:updated>2021-08-21T17:47:44.207Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*qalBx3e2XDufNjqiuAS5jQ.jpeg" /><figcaption>After synthesis of text input “A man fighting with a bull”</figcaption></figure><p>What’s up, guys!!</p><p><strong>This is my first story on Medium.</strong></p><p>Today, I’m going to do a GAN project with a multi-modal deep learning architecture called <strong>clip</strong> that is going to link text with visual elements. I’ll be combining it with a generative model, a transformer type of architecture so that I can take a text prompt and generate visuals and images, even make videos of sequences from that text prompt.</p><p>You can do it along with me. Let’s get into it:</p><p>I’m gonna work with two cutting-edge generative architectures that are going to allow us to do multi-modal generation. The ability to connect different modalities, in this case, text and images. Text and visual elements with a combination of two architectures: <strong>CLIP</strong> Architecture (by OpenAI) and Taming Transformers</p><h3>CLIP Architecture:</h3><p>Learning transferable visual models from natural language supervision and <strong>CLIP</strong> means <strong>C</strong>ontrastive <strong>L</strong>anguage <strong>I</strong>mage <strong>P</strong>re-training.</p><p>The trained model predicts which encoding of text and what text encoding corresponds with what encoding of what a visual encoding.</p><p>[<em> Sources: </em><a href="https://github.com/openai/CLIP"><em>CLIP GitHub,</em></a><em> </em><a href="https://arxiv.org/abs/2103.00020"><em>CLIP Paper</em></a><em>, </em><a href="https://openai.com/blog/clip/"><em>blog</em></a><em> </em>]</p><h3>Taming Transformers:</h3><p>Type of generative architecture that can create and invent text to follow the text prompt with more and more text. This is a different kind of transformer that uses an architecture called VQGAN. It combines elements of convolutional architecture with GAN types of elements. It uses a codebook, works with patches.</p><p>Creating the sequence of text elements is not very difficult but images have a very large no. of pixels which leads to the creation of long sequences in transformers.</p><p>But we can solve this by using — by working with patches. 16 x 16 patches of pixels so we reduce the dimensionality of the problem.</p><p>Codebook trains the network to learn matrices instead of working with pixels directly. It learns kinds of representations of parts of the image that are stored in the codebook, and then when it does generate through the decoder, it works by taking parts of the codebook. (It has different parts, convolutional, decoder, etc.)</p><h3>Optimization Process:</h3><p>Take the <strong>text phrase</strong> and pass it through the CLIP architecture to encode it. And get that encoding in 512 numbers (encoding of the Architecture, understanding of CLIP architecture of that text). Do the same thing with the image, but instead of sending the image as it is, augment it, rotate it, move it or create crops of it (20, 30, 40, 50,….). In this case, I’m gonna create 30 different crops. It is done to help the architecture to understand the image better by giving it multiple versions of it. So, I’m gonna send 30 crops of image clips (with specific rotations, translations) and encode its understanding of those crops. 30 sets of encodings or 512 values.</p><p>Now I’m gonna compare those encodings by using the function <strong>cosine similarity</strong>, a mathematical function that is used to calculate the similarity of mathematical vectors. It will help to calculate loss value, the performance of the network.</p><p>If I managed to get the encoding of the text as similar as possible to the encoding of the crops of the image, it would mean that the content of the image matched the content of the text.</p><p><strong>Include Prompt:</strong></p><p>What we want in the result:</p><ul><li>A monkey in the mt. Everest</li><li>20 people paragliding in the sky</li><li>Two people playing football</li></ul><p><strong>Exclude Prompt:</strong></p><p>What we don’t want in the result:</p><ul><li>Don’t want to have a blue color in the image.</li><li>Don’t want to have confusing things in the image.</li></ul><p><strong>Extra Prompt:</strong></p><p>What we want to apply to all of our <strong>includes</strong> prompts:</p><p>Eg.</p><p>Include prompts:</p><ul><li>A lad with a pink jacket.</li><li>A boy playing chess</li><li>An elephant with green legs</li></ul><p>Extra prompts:</p><ul><li>Watercolor paper texture</li></ul><p>Then watercolor paper texture will be applied to all of the include prompts.</p><p>Send them to clip to encode and eventually during the optimization, calculate the loss. Give some weight to the encoding of include texts and exclude ones to penalize so that one that should be excluded should increase value and one that should be included should decrease the loss value.</p><p>Also, one can begin the generation from a specific image/picture instead of noise input, and modify, edit that image in the direction specified by the text prompt.</p><p>Now, After generating new images, I’m gonna show you the capability of creating interpolations between the latent parameters generated by the process and then produce a video that shows the interpolations from one of the creations to other creations, and then show the video on a screen.</p><h3>Coding and Execution:</h3><pre>!git clone <a href="https://github.com/openai/CLIP.git">https://github.com/openai/CLIP.git</a><br>!git clone <a href="https://github.com/CompVis/taming-transformers">https://github.com/CompVis/taming-transformers</a></pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/0*mSITTKNecCdqAFzv" /></figure><p><strong>Install some libraries:</strong></p><pre>!pip install — no-deps ftfy regex tqdm<br>!pip install omegaconf==2.0.0 pytorch-lightning==1.0.8 <br>!pip uninstall torchtext — yes<br>!pip install einops</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hp_RcrtUneqdK10Y" /></figure><p><strong>Import libraries:</strong></p><pre># import libraries<br>import numpy as np<br>import torch, os, imageio, pdb, math<br>import torchvision<br>import torchvision.transforms as T<br>import torchvision.transforms.functional as TF</pre><pre>import PIL<br>import matplotlib.pyplot as plt</pre><pre>import yaml <br>from omegaconf import OmegaConf</pre><pre>from CLIP import clip</pre><pre>#import warnings<br>#warnings.filterwarnings(‘ignore’)</pre><p><strong>Helper functions:</strong></p><pre>def ShowFromTensor(tensor):<br>  img = tensor.clone()<br>  img = img.mul(255).byte()<br>  img = img.cpu().numpy().transpose((1,2,0))</pre><pre>plt.figure(figsize=(10,7))<br>  plt.axis(&#39;off&#39;)<br>  plt.imshow(img)<br>  plt.show()</pre><pre>def NormData(data):<br>  return (data.clip(-1,1)+1)/2 ### range between 0 and 1 in the result</pre><pre>### Parameters <br>learning_rate = .5<br>batch_size = 1<br>wd = .1 ## weight decay is regularization parameter, help to limit the size of weight and improve generalization capabilities of the architecture<br>noise_factor = .22 ## .1, .14 ...</pre><pre>total_iter=100 ## use more no. of iterations for more polished result <br>im_shape = [450, 450, 3] # height, width, channel<br>size1, size2, channels = im_shape</pre><p><strong>Now create a CLIP model:</strong></p><pre># Create CLIP model<br>clipmodel, _ = clip.load(&#39;ViT-B/32&#39;, jit=False)<br>clipmodel.eval()<br>print(clip.available_models())</pre><pre>print(&quot;Clip model visual input resolution: &quot;, clipmodel.visual.input_resolution)</pre><pre>device=torch.device(&quot;cuda:0&quot;)<br>torch.cuda.empty_cache()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/0*9Ix0na60cwDekyf0" /></figure><p>The CLIP downloads a pre-trained model, so we don’t need to train CLIP, we can proceed to use it in inference, eval mode to encode texts and images directly.</p><p><em>[‘RN50’, ‘RN101’, ‘RN50x4’, ‘RN50x16’, ‘ViT-B/32’, ‘ViT-B/16’]</em> are types of architectures that CLIP can use internally. (eg. RN50 — resNet architecture with 50 layers, ViT-B/32 — Visual Transformer)</p><p>And clip Model visual input resolution 224 pixels. This means, when we encode images in CLIP, we need to set them to 224 pixels.</p><h3>Taming transformer model:</h3><pre>%cd taming-transformers/</pre><pre>!mkdir -p models/vqgan_imagenet_f16_16384/checkpoints<br>!mkdir -p models/vqgan_imagenet_f16_16384/configs</pre><pre>if len(os.listdir(&#39;models/vqgan_imagenet_f16_16384/checkpoints/&#39;)) == 0:<br>   !wget &#39;<a href="https://heibox.uni-heidelberg.de/f/867b05fc8c4841768640/?dl=1&#39;">https://heibox.uni-heidelberg.de/f/867b05fc8c481768640/?dl=1&#39;</a> -O &#39;models/vqgan_imagenet_f16_16384/checkpoints/last.ckpt&#39; <br>   !wget &#39;<a href="https://heibox.uni-heidelberg.de/f/274fb24ed38341bfa753/?dl=1&#39;">https://heibox.uni-heidelberg.de/f/274fb24ed3831bfa753/?dl=1&#39;</a> -O &#39;models/vqgan_imagenet_f16_16384/configs/model.yaml&#39;</pre><p>Here, <em>vqgan_imagenet_f16_16384</em> means VQGAN image net is trained with images from the image metadata set f-16 because the file is named using downsampling factor f16 for each. And 16384 is codebook dimensionality.</p><p>Now create two checkpoints and configs folders if they don’t exist already.</p><p>Both links <strong><em>heidelberg.de</em></strong> are working to date in Nepal, but if they don’t work in the future there should be some alternative.</p><p>By running this, it downloads Heidelberg’s pre-trained VQGAN model, last checkpoints, and configuration information that will be in <em>model.yaml</em> file.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*71_KLK7bmdWOMJcY" /></figure><p>Now after downloading the checkpoint, let’s instantiate the Taming transformer VQGAN architecture.</p><pre>from taming.models.vqgan import VQModel</pre><pre>def LoadConfig(config_path, display=False):<br>   config_data = OmegaConf.load(config_path)<br>   if display:<br>     print(yaml.dump(OmegaConf.to_container(config_data)))<br>   return config_data</pre><pre>def LoadVQGAN(config, chk_path=None):<br>  model = VQModel(**config.model.params)<br>  if chk_path is not None:<br>    state_dict = torch.load(chk_path, map_location=&quot;cpu&quot;)[&quot;state_dict&quot;]<br>    missing, unexpected = model.load_state_dict(state_dict, strict=False)<br>  return model.eval()</pre><pre>def Generator(x):<br>  x = taming_model.post_quant_conv(x)<br>  x = taming_model.decoder(x)<br>  return x</pre><pre>taming_config=LoadConfig(&quot;./models/vqgan_imagenet_f16_16384/configs/model.yaml&quot;, display=True)<br>taming_model=LoadVQGAN(taming_config,chk_path=&quot;./models/vqgan_imagenet_f16_16384/checkpoints/last.ckpt&quot;).to(device)</pre><p>First, create a function for load configuration using library OmegaConf and dump to YAML file to see the configurations.</p><p>Second, create another function to load the VQGAN model. Use the previously imported model with the config file. Load state_dict dictionary that contains all the parameters of the model. And load checkpoint with path, map location to “CPU”. Now load the dictionary into the model.</p><p>Here, we’re going to use a model directly, no need to train so put it in evaluation or eval() mode.</p><p>The third and last function is Generator. Take input and generate images from it. For this input is passed through the taming model and output is passed to the decoder.</p><p>Then load configurations on the model.</p><p>(The <strong><em>models</em></strong> folder is within the <strong><em>taming-transformers</em></strong> folder as we did before, so paths are relative to the content of that folder)</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xHv5Da4yGAAIqWkH" /></figure><p>Declare the values (Latent space, parameters) that we are going to optimize:</p><pre>class Parameters(torch.nn.Module):<br>  def __init__(self):<br>    super(Parameters, self).__init__()<br>    self.data = .5*torch.randn(batch_size, 256, size1//16, size2//16).cuda() # 1x256x28.125x28.125 (450/16, 450/16)<br>    self.data = torch.nn.Parameter(torch.sin(self.data))</pre><pre>def forward(self):<br>    return self.data</pre><pre>def init_params():<br>  params=Parameters().cuda()<br>  optimizer = torch.optim.AdamW([{&#39;params&#39;:[params.data], &#39;lr&#39;:learning_rate}], weight_decay=wd)<br>  return params, optimizer</pre><p>Initialize data with random numbers from a normal distribution with parameters as batch size, channels, and size, where size is divided by 16 because of requirement(16 x 16 patches). For tensor of random value 1, it will be 1x256x28.125x28.125. (450/16 = 28.125, 450/16 = 28.125)</p><p>Here, multiplying by .5 is because personally experimentally it is found to be good before taking data from a normal distribution.</p><p>Then, in recurrent neural networks, they have clear indications of the positioning of the elements based on architecture itself but in transforming architectures, you just push all the data at once. This means it is the use of periodic mathematical functions to embed positioning information within the data. And we’re using mathematical sine.</p><p>Create a forward function which returns data just called.</p><p>Finally, create a helper function. In this call that function(Parameters), on-call refresh and reset those parameters then declare optimizer. (Adam optimizer is used for this.)</p><p>Encoding of text prompts in CLIP architecture:</p><pre># Let’s Encode prompts<br>normalize = torchvision.transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))</pre><pre>def encodeText(text):<br>  t=clip.tokenize(text).cuda()<br>  t=clipmodel.encode_text(t).detach().clone()<br>  return t</pre><pre>def createEncodings(include, exclude, extras):<br>  include_enc=[]<br>  for text in include:<br>    include_enc.append(encodeText(text))<br>  exclude_enc=encodeText(exclude) if exclude != &#39;&#39; else 0<br>  extras_enc=encodeText(extras) if extras !=&#39;&#39; else 0</pre><pre>return include_enc, exclude_enc, extras_enc</pre><pre>augTransform = torch.nn.Sequential(<br>    torchvision.transforms.RandomHorizontalFlip(),<br>    torchvision.transforms.RandomAffine(30, (.2, .2), fill=0)  <br>).cuda()</pre><pre>Params, optimizer = init_params()</pre><pre>with torch.no_grad():<br>  print(Params().shape)<br>  img= NormData(Generator(Params()).cpu()) # 1 x 3 x 450 x 450 [450 x 450]<br>  print(&quot;img dimensions: &quot;,img.shape)<br>  ShowFromTensor(img[0])</pre><p>Here, normalizing is required in this architecture so define a variable and use values for the mean, variance that has been prepared already for us.</p><p>Create a function that receives the text then calls the CLIP model to tokenize the text. Pass result through the encode function of the model and detach the result from the computation of gradients and will clone the results so that we can use our own memory space on the variable.</p><p>Now define a generic function that will be applied to exclude, include, and extras of our prompts.</p><p>When sending the image to encode, we’re not gonna send a single image. We also send a set of crops of the image. To declare a variable for augmentation transformation of the image. After doing some random rotations then some translations and remaining are filled with zeros.</p><p>[<strong>Note:</strong> <em>The augmentations are first applied to the single image produced by the generator and then from that output, the different crops are created.</em>]</p><p>Initialize parameters and optimizer and make a simple test to generate an image through a transformer generator with random initial parameters. Call generator function and pass parameters we declared before and put the result back on the CPU. It will return 1 in the first dimension then three channels, 448, 448. <strong>(<em>1 x 3 x 448 x 448 [450, 450] but we get 448 due to rounding.</em>)</strong></p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*CA4Pb_EpcO1P6A6A" /></figure><p>Create crops:</p><pre>def createCrops(img, num_crops=32): <br>  p=size1//2<br>  img = torch.nn.functional.pad(img, (p,p,p,p), mode=&#39;constant&#39;, value=0) # 1 x 3 x 672 x 672 (adding 112*2 on all sides to 448x448)</pre><pre>img = augTransform(img) #RandomHorizontalFlip and RandomAffine</pre><pre>crop_set = []<br>    for ch in range(num_crops):<br>      gap1= int(torch.normal(1.2, .3, ()).clip(.43, 1.9) * size1)<br>      offsetx = torch.randint(0, int(size1*2-gap1),())<br>      offsety = torch.randint(0, int(size1*2-gap1),())</pre><pre>crop=img[:,:,offsetx:offsetx+gap1, offsety:offsety+gap1]</pre><pre>crop = torch.nn.functional.interpolate(crop,(224,224), mode=&#39;bilinear&#39;, align_corners=True)<br>      crop_set.append(crop)</pre><pre>img_crops=torch.cat(crop_set,0) ## 30 x 3 x 224 x 224</pre><pre>randnormal = torch.randn_like(img_crops, requires_grad=False)<br>  num_rands=0<br>  randstotal=torch.rand((img_crops.shape[0],1,1,1)).cuda() #32<br>  <br>  for ns in range(num_rands):<br>    randstotal*=torch.rand((img_crops.shape[0],1,1,1)).cuda()</pre><pre>img_crops = img_crops + noise_factor*randstotal*randnormal</pre><pre>return img_crops</pre><p>Create a function called <strong>createCrops</strong>. And let’s set default value 32 for no. of crops value. Add some padding around the image so that we can rotate, translate and preserve image information.</p><p>Let’s set padding as height divided by 2 or 3. Then set padding on all sides as (p,p,p,p). So the dimension will be 1 x 3 x (448+112+112) x (448+112+112) = 1 x 3 x 672 x 672.</p><p>Now apply previously declared augmentations transformations (augTransforms). Set crops that are empty initially. Define a couple of variables or no. of pixels or numbers to use for offset and also for the amount of crop, here is gap1, gap2 defined.</p><p>Crop image keeping first two dimensions as they are and change last two dimensions as extended with gap1.</p><p>Resize crop to 224x224 and accumulate to crops dictionary we defined previously. Resolution will be 30 x 3 x 224 x 224.</p><p>Finally, add some noise to the crop. With noise factor and some random values from a normal distribution of the same dimensionality.</p><p><strong>Davinci Sfumato</strong> texture:-</p><p>The lines that are in the above code are actually for the sfumato effect. (You will know at the end.)</p><p>randnormal = torch.randn_like(img_crops, requires_grad=False)<br> num_rands=0<br> randstotal=torch.rand((img_crops.shape[0],1,1,1)).cuda() <em>#32</em><br> <br> for ns in range(num_rands):<br> randstotal*=torch.rand((img_crops.shape[0],1,1,1)).cuda()<br> img_crops = img_crops + noise_factor*randstotal*randnormal</p><p>[ <strong><em>Note:</em></strong><em> Davinci </em><a href="https://en.wikipedia.org/wiki/Sfumato#:~:text=Sfumato%20(Italian%3A%20%5Bsfu%CB%88ma%CB%90to%5D,out%2Dof%2Dfocus%20plane."><em>Sfumato</em></a> ]</p><p>Let’s create a function to see the generated image at any state:</p><pre>def showMe(Params, show_crop):<br>  with torch.no_grad():<br>    generated = Generator(Params())</pre><pre>if (show_crop):<br>      print(“Augmented cropped example”)<br>      aug_gen = generated.float() # 1 x 3 x 224 x 400 <br>      aug_gen = createCrops(aug_gen, num_crops=1)<br>      aug_gen_norm = NormData(aug_gen[0])<br>      ShowFromTensor(aug_gen_norm)</pre><pre>print(“Generation”)<br>    latest_gen=NormData(generated.cpu()) # 1 x 3 x 224 x 400<br>    ShowFromTensor(latest_gen[0])</pre><pre>return (latest_gen[0])</pre><p>Let’s don’t involve gradient here. Pass parameters that we’re used for the optimization of the generator, to generate an example image at the current state of the parameters. (1 x 3 x 450 x 450)</p><p>And now call createCrops function to create crops but only one crop. Normalize the result and show.</p><p>Then for generation, the latest generation is going to normalize what we already generated. Finally, show the image.</p><p>Optimizing the mode by tweaking the parameters:</p><pre># Optimization process</pre><pre>def optimizeResult(Params, prompt):<br>  alpha=1 ## the importance of the include encodings<br>  beta=.5 ## the importance of the exclude encodings</pre><pre>## image encoding<br>  out = Generator(Params())<br>  out = NormData(out)<br>  out = createCrops(out)<br>  out = normalize(out) # 32 x 3 x 448 x 448<br>  image_enc=clipmodel.encode_image(out) ## 32 x 512</pre><pre>## text encoding  w1 and w2<br>  final_enc = w1*prompt+w1*extras_enc # prompt and extras_enc:1x512<br>  final_text_include_enc = final_enc / final_enc.norm(dim=-1, keepdim=True) #1x512<br>  final_text_exclude_enc = exclude_enc</pre><pre>## calculate the loss<br>  main_loss = torch.cosine_similarity(final_text_include_enc, image_enc, -1) # 32<br>  penalize_loss = torch.cosine_similarity(final_text_exclude_enc, image_enc, -1) # 32</pre><pre>final_loss = -alpha*main_loss + beta*penalize_loss</pre><pre>return final_loss</pre><pre>def Optimize(Params, optimizer, prompt):<br>  loss = optimizeResult(Params, prompt).mean()<br>  optimizer.zero_grad()<br>  loss.backward()<br>  optimizer.step()<br>  return loss</pre><p>Let’s create a function called <strong>Optimize</strong> that will gonna receive the current state of the parameters, optimizer, and text prompt. Calculate current loss calling a function <strong>optimzeResult</strong> which we gonna declare. After this, calculate the mean we are gonna get the loss for each crop and calculate the average of it. Set optimizer to gradient value zero, do backpropagation, and tweak-update to step with values of parameters. So, this is an optimizing function.</p><p>Now, define the <strong>optimizeResult</strong> function which will find the lost value and lowest value that is gonna drive the <strong>optimize</strong> function. It’s gonna receive params, and prompt. Declare a couple of variables alpha, beta with values 1 and 0.5 respectively. They will represent the significance or importance of include and exclude encodings resp. (here, since alpha&gt;beta, include will be important than exclude during encodings)</p><p>After this generate a new image from parameters and normalize the result.</p><p><strong>[<em>Note:</em></strong><em> To calculate loss, encodings of text prompts </em><strong><em>and</em></strong><em> encodings of image crops generated from the current state of latent space parameters should be compared. So we need to pass parameters through a generator to generate a new image so that we can encode it.</em><strong>]</strong></p><p>And create crops, normalize them with extra normalization (for the images to match CLIP architecture). Then create an image encoding by calling the CLIP model. (32 crops composed of 500 so, encoding dimensionality be 512x512)</p><p>W1, W2 are weights for include and extras text encodings. Divide encoding values by their normalization to get them in the correct range.</p><p>Now calculate the loss using cosine similarity mathematical function. Main loss(include), penalize loss(exclude). (each of the 32 crops will be compared with the single encoding of include texts and exclude texts respectively)</p><p>Then total loss will be the summation of both losses as:</p><p>Main loss multiplied by alpha(include factor) AND Penalize loss multiplied by beta(exclude factor).</p><p>Now it’s time for training loop coding:</p><pre>### training loop<br>def training_loop(Params, optimizer, show_crop=False):<br>  res_img=[]<br>  res_z=[]</pre><pre>for prompt in include_enc:<br>    iteration=0<br>    Params, optimizer = init_params() # 1 x 256 x 14 x 25 (225/16, 400/16)</pre><pre>for it in range(total_iter):<br>      loss = Optimize(Params, optimizer, prompt)</pre><pre>if iteration&gt;=80 and iteration%show_step == 0:<br>        new_img = showMe(Params, show_crop)<br>        res_img.append(new_img)<br>        res_z.append(Params()) # 1 x 256 x 14 x 25<br>        print(&quot;loss:&quot;, loss.item(), &quot;\nno. of iteration:&quot;,iteration)</pre><pre>iteration+=1<br>    torch.cuda.empty_cache()<br>  return res_img, res_z</pre><p>Create a function that takes parameters, optimizer. Initialize each of the encodings with iteration set to zero. Initialize parameter on every call.</p><p>Calculate the loss calling optimize function defined previously. And display the image as you want. Here, I’m gonna show image 1 iteration before the final iteration. So, call showMe function and declare prompts, increase iterations. In the end, you can delete the cache of GPU.</p><p>It’s SHOWTIME:</p><pre>torch.cuda.empty_cache()<br>include=[‘A primeminister giving a speech in public’]<br>exclude=’watermark, cropped, confusing, blurry’<br>extras = “watercolor paper”<br>w1=1<br>w2=1<br>noise_factor= .28<br>total_iter=1000<br>show_step=100 # set this to see the result every 100 iterations<br>include_enc, exclude_enc, extras_enc = createEncodings(include, exclude, extras) <br>res_img, res_z=training_loop(Params, optimizer, show_crop=True)</pre><p>Output:</p><p>After 100 iterations crop and non-crop image results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*rB7E8Iq6PQvuxMMCvIvkyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*mJ-AVFZ-fzcxTTTXwbWQ1g.png" /></figure><p>And so on…</p><p>If you refresh and re-run from starting, it will show different images on the same step. It is because we’re using stochastic processes not deterministic.</p><p>Check resulting images dimensionalities:</p><pre>print(len(res_img), len(res_z))<br>print(res_img[0].shape, res_z[0].shape)<br>print(res_z[0].max(), res_z[0].min())</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0EDxeceGuYymMWPL" /></figure><p>Let’s see another example:</p><p><strong>Include:</strong> “A man fighting with a bull”</p><p><strong>Exclude:</strong> “Watermark, blurry, cropped, confusing, cut, incoherent”</p><p><strong>Extra:</strong> “ ”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/0*ofCDv0tesl4GebFR" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/0*MVVfncmQakBwgcSP" /></figure><p>Excellent !!</p><p><strong>[The best generation might not be the last one always… It could be one of previous]</strong></p><p>At last, Multiple prompts and results:</p><p><strong>Include:</strong> [ “A man fighting with a bull”, “A dog sleeping in the park”, “People striking in the road”]</p><p><strong>Exclude:</strong> “Watermark, blurry, cropped, confusing, cut, incoherent”</p><p><strong>Extra:</strong> “ ”</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=896b8a6588ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/text-to-image-synthesis-using-multimodal-vqgan-clip-architectures-896b8a6588ef">Text to Image Synthesis Using Multimodal (VQGAN + CLIP) Architectures</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text to Image Synthesis Using Multimodal (VQGAN + CLIP) Architectures]]></title>
            <link>https://sbmagar13.medium.com/text-to-image-synthesis-using-multimodal-vqgan-clip-architectures-fab2d243f9dd?source=rss-9e3c8e5630f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fab2d243f9dd</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Sagar Budhathoki Magar]]></dc:creator>
            <pubDate>Tue, 17 Aug 2021 14:00:30 GMT</pubDate>
            <atom:updated>2021-08-21T05:05:31.806Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*qalBx3e2XDufNjqiuAS5jQ.jpeg" /><figcaption>After synthesis of text input “A man fighting with a bull”</figcaption></figure><p>What’s up, guys!!</p><p><strong>This is my first story on Medium.</strong></p><p>Today, I’m going to do a GAN project with a multi-modal deep learning architecture called <strong>clip</strong> that is going to link text with visual elements. I’ll be combining it with a generative model, a transformer type of architecture so that I can take a text prompt and generate visuals and images, even make videos of sequences from that text prompt.</p><p>You can do it along with me. Let’s get into it:</p><p>I’m gonna work with two cutting-edge generative architectures that are going to allow us to do multi-modal generation. The ability to connect different modalities, in this case, text and images. Text and visual elements with a combination of two architectures: <strong>CLIP</strong> Architecture (by OpenAI) and Taming Transformers</p><h3><strong>CLIP</strong> Architecture:</h3><p>Learning transferable visual models from natural language supervision and <strong>CLIP</strong> means <strong>C</strong>ontrastive <strong>L</strong>anguage <strong>I</strong>mage <strong>P</strong>re-training.</p><p>The trained model predicts which encoding of text and what text encoding corresponds with what encoding of what a visual encoding.</p><p>[<em> Sources: </em><a href="https://github.com/openai/CLIP"><em>CLIP GitHub,</em></a><em> </em><a href="https://arxiv.org/abs/2103.00020"><em>CLIP Paper</em></a><em>, </em><a href="https://openai.com/blog/clip/"><em>blog</em></a><em> </em>]</p><h3><strong>Taming Transformers:</strong></h3><p>Type of generative architecture that can create and invent text to follow the text prompt with more and more text. This is a different kind of transformer that uses an architecture called VQGAN. It combines elements of convolutional architecture with GAN types of elements. It uses a codebook, works with patches.</p><p>Creating the sequence of text elements is not very difficult but images have a very large no. of pixels which leads to the creation of long sequences in transformers.</p><p>But we can solve this by using — by working with patches. 16 x 16 patches of pixels so we reduce the dimensionality of the problem.</p><p>Codebook trains the network to learn matrices instead of working with pixels directly. It learns kinds of representations of parts of the image that are stored in the codebook, and then when it does generate through the decoder, it works by taking parts of the codebook. (It has different parts, convolutional, decoder, etc.)</p><h3><strong>Optimization Process:</strong></h3><p>Take the <strong>text phrase</strong> and pass it through the CLIP architecture to encode it. And get that encoding in 512 numbers (encoding of the Architecture, understanding of CLIP architecture of that text). Do the same thing with the image, but instead of sending the image as it is, augment it, rotate it, move it or create crops of it (20, 30, 40, 50,….). In this case, I’m gonna create 30 different crops. It is done to help the architecture to understand the image better by giving it multiple versions of it. So, I’m gonna send 30 crops of image clips (with specific rotations, translations) and encode its understanding of those crops. 30 sets of encodings or 512 values.</p><p>Now I’m gonna compare those encodings by using the function <strong>cosine similarity</strong>, a mathematical function that is used to calculate the similarity of mathematical vectors. It will help to calculate loss value, the performance of the network.</p><p>If I managed to get the encoding of the text as similar as possible to the encoding of the crops of the image, it would mean that the content of the image matched the content of the text.</p><p><strong>Include Prompt:</strong></p><p>What we want in the result:</p><ul><li>A monkey in the mt. Everest</li><li>20 people paragliding in the sky</li><li>Two people playing football</li></ul><p><strong>Exclude Prompt:</strong></p><p>What we don’t want in the result:</p><ul><li>Don’t want to have a blue color in the image.</li><li>Don’t want to have confusing things in the image.</li></ul><p><strong>Extra Prompt:</strong></p><p>What we want to apply to all of our <strong>includes</strong> prompts:</p><p>Eg.</p><p>Include prompts:</p><ul><li>A lad with a pink jacket.</li><li>A boy playing chess</li><li>An elephant with green legs</li></ul><p>Extra prompts:</p><ul><li>Watercolor paper texture</li></ul><p>Then watercolor paper texture will be applied to all of the include prompts.</p><p>Send them to clip to encode and eventually during the optimization, calculate the loss. Give some weight to the encoding of include texts and exclude ones to penalize so that one that should be excluded should increase value and one that should be included should decrease the loss value.</p><p>Also, one can begin the generation from a specific image/picture instead of noise input, and modify, edit that image in the direction specified by the text prompt.</p><p>Now, After generating new images, I’m gonna show you the capability of creating interpolations between the latent parameters generated by the process and then produce a video that shows the interpolations from one of the creations to other creations, and then show the video on a screen.</p><h3><strong>Coding and Execution:</strong></h3><pre>!git clone <a href="https://github.com/openai/CLIP.git">https://github.com/openai/CLIP.git</a><br>!git clone <a href="https://github.com/CompVis/taming-transformers">https://github.com/CompVis/taming-transformers</a></pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/0*mSITTKNecCdqAFzv" /></figure><p><strong>Install some libraries:</strong></p><pre>!pip install — no-deps ftfy regex tqdm<br>!pip install omegaconf==2.0.0 pytorch-lightning==1.0.8 <br>!pip uninstall torchtext — yes<br>!pip install einops</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hp_RcrtUneqdK10Y" /></figure><p><strong>Import libraries:</strong></p><pre># import libraries<br>import numpy as np<br>import torch, os, imageio, pdb, math<br>import torchvision<br>import torchvision.transforms as T<br>import torchvision.transforms.functional as TF </pre><pre>import PIL<br>import matplotlib.pyplot as plt</pre><pre>import yaml <br>from omegaconf import OmegaConf</pre><pre>from CLIP import clip</pre><pre>#import warnings<br>#warnings.filterwarnings(‘ignore’)</pre><p><strong>Helper functions:</strong></p><pre>def ShowFromTensor(tensor):<br>  img = tensor.clone()<br>  img = img.mul(255).byte()<br>  img = img.cpu().numpy().transpose((1,2,0))</pre><pre>plt.figure(figsize=(10,7))<br>  plt.axis(&#39;off&#39;)<br>  plt.imshow(img)<br>  plt.show()</pre><pre>def NormData(data):<br>  return (data.clip(-1,1)+1)/2 ### range between 0 and 1 in the result</pre><pre>### Parameters <br>learning_rate = .5<br>batch_size = 1<br>wd = .1 ## weight decay is regularization parameter, help to limit the size of weight and improve generalization capabilities of the architecture<br>noise_factor = .22 ## .1, .14 ...</pre><pre>total_iter=100 ## use more no. of iterations for more polished result <br>im_shape = [450, 450, 3] # height, width, channel<br>size1, size2, channels = im_shape</pre><p><strong>Now create a CLIP model:</strong></p><pre># Create CLIP model<br>clipmodel, _ = clip.load(&#39;ViT-B/32&#39;, jit=False)<br>clipmodel.eval()<br>print(clip.available_models())</pre><pre>print(&quot;Clip model visual input resolution: &quot;, clipmodel.visual.input_resolution)</pre><pre>device=torch.device(&quot;cuda:0&quot;)<br>torch.cuda.empty_cache()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/0*9Ix0na60cwDekyf0" /></figure><p>The CLIP downloads a pre-trained model, so we don’t need to train CLIP, we can proceed to use it in inference, eval mode to encode texts and images directly.</p><p><em>[‘RN50’, ‘RN101’, ‘RN50x4’, ‘RN50x16’, ‘ViT-B/32’, ‘ViT-B/16’]</em> are types of architectures that CLIP can use internally. (eg. RN50 — resNet architecture with 50 layers, ViT-B/32 — Visual Transformer)</p><p>And clip Model visual input resolution 224 pixels. This means, when we encode images in CLIP, we need to set them to 224 pixels.</p><h3><strong>Taming transformer model:</strong></h3><pre>%cd taming-transformers/</pre><pre>!mkdir -p models/vqgan_imagenet_f16_16384/checkpoints<br>!mkdir -p models/vqgan_imagenet_f16_16384/configs</pre><pre>if len(os.listdir(&#39;models/vqgan_imagenet_f16_16384/checkpoints/&#39;)) == 0:<br>   !wget &#39;<a href="https://heibox.uni-heidelberg.de/f/867b05fc8c4841768640/?dl=1&#39;">https://heibox.uni-heidelberg.de/f/867b05fc8c481768640/?dl=1&#39;</a> -O &#39;models/vqgan_imagenet_f16_16384/checkpoints/last.ckpt&#39; <br>   !wget &#39;<a href="https://heibox.uni-heidelberg.de/f/274fb24ed38341bfa753/?dl=1&#39;">https://heibox.uni-heidelberg.de/f/274fb24ed3831bfa753/?dl=1&#39;</a> -O &#39;models/vqgan_imagenet_f16_16384/configs/model.yaml&#39;</pre><p>Here, <em>vqgan_imagenet_f16_16384</em> means VQGAN image net is trained with images from the image metadata set f-16 because the file is named using downsampling factor f16 for each. And 16384 is codebook dimensionality.</p><p>Now create two checkpoints and configs folders if they don’t exist already.</p><p>Both links <strong><em>heidelberg.de</em></strong> are working to date in Nepal, but if they don’t work in the future there should be some alternative.</p><p>By running this, it downloads Heidelberg’s pre-trained VQGAN model, last checkpoints, and configuration information that will be in <em>model.yaml</em> file.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*71_KLK7bmdWOMJcY" /></figure><p>Now after downloading the checkpoint, let’s instantiate the Taming transformer VQGAN architecture.</p><pre>from taming.models.vqgan import VQModel</pre><pre>def LoadConfig(config_path, display=False):<br>   config_data = OmegaConf.load(config_path)<br>   if display:<br>     print(yaml.dump(OmegaConf.to_container(config_data)))<br>   return config_data</pre><pre>def LoadVQGAN(config, chk_path=None):<br>  model = VQModel(**config.model.params)<br>  if chk_path is not None:<br>    state_dict = torch.load(chk_path, map_location=&quot;cpu&quot;)[&quot;state_dict&quot;]<br>    missing, unexpected = model.load_state_dict(state_dict, strict=False)<br>  return model.eval()</pre><pre>def Generator(x):<br>  x = taming_model.post_quant_conv(x)<br>  x = taming_model.decoder(x)<br>  return x</pre><pre>taming_config=LoadConfig(&quot;./models/vqgan_imagenet_f16_16384/configs/model.yaml&quot;, display=True)<br>taming_model=LoadVQGAN(taming_config,chk_path=&quot;./models/vqgan_imagenet_f16_16384/checkpoints/last.ckpt&quot;).to(device)</pre><p>First, create a function for load configuration using library OmegaConf and dump to YAML file to see the configurations.</p><p>Second, create another function to load the VQGAN model. Use the previously imported model with the config file. Load state_dict dictionary that contains all the parameters of the model. And load checkpoint with path, map location to “CPU”. Now load the dictionary into the model.</p><p>Here, we’re going to use a model directly, no need to train so put it in evaluation or eval() mode.</p><p>The third and last function is Generator. Take input and generate images from it. For this input is passed through the taming model and output is passed to the decoder.</p><p>Then load configurations on the model.</p><p>(The <strong><em>models</em></strong> folder is within the <strong><em>taming-transformers</em></strong> folder as we did before, so paths are relative to the content of that folder)</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xHv5Da4yGAAIqWkH" /></figure><p>Declare the values (Latent space, parameters) that we are going to optimize:</p><pre>class Parameters(torch.nn.Module):<br>  def __init__(self):<br>    super(Parameters, self).__init__()<br>    self.data = .5*torch.randn(batch_size, 256, size1//16, size2//16).cuda() # 1x256x28.125x28.125 (450/16, 450/16)<br>    self.data = torch.nn.Parameter(torch.sin(self.data))</pre><pre>def forward(self):<br>    return self.data</pre><pre>def init_params():<br>  params=Parameters().cuda()<br>  optimizer = torch.optim.AdamW([{&#39;params&#39;:[params.data], &#39;lr&#39;:learning_rate}], weight_decay=wd)<br>  return params, optimizer</pre><p>Initialize data with random numbers from a normal distribution with parameters as batch size, channels, and size, where size is divided by 16 because of requirement(16 x 16 patches). For tensor of random value 1, it will be 1x256x28.125x28.125. (450/16 = 28.125, 450/16 = 28.125)</p><p>Here, multiplying by .5 is because personally experimentally it is found to be good before taking data from a normal distribution.</p><p>Then, in recurrent neural networks, they have clear indications of the positioning of the elements based on architecture itself but in transforming architectures, you just push all the data at once. This means it is the use of periodic mathematical functions to embed positioning information within the data. And we’re using mathematical sine.</p><p>Create a forward function which returns data just called.</p><p>Finally, create a helper function. In this call that function(Parameters), on-call refresh and reset those parameters then declare optimizer. (Adam optimizer is used for this.)</p><p>Encoding of text prompts in CLIP architecture:</p><pre># Let’s Encode prompts<br>normalize = torchvision.transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))</pre><pre>def encodeText(text):<br>  t=clip.tokenize(text).cuda()<br>  t=clipmodel.encode_text(t).detach().clone()<br>  return t</pre><pre>def createEncodings(include, exclude, extras):<br>  include_enc=[]<br>  for text in include:<br>    include_enc.append(encodeText(text))<br>  exclude_enc=encodeText(exclude) if exclude != &#39;&#39; else 0<br>  extras_enc=encodeText(extras) if extras !=&#39;&#39; else 0</pre><pre>return include_enc, exclude_enc, extras_enc</pre><pre>augTransform = torch.nn.Sequential(<br>    torchvision.transforms.RandomHorizontalFlip(),<br>    torchvision.transforms.RandomAffine(30, (.2, .2), fill=0)  <br>).cuda()</pre><pre>Params, optimizer = init_params()</pre><pre>with torch.no_grad():<br>  print(Params().shape)<br>  img= NormData(Generator(Params()).cpu()) # 1 x 3 x 450 x 450 [450 x 450]<br>  print(&quot;img dimensions: &quot;,img.shape)<br>  ShowFromTensor(img[0])</pre><p>Here, normalizing is required in this architecture so define a variable and use values for the mean, variance that has been prepared already for us.</p><p>Create a function that receives the text then calls the CLIP model to tokenize the text. Pass result through the encode function of the model and detach the result from the computation of gradients and will clone the results so that we can use our own memory space on the variable.</p><p>Now define a generic function that will be applied to exclude, include, and extras of our prompts.</p><p>When sending the image to encode, we’re not gonna send a single image. We also send a set of crops of the image. To declare a variable for augmentation transformation of the image. After doing some random rotations then some translations and remaining are filled with zeros.</p><p>[<strong>Note:</strong> <em>The augmentations are first applied to the single image produced by the generator and then from that output, the different crops are created.</em>]</p><p>Initialize parameters and optimizer and make a simple test to generate an image through a transformer generator with random initial parameters. Call generator function and pass parameters we declared before and put the result back on the CPU. It will return 1 in the first dimension then three channels, 448, 448. <strong>(<em>1 x 3 x 448 x 448 [450, 450] but we get 448 due to rounding.</em>)</strong></p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*CA4Pb_EpcO1P6A6A" /></figure><p>Create crops:</p><pre>def createCrops(img, num_crops=32): <br>  p=size1//2<br>  img = torch.nn.functional.pad(img, (p,p,p,p), mode=&#39;constant&#39;, value=0) # 1 x 3 x 672 x 672 (adding 112*2 on all sides to 448x448)</pre><pre>  img = augTransform(img) #RandomHorizontalFlip and RandomAffine</pre><pre>  crop_set = []<br>    for ch in range(num_crops):<br>      gap1= int(torch.normal(1.2, .3, ()).clip(.43, 1.9) * size1)<br>      offsetx = torch.randint(0, int(size1*2-gap1),())<br>      offsety = torch.randint(0, int(size1*2-gap1),())</pre><pre>      crop=img[:,:,offsetx:offsetx+gap1, offsety:offsety+gap1]</pre><pre>      crop = torch.nn.functional.interpolate(crop,(224,224), mode=&#39;bilinear&#39;, align_corners=True)<br>      crop_set.append(crop)</pre><pre>  img_crops=torch.cat(crop_set,0) ## 30 x 3 x 224 x 224</pre><pre>  randnormal = torch.randn_like(img_crops, requires_grad=False)<br>  num_rands=0<br>  randstotal=torch.rand((img_crops.shape[0],1,1,1)).cuda() #32<br>  <br>  for ns in range(num_rands):<br>    randstotal*=torch.rand((img_crops.shape[0],1,1,1)).cuda()</pre><pre>  img_crops = img_crops + noise_factor*randstotal*randnormal</pre><pre>  return img_crops</pre><p>Create a function called <strong>createCrops</strong>. And let’s set default value 32 for no. of crops value. Add some padding around the image so that we can rotate, translate and preserve image information.</p><p>Let’s set padding as height divided by 2 or 3. Then set padding on all sides as (p,p,p,p). So the dimension will be 1 x 3 x (448+112+112) x (448+112+112) = 1 x 3 x 672 x 672.</p><p>Now apply previously declared augmentations transformations (augTransforms). Set crops that are empty initially. Define a couple of variables or no. of pixels or numbers to use for offset and also for the amount of crop, here is gap1, gap2 defined.</p><p>Crop image keeping first two dimensions as they are and change last two dimensions as extended with gap1.</p><p>Resize crop to 224x224 and accumulate to crops dictionary we defined previously. Resolution will be 30 x 3 x 224 x 224.</p><p>Finally, add some noise to the crop. With noise factor and some random values from a normal distribution of the same dimensionality.</p><p><strong>Davinci Sfumato</strong> texture:-</p><p>The lines that are in the above code are actually for the sfumato effect. (You will know at the end.)</p><p>randnormal = torch.randn_like(img_crops, requires_grad=False)<br> num_rands=0<br> randstotal=torch.rand((img_crops.shape[0],1,1,1)).cuda() <em>#32</em><br> <br> for ns in range(num_rands):<br> randstotal*=torch.rand((img_crops.shape[0],1,1,1)).cuda()<br> img_crops = img_crops + noise_factor*randstotal*randnormal</p><p>[ <strong><em>Note:</em></strong><em> Davinci </em><a href="https://en.wikipedia.org/wiki/Sfumato#:~:text=Sfumato%20(Italian%3A%20%5Bsfu%CB%88ma%CB%90to%5D,out%2Dof%2Dfocus%20plane."><em>Sfumato</em></a> ]</p><p>Let’s create a function to see the generated image at any state:</p><pre>def showMe(Params, show_crop):<br>  with torch.no_grad():<br>    generated = Generator(Params())</pre><pre>    if (show_crop):<br>      print(“Augmented cropped example”)<br>      aug_gen = generated.float() # 1 x 3 x 224 x 400 <br>      aug_gen = createCrops(aug_gen, num_crops=1)<br>      aug_gen_norm = NormData(aug_gen[0])<br>      ShowFromTensor(aug_gen_norm)</pre><pre>    print(“Generation”)<br>    latest_gen=NormData(generated.cpu()) # 1 x 3 x 224 x 400<br>    ShowFromTensor(latest_gen[0])</pre><pre>  return (latest_gen[0])</pre><p>Let’s don’t involve gradient here. Pass parameters that we’re used for the optimization of the generator, to generate an example image at the current state of the parameters. (1 x 3 x 450 x 450)</p><p>And now call createCrops function to create crops but only one crop. Normalize the result and show.</p><p>Then for generation, the latest generation is going to normalize what we already generated. Finally, show the image.</p><p>Optimizing the mode by tweaking the parameters:</p><pre># Optimization process</pre><pre>def optimizeResult(Params, prompt):<br>  alpha=1 ## the importance of the include encodings<br>  beta=.5 ## the importance of the exclude encodings</pre><pre>## image encoding<br>  out = Generator(Params())<br>  out = NormData(out)<br>  out = createCrops(out)<br>  out = normalize(out) # 32 x 3 x 448 x 448<br>  image_enc=clipmodel.encode_image(out) ## 32 x 512</pre><pre>## text encoding  w1 and w2<br>  final_enc = w1*prompt+w1*extras_enc # prompt and extras_enc:1x512<br>  final_text_include_enc = final_enc / final_enc.norm(dim=-1, keepdim=True) #1x512<br>  final_text_exclude_enc = exclude_enc</pre><pre>## calculate the loss<br>  main_loss = torch.cosine_similarity(final_text_include_enc, image_enc, -1) # 32<br>  penalize_loss = torch.cosine_similarity(final_text_exclude_enc, image_enc, -1) # 32</pre><pre>  final_loss = -alpha*main_loss + beta*penalize_loss</pre><pre>  return final_loss</pre><pre>def Optimize(Params, optimizer, prompt):<br>  loss = optimizeResult(Params, prompt).mean()<br>  optimizer.zero_grad()<br>  loss.backward()<br>  optimizer.step()<br>  return loss</pre><p>Let’s create a function called <strong>Optimize</strong> that will gonna receive the current state of the parameters, optimizer, and text prompt. Calculate current loss calling a function <strong>optimzeResult</strong> which we gonna declare. After this, calculate the mean we are gonna get the loss for each crop and calculate the average of it. Set optimizer to gradient value zero, do backpropagation, and tweak-update to step with values of parameters. So, this is an optimizing function.</p><p>Now, define the <strong>optimizeResult</strong> function which will find the lost value and lowest value that is gonna drive the <strong>optimize</strong> function. It’s gonna receive params, and prompt. Declare a couple of variables alpha, beta with values 1 and 0.5 respectively. They will represent the significance or importance of include and exclude encodings resp. (here, since alpha&gt;beta, include will be important than exclude during encodings)</p><p>After this generate a new image from parameters and normalize the result.</p><p><strong>[<em>Note:</em></strong><em> To calculate loss, encodings of text prompts </em><strong><em>and</em></strong><em> encodings of image crops generated from the current state of latent space parameters should be compared. So we need to pass parameters through a generator to generate a new image so that we can encode it.</em><strong>]</strong></p><p>And create crops, normalize them with extra normalization (for the images to match CLIP architecture). Then create an image encoding by calling the CLIP model. (32 crops composed of 500 so, encoding dimensionality be 512x512)</p><p>W1, W2 are weights for include and extras text encodings. Divide encoding values by their normalization to get them in the correct range.</p><p>Now calculate the loss using cosine similarity mathematical function. Main loss(include), penalize loss(exclude). (each of the 32 crops will be compared with the single encoding of include texts and exclude texts respectively)</p><p>Then total loss will be the summation of both losses as:</p><p>Main loss multiplied by alpha(include factor) AND Penalize loss multiplied by beta(exclude factor).</p><p>Now it’s time for training loop coding:</p><pre>### training loop<br>def training_loop(Params, optimizer, show_crop=False):<br>  res_img=[]<br>  res_z=[]</pre><pre>for prompt in include_enc:<br>    iteration=0<br>    Params, optimizer = init_params() # 1 x 256 x 14 x 25 (225/16, 400/16)</pre><pre>for it in range(total_iter):<br>      loss = Optimize(Params, optimizer, prompt)</pre><pre>if iteration&gt;=80 and iteration%show_step == 0:<br>        new_img = showMe(Params, show_crop)<br>        res_img.append(new_img)<br>        res_z.append(Params()) # 1 x 256 x 14 x 25<br>        print(&quot;loss:&quot;, loss.item(), &quot;\nno. of iteration:&quot;,iteration)</pre><pre>iteration+=1<br>    torch.cuda.empty_cache()<br>  return res_img, res_z</pre><p>Create a function that takes parameters, optimizer. Initialize each of the encodings with iteration set to zero. Initialize parameter on every call.</p><p>Calculate the loss calling optimize function defined previously. And display the image as you want. Here, I’m gonna show image 1 iteration before the final iteration. So, call showMe function and declare prompts, increase iterations. In the end, you can delete the cache of GPU.</p><p>It’s SHOWTIME:</p><pre>torch.cuda.empty_cache()<br>include=[‘A primeminister giving a speech in public’]<br>exclude=’watermark, cropped, confusing, blurry’<br>extras = “watercolor paper”<br>w1=1<br>w2=1<br>noise_factor= .28<br>total_iter=1000<br>show_step=100 # set this to see the result every 100 iterations<br>include_enc, exclude_enc, extras_enc = createEncodings(include, exclude, extras) <br>res_img, res_z=training_loop(Params, optimizer, show_crop=True)</pre><p>Output:</p><p>After 100 iterations crop and non-crop image results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*rB7E8Iq6PQvuxMMCvIvkyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*mJ-AVFZ-fzcxTTTXwbWQ1g.png" /></figure><p>And so on…</p><p>If you refresh and re-run from starting, it will show different images on the same step. It is because we’re using stochastic processes not deterministic.</p><p>Check resulting images dimensionalities:</p><pre>print(len(res_img), len(res_z))<br>print(res_img[0].shape, res_z[0].shape)<br>print(res_z[0].max(), res_z[0].min())</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0EDxeceGuYymMWPL" /></figure><p>Let’s see another example:</p><p><strong>Include:</strong> “A man fighting with a bull”</p><p><strong>Exclude:</strong> “Watermark, blurry, cropped, confusing, cut, incoherent”</p><p><strong>Extra:</strong> “ ”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/0*ofCDv0tesl4GebFR" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/0*MVVfncmQakBwgcSP" /></figure><p>Excellent !!</p><p><strong>[The best generation might not be the last one always… It could be one of previous]</strong></p><p>At last, Multiple prompts and results:</p><p><strong>Include:</strong> [ “A man fighting with a bull”, “A dog sleeping in the park”, “People striking in the road”]</p><p><strong>Exclude:</strong> “Watermark, blurry, cropped, confusing, cut, incoherent”</p><p><strong>Extra:</strong> “ ”</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fab2d243f9dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>