Skip to content

Forum in maintenance, we will back soon 🙂

Implementing Youtub...
 
Notifications
Clear all

Implementing Youtube-Title-Generator-WP-UI in my AI tools.

10 Posts
3 Users
1 Reactions
145 Views
(@sahu)
Posts: 7
Active Member
Topic starter
 

@ Hasan sir, I am a big fan of you. I love the way you teach & help everybody. Today I implemented "Youtube-Title-Generator-WP-UI" to my youtube title generator tools but gave some errors(Something Went Wrong, please try again later!). I shared the code tried. Sir any solution is highly appreciated.

 

<script>
    document.getElementById('topic').addEventListener('keydown', function(e) {
    if (e.key === 'Enter' || e.keyCode === 13) {
        e.preventDefault();
        document.getElementById('generate-button').click();
    }
});

document.getElementById("generate-button").addEventListener("click", function(e){
    e.preventDefault();

    var generateButton = this;

    if (generateButton.disabled) return;

    generateButton.disabled = true;

    var topic = document.getElementById('topic').value.trim();


    if (!topic) {
        showMessage('Please enter something!');
        generateButton.disabled = false;
        return;
    }

    // input prompt here

    var prompt = `
    As an expert YouTuber with 10 Years Experience.
    your task is to generate 10 YouTube video titles based on the INPUT VIDEO TOPIC 
    and ensure high CTR for my upcoming video.
    First, use your expertise to develop the first 5 titles,
    ensuring they are engaging, accurately represent the video content,
    and abide by YouTube's optimal practices for high CTR.
    For the remaining five, pick 5 templates that best fit the video's theme from the 
    given list and use them to craft the titles.
    Templates List:
    -How To Not (Unwanted Outcome)-(Encouraging Words)!!
    -The Simple (Task) that (Defeated) EVERYONE Except (Authority Figure)
    -6 TOP (Objects) to Save You From (Unwanted Event)
    -(Objects) I Never (Action) (Current Year)
    -(Activity) Challenge That Will Change Your Life (30 DAYS RESULTS)
    -12 (Objects) that can (Achieve Goal)
    -[Achieve Goal] on [Platform] (easy [Activity] for beginners!)
    -[Time Frame] Killer [Activity] ([Benefit])
    -How to (Achieve Goal) in (Time Frame) [by (Current Year)]
    INPUT VIDEO TOPIC = ${topic}
    IMPORTANT: The output should be a JSON array only, don't write anything else! `;

    var loading = document.getElementById('loading');
    var result = document.getElementById('result');
    var resultC = document.getElementById('result-container');

    loading.style.display = 'block';
    resultC.style.display = 'none';

    var formData = new FormData();
    formData.append('action', 'custom_tool_youtube_title_generator');
    formData.append('prompt', prompt);

    fetch('/wp-admin/admin-ajax.php', { method: 'POST', body: formData })
        .then(response => response.json())
        .then(data => {
            loading.style.display = 'none';
            if (data.data.success) { // Updated this line
                result.innerHTML = '';
                data.data.titles.forEach(title => {
    var card = document.createElement('div');
    card.className = 'card';
    var titleText = document.createElement('span');
    titleText.className = 'title-text';
    titleText.textContent = title;
    card.appendChild(titleText);
    var copyIconContainer = document.createElement('div');
    copyIconContainer.className = 'copy-icon-container';
    var copyIcon = document.createElement('i');
    copyIcon.className = 'fas fa-copy tiny-copy-icon';
    copyIcon.addEventListener('click', function() {
        navigator.clipboard.writeText(title);
        showMessage('Copied to clipboard!');
    });
    copyIconContainer.appendChild(copyIcon);
    card.appendChild(copyIconContainer);
    result.appendChild(card);
});

                resultC.style.display = 'block';
            } else {
                showMessage("AI bot not available, please try again later!");
            }
            generateButton.disabled = false;
        })
        .catch(error => {
            showMessage("Something Went Wrong, please try again later!");
            generateButton.disabled = false;
        });

});

document.getElementById('copy-button').addEventListener('click', function() {
    var titles = Array.from(document.getElementById('result').getElementsByClassName('card')).map(el => el.textContent).join('\n');
    navigator.clipboard.writeText(titles);
    showMessage('Copied to clipboard!');
});

document.getElementById('message-close').addEventListener('click', function() {
    document.getElementById('message-box').style.display = 'none';
});

function showMessage(message) {
    var messageBox = document.getElementById('message-box');
    var messageText = document.getElementById('message-text');
    messageText.textContent = message;
    messageBox.style.display = 'flex';
}

</script>
<?php
function custom_tool_youtube_title_generator() {
    // Get the topic from the AJAX request
    $prompt = $_POST['prompt'];

    // OpenAI API URL and key
    $api_url = 'https://api.openai.com/v1/chat/completions';
    $api_key = 'sk-XXX';  // Replace with your actual OpenAI API key

    // Headers for the OpenAI API
    $headers = [
        'Content-Type' => 'application/json',
        'Authorization' => 'Bearer ' . $api_key
    ];

    // Body for the OpenAI API
    $body = [
        'model' => 'gpt-3.5-turbo',
        'messages' => [['role' => 'user', 'content' => $prompt]],
        'temperature' => 0.7
    ];

    // Args for the WordPress HTTP API
    $args = [
        'method' => 'POST',
        'headers' => $headers,
        'body' => json_encode($body),
        'timeout' => 120
    ];

    // Send the request
    $response = wp_remote_request($api_url, $args);

    // Handle the response
    if (is_wp_error($response)) {
        $error_message = $response->get_error_message();
        wp_send_json_error("Something went wrong: $error_message");
    } else {
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            wp_send_json_error('Invalid JSON in API response');
        } elseif (!isset($data['choices'])) {
            wp_send_json_error('API request failed. Response: ' . $body);
        } else {
            wp_send_json_success($data);
        }
    }

    // Always die in functions echoing AJAX content
   wp_die();
}

add_action('wp_ajax_custom_tool_youtube_title_generator', 'custom_tool_youtube_title_generator');
add_action('wp_ajax_nopriv_custom_tool_youtube_title_generator', 'custom_tool_youtube_title_generator');
?>
 
Posted : 03/12/2024 4:11 pm
SSAdvisor
(@ssadvisor)
Posts: 1127
Noble Member
 

@sahu please give a screenshot of what the results are.

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 03/12/2024 8:09 pm
(@sahu)
Posts: 7
Active Member
Topic starter
 
yt1
 
Posted : 03/13/2024 3:52 pm
Hasan Aboul Hasan
(@admin)
Posts: 1185
Member Admin
 

@sahu, do you have an active OpenAI Subscription? and did you set the API key?

 
Posted : 03/14/2024 6:58 am
SSAdvisor
(@ssadvisor)
Posts: 1127
Noble Member
 

@sahu before you can use the OpenAI API you must purchase tokens to use; have you done that?

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 03/14/2024 2:35 pm
(@sahu)
Posts: 7
Active Member
Topic starter
 

@admin

Hi, Sir, I have an active OpenAI Subscription. It works fine in Python but to implement in UI to display results it gave an error. The main problem is in the javascript file which I can not configure properly.
In my Python code:
prompt = "email marketing"
class Titles(BaseModel):
titles: List[str]
result = structured_generator(openai_model,prompt,Titles)
return {
'statusCode': 200,
'body': json.dumps(result.titles)
}

if I return json.dumps(result) it will give this:
titles=['1. How to Effectively use EmailMarketing To Boost Business', '2. Common EmailMarketing Misconceptions and How To correct Them', '3. 10 Tips For Creating Engaging Email Campaigns', '4. How to Improve Email Open Rates to Get More Subscribers', '5. How to Use EmailMarketingt To Grow Your Audience and Sales']
if I return json.dumps(result.titles) it will give this:
[
"1. How to Effectively use EmailMarketing To Boost Business",
"2. Common EmailMarketing Misconceptions and How To correct Them",
"3. 10 Tips For Creating Engaging Email Campaigns",
"4. How to Improve Email Open Rates to Get More Subscribers",
"5. How to Use EmailMarketingt To Grow Your Audience and Sales"
]

So which one I send as a JSON data in the body section?

Now in javascript, I think this part gives the error:

if (data.data.success) { // Updated this line
result.innerHTML = '';
data.data.titles.forEach(title => {
var card = document.createElement('div');

Mainly for this part: data.data.titles.forEach(title =>
It can not iterate titles list items correctly. I tried hours but as a newbie, I can not configure it.
Sir Please help me.

This post was modified 6 months ago by dibyendu
 
Posted : 03/15/2024 6:30 am
SSAdvisor
(@ssadvisor)
Posts: 1127
Noble Member
 

@sahu here's a hint, use the code insertion icon (<>) above to share code to preserve the formatting. Is the UI in Python or Wordpress?

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 03/15/2024 7:54 pm
(@sahu)
Posts: 7
Active Member
Topic starter
 

Hi, I configured. There's something wrong in my php code. Any way thanks for prompt response.

 
Posted : 03/16/2024 12:16 pm
SSAdvisor reacted
SSAdvisor
(@ssadvisor)
Posts: 1127
Noble Member
 

@sahu did you figure out what was wrong?

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 03/16/2024 2:05 pm
Hasan Aboul Hasan
(@admin)
Posts: 1185
Member Admin
 

did you test the backend PHP function directly without the UI and check if it is working? you can test with tools like: https://reqbin.com/

 
Posted : 03/16/2024 3:21 pm
Share:
[the_ad_group id=”312″]