File size: 1,673 Bytes
7bf46e1
90f4ddb
 
 
7bf46e1
90f4ddb
7bf46e1
90f4ddb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bf46e1
 
 
 
 
 
 
 
 
 
90f4ddb
 
 
 
 
 
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
import os
import urllib
import urllib.parse

import youtube_transcript_api
from langchain.tools import BaseTool
from youtube_transcript_api.proxies import WebshareProxyConfig


class GetYouTubeTranscript(BaseTool):
    name: str = "get_youtube_transcript"
    description: str = (
        "Get the transcript of a YouTube video. Input should be the YouTube video URL."
    )

    def _run(self, url: str) -> str:
        """
        Fetches the transcript of a YouTube video given its URL.

        Args:
            url (str): The URL of the YouTube video.

        Returns:
            str: The full transcript of the video as a single string if successful,
                 or an error message if the transcript could not be fetched.
        """
        try:
            parsed_url = urllib.parse.urlparse(url)
            qparams = urllib.parse.parse_qs(parsed_url.query)
            video_id = qparams.get("v", [None])[0]
            if not video_id:
                return "Video ID not found in the URL"

            api = youtube_transcript_api._api.YouTubeTranscriptApi(
                proxy_config=WebshareProxyConfig(
                    proxy_username=os.getenv(
                        "YOUTUBE_PROXY_USERNAME", "your_proxy_username"
                    ),
                    proxy_password=os.getenv(
                        "YOUTUBE_PROXY_PASSWORD", "your_proxy_password"
                    ),
                )
            )
            transcript = api.fetch(video_id)
            full_transcript = "".join([t.text for t in transcript])
        except Exception as e:
            return f"Error fetching transcript: {e}"

        return full_transcript