Code viewer for World: Audio to Text

// Cloned by Lakshita Dubey on 2 Dec 2023 from World "Speech To Text World 2   (clone by Yana Koleva)" by Yana Koleva 
// Please leave this clone trail here.
 
/**
 * Authors - Lakshita Dubey 21107840
 * Authors - Yana Koleva - 21707609
 * Description - This is a starter world for CA318 Project Submission
 * This World Simply Calls the Two AI APIs used in this project and shows their usage in javascript
 * Requirements - The User needs an API key for the Deep Gram Speech to Text AI API 
 * API key - d6551802b3aad7be73ba6bf1ac8472b94d0809d4 (To test) more instructions below to get your own
 * */


const SpeechtoText = "https://developers.deepgram.com/reference/deepgram-api-overview";  
const twinword = "https://rapidapi.com/twinword/api/sentiment-analysis";
const themodel = "speech-recognition"; 
    

// default API key and prompt:

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


 
// -------------------------------------------------------------Html Webpage with CSS ------------------------------------------------------------------

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

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>

<div class="container">
  <h1 class="center-align">Speech To Text</h1>

  <div class="section">
    <center><a class="waves-effect waves-light btn" href='https://rapidapi.com/twinword/api/sentiment-analysis'>Sentiment Analysis Model</a>
    <a class="waves-effect waves-light btn" href="https://developers.deepgram.com/reference/deepgram-api-overview">Speech Recognition Model</a>
  </div>

  <div id="enter">
    <h5>Enter API Key</h5>
    <p> This is the API key required for Deepgram Speech to Text . <br>
    You can get your own key <a href = "https://developers.deepgram.com/reference/create-key">here</a>
    After Setting the Key upload a URL of audio to be transcribed! <br>
    Audio link 1 - <a href = "https://ancientbrain.com/uploads.php?userid=helloworld10">Lakshita's Audio Uploads</a><br>
    Audio link 2 - <a href = "https://ancientbrain.com/uploads.php?userid=kolevay2">Yana's Audio uploads</a><br>
    Press Transcribe to get the transcript and Sentiment Analysis you can also play Audio to compare the results 
    Can also use this example audio on Sports Injuries 
    <br> https://storage.googleapis.com/aai-web-samples/5_common_sports_injuries.mp3
    </p> 
    <input type="text" id="apikey" placeholder="Enter your API key here">
    <button onclick="setkey();" class="btn" >Set API Key</button>
  </div>

  <div class="card">
    <div class="card-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="playAudio();" class="btn">Play Audio</button>
    <button onclick="stopAudio();" class="btn">Stop Audio</button>
     
    </div>
  </div>

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

  <div class="card">
    <div class="card-content">
      <span class="card-title">Sentiment Analysis</span>
      <p id="them2"></p>
      <div id="threeDSceneContainer"></div>
    </div>
  </div>
</div>
`);

// ----------------------------------------Java Script Functions----------------------------------------------


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

//-- Play selected audio --
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
  }
}
//-- Analysis takes a param from transcript to analyse the produced transcript --
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 === 'positive') {
            $("#them2").html("<font color='green'><b>" + response.type + "</b></font>");
           
            
        } else {
            $("#them2").html("<font color='red'><b>" + response.type + "</b></font>");
            
        }
    });
}
// -- Transcribe from speech to text --
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;
      // Logging the transcript
      console.log(data);
      $("#them").html("<font color='green'><b>" + transcript + "</b></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);
}