How to Build an AI-Powered YouTube Title Generator with Django


Introduction

Hi, I’m Asif Khan, a Python developer with several years of experience in AI, machine learning, and web development. Today, I’m excited to share a comprehensive guide on building a YouTube title generator using Django and Google Gemini AI. In this project, you’ll learn how to build an AI-powered system that generates optimized and catchy YouTube video titles based on the description provided by the user. This tool is especially useful for content creators who want to improve their video titles for better engagement.

By following this guide, you’ll gain a deeper understanding of how to integrate Google Gemini AI with Django to create intelligent and dynamic web applications. Let’s dive into the project!


Why Build a YouTube Title Generator?

Here are a few key reasons why creating a YouTube title generator using AI is a valuable project:

  • Automated Content Creation: Save time by letting AI handle the brainstorming of titles for your YouTube videos.
  • SEO-Friendly: AI-generated titles can be optimized for search engines, improving your video’s visibility.
  • Consistent Quality: AI ensures that the titles maintain a consistent level of creativity and relevance.
  • Enhance Your Django Skills: You’ll improve your understanding of integrating external APIs into Django web applications.
  • Scalable: This project can be expanded to include additional features, such as title length optimization or keyword analysis.

Project Overview

In this project, you will build a simple web application using Django, which will take a user-inputted video description and return a catchy, AI-generated YouTube title. The AI part will be handled by Google Gemini AI, which is a powerful tool for natural language processing and generation.


Prerequisites

Before you begin, make sure you have the following prerequisites in place:

  • Basic understanding of Django and Python: Familiarity with Django views, forms, and templates is needed.
  • Google Cloud Account: You will need access to the Google Gemini AI API, which requires a Google Cloud account.
  • Installed Tools: Ensure you have Python 3.x and Django installed on your machine. If not, you can download them here for Python and install Django via pip.
  • Code Editor: You can use VS Code, PyCharm, or any other code editor.

Step-by-Step Guide

Step 1: Setting Up the Django Project

First, we need to set up the Django environment for the project:

  1. Create a Virtual Environment: python -m venv env source env/bin/activate # For Windows, use env\Scripts\activate
  2. Install Django: pip install django
  3. Create a New Django Project: django-admin startproject titlegen cd titlegen
  4. Start a New Django App: python manage.py startapp generator
  5. Migrate the Database:
    bash python manage.py migrate

Now, add the generator app to your INSTALLED_APPS in the settings.py file:

INSTALLED_APPS = [
    ...
    'generator',
]

Step 2: Set Up Google Gemini AI API

Next, we will integrate Google Gemini AI for title generation:

  1. Create a Google Cloud Project:
  1. Generate an API Key:
  • After enabling the API, create credentials for an API key. Save the API key, as you’ll need it to make requests from Django.
  1. Install Google Generative AI SDK:
  • Install the SDK for Google Gemini by running the following command:
    bash pip install google-generativeai

Step 3: Configure Django to Use Google Gemini AI

Now, we will configure Django to interact with Google Gemini AI. Add the following code in views.py in the generator app:

import google.generativeai as genai
from django.shortcuts import render
from django.http import JsonResponse

# Configure Google Gemini AI
genai.configure(api_key="your_google_gemini_ai_key")

# Define the generation configuration
generation_config = {
    "temperature": 1,
    "top_p": 0.95,
    "top_k": 64,
    "max_output_tokens": 8192,
}

def generate_content(prompt):
    """This function generates content based on the provided prompt."""
    model = genai.GenerativeModel(model_name="gemini-1.5-flash", generation_config=generation_config)
    chat_session = model.start_chat(history=[{"role": "user", "parts": [prompt]}])
    response = chat_session.send_message(prompt)
    return response.text

def generate_title(request):
    """This view handles the form submission and generates a title."""
    if request.method == 'POST':
        description = request.POST.get('description', '')
        if description:
            prompt = f"Generate a catchy YouTube video title for this description: \"{description}\""
            generated_title = generate_content(prompt)
            return JsonResponse({"generated_title": generated_title})
    return render(request, 'generate_title.html')

Step 4: Create or update the urls.py file in your app directory (e.g., titlegen/urls.py) to define the path for the YouTube title generator.

from django.urls import path
from .views import generate_title

urlpatterns = [
    path('', generate_title, name='generate_title'),
 
]

Step 5: Create an HTML Form for User Input

In your templates directory, create a file named generate_title.html. This file will contain a form where users can input the video description:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>YouTube Title Generator</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.8/clipboard.min.js"></script>
    <style>
        /* General Styles */
        body {
            font-family: 'Roboto', sans-serif;
            background-color: #f9f9f9;
            color: #333;
            text-align: center;
            margin: 0;
            padding: 0;
        }

        .container {
            max-width: 100%;
            width: 90%;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
            box-sizing: border-box;
            position: relative;
        }

        h1 {
            color: #ff5722;
            margin-bottom: 20px;
            font-size: 2em;
        }

        label {
            font-size: 1.1em;
            color: #333;
        }

        .text-box {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            box-sizing: border-box;
            margin-bottom: 15px;
            font-size: 1em;
            height: 100px;
            resize: vertical;
            background-color: #f5f5f5;
            transition: border-color 0.3s;
        }

        .text-box:focus {
            border-color: #ff5722;
            outline: none;
        }

        .result-box {
            width: 100%;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            box-sizing: border-box;
            margin-top: 20px;
            font-size: 1.2em;
            background-color: #e0ffe0;
            color: #333;
            min-height: 120px; /* Increased height for better visibility */
            overflow: auto;
            position: relative;
            display: none; /* Initially hidden */
        }

        .copy-icon {
            font-size: 1.5em;
            color: #4CAF50;
            cursor: pointer;
            margin-top: 10px;
            transition: color 0.3s, transform 0.3s;
        }

        .copy-icon:hover {
            color: #45a049;
            transform: scale(1.1);
        }

        .copy-feedback {
            display: none;
            position: absolute;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            background-color: #333;
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            font-size: 1em;
            z-index: 1000;
            animation: fadeInOut 2s ease-out;
        }

        @keyframes fadeInOut {
            0% { opacity: 0; }
            50% { opacity: 1; }
            100% { opacity: 0; }
        }

        .loading {
            display: none;
            font-size: 1.1em;
            color: #333;
            margin-top: 20px;
        }

        .loading .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #ff5722;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            animation: spin 1s linear infinite;
            display: inline-block;
            vertical-align: middle;
            margin-right: 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        input[type="submit"] {
            background: linear-gradient(90deg, #ff5722, #ff7043);
            border: none;
            color: white;
            font-size: 1.1em;
            padding: 15px 30px;
            border-radius: 5px;
            cursor: pointer;
            transition: background 0.3s, transform 0.3s;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        input[type="submit"]:hover {
            background: linear-gradient(90deg, #ff7043, #ff5722);
            transform: scale(1.05);
        }

        input[type="submit"]:active {
            background: linear-gradient(90deg, #ff5722, #ff7043);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }

        /* Responsive adjustments */
        @media (max-width: 768px) {
            h1 {
                font-size: 1.8em;
            }

            .text-box,
            .result-box {
                font-size: 1.1em;
                height: 120px; /* Increased height */
            }

            .copy-icon {
                font-size: 1.3em;
            }

            input[type="submit"] {
                font-size: 1em;
                padding: 12px 25px;
            }

            .container {
                width: 95%;
                padding: 15px;
                margin: 20px auto;
            }
        }

        @media (max-width: 480px) {
            h1 {
                font-size: 1.5em;
            }

            .text-box,
            .result-box {
                font-size: 1em;
                height: 140px; /* Further increased height */
            }

            .copy-icon {
                font-size: 1em;
            }

            input[type="submit"] {
                font-size: 0.9em;
                padding: 10px 20px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>YouTube Title Generator Tool</h1>
        <form method="post" id="titleForm">
            {% csrf_token %}
            <label for="description">Enter Video Description:</label><br><br>
            <textarea name="description" id="description" class="text-box" placeholder="Type your video description here..."></textarea><br>
            <input type="submit" value="Generate Title">
            <div class="loading">
                <div class="spinner"></div>
                <div>Generating...</div>
            </div>
        </form>

        <div id="generatedTitle" class="result-box"></div>
        <i id="copyIcon" class="copy-icon fas fa-copy" data-clipboard-target="#generatedTitle" title="Copy to Clipboard"></i>
        <div id="copyFeedback" class="copy-feedback">Title copied to clipboard!</div>
    </div>

    <script>
        // Initialize Clipboard.js
        var clipboard = new ClipboardJS('#copyIcon');

        clipboard.on('success', function(e) {
            var copyFeedback = document.getElementById('copyFeedback');
            copyFeedback.style.display = 'block';
            setTimeout(() => copyFeedback.style.display = 'none', 2000);
            e.clearSelection();
        });

        clipboard.on('error', function(e) {
            console.error('Error copying text: ', e);
        });

        document.getElementById('titleForm').onsubmit = function(event) {
            event.preventDefault();
            var description = document.getElementById('description').value;
            var submitButton = document.querySelector('input[type="submit"]');
            var loadingSpinner = document.querySelector('.loading');
            var generatedTitle = document.getElementById('generatedTitle');
            var copyIcon = document.getElementById('copyIcon');

            submitButton.disabled = true;
            loadingSpinner.style.display = 'flex';
            generatedTitle.style.display = 'none';
            copyIcon.style.display = 'none';

            fetch("{% url 'generate_title' %}", {
                method: 'POST',
                headers: {
                    'X-CSRFToken': '{{ csrf_token }}',
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `description=${encodeURIComponent(description)}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.generated_title) {
                    generatedTitle.innerText = data.generated_title;
                    submitButton.disabled = false;
                    loadingSpinner.style.display = 'none';
                    generatedTitle.style.display = 'block';
                    copyIcon.style.display = 'block';
                } else {
                    throw new Error('Title generation failed');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                submitButton.disabled = false;
                loadingSpinner.style.display = 'none';
                generatedTitle.style.display = 'none';
                copyIcon.style.display = 'none';
                alert('Error generating title. Please try again.');
            });
        };
    </script>
</body>
</html>

Step 6: Run the Django Development Server

Finally, start the Django development server to see your app in action:

python manage.py runserver

Visit http://127.0.0.1:8000/ in your browser. You can input a video description, and the AI-generated title will be displayed on the screen!


Scaling the Project Further

Now that you have the basic YouTube title generator running, you can scale the project by adding more features, such as:

  • SEO Optimization: Analyze the generated title for SEO ranking and suggest improvements.
  • Character Count Control: Ensure the generated title adheres to YouTube’s character limit.
  • Social Sharing: Allow users to share their generated titles on social media platforms.

Conclusion

Congratulations! You’ve successfully built a YouTube title generator using Django and Google Gemini AI. This project not only enhances your web development skills but also shows the potential of AI-powered applications in the creative content domain.

With just a few lines of code and the power of AI, you now have a tool that can generate catchy, optimized YouTube video titles. Feel free to explore other possibilities like adding keyword suggestions, optimizing for SEO, or even creating a full-fledged YouTube content generator.

For more tutorials and tech insights, don’t forget to check out my YouTube channel, blog, and follow me on Twitter for the latest updates!


About the Author
Asif Khan is a Python developer with years of experience in AI, machine learning, and web development. He specializes in building AI-driven applications that solve real-world problems. Follow Asif on YouTube and his Blog for more exciting project ideas.

Leave a Comment

Your email address will not be published. Required fields are marked *


Shopping Basket