Code viewer for World: Text to video with D-ID
// Cloned by Moses Crasto on 30 Nov 2023 from World "Chat with GPT model" by Starter user 
// Please leave this clone trail here.

var theprompt = "";
var Url = "https://api.d-id.com/";

// default body is margin 0 and padding 0 
// give it more whitespace:

$('body').css( "margin", "20px" );
$('body').css( "padding", "20px" );

document.write(`
    <div style="display: flex; justify-content: space-evenly;">
        <div>
            <h3>This uses <a href="https://docs.d-id.com/">D-ID AI API</a></h3>
            <div id=enterkey1>
                <h3>Enter API key for world to start</h3> 
            	<input style='width:25vw;' maxlength='2000' NAME="apikey" id="apikey" VALUE='' >  
            	<button onclick='setkey();'  class="ab-normbutton" >Set API key</button>
            </div>
            <div style="width:30vw; background-color:white; border: 1px solid black; margin:20; padding: 20px;">
                <h3>Enter text that you want the actor to say</h3>
                <p>The video might take some time to generate</p>
                <input style="width:80%;" id="me" value="">
                <button onclick="sendchat();" class="ab-normbutton">Send</button>
            </div>
            <div style="width:30vw; background-color:white; border: 1px solid black; margin:20; padding: 20px;">
                <h3>Select the language on input</h3>
                <input type="radio" id="option1" name="toggle" value="1">
                <label for="option1">English</label>
                <input type="radio" id="option2" name="toggle" value="2">
                <label for="option2">Irish</label>
                <input type="radio" id="option3" name="toggle" value="3">
                <label for="option3">French</label>
                <p>Here are options after selecting the language:<br> Irish- "Dia dhuit. Conas tá tú?"<br> French- "Bonjour. Comment vas-tu?"</p>
            </div>
        </div>
        <div style="width:500px; height:500px; border: 1px solid black; margin:20; padding: 20px;">
            <div id="them"></div>
        </div>
    </div>
`);

function setkey()          
{
	apikey =  jQuery("input#apikey").val();
	apikey = apikey.trim();
	$("#enterkey").html ( "<b>API key has been set. </b>" );
	starting();
}

var thatdata = {
    "source_url": "https://clips-presenters.d-id.com/amy/FLZ1USJl7m/vzswgDCwKZ/image.png",
    "driver_url": "bank://lively/driver-06",
    "script": {
        "type": "text",
        "ssml": true,
        "input": "<break time=\"5000ms\"/>",
        "provider": {
            "type": "microsoft",
            "voice_id": "en-US-JennyNeural"
        }
    },
    "config": {
        "fluent": true, //to get output video that starts and ends with the same frame
        "stitch": true //to get output video that contains the entire and not only a cropped video around the face area
    }
}

// string representing JSON
var thatdatastring = JSON.stringify ( thatdata ); 

function starting(){
    
    // HTTP headers must be set up with API key: 
    $.ajaxSetup({
       headers:
       {
            "Content-Type": "application/json",
            "Authorization": "Basic "+apikey  
       }
    });
    
    $.ajax({
        type: "POST",
        url: Url+"talks",
        data: thatdatastring,
        dataType: "json",
        success: function ( d, rc ) { successfnthat ( d, rc ); },
        error: function(e) { errorfn (e); }
    });
}

// global variable to examine return data
var answer;
var answerthat;

function successfnthat ( data, rc )
{
    console.log(data);
    console.log("here");
    id = data["id"];
    setTimeout(doSomething, 5000);
    function doSomething() {
        $.ajax({
            type: "GET",
            url: `${Url}talks/${id}`,
            success: function (d, rc) { successfthat(d, rc); },
            error: function (e) { errorfn(e); }
        });
    }
      
    function successfthat(data, rc) {
        console.log("in here");
        console.log(data);
        answerthat = data.result_url;
        $("#them").html(`<video width="500" height="500" loop autoplay><source src="${answerthat}"></video>`);
    }
}

var voice;
var style;

function sendchat()
{
    theprompt = $("#me").val();
    if($('input[name="toggle"]:checked').val() === 1){
        voice = "en-US-JennyNeural";
        style = "Sad";
    }else if($('input[name="toggle"]:checked').val() === 2){
        voice = "ga-IE-OrlaNeural";
        style = "Default";
    }else if($('input[name="toggle"]:checked').val() === 3){
        voice = "fr-FR-DeniseNeural";
        style = "Cheerful";
    }// voices from https://speech.microsoft.com/portal/voicegallery
    
    console.log(voice);
    console.log(style);
    console.log(theprompt);
    
    // construct request as JSON
    var thedata = {
        "script": {
            "type": "text", //can also be audio type "type": "audio"
            "ssml": true,
            "input": theprompt, //if type is audio "audio_url": "https://path.to/audio.mp3"
            "provider": {
            	"type": "microsoft",
            	"voice_id": voice,
            	"voice-config": {
            	    "style":style
            	}
            }
        },
        "driver_expressions": {
            "expressions": [
                {
                    "start_frame": 0,
                    "expression": "happy", // to change the expression to surprise or neutral or serious
                    "intensity": 1 //to control intensity of the expression (0 to 1.0)
                }
            ]
        },
        "presenter_id": "amy-FLZ1USJl7m",
        "driver_id": "vzswgDCwKZ",
        "background": {
            "color": "#aa22cc" //to change the background
        }
      };
       
    // string representing JSON
    var thedatastring = JSON.stringify ( thedata );   

    // POST to 3rd party URL: 
    $.ajax({
        type: "POST",
        url: Url+"clips",
        data: thedatastring,
        dataType: "json",
        success: function ( d, rc ) { successfn ( d, rc ); },
        error: function() { errorfn (); }
    });
}

function successfn ( data, rc )
{
    id = data["id"];
    console.log(id);
    console.log(data);
    setTimeout(doSomething, 15000);
    function doSomething() {
        $.ajax({
            type: "GET",
            url: `${Url}clips/${id}`,
            success: function (d, rc) { successf(d, rc); },
            error: function (e) { errorfn(e); }
        });
    }
      
    function successf(data, rc) {
        var answer = data.result_url;
        console.log(answer);
        $("#them").html(`<video id="myvideo" width="500" height="500" autoplay><source src="${answer}"></video>`);
        document.getElementById('myvideo').addEventListener('ended', myHandler, false);
    }
}

function myHandler(e) {
    var videoFile = answerthat;
    $('#myvideo').fadeOut(500, function () {
        // Change video source
        $('#myvideo source').attr('src', videoFile);
        
        // Load and fade in the new video
        $('#myvideo')[0].load();
        $('#myvideo').fadeIn(500);
        
        // Set loop attribute
        $('#myvideo').attr("loop", true);
    });
    document.getElementById('myvideo').removeEventListener('ended', myHandler, false)
}
 
function errorfn(e)
{
    console.log(e);
    $("#them").html ( "<font color=red><b> Unknown error. </b></font>" ); 
}