Download tools/get_youtube_transcript.py from andrei-sferdian/Agents_Course_Final_Assignment: direct link, hf CLI and curl.
- Browser
- Download file 1.67 kB
-
https://huggingface.co/spaces/andrei-sferdian/Agents_Course_Final_Assignment/resolve/main/tools/get_youtube_transcript.py
- Command line
-
hf download hf://spaces/andrei-sferdian/Agents_Course_Final_Assignment/tools/get_youtube_transcript.py
-
curl -L -o get_youtube_transcript.py https://huggingface.co/spaces/andrei-sferdian/Agents_Course_Final_Assignment/resolve/main/tools/get_youtube_transcript.py
1.67 kB
| 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 | |