Code viewer for World: FeelFlow

// Cloned by Lakshita Dubey on 3 Dec 2023 from World "working graph with design(clone by Yana Koleva)" by Yana Koleva 
// Please leave this clone trail here.
 

//https://ancientbrain.com/uploads/helloworld10/Recording.wav.mp3
// adapted from:
//  https://platform.openai.com/docs/api-reference/making-requests


const SpeechtoText = "https://developers.deepgram.com/docs/features-overview";          
 
const themodel = "speech-recognition";       
    

// default API key and prompt:

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


document.write(`

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<style>
  body {
    margin: 20px;
    padding: 40px;
    font-family: 'Times New Roman', sans-serif;
    background: linear-gradient(black, grey, white);
    color: #fff;
    text-shadow: 1px 1px 1px black;
    background-image: url("https://ancientbrain.com/uploads/kolevay2/bg.jpg");
  }
  html {
  scroll-behavior: smooth;
}

  .card-content h5,
  .card-content input,
  .card-content button {
    color: white;
    
  }

  .container {
    margin-bottom: 60px;
    margin-top: 60px;
  }

  .card {
    background: 1px 1px 1px black;
    opacity: 0.4;
    margin-bottom: 20px;
  }

  .btn,
  .section a,
  #enter button {
    color: black !important;
  }

  .btn {
    border-radius: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    appearance: none;
    padding: 15px 20px;
    background-clip: padding-box;
    background-color: rgba(0, 255, 0, 0.5);
    border-style: none;
    box-sizing: border-box;
    color: #fff;
    cursor: pointer;
    display: inline-block;
    flex-direction: row;
    flex-shrink: 0;
    font-family: 'Eina01', sans-serif;
    font-size: 25px;
    font-weight: 800;
    justify-content: center;
    line-height: 24px;
    margin: 20;
    min-height: 64px;
    outline: none;
    overflow: visible;
    padding: 19px 26px;
    pointer-events: auto;
    position: relative;
    text-align: center;
    text-decoration: none;
    text-transform: none;
    user-select: none;
    -webkit-user-select: none;
    touch-action: manipulation;
    vertical-align: middle;
    width: auto;
    word-break: keep-all;
    z-index: 0;
    transition: background-color 0.3s ease, transform 0.2s ease;
    border-radius: 25px;
    overflow: hidden;
  }

  .btn:hover {
    background-color: white;
    color: black;
  }

  .section {
    display: flex;
    justify-content: center;
  }

  input {
    color: white;
    font-size: 34px;
  }

  .section a {
    margin: 0 10px;
  }

  #uploadlink {
    width: 100%;
    padding: 10px;
    margin-bottom: 15px;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-sizing: border-box;
    font-size: 20px;
    text-color: white;
  }

  .card-title {
    color: white;
    font-size: 36px;
    margin-top: 200px;
  }

  #overlay {
    position: absolute;
    top: 20px;
    left: 20px;
    color: white;
    z-index: 1;
  }
  .transcribe-container {
  margin-bottom: 20px;
}

.transcribe-content {
    margin-top: 30px;
   background-color: rgba(255, 255, 255, 0.2); /* White background with reduced opacity */
  padding: 20px; /* Adjust padding as needed */
  border-radius: 10px;
}
.card-content:nth-child(3) {
  margin-top: 40px;
}
</style>

<div class="container">
  <h1 class="center-align">FeelFlow</h1>

  <div class="section">
    <a class="waves-effect waves-light btn" href='https://ancientbrain.com/world.php?world=2850716357'>Record your Feelings --> </a>
    <a class="waves-effect waves-light btn" href="https://www.twinword.com/api/">Analyse your Sentiments <3</a>
  </div>

  <div id="enter">
    <h5>Enter API Key</h5>
    <input type="text" id="apikey" placeholder="Enter your API key here">
    <button onclick="setkey();" class="btn" >Set API Key</button>
  </div>

    <div class="card-content transcribe-container">
    
      <div class="transcribe-content">
      <span class="card-title">Transcribe Audio</span>
      <input type="text" id="uploadlink" placeholder="Enter a URL">
      <button onclick="transcribe();" class="btn">Transcribe</button>
      <button onclick="summary();" class="btn">Summary</button>
      
      <button onclick="playAudio();" class="btn">Play Audio</button>
      <button onclick="stopAudio();" class="btn">Stop Audio</button>
     </div>
    </div>


    <div class="card-content" >
      <div class="transcribe-content">
      <span class="card-title">Transcribed Text</span>
      <p id="them"></p>
    </div></div>
    
    <div class="card-content" >
      <div class="transcribe-content">
      <span class="card-title">Summary</span>
      <p id="them3"></p>
    </div></div>


    <div class="card-content">
      <div class="transcribe-content">
      <span class="card-title">Sentiment Analysis</span>
      <p id="them2"></p>
      <canvas id="chartCanvas" width="400" height="400"></canvas>
    </div></div>

</div>
`);



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




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

var music;

function playAudio() {
  var audioURL = document.getElementById("uploadlink").value;
  music = new Audio(audioURL);
  
  // Play the audio when the user clicks the Play button
  music.play();
}

function stopAudio() {
  if (music) {
    music.pause(); // Pause the audio playback
    music.currentTime = 0; // Reset the playback to the beginning
  }
}

let myChart; // Declare myChart globally to store the chart instance

function analysis(transcript) {
    const settings = {
        async: true,
        crossDomain: true,
        url: 'https://twinword-twinword-bundle-v1.p.rapidapi.com/sentiment_analyze/',
        method: 'POST',
        headers: {
            'content-type': 'application/x-www-form-urlencoded',
            'X-RapidAPI-Key': 'ffa1596df2mshfca80b0d5ef8382p164dc7jsn549182e62873',
            'X-RapidAPI-Host': 'twinword-twinword-bundle-v1.p.rapidapi.com'
        },
        data: {
            text: transcript
        }
    };

    $.ajax(settings).done(function (response) {
        console.log(response);
        if (response.type) {
            if (response.type === 'positive') {
                $("#them2").html("<h3 style='color: white; font-size: 20px; font-family: Helvetica, Arial, sans-serif; padding: 40px;'> The overall sentiment" + response.type + "</h3>")
            } else {
                $("#them2").html("<h3 style='color: white; font-size: 20px; font-family: Helvetica, Arial, sans-serif; padding: 40px;'> The overall sentiment" + response.type + "</h3>")
            }
            // Extracting words and scores from the API response
            const words = response.keywords.map(item => item.word);
            const scores = response.keywords.map(item => item.score);

            // Prepare chart data
            const chartData = {
                backgroundColor: 'rgba(255, 255, 255, 0.5)',
                labels: words,
                datasets: [{
                    label: 'Word Scores',
                    data: scores,
                    backgroundColor: "#F5DEB3", 
                    borderColor: 'black', 
                    borderWidth: 5
                }]
            };

            // Chart configuration
            const ctx = document.getElementById('chartCanvas').getContext('2d'); // Assuming canvas ID is 'chartCanvas'
            const chartConfig = {
                type: 'bar',
                axisY:{
                            labelFontSize: 25
                        },
                        axisX:{
                            labelFontSize: 25
                        },
                data: chartData,
                options: {
                    scales: {
                       y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.1)',
                                borderColor: 'white',
                                borderWidth: 2
                            }
                        },
                        x: {
                            grid: {
                                color: 'rgba(0, 0, 0, 0.1)',
                                borderColor: 'white',
                                borderWidth: 2,
                                labelFontSize: 20
                            }
                        },
                    },
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top',
                            labels: {
                                color: 'white', // Legend label color
                                font: {
                                    size: 25
                                }
                            }
                        },
                        title: {
                            display: true,
                            text: 'Sentiment Analysis Chart',
                            color: 'black', // Title color
                            font: {
                                size: 18,
                                weight: 'bold'
                            }
                        },
                        
                    }
                    
                }
            };

            // Destroy existing chart if it exists
            if (myChart) {
                myChart.destroy();
            }

            // Create new chart
            myChart = new Chart(ctx, chartConfig);
        } else {
            // Handle cases where sentiment analysis fails
            $("#them2").html("<font color='red'><b>Unable to perform sentiment analysis.</b></font>");
        }
    }).fail(function (error) {
        // Handle AJAX request failure
        $("#them2").html("<font color='red'><h3>Error: " + error.statusText + "</h3></font>");
        $('body').css('background', 'linear-gradient(135deg, #ffcccc, #ffd9d9)');
        // Change text color to default for failure
        $("#them").css('color', 'white');
    });
}

function transcribe() {

  // Get the URL for transcription
  var audioURL = $("#uploadlink").val();


  // Construct the request object
  var requestData = {
    "url": audioURL
  };

  // Convert the request object to a JSON string
  var requestDataString = JSON.stringify(requestData);

  // Set up the settings similar to the original code
  var settings = {
    async: true,
    crossDomain: true,
    url: 'https://api.deepgram.com/v1/listen?filler_words=false&summarize=v2',
    method: 'POST',
    headers: {
      accept: 'application/json',
      'content-type': 'application/json',
      Authorization: 'Token ' + apikey // Use the apikey variable here
    },
    processData: false,
    interim_results: true,
    data: requestDataString,
    dataType: 'json',
    success: function (data, status, xhr) {
    
      var transcript = data.results.channels[0].alternatives[0].transcript;
      var summary = data.results.summary.short;
      console.log(summary);
      // Logging the transcript
      console.log(data);
    $("#them").html("<h3 style='color: white; font-size: 20px; font-family: Helvetica, Arial, sans-serif; padding: 40px;'>" + transcript + "</h3>");


     // $("#them").html("<font color='green'><h3>" + summary + "</h3></font>");
      analysis(transcript);
      // Handle successfulresponse here
      // Display or use the transcription results
      // handleTranscription(data);
    },
    error: function (xhr, status, error) {
      // Handle error response here
      console.error("Error:", error);
      $("#them").html("<font color='red'><b> Error in transcription. </b></font>");
    }
  };

  // Make a POST request to Deepgram's API using the configured settings
  $.ajax(settings);
}

function summary() {

  // Get the URL for transcription
  var audioURL = $("#uploadlink").val();


  // Construct the request object
  var requestData = {
    "url": audioURL
  };

  // Convert the request object to a JSON string
  var requestDataString = JSON.stringify(requestData);

  // Set up the settings similar to the original code
  var settings = {
    async: true,
    crossDomain: true,
    url: 'https://api.deepgram.com/v1/listen?filler_words=false&summarize=v2',
    method: 'POST',
    headers: {
      accept: 'application/json',
      'content-type': 'application/json',
      Authorization: 'Token ' + apikey // Use the apikey variable here
    },
    processData: false,
    interim_results: true,
    data: requestDataString,
    dataType: 'json',
    success: function (data, status, xhr) {
    
    var summary = data.results.summary.short;
      console.log(summary);
    $("#them3").html("<h3 style='color: white; font-size: 20px; font-family: Helvetica, Arial, sans-serif; padding: 40px;'>" + summary + "</h3>");


     //$("#them").html("<font color='green'><h3>" + summary + "</h3></font>")
    },
    error: function (xhr, status, error) {
      // Handle error response here
      console.error("Error:", error);
      $("#them").html("<font color='red'><b> Error in transcription. </b></font>");
    }
  };

  // Make a POST request to Deepgram's API using the configured settings
  $.ajax(settings);
}