| from smolagents import Tool | |
| from youtube_transcript_api import YouTubeTranscriptApi, NoTranscriptFound, TranscriptsDisabled | |
| import re | |
| class YouTubeTool(Tool): | |
| name = "youtube_reader" | |
| description= "Fetches the transcript for the youtube video url" | |
| inputs= {"video_url": {"type": "string", "description": "URL or ID of the Youtube video"}} | |
| output_type = "string" | |
| def forward(self, video_url: str) -> str: | |
| try: | |
| # Extract video ID | |
| match = re.search(r"v=([A-Za-z0-9_-]{11})", video_url) | |
| if not match: | |
| return "Invalid YouTube URL." | |
| video_id = match.group(1) | |
| # Fetch transcript | |
| transcript_list = YouTubeTranscriptApi.get_transcript(video_id) | |
| transcript_text = " ".join([t["text"] for t in transcript_list]) | |
| return transcript_text | |
| except NoTranscriptFound: | |
| return "Transcript not available for this video." | |
| except TranscriptsDisabled: | |
| return "Transcripts are disabled for this video." | |
| except Exception as e: | |
| return f"Error fetching transcript: {str(e)}" |