Commit ·
741f470
1
Parent(s): 7bfc491
Add youtube transcription tool
Browse files- Refactor AudioTranscriber for improved structure and error handling
Files changed (3)
- requirements.txt+2
- tools.py+64-18
- utils.py+1-6
58 unmodified lines59606162636458 unmodified linespython-dateutil==2.9.0.post0 ; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'python-dotenv==1.1.0python-multipart==0.0.20 ; python_version >= '3.8'pytz==2025.2pyyaml==6.0.2 ; python_version >= '3.8'regex==2024.11.6 ; python_version >= '3.8'58 unmodified lines596061626364656658 unmodified linespython-dateutil==2.9.0.post0 ; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'python-dotenv==1.1.0python-multipart==0.0.20 ; python_version >= '3.8'pytube==15.0.0pytubefix==9.0.1pytz==2025.2pyyaml==6.0.2 ; python_version >= '3.8'regex==2024.11.6 ; python_version >= '3.8'
2 unmodified lines3456783 unmodified lines12131415161767 unmodified lines85868788899091929394959697989910010110210310410510610718 unmodified lines1261271281291301311321 unmodified line13413513613713813973 unmodified lines21321421521621721821913 unmodified lines2332342352 unmodified linesimport jsonimport osimport base64from time import sleepfrom uuid import uuid43 unmodified linesfrom bs4 import BeautifulSoupfrom googlesearch import searchfrom pandas import read_excelfrom smolagents import tool, Toolfrom requests.exceptions import HTTPErrorfrom urllib3.exceptions import ReadTimeoutError67 unmodified linesreturn f"Error reading PDF file {file_name}: {e}"class AudioTranscriber(Tool): # pylint: disable=C0115name = "AudioTranscriber"description = "Extract text from audio files, such as MP3, MP4, WAV, etc."inputs = {"task_id": {"type": "string","description": "The ID of the task associated with the audio file.",},"file_name": {"type": "string","description": "The name of the audio file to transcribe.",},}output_type = "string"def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)region = os.getenv("AWS_REGION", "us-east-1")self.client = boto3.client("transcribe", region_name=region)18 unmodified linestry:bytes_result = s3_download_file(os.getenv("TARGET_BUCKET"), transcript_url.split("/")[-1])transcription_data = json.loads(bytes_result.read().decode("utf-8"))return transcription_data["transcripts"][0]["transcript"]except json.JSONDecodeError as e:print(f"Error decoding transcription JSON: {e}")raise1 unmodified lineprint(f"Error downloading or processing transcription file: {e}")raisedef forward(self, task_id: str, file_name: str) -> str: # pylint: disable=W0221try:file_content = get_file(task_id)73 unmodified linestry:html_content = BeautifulSoup(_get_content(url), "html.parser")# Remove headers and footersfor tag in html_content.find_all(["header", "footer", "nav", "aside"]):tag.decompose()except (ReadTimeoutError, HTTPError) as ex:print("Got HTTP error when requesting %s. Error %s", url, ex)13 unmodified linesreturn html_text.replace("\n", "")return "Could not retrieve any content from the search results."2 unmodified lines34567893 unmodified lines131415161718192067 unmodified lines8889909192939495969718 unmodified lines1161171181191201211221 unmodified line12412512612712812913013113213313413513613713813914014114214314414514614714814973 unmodified lines22322422522622722822923023113 unmodified lines2452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812 unmodified linesimport jsonimport osimport base64from io import BytesIOfrom time import sleepfrom uuid import uuid43 unmodified linesfrom bs4 import BeautifulSoupfrom googlesearch import searchfrom pandas import read_excelfrom pytubefix import YouTubefrom pytubefix.cli import on_progressfrom smolagents import tool, Toolfrom requests.exceptions import HTTPErrorfrom urllib3.exceptions import ReadTimeoutError67 unmodified linesreturn f"Error reading PDF file {file_name}: {e}"class AudioTranscriber:"""A class to handle audio transcription using AWS Transcribe."""def __init__(self):region = os.getenv("AWS_REGION", "us-east-1")self.client = boto3.client("transcribe", region_name=region)18 unmodified linestry:bytes_result = s3_download_file(os.getenv("TARGET_BUCKET"), transcript_url.split("/")[-1])transcription_data = json.loads(bytes_result.read().decode("utf-8"))return transcription_data["results"]["transcripts"][0]["transcript"]except json.JSONDecodeError as e:print(f"Error decoding transcription JSON: {e}")raise1 unmodified lineprint(f"Error downloading or processing transcription file: {e}")raiseclass AudioTranscriberTool(Tool, AudioTranscriber): # pylint: disable=C0115name = "AudioTranscriber"description = "Extract text from audio files, such as MP3, MP4, WAV, etc."inputs = {"task_id": {"type": "string","description": "The ID of the task associated with the audio file.",},"file_name": {"type": "string","description": "The name of the audio file to transcribe.",},}output_type = "string"def __init__(self, *args, **kwargs):Tool.__init__(self, *args, **kwargs)AudioTranscriber.__init__(self, *args, **kwargs)def forward(self, task_id: str, file_name: str) -> str: # pylint: disable=W0221try:file_content = get_file(task_id)73 unmodified linestry:html_content = BeautifulSoup(_get_content(url), "html.parser")# Remove headers and footersfor tag in html_content.find_all(["header", "footer", "nav", "aside", "script", "style", "noscript", "form"]):tag.decompose()except (ReadTimeoutError, HTTPError) as ex:print("Got HTTP error when requesting %s. Error %s", url, ex)13 unmodified linesreturn html_text.replace("\n", "")return "Could not retrieve any content from the search results."class YoutubeTranscriberTool(Tool, AudioTranscriber): # pylint: disable=C0115name = "YoutubeTranscriber"description = "Extract text from YouTube videos, do not work for video understanding."inputs = {"youtube_url": {"type": "string","description": "The URL of the YouTube video to transcribe.",},}output_type = "string"def __init__(self, *args, **kwargs):Tool.__init__(self, *args, **kwargs)AudioTranscriber.__init__(self, *args, **kwargs)def forward(self, youtube_url: str) -> str: # pylint: disable=W0221file_name = f"{uuid4()}.mp4"buffer = BytesIO()try:youtube_obj = YouTube(youtube_url, on_progress_callback=on_progress)youtube_obj.streams.filter(progressive=True).first().stream_to_buffer(buffer)except Exception as e:return f"Error fetching YouTube video {youtube_url}: {e}"try:s3_upload_file(buffer, os.getenv("SOURCE_BUCKET"), file_name)media_uri = f"s3://{os.getenv('SOURCE_BUCKET')}/{file_name}"job_name = f"{uuid4()}-{file_name.split('.', maxsplit=1)[0]}"self._transcribe_audio(job_name, media_uri)transcription = self._get_transcription(job_name)return transcriptionexcept Exception as e:return f"Error starting transcription job for {file_name}: {e}"
61 unmodified lines62636465666768697071727361 unmodified lines"""try:s3_client = boto3.client("s3")s3_client.put_object(Bucket=bucket_name,Key=object_name,Body=file_content.getvalue(),ContentType="application/octet-stream",)except Exception as e:print(f"Error uploading file to S3: {e}")raise61 unmodified lines6263646566676861 unmodified lines"""try:s3_client = boto3.client("s3")s3_client.put_object(Bucket=bucket_name, Key=object_name, Body=file_content.getvalue())except Exception as e:print(f"Error uploading file to S3: {e}")raise
requirements.txt+2
tools.py+64-18
utils.py+1-6