diff --git a/UltraSinger.py b/UltraSinger.py index 0cc98e4..f4ac493 100644 --- a/UltraSinger.py +++ b/UltraSinger.py @@ -15,13 +15,12 @@ from modules import os_helper from modules.Audio.denoise import ffmpeg_reduce_noise from modules.Audio.separation import separate_audio from modules.Audio.vocal_chunks import ( - convert_audio_to_mono_wav, - convert_wav_to_mp3, export_chunks_from_transcribed_data, export_chunks_from_ultrastar_data, - export_transcribed_data_to_csv, - remove_silence_from_transcribtion_data, ) +from modules.Audio.silence_processing import remove_silence_from_transcribtion_data +from modules.csv_export import export_transcribed_data_to_csv +from modules.Audio.convert_audio import convert_audio_to_mono_wav, convert_wav_to_mp3 from modules.Audio.youtube import ( download_youtube_audio, download_youtube_thumbnail, @@ -29,12 +28,12 @@ from modules.Audio.youtube import ( get_youtube_title, ) from modules.DeviceDetection.device_detection import get_available_device -from modules.Log import ( - PRINT_ULTRASTAR, - print_blue_highlighted_text, - print_gold_highlighted_text, - print_light_blue_highlighted_text, - print_red_highlighted_text, +from modules.console_colors import ( + ULTRASINGER_HEAD, + blue_highlighted, + gold_highlighted, + light_blue_highlighted, + red_highlighted, ) from modules.Midi import midi_creator from modules.Midi.midi_creator import ( @@ -78,7 +77,7 @@ def get_confidence(pitched_data, threshold): def convert_ultrastar_note_numbers(midi_notes): """Docstring""" - print(f"{PRINT_ULTRASTAR} Creating Ultrastar notes from midi data") + print(f"{ULTRASINGER_HEAD} Creating Ultrastar notes from midi data") ultrastar_note_numbers = [] for i, note in enumerate(midi_notes): @@ -97,7 +96,7 @@ def convert_ultrastar_note_numbers(midi_notes): def pitch_each_chunk_with_crepe(directory): """Docstring""" print( - f"{PRINT_ULTRASTAR} Pitching each chunk with {print_blue_highlighted_text('crepe')}" + f"{ULTRASINGER_HEAD} Pitching each chunk with {blue_highlighted('crepe')}" ) midi_notes = [] @@ -156,7 +155,7 @@ def get_bpm_from_data(data, sampling_rate): wav_tempo = librosa.beat.tempo(onset_envelope=onset_env, sr=sampling_rate) print( - f"{PRINT_ULTRASTAR} BPM is {print_blue_highlighted_text(str(round(wav_tempo[0], 2)))}" + f"{ULTRASINGER_HEAD} BPM is {blue_highlighted(str(round(wav_tempo[0], 2)))}" ) return wav_tempo[0] @@ -265,7 +264,7 @@ def hyphenate_each_word(language, transcribed_data): lang_region = language_check(language) if lang_region is None: print( - f"{PRINT_ULTRASTAR} {print_red_highlighted_text('Error in hyphenation for language ')} {print_blue_highlighted_text(language)} {print_red_highlighted_text(', maybe you want to disable it?')}" + f"{ULTRASINGER_HEAD} {red_highlighted('Error in hyphenation for language ')} {blue_highlighted(language)} {red_highlighted(', maybe you want to disable it?')}" ) return None @@ -281,13 +280,13 @@ def print_support(): """Docstring""" print() print( - f"{PRINT_ULTRASTAR} {print_gold_highlighted_text('Do you like UltraSinger? And want it to be even better? Then help with your')} {print_light_blue_highlighted_text('support')}{print_gold_highlighted_text('!')}" + f"{ULTRASINGER_HEAD} {gold_highlighted('Do you like UltraSinger? And want it to be even better? Then help with your')} {light_blue_highlighted('support')}{gold_highlighted('!')}" ) print( - f"{PRINT_ULTRASTAR} See project page -> https://github.com/rakuri255/UltraSinger" + f"{ULTRASINGER_HEAD} See project page -> https://github.com/rakuri255/UltraSinger" ) print( - f"{PRINT_ULTRASTAR} {print_gold_highlighted_text('This will help alot to keep this project alive and improved.')}" + f"{ULTRASINGER_HEAD} {gold_highlighted('This will help alot to keep this project alive and improved.')}" ) @@ -299,7 +298,7 @@ def run(): if not is_audio: # Parse Ultrastar txt print( - f"{PRINT_ULTRASTAR} {print_gold_highlighted_text('re-pitch mode')}" + f"{ULTRASINGER_HEAD} {gold_highlighted('re-pitch mode')}" ) ( basename_without_ext, @@ -310,7 +309,7 @@ def run(): ) = parse_ultrastar_txt() elif settings.input_file_path.startswith("https:"): # Youtube print( - f"{PRINT_ULTRASTAR} {print_gold_highlighted_text('full automatic mode')}" + f"{ULTRASINGER_HEAD} {gold_highlighted('full automatic mode')}" ) ( basename_without_ext, @@ -319,7 +318,7 @@ def run(): ) = download_from_youtube() else: # Audio File print( - f"{PRINT_ULTRASTAR} {print_gold_highlighted_text('full automatic mode')}" + f"{ULTRASINGER_HEAD} {gold_highlighted('full automatic mode')}" ) ( basename_without_ext, @@ -429,7 +428,7 @@ def get_unused_song_output_dir(path): i += 1 if i > 999: print( - f"{PRINT_ULTRASTAR} {print_red_highlighted_text('Error: Could not create output folder! (999) is the maximum number of tries.')}" + f"{ULTRASINGER_HEAD} {red_highlighted('Error: Could not create output folder! (999) is the maximum number of tries.')}" ) sys.exit(1) return path @@ -488,7 +487,7 @@ def calculate_score_points( ) else: print( - f"{PRINT_ULTRASTAR} {print_blue_highlighted_text('Score of original Ultrastar txt')}" + f"{ULTRASINGER_HEAD} {blue_highlighted('Score of original Ultrastar txt')}" ) ( simple_score, @@ -500,7 +499,7 @@ def calculate_score_points( simple_score, accurate_score ) print( - f"{PRINT_ULTRASTAR} {print_blue_highlighted_text('Score of re-pitched Ultrastar txt')}" + f"{ULTRASINGER_HEAD} {blue_highlighted('Score of re-pitched Ultrastar txt')}" ) ultrastar_class = ultrastar_parser.parse_ultrastar_txt( ultrastar_file_output @@ -661,7 +660,7 @@ def parse_ultrastar_txt(): def create_midi_file(is_audio, real_bpm, song_output, ultrastar_class): """Docstring""" print( - f"{PRINT_ULTRASTAR} Creating Midi with {print_blue_highlighted_text('pretty_midi')}" + f"{ULTRASINGER_HEAD} Creating Midi with {blue_highlighted('pretty_midi')}" ) if is_audio: voice_instrument = [ diff --git a/modules/Audio/convert_audio.py b/modules/Audio/convert_audio.py new file mode 100644 index 0000000..6642706 --- /dev/null +++ b/modules/Audio/convert_audio.py @@ -0,0 +1,28 @@ +"""Convert audio to other formats""" + +from pydub import AudioSegment + +from modules.console_colors import ULTRASINGER_HEAD + + +def convert_audio_to_mono_wav(input_file: str, output_file: str) -> None: + """Convert audio to mono wav""" + print(f"{ULTRASINGER_HEAD} Converting audio for AI") + + if ".mp3" in input_file: + sound = AudioSegment.from_mp3(input_file) + elif ".wav" in input_file: + sound = AudioSegment.from_wav(input_file) + else: + raise ValueError("data format not supported") + + sound = sound.set_channels(1) + sound.export(output_file, format="wav") + + +def convert_wav_to_mp3(input_file: str, output_file: str) -> None: + """Convert wav to mp3""" + print(f"{ULTRASINGER_HEAD} Converting wav to mp3") + + sound = AudioSegment.from_wav(input_file) + sound.export(output_file, format="mp3") diff --git a/modules/Audio/denoise.py b/modules/Audio/denoise.py index 16297c0..5987739 100644 --- a/modules/Audio/denoise.py +++ b/modules/Audio/denoise.py @@ -1,12 +1,13 @@ -"""Docstring""" +"""Reduce noise from audio""" import ffmpeg -from modules.Log import PRINT_ULTRASTAR, print_blue_highlighted_text +from modules.console_colors import ULTRASINGER_HEAD, blue_highlighted -def ffmpeg_reduce_noise(input_file_path, output_file): - """Docstring""" +def ffmpeg_reduce_noise(input_file_path: str, output_file: str) -> None: + """Reduce noise from vocal audio with ffmpeg.""" + # Denoise audio samples with FFT. # A description of the accepted parameters follows. @@ -19,7 +20,7 @@ def ffmpeg_reduce_noise(input_file_path, output_file): # With this enabled, noise floor is automatically adjusted. print( - f"{PRINT_ULTRASTAR} Reduce noise from vocal audio with {print_blue_highlighted_text('ffmpeg')}." + f"{ULTRASINGER_HEAD} Reduce noise from vocal audio with {blue_highlighted('ffmpeg')}." ) ( ffmpeg.input(input_file_path) diff --git a/modules/Audio/separation.py b/modules/Audio/separation.py index 902dfe2..4797ad1 100644 --- a/modules/Audio/separation.py +++ b/modules/Audio/separation.py @@ -1,20 +1,20 @@ -"""Docstring""" +"""Separate vocals from audio""" import subprocess -from modules.Log import ( - PRINT_ULTRASTAR, - print_blue_highlighted_text, - print_red_highlighted_text, +from modules.console_colors import ( + ULTRASINGER_HEAD, + blue_highlighted, + red_highlighted, ) from modules.os_helper import current_executor_path, move, path_join -def separate_audio(input_file_path, output_file, device="cpu"): - """Docstring""" +def separate_audio(input_file_path: str, output_file: str, device="cpu") -> None: + """Separate vocals from audio with demucs.""" print( - f"{PRINT_ULTRASTAR} Separating vocals from audio with {print_blue_highlighted_text('demucs')} and {print_red_highlighted_text(device)} as worker." + f"{ULTRASINGER_HEAD} Separating vocals from audio with {blue_highlighted('demucs')} and {red_highlighted(device)} as worker." ) # Model selection? # -n mdx_q diff --git a/modules/Audio/silence_processing.py b/modules/Audio/silence_processing.py new file mode 100644 index 0000000..c140555 --- /dev/null +++ b/modules/Audio/silence_processing.py @@ -0,0 +1,53 @@ +"""Silence processing module""" + +import librosa + +from modules.console_colors import ULTRASINGER_HEAD + + +def remove_silence_from_transcribtion_data(audio_path: str, transcribed_data: []) -> []: + """Remove silence from given transcribtion data""" + + print( + f"{ULTRASINGER_HEAD} Removing silent start and ending, from transcription data" + ) + + audio, sample_rate = librosa.load(audio_path, sr=None) + + for i, data in enumerate(transcribed_data): + start_time = data.start + end_time = data.end + start_sample = int(start_time * sample_rate) + end_sample = int(end_time * sample_rate) + chunk = audio[start_sample:end_sample] + + # todo: why 5 works good? It should be 40db ?!? + # max_dB = librosa.amplitude_to_db(chunk, ref=np.max) + silence_threshold = 5 + onsets = librosa.effects.split( + chunk, top_db=silence_threshold, frame_length=2048, hop_length=100 + ) + + # Get the duration of the first and last silent intervals + if len(onsets) > 0: + first_silence = onsets[0][0] + last_silence = len(chunk) - onsets[-1][1] + + first_silence_duration = librosa.samples_to_time( + first_silence, sr=sample_rate + ) + last_silence_duration = librosa.samples_to_time( + last_silence, sr=sample_rate + ) + else: + first_silence_duration = 0 + last_silence_duration = 0 + + data.start = ( + data.start + first_silence_duration + ) + data.end = ( + data.end - last_silence_duration + ) + + return transcribed_data diff --git a/modules/Audio/vocal_chunks.py b/modules/Audio/vocal_chunks.py index e24fbc0..72d6f04 100644 --- a/modules/Audio/vocal_chunks.py +++ b/modules/Audio/vocal_chunks.py @@ -1,41 +1,16 @@ -"""Docstring""" +"""Vocal chunks module.""" -import csv import os import re import wave -import librosa -from pydub import AudioSegment - -from modules.Log import PRINT_ULTRASTAR +from modules.console_colors import ULTRASINGER_HEAD from modules.os_helper import create_folder from modules.Ultrastar.ultrastar_converter import ( get_end_time_from_ultrastar, get_start_time_from_ultrastar, ) - - -def convert_audio_to_mono_wav(input_file, output_file): - """Convert audio to mono wav""" - print(f"{PRINT_ULTRASTAR} Converting audio for AI") - - if ".mp3" in input_file: - sound = AudioSegment.from_mp3(input_file) - elif ".wav" in input_file: - sound = AudioSegment.from_wav(input_file) - else: - raise ValueError("data format not supported") - - sound = sound.set_channels(1) - sound.export(output_file, format="wav") - - -def convert_wav_to_mp3(input_file, output_file): - """Docstring""" - - sound = AudioSegment.from_wav(input_file) - sound.export(output_file, format="mp3") +from modules.Ultrastar.ultrastar_txt import UltrastarTxt class AudioManipulation: @@ -43,11 +18,11 @@ class AudioManipulation: def export_chunks_from_transcribed_data( - audio_filename, transcribed_data, output_folder_name -): + audio_filename: str, transcribed_data: [], output_folder_name: str +) -> None: """Export transcribed_data as vocal chunks wav files""" print( - f"{PRINT_ULTRASTAR} Export transcribed data as vocal chunks wav files" + f"{ULTRASINGER_HEAD} Export transcribed data as vocal chunks wav files" ) wave_file = wave.open(audio_filename, "rb") @@ -65,59 +40,11 @@ def export_chunks_from_transcribed_data( wave_file.close() -def remove_silence_from_transcribtion_data(audio_path, transcribed_data): - """Docstring""" - - print( - f"{PRINT_ULTRASTAR} Removing silent start and ending, from transcription data" - ) - - audio, sample_rate = librosa.load(audio_path, sr=None) - - for i, data in enumerate(transcribed_data): - start_time = data.start - end_time = data.end - start_sample = int(start_time * sample_rate) - end_sample = int(end_time * sample_rate) - chunk = audio[start_sample:end_sample] - - # todo: why 5 works good? It should be 40db ?!? - # max_dB = librosa.amplitude_to_db(chunk, ref=np.max) - silence_threshold = 5 - onsets = librosa.effects.split( - chunk, top_db=silence_threshold, frame_length=2048, hop_length=100 - ) - - # Get the duration of the first and last silent intervals - if len(onsets) > 0: - first_silence = onsets[0][0] - last_silence = len(chunk) - onsets[-1][1] - - first_silence_duration = librosa.samples_to_time( - first_silence, sr=sample_rate - ) - last_silence_duration = librosa.samples_to_time( - last_silence, sr=sample_rate - ) - else: - first_silence_duration = 0 - last_silence_duration = 0 - - data.start = ( - data.start + first_silence_duration - ) - data.end = ( - data.end - last_silence_duration - ) - - return transcribed_data - - def export_chunks_from_ultrastar_data( - audio_filename, ultrastar_data, folder_name -): + audio_filename: str, ultrastar_data: UltrastarTxt, folder_name: str +) -> None: """Export ultrastar data as vocal chunks wav files""" - print(f"{PRINT_ULTRASTAR} Export Ultrastar data as vocal chunks wav files") + print(f"{ULTRASINGER_HEAD} Export Ultrastar data as vocal chunks wav files") create_folder(folder_name) @@ -137,7 +64,7 @@ def export_chunks_from_ultrastar_data( ) -def export_chunk_to_wav_file(chunk, folder_name, i, word, wave_file): +def export_chunk_to_wav_file(chunk, folder_name: str, i: int, word: str, wave_file) -> None: """Export vocal chunks to wav file""" clean_word = re.sub("[^A-Za-z0-9]+", "", word) @@ -150,7 +77,7 @@ def export_chunk_to_wav_file(chunk, folder_name, i, word, wave_file): chunk_file.writeframes(chunk) -def get_chunk(end_byte, start_byte, wave_file): +def get_chunk(end_byte: int, start_byte: int, wave_file): """ Gets the chunk from wave file. Returns chunk as n frames of audio, as a bytes object. @@ -160,22 +87,3 @@ def get_chunk(end_byte, start_byte, wave_file): wave_file.setpos(start_byte) # ({:.2f}) chunk = wave_file.readframes(end_byte - start_byte) return chunk - - -def export_transcribed_data_to_csv(transcribed_data, filename): - """Export transcribed data to csv""" - print(f"{PRINT_ULTRASTAR} Exporting transcribed data to CSV") - - with open(filename, "w", encoding="utf-8", newline="") as csvfile: - writer = csv.writer(csvfile) - header = ["word", "start", "end", "confidence"] - writer.writerow(header) - for i, data in enumerate(transcribed_data): - writer.writerow( - [ - data.word, - data.start, - data.end, - data.conf, - ] - ) diff --git a/modules/Audio/youtube.py b/modules/Audio/youtube.py index ffdde66..6ea553e 100644 --- a/modules/Audio/youtube.py +++ b/modules/Audio/youtube.py @@ -1,4 +1,4 @@ -"""Docstring""" +"""YouTube Downloader""" import io import os @@ -6,11 +6,11 @@ import os import yt_dlp from PIL import Image -from modules.Log import PRINT_ULTRASTAR +from modules.console_colors import ULTRASINGER_HEAD -def get_youtube_title(url): - """Docstring""" +def get_youtube_title(url: str) -> str: + """Get the title of the YouTube video""" ydl_opts = {} with yt_dlp.YoutubeDL(ydl_opts) as ydl: @@ -21,10 +21,10 @@ def get_youtube_title(url): return result["title"] -def download_youtube_audio(url, clear_filename, output_path): - """Docstring""" +def download_youtube_audio(url: str, clear_filename: str, output_path: str): + """Download audio from YouTube""" - print(f"{PRINT_ULTRASTAR} Downloading Audio") + print(f"{ULTRASINGER_HEAD} Downloading Audio") ydl_opts = { "format": "bestaudio/best", "outtmpl": output_path + "/" + clear_filename, @@ -36,10 +36,10 @@ def download_youtube_audio(url, clear_filename, output_path): start_download(ydl_opts, url) -def download_youtube_thumbnail(url, clear_filename, output_path): - """Docstring""" +def download_youtube_thumbnail(url: str, clear_filename: str, output_path: str): + """Download thumbnail from YouTube""" - print(f"{PRINT_ULTRASTAR} Downloading thumbnail") + print(f"{ULTRASINGER_HEAD} Downloading thumbnail") ydl_opts = { "skip_download": True, "writethumbnail": True, @@ -48,8 +48,8 @@ def download_youtube_thumbnail(url, clear_filename, output_path): download_and_convert_thumbnail(ydl_opts, url, clear_filename, output_path) -def download_and_convert_thumbnail(ydl_opts, url, clear_filename, output_path): - """Docstring""" +def download_and_convert_thumbnail(ydl_opts, url: str, clear_filename: str, output_path: str) -> None: + """Download and convert thumbnail from YouTube""" with yt_dlp.YoutubeDL(ydl_opts) as ydl: info_dict = ydl.extract_info(url, download=False) @@ -63,10 +63,10 @@ def download_and_convert_thumbnail(ydl_opts, url, clear_filename, output_path): ) -def download_youtube_video(url, clear_filename, output_path): - """Docstring""" +def download_youtube_video(url: str, clear_filename: str, output_path: str) -> None: + """Download video from YouTube""" - print(f"{PRINT_ULTRASTAR} Downloading Video") + print(f"{ULTRASINGER_HEAD} Downloading Video") ydl_opts = { "format": "bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4", "outtmpl": output_path + "/" + clear_filename + ".mp4", @@ -74,8 +74,8 @@ def download_youtube_video(url, clear_filename, output_path): start_download(ydl_opts, url) -def start_download(ydl_opts, url): - """Docstring""" +def start_download(ydl_opts, url: str) -> None: + """Start the download the ydl_opts""" with yt_dlp.YoutubeDL(ydl_opts) as ydl: errors = ydl.download(url) diff --git a/modules/DeviceDetection/device_detection.py b/modules/DeviceDetection/device_detection.py index cb8e43c..6ba0cec 100644 --- a/modules/DeviceDetection/device_detection.py +++ b/modules/DeviceDetection/device_detection.py @@ -2,7 +2,7 @@ import tensorflow as tf -from modules.Log import PRINT_ULTRASTAR, print_red_highlighted_text +from modules.console_colors import ULTRASINGER_HEAD, red_highlighted def get_available_device(): @@ -11,16 +11,16 @@ def get_available_device(): if not gpus: print( - f"{PRINT_ULTRASTAR} There are no GPUs available. Using {print_red_highlighted_text('cpu')}." + f"{ULTRASINGER_HEAD} There are no GPUs available. Using {red_highlighted('cpu')}." ) return "cpu" - print(f"{PRINT_ULTRASTAR} Found available GPUs:") + print(f"{ULTRASINGER_HEAD} Found available GPUs:") for gpu in gpus: print(f"Name: {gpu.name}, Type: {gpu.device_type}") # Todo: Finish this print( - f"{PRINT_ULTRASTAR} GPU usage are currently in development. Using {print_red_highlighted_text('cpu')}" + f"{ULTRASINGER_HEAD} GPU usage are currently in development. Using {red_highlighted('cpu')}" ) return "cpu" diff --git a/modules/Log.py b/modules/Log.py deleted file mode 100644 index 8f0dd27..0000000 --- a/modules/Log.py +++ /dev/null @@ -1,45 +0,0 @@ -"""Docstring""" - -PRINT_ULTRASTAR = "\033[92m[UltraSinger]\033[0m" - - -def print_blue_highlighted_text(text): - """Docstring""" - return Bcolors.BLUE + text + Bcolors.ENDC - - -def print_gold_highlighted_text(text): - """Docstring""" - return Bcolors.Gold + text + Bcolors.ENDC - - -def print_light_blue_highlighted_text(text): - """Docstring""" - return Bcolors.LightBlue + text + Bcolors.ENDC - - -def print_underlined_text(text): - """Docstring""" - return Bcolors.Underline + text + Bcolors.ENDC - - -def print_red_highlighted_text(text): - """Docstring""" - return Bcolors.RED + text + Bcolors.ENDC - - -def print_cyan_highlighted_text(text): - """Docstring""" - return Bcolors.Cyan + text + Bcolors.ENDC - - -class Bcolors: - """Docstring""" - - BLUE = "\033[94m" - RED = "\033[91m" - LightBlue = "\033[96m" - Cyan = "\033[36m" - Gold = "\033[93m" - Underline = "\033[4m" - ENDC = "\033[0m" diff --git a/modules/Midi/midi_creator.py b/modules/Midi/midi_creator.py index 1b3806d..0141148 100644 --- a/modules/Midi/midi_creator.py +++ b/modules/Midi/midi_creator.py @@ -13,16 +13,16 @@ from modules.Ultrastar.ultrastar_converter import ( get_start_time_from_ultrastar, ultrastar_note_to_midi_note, ) -from modules.Log import ( - PRINT_ULTRASTAR, - print_red_highlighted_text, +from modules.console_colors import ( + ULTRASINGER_HEAD, + red_highlighted, ) def convert_ultrastar_to_midi_instrument(ultrastar_class): """Docstring""" - print(f"{PRINT_ULTRASTAR} Creating midi instrument from Ultrastar txt") + print(f"{ULTRASINGER_HEAD} Creating midi instrument from Ultrastar txt") instrument = pretty_midi.Instrument(program=0) velocity = 100 @@ -42,7 +42,7 @@ def convert_ultrastar_to_midi_instrument(ultrastar_class): def instruments_to_midi(instruments, bpm, midi_output): """Docstring""" - print(f"{PRINT_ULTRASTAR} Creating midi file -> {midi_output}") + print(f"{ULTRASINGER_HEAD} Creating midi file -> {midi_output}") midi_data = pretty_midi.PrettyMIDI(initial_tempo=bpm) for instrument in instruments: @@ -81,7 +81,7 @@ def find_nearest_index(array, value): def create_midi_notes_from_pitched_data(start_times, end_times, pitched_data): """Docstring""" - print(f"{PRINT_ULTRASTAR} Creating midi notes from pitched data") + print(f"{ULTRASINGER_HEAD} Creating midi notes from pitched data") midi_notes = [] @@ -108,7 +108,7 @@ def create_midi_note_from_pitched_data(start_time, end_time, pitched_data): # fixme: why is end smaller as start? if end < start: - print(f"{PRINT_ULTRASTAR} {print_red_highlighted_text('Error: end time is smaller as start time. The note is C0 now ...')}") + print(f"{ULTRASINGER_HEAD} {red_highlighted('Error: end time is smaller as start time. The note is C0 now ...')}") return "C0" if start == end: diff --git a/modules/Pitcher/pitcher.py b/modules/Pitcher/pitcher.py index e58e29a..39d2837 100644 --- a/modules/Pitcher/pitcher.py +++ b/modules/Pitcher/pitcher.py @@ -5,10 +5,10 @@ import csv import crepe from scipy.io import wavfile -from modules.Log import ( - PRINT_ULTRASTAR, - print_blue_highlighted_text, - print_red_highlighted_text, +from modules.console_colors import ( + ULTRASINGER_HEAD, + blue_highlighted, + red_highlighted, ) from modules.Pitcher.pitched_data import PitchedData @@ -16,7 +16,7 @@ from modules.Pitcher.pitched_data import PitchedData def get_pitch_with_crepe_file(filename, step_size, model_capacity): """Docstring""" print( - f"{PRINT_ULTRASTAR} Pitching with {print_blue_highlighted_text('crepe')} and model {print_blue_highlighted_text(model_capacity)} and {print_red_highlighted_text('cpu')} as worker" + f"{ULTRASINGER_HEAD} Pitching with {blue_highlighted('crepe')} and model {blue_highlighted(model_capacity)} and {red_highlighted('cpu')} as worker" ) # Todo: add GPU support by using torchcrepe sample_rate, audio = wavfile.read(filename) diff --git a/modules/Speech_Recognition/Vosk.py b/modules/Speech_Recognition/Vosk.py index fdd465a..0f1c0b7 100644 --- a/modules/Speech_Recognition/Vosk.py +++ b/modules/Speech_Recognition/Vosk.py @@ -5,7 +5,7 @@ import wave from vosk import KaldiRecognizer, Model -from modules.Log import PRINT_ULTRASTAR +from modules.console_colors import ULTRASINGER_HEAD from modules.Speech_Recognition.TranscribedData import TranscribedData # todo: Rename to Transcoder? @@ -15,7 +15,7 @@ def transcribe_with_vosk(audio_filename, model_path): """Docstring""" # Code from here: https://towardsdatascience.com/speech-recognition-with-timestamps-934ede4234b2 print( - f"{PRINT_ULTRASTAR} Transcribing {audio_filename} with vosk and model {model_path}" + f"{ULTRASINGER_HEAD} Transcribing {audio_filename} with vosk and model {model_path}" ) model = Model(model_path) diff --git a/modules/Speech_Recognition/Whisper.py b/modules/Speech_Recognition/Whisper.py index 11cd68e..09d1e0e 100644 --- a/modules/Speech_Recognition/Whisper.py +++ b/modules/Speech_Recognition/Whisper.py @@ -2,10 +2,10 @@ import whisperx -from modules.Log import ( - PRINT_ULTRASTAR, - print_blue_highlighted_text, - print_red_highlighted_text, +from modules.console_colors import ( + ULTRASINGER_HEAD, + blue_highlighted, + red_highlighted, ) from modules.Speech_Recognition.TranscribedData import TranscribedData @@ -14,7 +14,7 @@ def transcribe_with_whisper(audio_path, model, device="cpu"): """Docstring""" print( - f"{PRINT_ULTRASTAR} Loading {print_blue_highlighted_text('whisper')} with model {print_blue_highlighted_text(model)} and {print_red_highlighted_text(device)} as worker" + f"{ULTRASINGER_HEAD} Loading {blue_highlighted('whisper')} with model {blue_highlighted(model)} and {red_highlighted(device)} as worker" ) batch_size = 16 # reduce if low on GPU mem @@ -28,7 +28,7 @@ def transcribe_with_whisper(audio_path, model, device="cpu"): ) audio = whisperx.load_audio(audio_path) - print(f"{PRINT_ULTRASTAR} Transcribing {audio_path}") + print(f"{ULTRASINGER_HEAD} Transcribing {audio_path}") result = loaded_whisper_model.transcribe(audio, batch_size=batch_size) language = result["language"] @@ -54,7 +54,7 @@ def transcribe_with_whisper(audio_path, model, device="cpu"): for obj in segment["words"]: if len(obj) < 4: print( - f"{print_red_highlighted_text('Error: Skipping Word {}, because of missing timings'.format(obj['word']))}" + f"{red_highlighted('Error: Skipping Word {}, because of missing timings'.format(obj['word']))}" ) continue vtd = TranscribedData(obj) # create custom Word object diff --git a/modules/Speech_Recognition/hyphenation.py b/modules/Speech_Recognition/hyphenation.py index 85cef3c..89f7009 100644 --- a/modules/Speech_Recognition/hyphenation.py +++ b/modules/Speech_Recognition/hyphenation.py @@ -4,9 +4,9 @@ import string from hyphen import Hyphenator, dictools -from modules.Log import ( - PRINT_ULTRASTAR, - print_blue_highlighted_text, +from modules.console_colors import ( + ULTRASINGER_HEAD, + blue_highlighted, ) @@ -25,7 +25,7 @@ def language_check(language="en"): return None print( - f"{PRINT_ULTRASTAR} Hyphenate using language code: {print_blue_highlighted_text(lang_region)}" + f"{ULTRASINGER_HEAD} Hyphenate using language code: {blue_highlighted(lang_region)}" ) return lang_region diff --git a/modules/Speech_Recognition/speech_recognition.py b/modules/Speech_Recognition/speech_recognition.py index 88c5de7..08d829d 100644 --- a/modules/Speech_Recognition/speech_recognition.py +++ b/modules/Speech_Recognition/speech_recognition.py @@ -6,7 +6,7 @@ import speech_recognition as sr from pydub import AudioSegment from pydub.silence import split_on_silence -from modules.Log import PRINT_ULTRASTAR +from modules.console_colors import ULTRASINGER_HEAD # todo: Code from here: https://www.thepythoncode.com/article/using-speech-recognition-to-convert-speech-to-text-python @@ -96,9 +96,9 @@ def transcribe_audio(audio_file): end_time, ) except sr.UnknownValueError: - print(f"{PRINT_ULTRASTAR} Could not understand audio") + print(f"{ULTRASINGER_HEAD} Could not understand audio") except sr.RequestError as error: - print(f"{PRINT_ULTRASTAR} Error with recognizing service; {error}") + print(f"{ULTRASINGER_HEAD} Error with recognizing service; {error}") class SpeechToText: diff --git a/modules/Ultrastar/ultrastar_parser.py b/modules/Ultrastar/ultrastar_parser.py index b51d7d9..e68ab30 100644 --- a/modules/Ultrastar/ultrastar_parser.py +++ b/modules/Ultrastar/ultrastar_parser.py @@ -1,6 +1,6 @@ """Docstring""" -from modules.Log import PRINT_ULTRASTAR +from modules.console_colors import ULTRASINGER_HEAD from modules.Ultrastar.ultrastar_converter import ( get_end_time_from_ultrastar, get_start_time_from_ultrastar, @@ -10,7 +10,7 @@ from modules.Ultrastar.ultrastar_txt import UltrastarTxt def parse_ultrastar_txt(input_file): """Docstring""" - print(f"{PRINT_ULTRASTAR} Parse ultrastar txt -> {input_file}") + print(f"{ULTRASINGER_HEAD} Parse ultrastar txt -> {input_file}") with open(input_file, "r", encoding="utf-8") as file: txt = file.readlines() diff --git a/modules/Ultrastar/ultrastar_score_calculator.py b/modules/Ultrastar/ultrastar_score_calculator.py index e4d4cb5..20fe33b 100644 --- a/modules/Ultrastar/ultrastar_score_calculator.py +++ b/modules/Ultrastar/ultrastar_score_calculator.py @@ -2,13 +2,13 @@ import librosa -from modules.Log import ( - PRINT_ULTRASTAR, - print_blue_highlighted_text, - print_cyan_highlighted_text, - print_gold_highlighted_text, - print_light_blue_highlighted_text, - print_underlined_text, +from modules.console_colors import ( + ULTRASINGER_HEAD, + blue_highlighted, + cyan_highlighted, + gold_highlighted, + light_blue_highlighted, + underlined, ) from modules.Midi.midi_creator import create_midi_note_from_pitched_data from modules.Ultrastar.ultrastar_converter import ( @@ -78,14 +78,14 @@ def print_score(score): """Docstring""" print( - f"{PRINT_ULTRASTAR} Total: {print_cyan_highlighted_text(str(score.score))}, notes: {print_blue_highlighted_text(str(score.notes))}, line bonus: {print_light_blue_highlighted_text(str(score.line_bonus))}, golden notes: {print_gold_highlighted_text(str(score.golden))}" + f"{ULTRASINGER_HEAD} Total: {cyan_highlighted(str(score.score))}, notes: {blue_highlighted(str(score.notes))}, line bonus: {light_blue_highlighted(str(score.line_bonus))}, golden notes: {gold_highlighted(str(score.golden))}" ) def calculate_score(pitched_data, ultrastar_class): """Docstring""" - print(PRINT_ULTRASTAR + " Calculating Ultrastar Points") + print(ULTRASINGER_HEAD + " Calculating Ultrastar Points") simple_points = Points() accurate_points = Points() @@ -154,11 +154,11 @@ def print_score_calculation(simple_points, accurate_points): """Docstring""" print( - f"{PRINT_ULTRASTAR} {print_underlined_text('Simple (octave high ignored)')} points" + f"{ULTRASINGER_HEAD} {underlined('Simple (octave high ignored)')} points" ) print_score(simple_points) print( - f"{PRINT_ULTRASTAR} {print_underlined_text('Accurate (octave high matches)')} points:" + f"{ULTRASINGER_HEAD} {underlined('Accurate (octave high matches)')} points:" ) print_score(accurate_points) diff --git a/modules/Ultrastar/ultrastar_txt.py b/modules/Ultrastar/ultrastar_txt.py index 2121059..7425378 100644 --- a/modules/Ultrastar/ultrastar_txt.py +++ b/modules/Ultrastar/ultrastar_txt.py @@ -11,7 +11,7 @@ class UltrastarTxt: bpm = "" cover = None creator = "UltraSinger [GitHub]" - fixer = "YOUR NAME" + fixer = "YOUR NAME" # Only for UltraStar World Party comment = "UltraSinger [GitHub]" startBeat = [] startTimes = [] diff --git a/modules/Ultrastar/ultrastar_writer.py b/modules/Ultrastar/ultrastar_writer.py index dd7f52e..8304ae4 100644 --- a/modules/Ultrastar/ultrastar_writer.py +++ b/modules/Ultrastar/ultrastar_writer.py @@ -4,7 +4,7 @@ import re import langcodes -from modules.Log import PRINT_ULTRASTAR +from modules.console_colors import ULTRASINGER_HEAD from modules.Ultrastar.ultrastar_converter import ( real_bpm_to_ultrastar_bpm, second_to_beat, @@ -41,7 +41,7 @@ def create_ultrastar_txt_from_automation( """Docstring""" print( - f"{PRINT_ULTRASTAR} Creating {ultrastar_file_output} from transcription." + f"{ULTRASINGER_HEAD} Creating {ultrastar_file_output} from transcription." ) real_bpm = real_bpm_to_ultrastar_bpm(bpm) diff --git a/modules/console_colors.py b/modules/console_colors.py new file mode 100644 index 0000000..c4cc6f8 --- /dev/null +++ b/modules/console_colors.py @@ -0,0 +1,45 @@ +"""Colors for the console""" + +ULTRASINGER_HEAD = "\033[92m[UltraSinger]\033[0m" + + +def blue_highlighted(text: str) -> str: + """Returns a blue highlighted text""" + return f"{Bcolors.blue}{text}{Bcolors.endc}" + + +def gold_highlighted(text: str) -> str: + """Returns a gold highlighted text""" + return f"{Bcolors.gold}{text}{Bcolors.endc}" + + +def light_blue_highlighted(text: str) -> str: + """Returns a light blue highlighted text""" + return f"{Bcolors.light_blue}{text}{Bcolors.endc}" + + +def underlined(text: str) -> str: + """Returns an underlined text""" + return f"{Bcolors.underline}{text}{Bcolors.endc}" + + +def red_highlighted(text: str) -> str: + """Returns a red highlighted text""" + return f"{Bcolors.red}{text}{Bcolors.endc}" + + +def cyan_highlighted(text: str) -> str: + """Returns a cyan highlighted text""" + return f"{Bcolors.cyan}{text}{Bcolors.endc}" + + +class Bcolors: + """Colors for the console""" + + blue = "\033[94m" + red = "\033[91m" + light_blue = "\033[96m" + cyan = "\033[36m" + gold = "\033[93m" + underline = "\033[4m" + endc = "\033[0m" diff --git a/modules/csv_export.py b/modules/csv_export.py new file mode 100644 index 0000000..680507e --- /dev/null +++ b/modules/csv_export.py @@ -0,0 +1,24 @@ +"""CSV export module""" + +import csv + +from modules.console_colors import ULTRASINGER_HEAD + + +def export_transcribed_data_to_csv(transcribed_data: [], filename: str) -> None: + """Export transcribed data to csv""" + print(f"{ULTRASINGER_HEAD} Exporting transcribed data to CSV") + + with open(filename, "w", encoding="utf-8", newline="") as csvfile: + writer = csv.writer(csvfile) + header = ["word", "start", "end", "confidence"] + writer.writerow(header) + for i, data in enumerate(transcribed_data): + writer.writerow( + [ + data.word, + data.start, + data.end, + data.conf, + ] + ) diff --git a/modules/os_helper.py b/modules/os_helper.py index 0a2870e..8f2f9bd 100644 --- a/modules/os_helper.py +++ b/modules/os_helper.py @@ -3,12 +3,12 @@ import os import shutil -from modules.Log import PRINT_ULTRASTAR +from modules.console_colors import ULTRASINGER_HEAD def create_folder(folder_name): """Docstring""" - print(f"{PRINT_ULTRASTAR} Creating output folder. -> {folder_name}") + print(f"{ULTRASINGER_HEAD} Creating output folder. -> {folder_name}") is_exist = os.path.exists(folder_name) if not is_exist: os.makedirs(folder_name)