74 lines
2.3 KiB
Python
74 lines
2.3 KiB
Python
import logging
|
|
import os
|
|
|
|
from pydub import AudioSegment
|
|
from pytube import YouTube, exceptions as pytube_exceptions
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
|
|
|
|
class FileManager:
|
|
"""
|
|
FileManager class that handles operations such as downloading and converting audio.
|
|
"""
|
|
|
|
def __init__(self):
|
|
pass
|
|
|
|
@staticmethod
|
|
def download_youtube_audio(youtube_link: str, filename: str):
|
|
"""
|
|
Downloads audio from a YouTube link and saves it in the location specified by filename.
|
|
"""
|
|
try:
|
|
yt = YouTube(youtube_link)
|
|
except pytube_exceptions.PytubeError as e:
|
|
logging.error("An Error occurred while fetching the YouTube video: " + str(e))
|
|
return
|
|
|
|
audio_stream = yt.streams.get_audio_only()
|
|
|
|
if not os.path.exists(filename):
|
|
try:
|
|
audio_stream.download(filename=filename)
|
|
logging.info(f"Downloaded {youtube_link} successfully.")
|
|
except Exception as e:
|
|
logging.error("An Error occurred while downloading the YouTube video: " + str(e))
|
|
return
|
|
|
|
@staticmethod
|
|
def convert_to_wav(mp4_file: str, wav_file: str):
|
|
"""
|
|
Converts a mp4 audio file into wav format.
|
|
"""
|
|
try:
|
|
sound = AudioSegment.from_file(mp4_file, format="mp4")
|
|
sound.export(wav_file, format="wav")
|
|
except Exception as e:
|
|
logging.error(f"An error occurred while converting {mp4_file} to wav: {e}")
|
|
|
|
@staticmethod
|
|
def load_local_file(local_file_path: str) -> str:
|
|
"""
|
|
Loads a local file and converts it to wav format.
|
|
Return wav file path.
|
|
"""
|
|
ext = os.path.splitext(local_file_path)[-1].lower()
|
|
|
|
if ext in [".mp4", ".mp3"]:
|
|
wav_file = local_file_path.replace(ext, ".wav")
|
|
try:
|
|
audio = AudioSegment.from_file(local_file_path, format=ext[1:])
|
|
audio.export(wav_file, format="wav")
|
|
except Exception as e:
|
|
logging.error(f"An error occurred while converting {local_file_path} to wav: {e}")
|
|
|
|
return wav_file
|
|
|
|
elif ext == ".wav":
|
|
return local_file_path
|
|
|
|
else:
|
|
logging.error(f"Unsupported file format: {ext}.")
|
|
raise ValueError("Unsupported file format.")
|