File size: 7,873 Bytes
58ed516 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 |
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.
|