Creating YouTube to MP3 Converter using Python, Nginx, Gunicorn, and SQLite


So you downloaded a great tune from YouTube and want to convert it to MP3 format to build your dream playlist. But, oh no! You don't have the right tool for the job. Don't worry, my friend, you've come to the right blog post!

In this tutorial, I will guide you on how to create your own YouTube to MP3 converter website using Python, Nginx, Gunicorn, and SQLite. It sounds fancy, but fear not! We will break it down step by step.

    Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setting Up the Project
  4. Installing the Dependencies
  5. Building the Web Scraping Function
  6. Designing the Web Interface
  7. Setting Up the Database
  8. Creating the Conversion Logic
  9. Deploying with Nginx and Gunicorn
  10. Conclusion

Introduction

Imagine having a website that allows you to convert YouTube videos to MP3 with just a few clicks. No more convoluted software or shady online services. With your very own YouTube to MP3 converter website, you'll have the power to create your perfect playlist in minutes!

Prerequisites

Before diving into the project, let's make sure you have all the necessary prerequisites:

Now that we have everything set up, let's move on to creating our amazing YouTube to MP3 converter website!

Setting Up the Project

To get started, let's set up the project structure. Open your terminal and create a new directory for your project. For example, run the following command:

mkdir youtube-to-mp3-converter
cd youtube-to-mp3-converter

Within this directory, we will organize our code and files as we progress.

Installing the Dependencies

Our first task is to install the necessary Python packages for our project. In your terminal, run the following command to set up a virtual environment:

python3 -m venv venv

Activate the virtual environment:

source venv/bin/activate

Now, let's install the required packages:

pip install flask youtube-dl

Building the Web Scraping Function

To convert YouTube videos to MP3, we need a way to extract the audio from the video. Luckily, we have the youtube_dl library in Python that can handle this for us.

Create a new Python file called youtube_converter.py and add the following code:

from youtube_dl import YoutubeDL
    def convert_to_mp3(url):
        ydl_opts = {
            'format': 'bestaudio/best',
            'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
          }],
        }
        with YoutubeDL(ydl_opts) as ydl:
        result = ydl.extract_info(url, download=False)
        audio_url = result['url']
        return audio_url

This function takes a YouTube video URL as input and returns the URL for the extracted audio in MP3 format.

Designing the Web Interface

Now it's time to design the web interface for our YouTube to MP3 converter website. Create a new Python file called app.py.

from flask import Flask, render_template, request, redirect
from youtube_converter import convert_to_mp3
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def home():
    if request.method == 'POST':
        youtube_url = request.form['youtube_url']
        audio_url = convert_to_mp3(youtube_url)
        # Save the audio_url to the database (we'll cover this later)
        return redirect('/')
    else:
        return render_template('index.html')

In this code snippet, we have defined a Flask route for the home page. If the request method is POST, we extract the YouTube URL from the form input and convert it to MP3 using our convert_to_mp3 function. We then save the audio_url in the database, which we will cover shortly. Finally, we redirect the user back to the home page.

Setting Up the Database

To keep track of all the conversions, we'll use SQLite as our database. Create a new file named database.py and add the following code:

import sqlite3
DB_NAME = 'conversions.db'
def create_table():
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS conversions
    (youtube_url text, audio_url text)''')
    conn.commit()
    conn.close()

This code creates a conversions table with columns for the YouTube URL and the corresponding audio URL. Note that we are using a file-based database, so you will find the conversions.db file in your project directory.

To call this function, modify app.py as follows:

from database import create_table

# ...
if __name__ == '__main__':
create_table()
app.run(debug=True)

Now, whenever we run app.py, the create_table function will be called to ensure the conversions table is set up.

Creating the Conversion Logic

With the database set up, we can now update our app.py file to include the conversion history on the home page. Modify the / route as follows:

from database import create_table
# ...
@app.route('/', methods=['GET', 'POST'])
def home():
    if request.method == 'POST':
        youtube_url = request.form['youtube_url']
        audio_url = convert_to_mp3(youtube_url)
        # Save the youtube_url and audio_url to the database
        conn = sqlite3.connect(DB_NAME)
        c = conn.cursor()
        c.execute("INSERT INTO conversions VALUES (?, ?)", (youtube_url,
        audio_url))
        conn.commit()
        conn.close()
        return redirect('/')
    else:
        conn = sqlite3.connect(DB_NAME)
        c = conn.cursor()
        c.execute("SELECT * FROM conversions")
        conversions = c.fetchall()
        conn.close()
        return render_template('index.html', conversions=conversions)

In this updated code, we fetch all the conversion records from the conversions table and pass them to the index.html template. We also modified the database logic to save both the youtube_url and the converted audio_url into the database.

Deploying with Nginx and Gunicorn

Congratulations! You've built the foundation of your YouTube to MP3 converter website. Now it's time to deploy it using Nginx and Gunicorn to make it accessible to the world.

First, create a new file named wsgi.py in your project directory and add the following code:

from app import app

if __name__ == '__main__':
app.run()

Next, let's configure Nginx and Gunicorn. Open your terminal and create a new Nginx configuration file:

sudo nano /etc/nginx/sites-available/youtube-to-mp3-converter

Add the following contents:

server {
    listen 80;
    listen [::]:80;
    server_name your_domain.com;
    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Make sure to replace your_domain.com with your actual domain or server IP address.

Save the file, exit the editor, and create a symlink to enable the site:

sudo ln -s /etc/nginx/sites-available/youtube-to-mp3-converter
/etc/nginx/sites-enabled/

Now, let's configure Gunicorn. Open your terminal and create a new file named gunicorn.service:

sudo nano /etc/systemd/system/gunicorn.service

Add the following contents:

[Unit]
Description=Gunicorn Service
After=network.target
[Service]
User=your_username
Group=www-data
WorkingDirectory=/path/to/your/project
ExecStart=/path/to/venv/bin/gunicorn --workers 3 --bind
unix:/path/to/your/project/gunicorn.sock wsgi:app
[Install]
WantedBy=multi-user.target

Make sure to replace your_username and path/to/your/project with your actual username and project path.

Save the file, exit the editor, and enable the Gunicorn service:

sudo systemctl enable gunicorn
sudo systemctl start gunicorn

To start serving your website, restart Nginx:

sudo systemctl restart nginx

Congratulations! You've successfully deployed your YouTube to MP3 converter website using Python, Nginx, Gunicorn, and SQLite. Give yourself a pat on the back!

Conclusion

In this tutorial, we learned how to create a YouTube to MP3 converter website using Python,Nginx, Gunicorn, and SQLite. We covered setting up the project structure, installing the necessary dependencies, building the web scraping function, designing the web interface, setting up the database, creating the conversion logic, and deploying with Nginx and Gunicorn.

Now it's time for you to add your personal touch and make it your own masterpiece. Happy coding and enjoy building the ultimate MP3 playlist!