diff --git a/ComSemApp/student/youglish-api-sandbox.js b/ComSemApp/student/youglish-api-sandbox.js new file mode 100644 index 000000000..b7cbf745c --- /dev/null +++ b/ComSemApp/student/youglish-api-sandbox.js @@ -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) => `${match}` + ); + $('#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(); +}); diff --git a/ComSemApp/templates/ComSemApp/youglish-test.html b/ComSemApp/templates/ComSemApp/youglish-test.html new file mode 100644 index 000000000..1437e2a6a --- /dev/null +++ b/ComSemApp/templates/ComSemApp/youglish-test.html @@ -0,0 +1,85 @@ + + + + + + + + + API Test + + + + + + +

Youglish API Test

+
+ + +
+ + / + +
+ + +
+
+ + + + + + + + + + diff --git a/ComSemApp/urls.py b/ComSemApp/urls.py index 739539193..fe9b8a486 100644 --- a/ComSemApp/urls.py +++ b/ComSemApp/urls.py @@ -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'), @@ -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'), ] diff --git a/ComSemApp/views.py b/ComSemApp/views.py index c12268f98..31660b0c5 100644 --- a/ComSemApp/views.py +++ b/ComSemApp/views.py @@ -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 @@ -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'})