| |
| |
| |
| |
| |
| |
| |
| class YoutubeLoader { |
| #videoId; |
| #language; |
| #addVideoInfo; |
|
|
| constructor({ videoId = null, language = null, addVideoInfo = false } = {}) { |
| if (!videoId) throw new Error("Invalid video id!"); |
| this.#videoId = videoId; |
| this.#language = language; |
| this.#addVideoInfo = addVideoInfo; |
| } |
|
|
| |
| |
| |
| |
| |
| static getVideoID(url) { |
| const match = url.match( |
| /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#&?]*).*/ |
| ); |
| if (match !== null && match[1].length === 11) { |
| return match[1]; |
| } else { |
| throw new Error("Failed to get youtube video id from the url"); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| static createFromUrl(url, config = {}) { |
| const videoId = YoutubeLoader.getVideoID(url); |
| return new YoutubeLoader({ ...config, videoId }); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| async load() { |
| let transcript; |
| const metadata = { |
| source: this.#videoId, |
| }; |
| try { |
| const { YoutubeTranscript } = require("./youtube-transcript"); |
| transcript = await YoutubeTranscript.fetchTranscript(this.#videoId, { |
| lang: this.#language, |
| }); |
| if (!transcript) { |
| throw new Error("Transcription not found"); |
| } |
| if (this.#addVideoInfo) { |
| const { Innertube } = require("youtubei.js"); |
| const youtube = await Innertube.create(); |
| const info = (await youtube.getBasicInfo(this.#videoId)).basic_info; |
| metadata.description = info.short_description; |
| metadata.title = info.title; |
| metadata.view_count = info.view_count; |
| metadata.author = info.author; |
| } |
| } catch (e) { |
| throw new Error( |
| `Failed to get YouTube video transcription: ${e?.message}` |
| ); |
| } |
| return [ |
| { |
| pageContent: transcript, |
| metadata, |
| }, |
| ]; |
| } |
| } |
|
|
| module.exports.YoutubeLoader = YoutubeLoader; |
|
|