rithuparan07 commited on
Commit
58ed516
1 Parent(s): 3d0b04f

Create code

Browse files
Files changed (1) hide show
  1. code +233 -0
code ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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.
2
+
3
+ 1. Python Example
4
+
5
+ python
6
+
7
+ Copy code
8
+ import requests
9
+ from youtube_transcript_api import YouTubeTranscriptApi
10
+
11
+ API_KEY = 'your_huggingface_api_key'
12
+ MODEL_ENDPOINT = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn" # Change model as needed
13
+
14
+ def get_video_id(url):
15
+ if "youtube.com" in url:
16
+ return url.split("v=")[1].split("&")[0]
17
+ elif "youtu.be" in url:
18
+ return url.split("/")[-1]
19
+ return None
20
+
21
+ def fetch_transcript(video_id):
22
+ try:
23
+ transcript = YouTubeTranscriptApi.get_transcript(video_id)
24
+ return " ".join([item['text'] for item in transcript])
25
+ except Exception as e:
26
+ print(f"Error fetching transcript: {e}")
27
+ return None
28
+
29
+ def summarize_text(text):
30
+ headers = {
31
+ "Authorization": f"Bearer {API_KEY}",
32
+ "Content-Type": "application/json"
33
+ }
34
+ payload = {
35
+ "inputs": text,
36
+ "parameters": {
37
+ "min_length": 50,
38
+ "max_length": 150
39
+ }
40
+ }
41
+ response = requests.post(MODEL_ENDPOINT, headers=headers, json=payload)
42
+ if response.status_code == 200:
43
+ return response.json()[0]['summary_text']
44
+ else:
45
+ print(f"Error in summarization: {response.status_code} - {response.text}")
46
+ return None
47
+
48
+ def youtube_video_summary(url):
49
+ video_id = get_video_id(url)
50
+ if not video_id:
51
+ print("Invalid YouTube URL")
52
+ return None
53
+ transcript_text = fetch_transcript(video_id)
54
+ if not transcript_text:
55
+ print("Could not retrieve transcript.")
56
+ return None
57
+ return summarize_text(transcript_text)
58
+
59
+ # Example usage
60
+ video_url = "https://www.youtube.com/watch?v=your_video_id"
61
+ summary = youtube_video_summary(video_url)
62
+ if summary:
63
+ print("Summary of the video:")
64
+ print(summary)
65
+
66
+
67
+
68
+ 2. JavaScript (Node.js) Example
69
+
70
+ javascript
71
+
72
+ Copy code
73
+ const axios = require('axios');
74
+ const { getTranscript } = require('youtube-transcript-api');
75
+
76
+ const API_KEY = 'your_huggingface_api_key';
77
+ const MODEL_ENDPOINT = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"; // Change model as needed
78
+
79
+ const getVideoId = (url) => {
80
+ const urlParams = new URLSearchParams(new URL(url).search);
81
+ return urlParams.get('v') || url.split('/').pop();
82
+ };
83
+
84
+ const fetchTranscript = async (videoId) => {
85
+ try {
86
+ const transcript = await getTranscript(videoId);
87
+ return transcript.map(item => item.text).join(' ');
88
+ } catch (error) {
89
+ console.error('Error fetching transcript:', error);
90
+ return null;
91
+ }
92
+ };
93
+
94
+ const summarizeText = async (text) => {
95
+ try {
96
+ const response = await axios.post(MODEL_ENDPOINT, {
97
+ inputs: text,
98
+ parameters: { min_length: 50, max_length: 150 }
99
+ }, {
100
+ headers: { Authorization: `Bearer ${API_KEY}` }
101
+ });
102
+ return response.data[0].summary_text;
103
+ } catch (error) {
104
+ console.error('Error summarizing text:', error);
105
+ return null;
106
+ }
107
+ };
108
+
109
+ const youtubeVideoSummary = async (url) => {
110
+ const videoId = getVideoId(url);
111
+ const transcriptText = await fetchTranscript(videoId);
112
+ if (!transcriptText) {
113
+ console.log("Could not retrieve transcript.");
114
+ return null;
115
+ }
116
+ const summary = await summarizeText(transcriptText);
117
+ return summary;
118
+ };
119
+
120
+ // Example usage
121
+ const videoUrl = "https://www.youtube.com/watch?v=your_video_id";
122
+ youtubeVideoSummary(videoUrl)
123
+ .then(summary => {
124
+ if (summary) {
125
+ console.log("Summary of the video:");
126
+ console.log(summary);
127
+ }
128
+ });
129
+
130
+ 3. Java Example
131
+
132
+ 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.
133
+
134
+ xml
135
+ Copy code
136
+ <dependency>
137
+ <groupId>com.squareup.okhttp3</groupId>
138
+ <artifactId>okhttp</artifactId>
139
+ <version>4.9.1</version>
140
+ </dependency>
141
+ java
142
+ Copy code
143
+ import okhttp3.*;
144
+ import org.json.JSONArray;
145
+ import org.json.JSONObject;
146
+
147
+ import java.io.IOException;
148
+
149
+ public class YouTubeSummarizer {
150
+ private static final String API_KEY = "your_huggingface_api_key";
151
+ private static final String MODEL_ENDPOINT = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"; // Change model as needed
152
+
153
+ public static String getVideoId(String url) {
154
+ if (url.contains("youtube.com")) {
155
+ return url.split("v=")[1].split("&")[0];
156
+ } else if (url.contains("youtu.be")) {
157
+ return url.substring(url.lastIndexOf("/") + 1);
158
+ }
159
+ return null;
160
+ }
161
+
162
+ public static String fetchTranscript(String videoId) {
163
+ // Use any YouTube transcript API or library to fetch the transcript
164
+ // This part is simplified; implement based on your chosen method
165
+ return "Transcribed text goes here.";
166
+ }
167
+
168
+ public static String summarizeText(String text) throws IOException {
169
+ OkHttpClient client = new OkHttpClient();
170
+
171
+ RequestBody body = RequestBody.create(
172
+ MediaType.parse("application/json"),
173
+ new JSONObject()
174
+ .put("inputs", text)
175
+ .put("parameters", new JSONObject().put("min_length", 50).put("max_length", 150))
176
+ .toString()
177
+ );
178
+
179
+ Request request = new Request.Builder()
180
+ .url(MODEL_ENDPOINT)
181
+ .post(body)
182
+ .addHeader("Authorization", "Bearer " + API_KEY)
183
+ .addHeader("Content-Type", "application/json")
184
+ .build();
185
+
186
+ Response response = client.newCall(request).execute();
187
+ if (response.isSuccessful()) {
188
+ JSONArray jsonArray = new JSONArray(response.body().string());
189
+ return jsonArray.getJSONObject(0).getString("summary_text");
190
+ } else {
191
+ System.out.println("Error summarizing text: " + response.code());
192
+ return null;
193
+ }
194
+ }
195
+
196
+ public static void main(String[] args) throws IOException {
197
+ String videoUrl = "https://www.youtube.com/watch?v=your_video_id";
198
+ String videoId = getVideoId(videoUrl);
199
+ String transcriptText = fetchTranscript(videoId);
200
+ String summary = summarizeText(transcriptText);
201
+ System.out.println("Summary of the video:");
202
+ System.out.println(summary);
203
+ }
204
+ }
205
+ Explanation of Each Example
206
+ Python Example:
207
+
208
+ Uses youtube-transcript-api to fetch transcripts.
209
+ Sends the transcript to the Hugging Face API for summarization.
210
+ JavaScript (Node.js) Example:
211
+
212
+ Uses youtube-transcript-api to fetch transcripts.
213
+ Sends a POST request to the Hugging Face API to summarize the transcript.
214
+
215
+
216
+ Java Example:
217
+
218
+ Implements a basic structure to fetch a transcript and summarize it.
219
+ Uses OkHttp for HTTP requests.
220
+
221
+ Notes
222
+ API Key: Ensure you replace your_huggingface_api_key with your actual Hugging Face API key in all examples.
223
+ 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.
224
+ 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.
225
+ 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.
226
+
227
+
228
+
229
+
230
+
231
+
232
+
233
+