Yes, smolagents can be used to create a system that automates the process of collecting, transcribing, and adding public speeches from a public figure to a website repository. Here's a breakdown of how you can achieve this using smolagents and related tools:
1. Overall Architecture
You'll need a multi-step process, potentially orchestrated by a CodeAgent, to handle each speech:
-
Search for Latest Speeches: Use a tool like DuckDuckGoSearchTool or a custom Google Search tool (if you have a SerpAPI key) to find recent YouTube videos of the public figure. You will construct a search query like: "[Public Figure Name] speech youtube".
-
Download YouTube Video: You'll need a tool to download the YouTube video. You can create a custom tool using the youtube-dl or yt-dlp library, or use an existing tool from the Hugging Face Hub (if available). This tool would take the YouTube video URL as input and save the video to a local file.
-
Extract Audio: Create a custom tool using libraries like moviepy or ffmpeg to extract the audio from the downloaded video file. This tool would take the video file path as input and output the audio file.
-
Transcribe Audio: You can use the SpeechToTextTool (which uses the Whisper model) to transcribe the extracted audio. This tool takes the audio file path as input and returns the transcribed text.
-
Create Website Entry: This step involves interacting with your website's backend. You'll need a custom tool to handle this. This tool would:
- Take the public figure's name, the title of the speech, the transcribed text, and potentially the audio and video file paths as input.
- Generate the HTML or Markdown content for the speech entry on your website.
- Use an API call or file system manipulation (depending on your website's architecture) to add the new entry to the website's content.
2. Smolagents Implementation
from smolagents import CodeAgent, HfApiModel, DuckDuckGoSearchTool
from smolagents.tools import Tool
from typing import Optional
import re
import requests
from markdownify import markdownify
from requests.exceptions import RequestException
# Define your custom tools
class VisitWebpageTool(Tool):
name = "visit_webpage"
description = (
"Visits a webpage at the given url and reads its content as a markdown string. Use this to browse webpages."
)
inputs = {
"url": {
"type": "string",
"description": "The url of the webpage to visit.",
}
}
output_type = "string"
def forward(self, url: str) -> str:
try:
# Send a GET request to the URL with a 20-second timeout
response = requests.get(url, timeout=20)
response.raise_for_status() # Raise an exception for bad status codes
# Convert the HTML content to Markdown
markdown_content = markdownify(response.text).strip()
# Remove multiple line breaks
markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
return markdown_content
except requests.exceptions.Timeout:
return "The request timed out. Please try again later or check the URL."
except RequestException as e:
return f"Error fetching the webpage: {str(e)}"
except Exception as e:
return f"An unexpected error occurred: {str(e)}"
class YoutubeTool(Tool):
name = "youtube_downloader"
description = """Downloads youtube videos from the link"""
inputs = {
"link": {
"type": "string",
"description": "The link of the youtube video to downloads",
},
"path": {
"type": "string",
"description": "The path to save the youtube video",
"nullable": True,
},
}
output_type = "string"
def forward(self, link: str, path: Optional[str] = None) -> str:
try:
from pytube import YouTube
except ImportError:
raise ImportError("Please install pytube to use YoutubeTool: pip install pytube")
try:
yt = YouTube(link)
stream = yt.streams.get_highest_resolution()
# Replace spaces with underscores for valid file path
title = re.sub(r"\s+", "_", yt.title)
path_name = path if path else f"./{title}.mp4"
stream.download(filename=path_name)
return f"Youtube video downloaded succesfully to {path_name}"
except Exception as e:
raise ValueError(f"Error downloading the video: {e}")
from smolagents import CodeAgent, HfApiModel, DuckDuckGoSearchTool, SpeechToTextTool
from smolagents.tools import Tool
from typing import Optional
import re
import requests
from markdownify import markdownify
from requests.exceptions import RequestException
# Define your custom tools
class VisitWebpageTool(Tool):
name = "visit_webpage"
description = (
"Visits a webpage at the given url and reads its content as a markdown string. Use this to browse webpages."
)
inputs = {
"url": {
"type": "string",
"description": "The url of the webpage to visit.",
}
}
output_type = "string"
def forward(self, url: str) -> str:
try:
# Send a GET request to the URL with a 20-second timeout
response = requests.get(url, timeout=20)
response.raise_for_status() # Raise an exception for bad status codes
# Convert the HTML content to Markdown
markdown_content = markdownify(response.text).strip()
# Remove multiple line breaks
markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
return markdown_content
except requests.exceptions.Timeout:
return "The request timed out. Please try again later or check the URL."
except RequestException as e:
return f"Error fetching the webpage: {str(e)}"
except Exception as e:
return f"An unexpected error occurred: {str(e)}"
class YoutubeTool(Tool):
name = "youtube_downloader"
description = """Downloads youtube videos from the link"""
inputs = {
"link": {
"type": "string",
"description": "The link of the youtube video to downloads",
},
"path": {
"type": "string",
"description": "The path to save the youtube video",
"nullable": True,
},
}
output_type = "string"
def forward(self, link: str, path: Optional[str] = None) -> str:
try:
from pytube import YouTube
except ImportError:
raise ImportError("Please install pytube to use YoutubeTool: pip install pytube")
try:
yt = YouTube(link)
stream = yt.streams.get_highest_resolution()
# Replace spaces with underscores for valid file path
title = re.sub(r"\s+", "_", yt.title)
path_name = path if path else f"./{title}.mp4"
stream.download(filename=path_name)
return f"Youtube video downloaded succesfully to {path_name}"
except Exception as e:
raise ValueError(f"Error downloading the video: {e}")
class AudioExtraction(Tool):
name = "audio_extraction"
description = """Extract the audio from a video file"""
inputs = {
"video": {
"type": "string",
"description": "The path to the video file to extract the audio from",
},
"path": {
"type": "string",
"description": "The path to save the audio",
"nullable": True,
},
}
output_type = "string"
def forward(self, video: str, path: Optional[str] = None) -> str:
try:
import moviepy.editor as mp
except ImportError:
raise ImportError(
"Please install moviepy to use AudioExtractionTool: pip install moviepy"
)
try:
clip = mp.VideoFileClip(video)
title = re.sub(r"\s+", "_", clip.filename)
path_name = path if path else f"./{title}.mp3"
clip.audio.write_audiofile(path_name)
return f"Audio extracted succesfully to {path_name}"
except Exception as e:
raise ValueError(f"Error extracting the audio: {e}")
# Initialize the agent with the tools
# Note: Add translation to translate to multiple languages and website entry tool when created
tools = [DuckDuckGoSearchTool(), VisitWebpageTool(), YoutubeTool(), AudioExtraction(),SpeechToTextTool()]
agent = CodeAgent(tools=tools, model=HfApiModel())
# Define the task
task = """
Find the latest public speeches from [Public Figure Name] on YouTube.
Download the video, extract the audio, and transcribe the speech using Whisper.
Finally, create an entry on the website repository with the speech.
"""
# Run the agent
agent.run(task)
3. Considerations
- Website Integration: The most complex part is the
website_entry tool. This requires deep knowledge of how your website is structured (database, file system, API, etc.).
- Error Handling: Implement robust error handling to catch issues during video download, audio extraction, transcription, or website entry creation. The agent should be able to retry or skip videos if errors occur.
- Rate Limiting: Be mindful of YouTube's and other services' rate limits. Implement delays and error handling to avoid being blocked.
- Ethical Considerations: Ensure you have the right to download and transcribe these public speeches. Respect copyright and privacy.
4. Additional Tips
- Start Simple: Begin by creating a basic version that only handles one video. Once that's working, expand it to handle multiple videos and improve error handling.
- Logging: Implement detailed logging to track the agent's progress and debug issues.
- Human Intervention: Consider adding a human review step to check the quality of the transcriptions before adding them to the website.
While smolagents doesn't provide all the tools out-of-the-box, it provides the framework to build a powerful agentic system to automate this complex task. You'll need to create the custom tools for YouTube downloading, audio extraction, and website entry. The CodeAgent is well-suited for this task because it allows you to write code to orchestrate the different tools and handle data manipulation.