Code viewer for World: Chat with GPT model (clone...
/*

// Cloned by Venkatraman Palani on 28 Nov 2023 from World "Chat with GPT model" by Starter user 
// Please leave this clone trail here.
 


// talk to OpenAI GPT model (ChatGPT)
// adapted from:
//  https://platform.openai.com/docs/api-reference/making-requests


const openaiURL = "https://api.openai.com/v1/chat/completions";           // can POST to this 3rd party URL
  
const themodel = "gpt-3.5-turbo";       // the OpenAI model we are going to talk to 
    

// default API key and prompt:

var apikey = "";
var theprompt = "hello";


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

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


 
document.write ( `

<h1> Chat with GPT model </h1>

Running World:
<a href='https://ancientbrain.com/world.php?world=2850716357'>Chat with GPT model</a>.
<br> 
Chat with
  <A HREF="https://platform.openai.com/docs/models/overview">GPT 3.5</A>
 using the 
<A HREF="https://en.wikipedia.org/wiki/OpenAI">OpenAI    </A>  API.
 <br> 
 This is the model
   <A HREF="https://en.wikipedia.org/wiki/ChatGPT">ChatGPT</A>   uses.

<pre>

</pre>

<h3> Enter API key </h3>

The crucial thing is you need an    "API key" to talk to OpenAI. <br>
Register for free and get your API key  
<a href='https://platform.openai.com/account/api-keys'>here</a>.
<br>
You enter your API key below and then chat away.
Then communications to OpenAI come from your IP address using your API key. 
<br>
This World   will never  store your API key. 
You can view the <a href='https://ancientbrain.com/viewjs.php?world=2850716357'> source code</a>  to see that is true!
<p>

<div id=enterkey>
Enter API key: 
	<input    style='width:25vw;'    maxlength='2000'   NAME="apikey"    id="apikey"       VALUE='' >  
	<button onclick='setkey();'  class=ab-normbutton >Set API key</button>
</div>

<pre>

</pre>

<div style="width:60vw; background-color:white;  border: 1px solid black; margin:20; padding: 20px;">
<h3> Enter a "prompt" </h3>
<INPUT style="width:50vw;" id=me value="when did henry vii die?" >
<button onclick="sendchat();"     class=ab-normbutton > Send </button> 
</div>

<div style="width:60vw; background-color:#ffffcc;  border: 1px solid black; margin:20; padding: 20px;">
<h3> GPT replies </h3>
<div id=them > </div>
</div>
 
 <p> <i> Be warned that GPT replies are often completely inaccurate.<br> 
 All LLM systems <a href="https://www.google.com/search?q=llm+hallucination"> "hallucinate"</a>.
 It is how they work. </i> </p>

<pre>

</pre>

` );




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



// Enter will also send chat:

	document.getElementById('me').onkeydown   = function(event) 	{ if (event.keyCode == 13)  sendchat(); };




// --- Send my line of text ----------------------------------------------------------------

function sendchat()
{
  theprompt = $("#me").val();
  
// construct request as JSON
// "Lowering temperature means it will take fewer risks, and completions will be more accurate and deterministic. Increasing temperature will result in more diverse completions."

var thedata = {
     "model": themodel,
     "temperature": 0.7,
     "messages": [{
         "role": "user", 
         "content": theprompt
        }] 
   };
   
// then as string representing that JSON:
var thedatastring = JSON.stringify ( thedata );   
   
// HTTP headers must be set up with API key: 

$.ajaxSetup({
   headers:
   {
        "Content-Type": "application/json",
        "Authorization": "Bearer " + apikey  
   }
});


// POST to 3rd party URL: 

 $.ajax({
    type: "POST",
    url: openaiURL,
    data: thedatastring,
    dataType: "json",
    success: function ( d, rc ) { successfn ( d, rc ); },
      error: function()         { errorfn (); }
 });
 
}


 
 // global variable to examine return data in console 
 var a;
 
 
 
 function successfn ( data, rc )
 {
     a = data;
     var answer = a["choices"][0].message.content;
     $("#them").html ( answer );
 }
 
 function errorfn()
 {
     if ( apikey == "" )    $("#them").html ( "<font color=red><b> Enter API key to be able to chat. </b></font>" );
     else                   $("#them").html ( "<font color=red><b> Unknown error. </b></font>" ); 
 }
 
 
*/

/*
const options = {
  method: 'POST',
  headers: {
    'xi-api-key': '880a3b9e11cf2d73998a00b30f343968',
    'Content-Type': 'application/json'
  },
  body: '{"model_id":"eleven_monolingual_v1","text":"Baba Yaga John Wick is a killer man of focus and sheer will plus motivation","voice_settings":{"similarity_boost":0.5,"stability":0.5,"style":1,"use_speaker_boost":true}}'
};
*/

/*
$.ajax({
    url: 'https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM?output_format=mp3_44100_64',
    method: 'POST',
    headers: {
        'xi-api-key': '880a3b9e11cf2d73998a00b30f343968',
        'Content-Type': 'application/json'
    },
    data: JSON.stringify({
        model_id: "eleven_monolingual_v1",
        text: "Baba Yaga John Wick is a killer man of focus and sheer will plus motivation",
        voice_settings: {
            similarity_boost: 0.5,
            stability: 0.5,
            style: 1,
            use_speaker_boost: true
        }
    }),
    success: function(response) {
        console.log(response);
    },
    error: function(err) {
        console.error(err);
    }
});
*/


/*
fetch('https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM?output_format=mp3_44100_64', options)
  .then( res => res.json() )
  .then( res => console.log(res) );
  
*/

/*
fetch('https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM?output_format=mp3_44100_64', options)
  .then(response => response.json())
  .then(response => console.log(response))
//.catch(err => console.error(err));
*/

/*
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Text to Speech</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <button id="convertText">Convert Text to Speech</button>
    <audio id="audioPlayer" controls></audio>

    <script>
        // Your JavaScript goes here
    </script>
</body>
</html>
```



```javascript
$(document).ready(function() {
    $('#convertText').click(function() {
        $.ajax({
            url: 'https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM?output_format=mp3_44100_64',
            method: 'POST',
            headers: {
                'xi-api-key': '880a3b9e11cf2d73998a00b30f343968',
                'Content-Type': 'application/json'
            },
            data: JSON.stringify({
                model_id: "eleven_monolingual_v1",
                text: "Baba Yaga John Wick is a killer man of focus and sheer will plus motivation",
                voice_settings: {
                    similarity_boost: 0.5,
                    stability: 0.5,
                    style: 1,
                    use_speaker_boost: true
                }
            }),
            success: function(response) {
                // Assuming the response contains the URL of the MP3 file
                if (response && response.url) {
                    $('#audioPlayer').attr('src', response.url);
                    $('#audioPlayer')[0].play();
                }
            },
            error: function(err) {
                console.error('Error: ', err);
            }
        });
    });
});
```
*/


/*

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Text to Speech</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <button id="convertText">Convert Text to Speech</button>
    <audio id="audioPlayer" controls></audio>

    <script>
        $(document).ready(function() {
            $('#convertText').click(function() {
                $.ajax({
                    url: 'https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM?output_format=mp3_44100_64',
                    method: 'POST',
                    headers: {
                        'xi-api-key': '880a3b9e11cf2d73998a00b30f343968',
                        'Content-Type': 'application/json'
                    },
                    data: JSON.stringify({
                        model_id: "eleven_monolingual_v1",
                        text: "Baba Yaga John Wick is a killer man of focus and sheer will plus motivation",
                        voice_settings: {
                            similarity_boost: 0.5,
                            stability: 0.5,
                            style: 1,
                            use_speaker_boost: true
                        }
                    }),
                    xhrFields: {
                        responseType: 'blob' // to handle binary data
                    },
                    success: function(blob) {
                        // Create a URL from the blob
                        var url = window.URL.createObjectURL(blob);
                        $('#audioPlayer').attr('src', url);
                        $('#audioPlayer')[0].play();
                    },
                    error: function(err) {
                        console.error('Error: ', err);
                    }
                });
            });
        });
    </script>
</body>
</html>

*/



/*
        document.write('<button id="convertText">Convert Text to Speech</button>');
        document.write('<audio id="audioPlayer" controls></audio>');

        // When the document is fully loaded
        $(document).ready(function() {
            $('#convertText').click(function() {
                $.ajax({
                    url: 'https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM?output_format=mp3_44100_64',
                    method: 'POST',
                    headers: {
                        'xi-api-key': '880a3b9e11cf2d73998a00b30f343968',
                        'Content-Type': 'application/json'
                    },
                    data: JSON.stringify({
                        model_id: "eleven_monolingual_v1",
                        text: "Baba Yaga John Wick is a killer man of focus and sheer will plus motivation",
                        voice_settings: {
                            similarity_boost: 0.5,
                            stability: 0.5,
                            style: 1,
                            use_speaker_boost: true
                        }
                    }),
                    xhrFields: {
                        responseType: 'blob' // to handle binary data
                    },
                    success: function(blob) {
                        // Create a URL from the blob
                        var url = window.URL.createObjectURL(blob);
                        $('#audioPlayer').attr('src', url);
                        $('#audioPlayer')[0].play();
                    },
                    error: function(err) {
                        console.error('Error: ', err);
                    }
                });
            });
        });

*/


/*
        // Write the HTML content for text input, button, and audio player
        document.write('<input id="textInput" type="text" placeholder="Enter text here...">');
        document.write('<button id="convertText">Convert Text to Speech</button>');
        document.write('<audio id="audioPlayer" controls></audio>');

        $(document).ready(function() {
            $('#convertText').click(function() {
                var textToConvert = $('#textInput').val(); // Get the input text
                if (textToConvert) {
                    $.ajax({
                        url: 'https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM?output_format=mp3_44100_64',
                        method: 'POST',
                        headers: {
                            'xi-api-key': '880a3b9e11cf2d73998a00b30f343968',
                            'Content-Type': 'application/json'
                        },
                        data: JSON.stringify({
                            model_id: "eleven_monolingual_v1",
                            text: textToConvert, // Use the input text for the API call
                            voice_settings: {
                                similarity_boost: 0.5,
                                stability: 0.5,
                                style: 1,
                                use_speaker_boost: true
                            }
                        }),
                        xhrFields: {
                            responseType: 'blob' // to handle binary data
                        },
                        success: function(blob) {
                            var url = window.URL.createObjectURL(blob);
                            $('#audioPlayer').attr('src', url);
                            $('#audioPlayer')[0].play();
                        },
                        error: function(err) {
                            console.error('Error: ', err);
                        }
                    });
                } else {
                    alert("Please enter some text to convert.");
                }
            });
        });

*/



/*
        document.write('<style>');
        document.write('body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; flex-direction: column; height: 100vh; background-color: #f2f2f2; margin: 0; padding: 20px; }');
        document.write('#textInput { padding: 10px; width: 300px; margin-bottom: 10px; border: 1px solid #ddd; border-radius: 4px; }');
        document.write('#convertText { padding: 10px 20px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }');
        document.write('#convertText:hover { background-color: #0056b3; }');
        document.write('#audioPlayer { margin-top: 20px; width: 300px; }');
        document.write('</style>');

        document.write('<input id="textInput" type="text" placeholder="Enter text here...">');
        document.write('<button id="convertText">Convert Text to Speech</button>');
        document.write('<audio id="audioPlayer" controls></audio>');

        $(document).ready(function() {
            $('#convertText').click(function() {
                var textToConvert = $('#textInput').val();
                if (textToConvert) {
                    $.ajax({
                        url: 'https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM?output_format=mp3_44100_64',
                        method: 'POST',
                        headers: {
                            'xi-api-key': '880a3b9e11cf2d73998a00b30f343968',
                            'Content-Type': 'application/json'
                        },
                        data: JSON.stringify({
                            model_id: "eleven_monolingual_v1",
                            text: textToConvert, // Use the input text for the API call
                            voice_settings: {
                                similarity_boost: 0.5,
                                stability: 0.5,
                                style: 1,
                                use_speaker_boost: true
                            }
                        }),
                        xhrFields: {
                            responseType: 'blob' // to handle binary data
                        },
                        success: function(blob) {
                            var url = window.URL.createObjectURL(blob);
                            $('#audioPlayer').attr('src', url);
                            $('#audioPlayer')[0].play();
                        },
                        error: function(err) {
                            console.error('Error: ', err);
                        }
                    });
                } else {
                    alert("Please enter some text to convert.");
                }
            });
        });
*/




/*
document.write('<style>');
        document.write('body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; flex-direction: column; height: 100vh; background-color: #f2f2f2; margin: 0; padding: 20px; }');
        document.write('.voice-info { margin-top: 10px; padding: 10px; border: 1px solid #ddd; border-radius: 4px; background-color: #fff; }');
        document.write('</style>');

        document.write('<select id="voiceSelect"></select>');
        document.write('<div id="voiceInfo" class="voice-info"></div>');
        document.write('<input id="textInput" type="text" placeholder="Enter text here...">');
        document.write('<button id="convertText">Convert Text to Speech</button>');
        document.write('<audio id="audioPlayer" controls></audio>');

        $(document).ready(function() {
            // Fetching voice data from the JSON file
            $.ajax({
                url: 'https://ancientbrain.com/uploads/palaniv2/voices.json',
                method: 'GET',
                dataType: 'json',
                success: function(data) {
                    var voices = data;
                    
                    // Populate the dropdown
                    voices.forEach(function(voice) {
                        $('#voiceSelect').append(new Option(voice.name, voice.voice_id));
                    });

                    // Display voice information
                    $('#voiceSelect').change(function() {
                        var selectedVoice = voices.find(v => v.voice_id === this.value);
                        var infoText = 'Accent: ' + selectedVoice.labels.accent + '<br>' +
                                       'Description: ' + selectedVoice.labels.description + '<br>' +
                                       'Age: ' + selectedVoice.labels.age + '<br>' +
                                       'Gender: ' + selectedVoice.labels.gender + '<br>' +
                                       'Use Case: ' + selectedVoice.labels['use case'];
                        $('#voiceInfo').html(infoText);
                    }).change();
                },
                error: function(err) {
                    console.error('Error fetching voice data: ', err);
                }
            });

            $('#convertText').click(function() {
                var selectedVoiceId = $('#voiceSelect').val();
                var textToConvert = $('#textInput').val();
                if (textToConvert) {
                    $.ajax({
                        url: 'https://api.elevenlabs.io/v1/text-to-speech/' + selectedVoiceId + '?output_format=mp3_44100_64',
                        method: 'POST',
                        headers: {
                            'xi-api-key': '880a3b9e11cf2d73998a00b30f343968',
                            'Content-Type': 'application/json'
                        },
                        data: JSON.stringify({
                            text: textToConvert,
                            voice_settings: {
                                similarity_boost: 0.5,
                                stability: 0.5,
                                style: 1,
                                use_speaker_boost: true
                            }
                        }),
                        xhrFields: {
                            responseType: 'blob'
                        },
                        success: function(blob) {
                            var url = window.URL.createObjectURL(blob);
                            $('#audioPlayer').attr('src', url);
                            $('#audioPlayer')[0].play();
                        },
                        error: function(err) {
                            console.error('Error: ', err);
                        }
                    });
                } else {
                    alert("Please enter some text to convert.");
                }
            });
        });
        
*/





/*
document.write('<style>');
        document.write('body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; flex-direction: column; height: 100vh; background-color: #f2f2f2; margin: 0; padding: 20px; }');
        document.write('.voice-info { margin-top: 10px; padding: 10px; border: 1px solid #ddd; border-radius: 4px; background-color: #fff; }');
        document.write('#textInput { padding: 10px; width: 300px; margin-bottom: 10px; border: 1px solid #ddd; border-radius: 4px; }');
        document.write('#convertText { padding: 10px 20px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }');
        document.write('#convertText:hover { background-color: #0056b3; }');
        document.write('#audioPlayer { margin-top: 20px; width: 300px; }');
        document.write('</style>');

        document.write('<select id="voiceSelect"></select>');
        document.write('<div id="voiceInfo" class="voice-info"></div>');
        document.write('<input id="textInput" type="text" placeholder="Enter text here...">');
        document.write('<button id="convertText">Convert Text to Speech</button>');
        document.write('<audio id="audioPlayer" controls></audio>');

        function handleVoiceData(voices) {
            // Populate the dropdown
            voices.forEach(function(voice) {
                $('#voiceSelect').append(new Option(voice.name, voice.voice_id));
            });

            // Display voice information
            $('#voiceSelect').change(function() {
                var selectedVoice = voices.find(v => v.voice_id === this.value);
                var infoText = 'Accent: ' + selectedVoice.labels.accent + '<br>' +
                               'Description: ' + selectedVoice.labels.description + '<br>' +
                               'Age: ' + selectedVoice.labels.age + '<br>' +
                               'Gender: ' + selectedVoice.labels.gender + '<br>' +
                               'Use Case: ' + selectedVoice.labels['use case'];
                $('#voiceInfo').html(infoText);
            }).change();
        }

        $(document).ready(function() {
            // Add a script tag to load the JSONP data
            var script = document.createElement('script');
            script.src = 'https://ancientbrain.com/uploads/palaniv2/voices.jsonp'; // JSONP URL
            document.head.appendChild(script);

            $('#convertText').click(function() {
                var selectedVoiceId = $('#voiceSelect').val();
                var textToConvert = $('#textInput').val();
                if (textToConvert) {
                    $.ajax({
                        url: 'https://api.elevenlabs.io/v1/text-to-speech/' + selectedVoiceId + '?output_format=mp3_44100_64',
                        method: 'POST',
                        headers: {
                            'xi-api-key': '880a3b9e11cf2d73998a00b30f343968',
                            'Content-Type': 'application/json'
                        },
                        data: JSON.stringify({
                            text: textToConvert,
                            voice_settings: {
                                similarity_boost: 0.5,
                                stability: 0.5,
                                style: 1,
                                use_speaker_boost: true
                            }
                        }),
                        xhrFields: {
                            responseType: 'blob'
                        },
                        success: function(blob) {
                            var url = window.URL.createObjectURL(blob);
                            $('#audioPlayer').attr('src', url);
                            $('#audioPlayer')[0].play();
                        },
                        error: function(err) {
                            console.error('Error: ', err);
                        }
                    });
                } else {
                    alert("Please enter some text to convert.");
                }
            });
        });
        
*/


/*

        document.write('<style>');
        document.write('body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; flex-direction: column; height: 100vh; background-color: #f2f2f2; margin: 0; padding: 20px; }');
        document.write('.voice-info { margin-top: 10px; padding: 10px; border: 1px solid #ddd; border-radius: 4px; background-color: #fff; }');
        document.write('#textInput { padding: 10px; width: 300px; margin-bottom: 10px; border: 1px solid #ddd; border-radius: 4px; }');
        document.write('#convertText { padding: 10px 20px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }');
        document.write('#convertText:hover { background-color: #0056b3; }');
        document.write('#audioPlayer { margin-top: 20px; width: 300px; }');
        document.write('</style>');

        document.write('<select id="voiceSelect"></select>');
        document.write('<div id="voiceInfo" class="voice-info"></div>');
        document.write('<input id="textInput" type="text" placeholder="Enter text here...">');
        document.write('<button id="convertText">Convert Text to Speech</button>');
        document.write('<audio id="audioPlayer" controls></audio>');

        $(document).ready(function() {
            // Fetching voice data using $.getJSON
            $.getJSON('/uploads/palaniv2/voices.json', function(data) {
                // Populate the dropdown
                console.log(data);
                if (typeof data === 'string') {
                    data = JSON.parse(data);
                }
                
                var voices = data.voices;
                voices.forEach(function(voice) {
                    /*var name = voice.name;
                    var attributes = voice.labels;
                    var dropdownHtml = '<div class="dropdown">' +
                               '<button>' + name + '</button>' +
                               '<div class="dropdown-content">' +
                               '<p><b>Voice ID:</b> ' + voice.voice_id + '</p>' +
                               '<p><b>Accent:</b> ' + attributes.accent + '</p>' +
                               '<p><b>Description:</b> ' + attributes.description + '</p>' +
                               '<p><b>Age:</b> ' + attributes.age + '</p>' +
                               '<p><b>Gender:</b> ' + attributes.gender + '</p>' +
                               '<p><b>Use Case:</b> ' + attributes['use case'] + '</p>' +
                               '</div></div>';
                    document.write(dropdownHtml); (*)/
                    
                    $('#voiceSelect').append(new Option(voice.name, voice.voice_id));
                });
                
                //data.forEach(function(voice) {
                //    $('#voiceSelect').append(new Option(voice.name, voice.voice_id));
                //});

                // Initial display of voice information
                //displayVoiceInfo(data[0]);
                displayVoiceInfo(voices[0]);
                
                // Update voice information when a new voice is selected
                //$('#voiceSelect').change(function() {
                //    var selectedVoice = data.find(v => v.voice_id === this.value);
                //    displayVoiceInfo(selectedVoice);
                //});
                $('#voiceSelect').change(function() {
                    var selectedVoice = voices.find(v => v.voice_id === this.value);
                    displayVoiceInfo(selectedVoice);
                });
            }).fail(function(jqxhr, textStatus, error) {
                var err = textStatus + ", " + error;
                console.error("Request Failed: " + err);
            });

            function displayVoiceInfo(voice) {
                var infoText = 'Accent: ' + voice.labels.accent + '<br>' +
                               'Description: ' + voice.labels.description + '<br>' +
                               'Age: ' + voice.labels.age + '<br>' +
                               'Gender: ' + voice.labels.gender + '<br>' +
                               'Use Case: ' + voice.labels['use case'];
                $('#voiceInfo').html(infoText);
            }

            $('#convertText').click(function() {
                var selectedVoiceId = $('#voiceSelect').val();
                var textToConvert = $('#textInput').val();
                if (textToConvert) {
                    $.ajax({
                        url: 'https://api.elevenlabs.io/v1/text-to-speech/' + selectedVoiceId + '?output_format=mp3_44100_64',
                        method: 'POST',
                        headers: {
                            'xi-api-key': '880a3b9e11cf2d73998a00b30f343968',
                            'Content-Type': 'application/json'
                        },
                        data: JSON.stringify({
                            text: textToConvert,
                            voice_settings: {
                                similarity_boost: 0.5,
                                stability: 0.5,
                                style: 1,
                                use_speaker_boost: true
                            }
                        }),
                        xhrFields: {
                            responseType: 'blob'
                        },
                        success: function(blob) {
                            var url = window.URL.createObjectURL(blob);
                            $('#audioPlayer').attr('src', url);
                            $('#audioPlayer')[0].play();
                        },
                        error: function(err) {
                            console.error('Error: ', err);
                        }
                    });
                } else {
                    alert("Please enter some text to convert.");
                }
            });
        });

*/

//-------------------------------------//

/*
document.write(`
<style>
    body { font-family: Arial, sans-serif; }
    .dropdown { position: relative; display: inline-block; }
    .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); padding: 12px 16px; z-index: 1; }
    .dropdown:hover .dropdown-content { display: block; }
</style>
<div id="voice-dropdowns"></div>
`);

$(document).ready(function() {
    $.getJSON('/uploads/palaniv2/voices.json', function(data) {
        var voices = data.voices;
        voices.forEach(function(voice) {
            var name = voice.name;
            var attributes = voice.labels;
            var dropdownHtml = '<div class="dropdown">' +
                               '<button>' + name + '</button>' +
                               '<div class="dropdown-content">' +
                               '<p><b>Voice ID:</b> ' + voice.voice_id + '</p>' +
                               '<p><b>Accent:</b> ' + attributes.accent + '</p>' +
                               '<p><b>Description:</b> ' + attributes.description + '</p>' +
                               '<p><b>Age:</b> ' + attributes.age + '</p>' +
                               '<p><b>Gender:</b> ' + attributes.gender + '</p>' +
                               '<p><b>Use Case:</b> ' + attributes['use case'] + '</p>' +
                               '</div></div>';
            document.write(dropdownHtml);
        });
    }).fail(function() {
        console.error("Error fetching the JSON data");
    });
});
*/



//--------------

/*
        document.write('<style>');
        document.write('body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; flex-direction: column; height: 100vh; background-color: #f2f2f2; margin: 0; padding: 20px; }');
        document.write('.voice-info { margin-top: 10px; padding: 10px; border: 1px solid #ddd; border-radius: 4px; background-color: #fff; }');
        document.write('#textInput { padding: 10px; width: 300px; margin-bottom: 10px; border: 1px solid #ddd; border-radius: 4px; }');
        document.write('#convertText { padding: 10px 20px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }');
        document.write('#convertText:hover { background-color: #0056b3; }');
        document.write('#audioPlayer { margin-top: 20px; width: 300px; }');
        document.write('</style>');

        document.write('<select id="voiceSelect"></select>');
        document.write('<div id="voiceInfo" class="voice-info"></div>');
        document.write('<input id="textInput" type="text" placeholder="Enter text here...">');
        document.write('<button id="convertText">Convert Text to Speech</button>');
        document.write('<audio id="audioPlayer" controls></audio>');

        $(document).ready(function() {
            var voices = []; // Variable to hold the voices data

            // Fetching voice data using $.getJSON
            $.getJSON('/uploads/palaniv2/voices.json', function(data) {
                voices = data; // Assigning the fetched data to the voices variable

                // Populate the dropdown
                voices.forEach(function(voice) {
                    $('#voiceSelect').append(new Option(voice.name, voice.voice_id));
                });

                // Initial display of voice information
                if (voices.length > 0) {
                    displayVoiceInfo(voices[0]);
                }

                // Update voice information when a new voice is selected
                $('#voiceSelect').change(function() {
                    var selectedVoice = voices.find(v => v.voice_id === this.value);
                    displayVoiceInfo(selectedVoice);
                });
            }).fail(function(jqxhr, textStatus, error) {
                var err = textStatus + ", " + error;
                console.error("Request Failed: " + err);
            });

            function displayVoiceInfo(voice) {
                var infoText = 'Accent: ' + voice.labels.accent + '<br>' +
                               'Description: ' + voice.labels.description + '<br>' +
                               'Age: ' + voice.labels.age + '<br>' +
                               'Gender: ' + voice.labels.gender + '<br>' +
                               'Use Case: ' + voice.labels['use case'];
                $('#voiceInfo').html(infoText);
            }

            $('#convertText').click(function() {
                var selectedVoiceId = $('#voiceSelect').val();
                var textToConvert = $('#textInput').val();
                if (textToConvert) {
                    $.ajax({
                        url: 'https://api.elevenlabs.io/v1/text-to-speech/' + selectedVoiceId + '?output_format=mp3_44100_64',
                        method: 'POST',
                        headers: {
                            'xi-api-key': '880a3b9e11cf2d73998a00b30f343968',
                            'Content-Type': 'application/json'
                        },
                        data: JSON.stringify({
                            text: textToConvert,
                            voice_settings: {
                                similarity_boost: 0.5,
                                stability: 0.5,
                                style: 1,
                                use_speaker_boost: true
                            }
                        }),
                        xhrFields: {
                            responseType: 'blob'
                        },
                        success: function(blob) {
                            var url = window.URL.createObjectURL(blob);
                            $('#audioPlayer').attr('src', url);
                            $('#audioPlayer')[0].play();
                        },
                        error: function(err) {
                            console.error('Error: ', err);
                        }
                    });
                } else {
                    alert("Please enter some text to convert.");
                }
            });
        });

*/




//++++++++++++++++++++//


        document.write('<style>');
        document.write('body { font-family: Arial, sans-serif; display: flex; flex-direction: column; align-items: center; background-color: #f2f2f2; margin: 0; padding: 20px; }');
        document.write('.section { margin-bottom: 20px; }');
        document.write('.voice-info, .image-container { margin-top: 10px; padding: 10px; border: 1px solid #ddd; border-radius: 4px; background-color: #fff; }');
        document.write('input, button { padding: 10px; margin-bottom: 10px; border: 1px solid #ddd; border-radius: 4px; }');
        document.write('button { background-color: #007bff; color: white; border: none; cursor: pointer; }');
        document.write('button:hover { background-color: #0056b3; }');
        document.write('audio, img { margin-top: 20px; max-width: 300px; }');
        document.write('</style>');

        // Text to Speech Section
        document.write('<div class="section">');
        document.write('<h2>Text to Speech</h2>');
        document.write('<select id="voiceSelect"></select>');
        document.write('<div id="voiceInfo" class="voice-info"></div>');
        document.write('<input id="textInput" type="text" placeholder="Enter text here...">');
        document.write('<button id="convertText">Convert Text to Speech</button>');
        document.write('<audio id="audioPlayer" controls></audio>');
        document.write('</div>');

        // Text to Image Section
        document.write('<div class="section">');
        document.write('<h2>Text to Image</h2>');
        document.write('<input id="textPrompt" type="text" placeholder="Enter your prompt...">');
        document.write('<button id="generateImage">Generate Image</button>');
        document.write('<div id="imageContainer" class="image-container"></div>');
        document.write('</div>');

        $(document).ready(function() {
            // Text to Speech functionality
            /*$.getJSON('/uploads/palaniv2/voices.json', function(data) {
                var voices = data; // Assigning fetched data to voices variable
                voices.forEach(function(voice) {
                    $('#voiceSelect').append(new Option(voice.name, voice.voice_id));
                });

                displayVoiceInfo(voices[0]); // Initial display of voice information

                $('#voiceSelect').change(function() {
                    var selectedVoice = voices.find(v => v.voice_id === this.value);
                    displayVoiceInfo(selectedVoice);
                });
            });*/
            // Fetching voice data using $.getJSON
            $.getJSON('/uploads/palaniv2/voices.json', function(data) {
                // Populate the dropdown
                console.log(data);
                if (typeof data === 'string') {
                    data = JSON.parse(data);
                }
                
                var voices = data.voices;
                voices.forEach(function(voice) {
                    /*var name = voice.name;
                    var attributes = voice.labels;
                    var dropdownHtml = '<div class="dropdown">' +
                               '<button>' + name + '</button>' +
                               '<div class="dropdown-content">' +
                               '<p><b>Voice ID:</b> ' + voice.voice_id + '</p>' +
                               '<p><b>Accent:</b> ' + attributes.accent + '</p>' +
                               '<p><b>Description:</b> ' + attributes.description + '</p>' +
                               '<p><b>Age:</b> ' + attributes.age + '</p>' +
                               '<p><b>Gender:</b> ' + attributes.gender + '</p>' +
                               '<p><b>Use Case:</b> ' + attributes['use case'] + '</p>' +
                               '</div></div>';
                    document.write(dropdownHtml); */
                    
                    $('#voiceSelect').append(new Option(voice.name, voice.voice_id));
                });
                
                //data.forEach(function(voice) {
                //    $('#voiceSelect').append(new Option(voice.name, voice.voice_id));
                //});

                // Initial display of voice information
                //displayVoiceInfo(data[0]);
                displayVoiceInfo(voices[0]);
                
                // Update voice information when a new voice is selected
                //$('#voiceSelect').change(function() {
                //    var selectedVoice = data.find(v => v.voice_id === this.value);
                //    displayVoiceInfo(selectedVoice);
                //});
                $('#voiceSelect').change(function() {
                    var selectedVoice = voices.find(v => v.voice_id === this.value);
                    displayVoiceInfo(selectedVoice);
                });
            }).fail(function(jqxhr, textStatus, error) {
                var err = textStatus + ", " + error;
                console.error("Request Failed: " + err);
            });

            function displayVoiceInfo(voice) {
                var infoText = 'Accent: ' + voice.labels.accent + '<br>' +
                               'Description: ' + voice.labels.description + '<br>' +
                               'Age: ' + voice.labels.age + '<br>' +
                               'Gender: ' + voice.labels.gender + '<br>' +
                               'Use Case: ' + voice.labels['use case'];
                $('#voiceInfo').html(infoText);
            }

            $('#convertText').click(function() {
                var selectedVoiceId = $('#voiceSelect').val();
                var textToConvert = $('#textInput').val();
                if (textToConvert) {
                    $.ajax({
                        url: 'https://api.elevenlabs.io/v1/text-to-speech/' + selectedVoiceId + '?output_format=mp3_44100_64',
                        method: 'POST',
                        headers: {
                            'xi-api-key': '880a3b9e11cf2d73998a00b30f343968',
                            'Content-Type': 'application/json'
                        },
                        data: JSON.stringify({
                            text: textToConvert,
                            voice_settings: {
                                similarity_boost: 0.5,
                                stability: 0.5,
                                style: 1,
                                use_speaker_boost: true
                            }
                        }),
                        xhrFields: {
                            responseType: 'blob'
                        },
                        success: function(blob) {
                            var url = window.URL.createObjectURL(blob);
                            $('#audioPlayer').attr('src', url);
                            $('#audioPlayer')[0].play();
                        },
                        error: function(err) {
                            console.error('Error: ', err);
                        }
                    });
                } else {
                    alert("Please enter some text to convert.");
                }
            });

            // Text to Image functionality
            $('#generateImage').click(function() {
                var promptText = $('#textPrompt').val(); // Get the prompt from the input field
                if (promptText) {
                    var form = new FormData();
                    form.append('prompt', promptText);

                    $.ajax({
                        url: 'https://clipdrop-api.co/text-to-image/v1',
                        method: 'POST',
                        headers: {
                            'x-api-key': 'fd4b30dc0508f49d6b08bc746fb8dc9f0c6aab1d5732afcd1214cde14c1c681ddf49e4b0b5c724c1528d09d4328835d2'
                        },
                        processData: false,
                        contentType: false,
                        data: form,
                        xhrFields: {
                            responseType: 'blob' // Handle binary data response
                        },
                        success: function(blob) {
                            var imageUrl = window.URL.createObjectURL(blob);
                            $('#imageContainer').html('<img src="' + imageUrl + '" alt="Generated Image"/>');
                        },
                        error: function(xhr, status, error) {
                            console.error('Error: ', error);
                        }
                    });
                } else {
                    alert("Please enter a prompt for the image.");
                }
            });
        });
            /*
            $('#generateImage').click(function() {
                var promptText = $('#textPrompt').val(); // Get the prompt from the input field
                if (promptText) {
                    var form = new FormData();
                    form.append('prompt', promptText);

                    $.ajax({
                        url: 'https://clipdrop-api.co/text-to-image/v1',
                        method: 'POST',
                        headers: {
                            'x-api-key': 'fd4b30dc0508f49d6b08bc746fb8dc9f0c6aab1d5732afcd1214cde14c1c681ddf49e4b0b5c724c1528d09d4328835d2'
                        },
                        processData: false,
                        contentType: false,
                        data: form,
                        success: function(response) {
                            // Handle the response (assuming it's a URL to the image)
                            $('#imageContainer').html('<img src="' + response + '" alt="Generated Image"/>');
                        },
                        error: function(xhr, status, error) {
                            console.error('Error: ', error);
                        }
                    });
                } else {
                    alert("Please enter a prompt for the image.");
                }
            });
        });*/