Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions ComSemApp/student/youglish-api-sandbox.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/*
This code is an implementation of the Youglish API that allows a user to search for a word and retrieve relevant YouTube videos containing the word.
The code fetches video details from the YouTube API, displays the videos in a player, and allows the user to navigate through the videos.

Youglish API - Receives requests from the client and sends them to the Youglish API. It then returns the response to the client-side code.
YouTube API - A set of RESTful APIs that provides functionality to search for videos, retrieve video details, and play videos from youtube.
jQuery - A JavaScript library that simplifies DOM manipulation, event handling, and Ajax interactions.
Ajax - A technique used to make asynchronous HTTP requests from the client-side code to the server-side code.

C:/Users/Jared/GonzagaCPSC/YouglishAPI_JQuery-AJAX/youglish-test.html
*/

$(document).ready(function() {

// Define the URL for the Youglish proxy API and the query string

//use this for node server
const apiUrl = 'http://localhost:3000/youglish-proxy';
//use this apiUrl if using Django
//const apiUrl = '/youglish-proxy';

const query = 'explaining'; //replace with searched for word

// Initialize empty arrays and variables to hold video data
let videos = [];
let currentVideoIndex = 0;


// Function to display the sentence with highlighting
function displaySentence(sentence, query) {
const highlightedSentence = sentence.replace(
new RegExp(`\\b${query}\\b`, 'gi'),
(match) => `<mark>${match}</mark>`
);
$('#sentence-container').html(highlightedSentence);
}

//Function displays the video at the specified index.
async function displayVideo(videoIndex, sentences = 2) {
if (videoIndex >= videos.length) {
console.warn('No more available videos.');
return;
}

const videoId = videos[videoIndex].vid;
const startTime = videos[videoIndex].start;
const sentenceDuration = videos[videoIndex].dur;
const endTime = startTime + sentences * sentenceDuration;

console.log('Extracted video ID:', videoId);

const iframe = document.createElement('iframe');
iframe.width = '480';
iframe.height = '270';
iframe.src = `https://www.youtube.com/embed/${videoId}?start=${startTime}&end=${endTime}&autoplay=1&enablejsapi=1`;
iframe.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';

const videoContainer = document.getElementById('video-container');
videoContainer.innerHTML = ''; // Clear the previous iframe
videoContainer.appendChild(iframe);

$('#video-index').text(videoIndex + 1);
currentVideoIndex = videoIndex;

displaySentence(videos[videoIndex].display, query);
}

function displayVideos(results) {
videos = results;
// Update the total number of videos displayed
$('#total-videos').text(videos.length);
displayVideo(currentVideoIndex);
}

// Set a click event for the 'Previous Video' button
$('#prev-video').on('click', function() {
if (currentVideoIndex > 0) {
currentVideoIndex--;
displayVideo(currentVideoIndex);
}
});

// Set a click event for the 'Next Video' button
$('#next-video').on('click', function() {
if (currentVideoIndex < videos.length - 1) {
currentVideoIndex++;
displayVideo(currentVideoIndex);
}
});

function getYouglishData() {
// Make a GET request to the Youglish API to retrieve data
$.ajax({
url: apiUrl,
type: 'GET',
dataType: 'json',
data: {
'q': query,
'max': 3,
},
success: function(response) {
console.log(response);
displayVideos(response.results);
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('Error:', textStatus, errorThrown);
},
});
}

// Retrieve Youglish data when the page loads
getYouglishData();
});
85 changes: 85 additions & 0 deletions ComSemApp/templates/ComSemApp/youglish-test.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<!--
This HTML code creates a webpage that uses jQuery and the YouTube iFrame API to display a video player and allows the user to navigate between videos.
It also includes a custom JavaScript file that interacts with the Youglish API to fetch videos and update the player.

jQuery: A JavaScript library used to simplify HTML DOM manipulation and event handling
YouTube iFrame API: A JavaScript API by YouTube that allows for the embedding of YouTube videos on a webpage and interaction with them using the iFrame player API.
-->

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API Test</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://www.youtube.com/iframe_api"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
}

/* Add these styles to center the buttons and text */
#controls-container {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
margin-top: 20px;
}

/* Add this style to add a border around the display text */
#sentence-container {
color: #000;
background-color: #f8f9fa;
border: 1px solid #ced4da;
border-radius: 5px;
margin-top: 20px;
padding: 20px;
font-size: 16px;
text-align: center;
}

/* Add this style to make the display text look more like Youglish */
#sentence-container mark {
background-color: #ffff7f;
font-weight: bold;
padding: 0 5px;
}

#video-container {
margin: 0 auto;
display: flex;
justify-content: center;
}

</style>
</head>

<body>
<h1>Youglish API Test</h1>
<div id="video-container"></div>

<!-- Wrap the buttons and index in a container div and center it -->
<div id="controls-container">
<button id="prev-video">Previous Video</button>
<span id="video-index" style="font-size: 24px;"></span> / <span id="total-videos" style="font-size: 24px;"></span>
<button id="next-video">Next Video</button>
</div>

<!-- Add a border around the display text -->
<div id="sentence-container" style="border: 1px solid #ced4da;">
</div>

<script src="youglish-api.js"></script>
</body>

</html>





4 changes: 4 additions & 0 deletions ComSemApp/urls.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
from django.conf.urls import url, include
from django.urls import path

from . import views
from ComSemApp.utils import transcribe

from .views import youglish_proxy

urlpatterns = [
url(r'^$', views.About.as_view(), name='about'),
url(r'^about/teacher/$', views.AboutTeacher.as_view(), name='about_teacher'),
Expand All @@ -14,4 +17,5 @@
url(r'^student/', include('ComSemApp.student.urls', namespace='student')),
url(r'^corpus/', include('ComSemApp.corpus.urls', namespace='corpus')),
url(r'^transcribe_audio/', transcribe, name='transcribe_audio'),
path('youglish-proxy/', youglish_proxy, name='youglish_proxy'),
]
33 changes: 33 additions & 0 deletions ComSemApp/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
from .models import Admin, Teacher, Student
from ComSemApp.administrator.forms import SignupForm, ContactForm

from django.http import JsonResponse
from .api_keys import API_KEY, YOUTUBE_API_KEY

# TODO - these are the sort of extra views that don't exactly fit into one of the existing "apps"
# and should be reorganized and tested

Expand Down Expand Up @@ -89,3 +92,33 @@ def initiate_roles(request):

if Student.objects.filter(user=request.user).exists():
return redirect('/student/')


def youglish_proxy(request):
if request.method == 'GET':
query = request.GET.get('q')
skip = request.GET.get('skip', 0)
max = request.GET.get('max', 10)

youglish_url = f'https://youglish.com/api/v1/videos/search?key={API_KEY}&query={query}&lg=english&max={max}&skip={skip}'

try:
# Make a GET request to the Youglish API using requests
response = requests.get(youglish_url)
data = response.json()

# Add YouTube video details to each video result
for video in data['results']:
video_id = video['vid']
video_url = f'https://www.googleapis.com/youtube/v3/videos?id={video_id}&key={YOUTUBE_API_KEY}&part=snippet'
youtube_response = requests.get(video_url).json()
video['title'] = youtube_response['items'][0]['snippet']['title']
video['thumbnail'] = youtube_response['items'][0]['snippet']['thumbnails']['default']['url']

# Return the response data as a JSON object to the client
return JsonResponse(data)
except Exception as e:
print(e)
return JsonResponse({'error': 'An error occurred while fetching data from Youglish API'})

return JsonResponse({'error': 'Invalid Request'})