Update: Refactored the code

This commit is contained in:
Izaya Orihara
2023-10-06 15:45:33 +02:00
parent 0b1c24de2a
commit 57cc73a439
4 changed files with 165 additions and 82 deletions
+51 -19
View File
@@ -1,41 +1,73 @@
import logging
import os
from pydub import AudioSegment
from pytube import YouTube
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
def download_youtube_audio(self, youtube_link, filename):
yt = YouTube(youtube_link)
@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
# Get the highest quality audio stream
audio_stream = yt.streams.get_audio_only()
# Download if the file doesn't already exist
if not os.path.exists(filename):
audio_stream.download(filename=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
def convert_to_wav(self, mp4_file, wav_file):
sound = AudioSegment.from_file(mp4_file, format="mp4")
sound.export(wav_file, format="wav")
@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}")
def load_local_file(self, local_file_path):
# Check the file type
@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 == ".mp4":
wav_file = local_file_path.replace(".mp4", ".wav")
self.convert_to_wav(local_file_path, wav_file)
return wav_file
elif ext == ".mp3":
wav_file = local_file_path.replace(".mp3", ".wav")
audio = AudioSegment.from_file(local_file_path, format="mp3")
audio.export(wav_file, format="wav")
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.")