rithuparan07's picture
Create code
58ed516 verified
Creating a YouTube video summarizer that works with multiple languages can be approached by adjusting the code and configuration to accommodate various language models and APIs. Below are examples of how you can implement the summarizer in different programming languages, including Python, JavaScript (Node.js), and Java. Each example will use the Hugging Face API to summarize the text after fetching the transcript.
1. Python Example
python
Copy code
import requests
from youtube_transcript_api import YouTubeTranscriptApi
API_KEY = 'your_huggingface_api_key'
MODEL_ENDPOINT = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn" # Change model as needed
def get_video_id(url):
if "youtube.com" in url:
return url.split("v=")[1].split("&")[0]
elif "youtu.be" in url:
return url.split("/")[-1]
return None
def fetch_transcript(video_id):
try:
transcript = YouTubeTranscriptApi.get_transcript(video_id)
return " ".join([item['text'] for item in transcript])
except Exception as e:
print(f"Error fetching transcript: {e}")
return None
def summarize_text(text):
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
payload = {
"inputs": text,
"parameters": {
"min_length": 50,
"max_length": 150
}
}
response = requests.post(MODEL_ENDPOINT, headers=headers, json=payload)
if response.status_code == 200:
return response.json()[0]['summary_text']
else:
print(f"Error in summarization: {response.status_code} - {response.text}")
return None
def youtube_video_summary(url):
video_id = get_video_id(url)
if not video_id:
print("Invalid YouTube URL")
return None
transcript_text = fetch_transcript(video_id)
if not transcript_text:
print("Could not retrieve transcript.")
return None
return summarize_text(transcript_text)
# Example usage
video_url = "https://www.youtube.com/watch?v=your_video_id"
summary = youtube_video_summary(video_url)
if summary:
print("Summary of the video:")
print(summary)
2. JavaScript (Node.js) Example
javascript
Copy code
const axios = require('axios');
const { getTranscript } = require('youtube-transcript-api');
const API_KEY = 'your_huggingface_api_key';
const MODEL_ENDPOINT = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"; // Change model as needed
const getVideoId = (url) => {
const urlParams = new URLSearchParams(new URL(url).search);
return urlParams.get('v') || url.split('/').pop();
};
const fetchTranscript = async (videoId) => {
try {
const transcript = await getTranscript(videoId);
return transcript.map(item => item.text).join(' ');
} catch (error) {
console.error('Error fetching transcript:', error);
return null;
}
};
const summarizeText = async (text) => {
try {
const response = await axios.post(MODEL_ENDPOINT, {
inputs: text,
parameters: { min_length: 50, max_length: 150 }
}, {
headers: { Authorization: `Bearer ${API_KEY}` }
});
return response.data[0].summary_text;
} catch (error) {
console.error('Error summarizing text:', error);
return null;
}
};
const youtubeVideoSummary = async (url) => {
const videoId = getVideoId(url);
const transcriptText = await fetchTranscript(videoId);
if (!transcriptText) {
console.log("Could not retrieve transcript.");
return null;
}
const summary = await summarizeText(transcriptText);
return summary;
};
// Example usage
const videoUrl = "https://www.youtube.com/watch?v=your_video_id";
youtubeVideoSummary(videoUrl)
.then(summary => {
if (summary) {
console.log("Summary of the video:");
console.log(summary);
}
});
3. Java Example
For Java, you can use libraries like OkHttp for HTTP requests. Ensure you have the required dependencies in your pom.xml if you're using Maven.
xml
Copy code
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
java
Copy code
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
public class YouTubeSummarizer {
private static final String API_KEY = "your_huggingface_api_key";
private static final String MODEL_ENDPOINT = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"; // Change model as needed
public static String getVideoId(String url) {
if (url.contains("youtube.com")) {
return url.split("v=")[1].split("&")[0];
} else if (url.contains("youtu.be")) {
return url.substring(url.lastIndexOf("/") + 1);
}
return null;
}
public static String fetchTranscript(String videoId) {
// Use any YouTube transcript API or library to fetch the transcript
// This part is simplified; implement based on your chosen method
return "Transcribed text goes here.";
}
public static String summarizeText(String text) throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(
MediaType.parse("application/json"),
new JSONObject()
.put("inputs", text)
.put("parameters", new JSONObject().put("min_length", 50).put("max_length", 150))
.toString()
);
Request request = new Request.Builder()
.url(MODEL_ENDPOINT)
.post(body)
.addHeader("Authorization", "Bearer " + API_KEY)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
JSONArray jsonArray = new JSONArray(response.body().string());
return jsonArray.getJSONObject(0).getString("summary_text");
} else {
System.out.println("Error summarizing text: " + response.code());
return null;
}
}
public static void main(String[] args) throws IOException {
String videoUrl = "https://www.youtube.com/watch?v=your_video_id";
String videoId = getVideoId(videoUrl);
String transcriptText = fetchTranscript(videoId);
String summary = summarizeText(transcriptText);
System.out.println("Summary of the video:");
System.out.println(summary);
}
}
Explanation of Each Example
Python Example:
Uses youtube-transcript-api to fetch transcripts.
Sends the transcript to the Hugging Face API for summarization.
JavaScript (Node.js) Example:
Uses youtube-transcript-api to fetch transcripts.
Sends a POST request to the Hugging Face API to summarize the transcript.
Java Example:
Implements a basic structure to fetch a transcript and summarize it.
Uses OkHttp for HTTP requests.
Notes
API Key: Ensure you replace your_huggingface_api_key with your actual Hugging Face API key in all examples.
Transcript Fetching: The transcript fetching part may require you to use a dedicated service or API. The provided code outlines where to implement this logic.
Model Endpoint: You can change the model endpoint in the code to use different models from Hugging Face that support multi-language summarization, such as models trained specifically for various languages.
These examples give you a foundation for implementing a multi-language YouTube video summarizer in different programming languages. Adjust the fetching and summarization logic as needed based on your requirements and the available libraries or APIs.