diff --git a/src/Settings.py b/src/Settings.py index e36d34b..eab956f 100644 --- a/src/Settings.py +++ b/src/Settings.py @@ -20,7 +20,7 @@ class Settings: # Process data Paths input_file_path = "" - output_file_path = "" + output_folder_path = "" language = None format_version = "1.0.0" diff --git a/src/UltraSinger.py b/src/UltraSinger.py index 2e6aa14..73b7964 100644 --- a/src/UltraSinger.py +++ b/src/UltraSinger.py @@ -1,11 +1,10 @@ """UltraSinger uses AI to automatically create UltraStar song files""" import copy +import re import getopt import os import sys -import re - import Levenshtein import librosa @@ -32,7 +31,6 @@ from modules.Audio.youtube import ( download_youtube_video, get_youtube_title, ) -from modules.DeviceDetection.device_detection import check_gpu_support from modules.console_colors import ( ULTRASINGER_HEAD, blue_highlighted, @@ -46,8 +44,7 @@ from modules.Midi.midi_creator import ( create_midi_notes_from_pitched_data, convert_midi_notes_to_ultrastar_notes, most_frequent, - MidiSegment, - convert_ultrastar_to_midi_instrument, + create_midi_instrument, instruments_to_midi ) from modules.Pitcher.pitcher import ( @@ -63,20 +60,19 @@ from modules.Speech_Recognition.Whisper import transcribe_with_whisper from modules.Ultrastar import ( ultrastar_score_calculator, ultrastar_writer, - ultrastar_converter, ultrastar_parser, ) -from modules.Ultrastar.ultrastar_txt import UltrastarTxtValue, FILE_ENCODING -from Settings import Settings +from modules.Ultrastar.ultrastar_txt import FILE_ENCODING +from modules.help_print import print_support, print_help from modules.os_helper import check_file_exists from modules.plot import plot, plot_spectrogram from modules.musicbrainz_client import get_music_infos from modules.sheet import create_sheet from modules.ProcessData import * +from Settings import Settings +from modules.DeviceDetection.device_detection import check_gpu_support settings = Settings() -process_data = ProcessData() - def pitch_each_chunk_with_crepe(directory: str) -> list[str]: """Pitch each chunk with crepe and return midi notes""" @@ -175,66 +171,6 @@ def correct_words(recognized_words, word_list_file): return recognized_words -def print_help() -> None: - """Print help text""" - help_string = """ - UltraSinger.py [opt] [mode] [transcription] [pitcher] [extra] - - [opt] - -h This help text. - -i Ultrastar.txt - audio like .mp3, .wav, youtube link - -o Output folder - - [mode] - ## INPUT is audio ## - default Creates all - - # Single file creation selection is in progress, you currently getting all! - (-u Create ultrastar txt file) # In Progress - (-m Create midi file) # In Progress - (-s Create sheet file) # In Progress - - ## INPUT is ultrastar.txt ## - default Creates all - - # Single selection is in progress, you currently getting all! - (-r repitch Ultrastar.txt (input has to be audio)) # In Progress - (-p Check pitch of Ultrastar.txt input) # In Progress - (-m Create midi file) # In Progress - - [transcription] - # Default is whisper - --whisper Multilingual model > tiny|base|small|medium|large-v1|large-v2 >> ((default) is large-v2 - English-only model > tiny.en|base.en|small.en|medium.en - --whisper_align_model Use other languages model for Whisper provided from huggingface.co - --language Override the language detected by whisper, does not affect transcription but steps after transcription - --whisper_batch_size Reduce if low on GPU mem >> ((default) is 16) - --whisper_compute_type Change to "int8" if low on GPU mem (may reduce accuracy) >> ((default) is "float16" for cuda devices, "int8" for cpu) - - [pitcher] - # Default is crepe - --crepe tiny|full >> ((default) is full) - --crepe_step_size unit is miliseconds >> ((default) is 10) - - [extra] - --hyphenation True|False >> ((default) is True) - --disable_separation True|False >> ((default) is False) - --disable_karaoke True|False >> ((default) is False) - --create_audio_chunks True|False >> ((default) is False) - --keep_cache True|False >> ((default) is False) - --plot True|False >> ((default) is False) - --format_version 0.3.0|1.0.0|1.1.0 >> ((default) is 1.0.0) - --musescore_path path to MuseScore executable - - [device] - --force_cpu True|False >> ((default) is False) All steps will be forced to cpu - --force_whisper_cpu True|False >> ((default) is False) Only whisper will be forced to cpu - --force_crepe_cpu True|False >> ((default) is False) Only crepe will be forced to cpu - """ - print(help_string) - - def remove_unecessary_punctuations(transcribed_data: list[TranscribedData]) -> None: """Remove unecessary punctuations from transcribed data""" punctuation = ".," @@ -268,19 +204,6 @@ def hyphenate_each_word( return hyphenated_word -def print_support() -> None: - """Print support text""" - print() - print( - f"{ULTRASINGER_HEAD} {gold_highlighted('Do you like UltraSinger? Want it to be even better? Then help with your')} {light_blue_highlighted('support')}{gold_highlighted('!')}" - ) - print( - f"{ULTRASINGER_HEAD} See project page -> https://github.com/rakuri255/UltraSinger" - ) - print( - f"{ULTRASINGER_HEAD} {gold_highlighted('This will help a lot to keep this project alive and improved.')}" - ) - def print_version() -> None: """Print version text""" print() @@ -299,90 +222,92 @@ def run() -> tuple[str, Score, Score]: """The processing function of this program""" settings.input_file_is_ultrastar_txt = settings.input_file_path.endswith(".txt") - ultrastar_class = None - real_bpm = None - - if settings.input_file_is_ultrastar_txt: # Parse Ultrastar txt + if settings.input_file_is_ultrastar_txt: + # Parse Ultrastar txt ( - process_data.basename, - real_bpm, - settings.song_output, - ultrastar_audio_input_path, + basename, + settings.output_folder_path, + audio_file_path, ultrastar_class, ) = parse_ultrastar_txt() + process_data = from_ultrastar_txt(ultrastar_class) + process_data.basename = basename + process_data.process_data_paths.audio_output_file_path = audio_file_path + #todo: only ignore whisper + settings.ignore_audio = True - if not ultrastar_class.mp3: - print( - f"{ULTRASINGER_HEAD} {red_highlighted('Error!')} The provided text file does not have a reference to " - f"an audio file." - ) - exit(1) - elif settings.input_file_path.startswith("https:"): # Youtube + elif settings.input_file_path.startswith("https:"): + # Youtube print(f"{ULTRASINGER_HEAD} {gold_highlighted('full automatic mode')}") + process_data = ProcessData() ( process_data.basename, - settings.song_output, - ultrastar_audio_input_path, + settings.output_folder_path, + process_data.process_data_paths.audio_output_file_path, process_data.media_info, ) = download_from_youtube() - else: # Audio File + else: + # Audio File print(f"{ULTRASINGER_HEAD} {gold_highlighted('full automatic mode')}") + process_data = ProcessData() ( process_data.basename, - settings.song_output, - ultrastar_audio_input_path, + settings.output_folder_path, + process_data.process_data_paths.audio_output_file_path, process_data.media_info, ) = infos_from_audio_input_file() - process_data.process_data_paths.cache_path = ( - os.path.join(settings.song_output, "cache") + process_data.process_data_paths.cache_folder_path = ( + os.path.join(settings.output_folder_path, "cache") if settings.cache_override_path is None else settings.cache_override_path ) + # Set processing audio to cache file process_data.process_data_paths.processing_audio_path = os.path.join( - process_data.process_data_paths.cache_path, process_data.basename + ".wav" + process_data.process_data_paths.cache_folder_path, process_data.basename + ".wav" ) - os_helper.create_folder(process_data.process_data_paths.cache_path) + os_helper.create_folder(process_data.process_data_paths.cache_folder_path) # Separate vocal from audio - audio_separation_path = separate_vocal_from_audio( - process_data.basename, process_data.process_data_paths.cache_path, ultrastar_audio_input_path + audio_separation_folder_path = separate_vocal_from_audio( + process_data.process_data_paths.cache_folder_path, process_data.process_data_paths.audio_output_file_path, + process_data.process_data_paths.processing_audio_path ) - vocals_path = os.path.join(audio_separation_path, "vocals.wav") - instrumental_path = os.path.join(audio_separation_path, "no_vocals.wav") + process_data.process_data_paths.vocals_audio_file_path = os.path.join(audio_separation_folder_path, "vocals.wav") + process_data.process_data_paths.instrumental_audio_file_path = os.path.join(audio_separation_folder_path, "no_vocals.wav") # Move instrumental and vocals # Todo: this is ultraStar specific if settings.create_karaoke and version.parse(settings.format_version) < version.parse("1.1.0"): - karaoke_output_path = os.path.join(settings.song_output, process_data.basename + " [Karaoke].mp3") - convert_wav_to_mp3(instrumental_path, karaoke_output_path) + karaoke_output_path = os.path.join(settings.output_folder_path, process_data.basename + " [Karaoke].mp3") + convert_wav_to_mp3(process_data.process_data_paths.instrumental_audio_file_path, karaoke_output_path) if version.parse(settings.format_version) >= version.parse("1.1.0"): - instrumental_output_path = os.path.join(settings.song_output, process_data.basename + " [Instrumental].mp3") - convert_wav_to_mp3(instrumental_path, instrumental_output_path) - vocals_output_path = os.path.join(settings.song_output, process_data.basename + " [Vocals].mp3") - convert_wav_to_mp3(vocals_path, vocals_output_path) + instrumental_output_path = os.path.join(settings.output_folder_path, process_data.basename + " [Instrumental].mp3") + convert_wav_to_mp3(process_data.process_data_paths.instrumental_audio_file_path, instrumental_output_path) + vocals_output_path = os.path.join(settings.output_folder_path, process_data.basename + " [Vocals].mp3") + convert_wav_to_mp3(process_data.process_data_paths.vocals_audio_file_path, vocals_output_path) if settings.use_separated_vocal: - input_path = vocals_path + input_path = process_data.process_data_paths.vocals_audio_file_path else: - input_path = ultrastar_audio_input_path + input_path = process_data.process_data_paths.audio_output_file_path # Denoise vocal audio denoised_output_path = os.path.join( - process_data.process_data_paths.cache_path, process_data.basename + "_denoised.wav" + process_data.process_data_paths.cache_folder_path, process_data.basename + "_denoised.wav" ) denoise_vocal_audio(input_path, denoised_output_path) # Convert to mono audio mono_output_path = os.path.join( - process_data.process_data_paths.cache_path, process_data.basename + "_mono.wav" + process_data.process_data_paths.cache_folder_path, process_data.basename + "_mono.wav" ) convert_audio_to_mono_wav(denoised_output_path, mono_output_path) # Mute silence sections mute_output_path = os.path.join( - process_data.process_data_paths.cache_path, process_data.basename + "_mute.wav" + process_data.process_data_paths.cache_folder_path, process_data.basename + "_mute.wav" ) mute_no_singing_parts(mono_output_path, mute_output_path) @@ -390,17 +315,17 @@ def run() -> tuple[str, Score, Score]: process_data.process_data_paths.processing_audio_path = mute_output_path # Audio transcription - language = settings.language + process_data.media_info.language = settings.language if not settings.ignore_audio: - transcription_result = transcribe_audio(process_data.process_data_paths.cache_path) - if language is None: - language = transcription_result.detected_language + transcription_result = transcribe_audio(process_data.process_data_paths.cache_folder_path, process_data.process_data_paths.processing_audio_path) + if process_data.media_info.language is None: + process_data.media_info.language = transcription_result.detected_language process_data.transcribed_data = transcription_result.transcribed_data remove_unecessary_punctuations(process_data.transcribed_data) if settings.hyphenation: - hyphen_words = hyphenate_each_word(language, process_data.transcribed_data) + hyphen_words = hyphenate_each_word(process_data.media_info.language, process_data.transcribed_data) if hyphen_words is not None: process_data.transcribed_data = add_hyphen_to_data(process_data.transcribed_data, hyphen_words) @@ -413,47 +338,73 @@ def run() -> tuple[str, Score, Score]: # --corrected_words = correct_words(vosk_speech, lyric) # Create audio chunks + # Fixme if settings.create_audio_chunks: create_audio_chunks( - process_data.process_data_paths.cache_path, + process_data.process_data_paths.cache_folder_path, process_data.transcribed_data, - ultrastar_audio_input_path, + process_data.process_data_paths.audio_output_file_path, ultrastar_class, ) # Pitch the audio - midi_segments, process_data.pitched_data, ultrastar_note_numbers, process_data.transcribed_data = pitch_audio( - process_data.transcribed_data, ultrastar_class, process_data.process_data_paths.cache_path - ) + process_data.pitched_data = pitch_audio(process_data.process_data_paths) + + # Todo: to function + start_times = [] + end_times = [] + words = [] + if not settings.ignore_audio: + + for i, midi_segment in enumerate(process_data.transcribed_data): + start_times.append(midi_segment.start) + end_times.append(midi_segment.end) + words.append(midi_segment.word) + process_data.midi_segments = create_midi_notes_from_pitched_data(start_times, end_times, words, process_data.pitched_data) + # Todo: this is also in converter? + # else: + # for i, note_lines in enumerate(ultrastar_class.UltrastarNoteLines): + # start_times.append(note_lines.startTime) + # end_times.append(note_lines.endTime) + # words.append(note_lines.word) + # midi_segments = create_midi_notes_from_pitched_data(start_times, end_times, words, process_data.pitched_data) + + # fixme: whats that? + new_transcribed_data = [] + for i, midi_segment in enumerate(process_data.midi_segments): + transcribed_midi_data = TranscribedData(word=midi_segment.word, start=midi_segment.start, end=midi_segment.end, is_hyphen= None, confidence= 1) + new_transcribed_data.append(transcribed_midi_data) + process_data.transcribed_data = new_transcribed_data + # ---- # Create plot if settings.create_plot: - vocals_path = os.path.join(audio_separation_path, "vocals.wav") - plot_spectrogram(vocals_path, settings.song_output, "vocals.wav") - plot_spectrogram(process_data.process_data_paths.processing_audio_path, settings.song_output, "processing audio") - plot(process_data.pitched_data, settings.song_output, midi_segments) + plot_spectrogram(process_data.process_data_paths.vocals_audio_file_path, settings.output_folder_path, "vocals.wav") + plot_spectrogram(process_data.process_data_paths.processing_audio_path, settings.output_folder_path, "processing audio") + plot(process_data.pitched_data, settings.output_folder_path, process_data.midi_segments) # Write Ultrastar txt if not settings.ignore_audio: real_bpm, ultrastar_file_output = create_ultrastar_txt_from_automation( process_data.basename, - settings.song_output, - ultrastar_audio_input_path, - ultrastar_note_numbers, - language, # todo: to media_info + settings.output_folder_path, + process_data.transcribed_data, + process_data.process_data_paths.audio_output_file_path, + process_data.midi_segments, process_data.media_info ) else: ultrastar_file_output = create_ultrastar_txt_from_ultrastar_data( - settings.song_output, ultrastar_class, ultrastar_note_numbers + settings.output_folder_path, process_data.media_info.title, process_data.midi_segments ) + # Calc Points + # Todo: UltraStar specific simple_score = None accurate_score = None if settings.calculate_score: - # Calc Points ultrastar_class, simple_score, accurate_score = calculate_score_points( - process_data.pitched_data, ultrastar_class, ultrastar_file_output + process_data, ultrastar_file_output ) # Add calculated score to Ultrastar txt #Todo: Missing Karaoke @@ -461,14 +412,14 @@ def run() -> tuple[str, Score, Score]: # Midi if settings.create_midi: - create_midi_file(real_bpm, settings.song_output, ultrastar_class, process_data.basename) + create_midi_file(process_data.media_info.bpm, settings.output_folder_path, ultrastar_class, process_data.basename) # Sheet music - create_sheet(midi_segments, settings, process_data.basename, process_data.media_info, real_bpm) + create_sheet(process_data.midi_segments, settings, process_data.basename, process_data.media_info, process_data.media_info.bpm) # Cleanup if not settings.keep_cache: - remove_cache_folder(process_data.process_data_paths.cache_path) + remove_cache_folder(process_data.process_data_paths.cache_folder_path) # Print Support print_support() @@ -516,16 +467,16 @@ def get_unused_song_output_dir(path: str) -> str: return path -def transcribe_audio(cache_path: str) -> TranscriptionResult: +def transcribe_audio(cache_folder_path: str, processing_audio_path: str) -> TranscriptionResult: """Transcribe audio with AI""" transcription_result = None if settings.transcriber == "whisper": transcription_config = f"{settings.transcriber}_{settings.whisper_model}_{settings.pytorch_device}_{settings.whisper_align_model}_{settings.whisper_align_model}_{settings.whisper_batch_size}_{settings.whisper_compute_type}_{settings.language}" - transcription_path = os.path.join(cache_path, f"{transcription_config}.json") + transcription_path = os.path.join(cache_folder_path, f"{transcription_config}.json") cached_transcription_available = check_file_exists(transcription_path) if settings.skip_cache_transcription or not cached_transcription_available: transcription_result = transcribe_with_whisper( - process_data.process_data_paths.processing_audio_path, + processing_audio_path, settings.whisper_model, settings.pytorch_device, settings.whisper_align_model, @@ -545,15 +496,13 @@ def transcribe_audio(cache_path: str) -> TranscriptionResult: return transcription_result -def separate_vocal_from_audio( - basename_without_ext: str, cache_path: str, ultrastar_audio_input_path: str -) -> str: +def separate_vocal_from_audio(cache_folder_path: str, ultrastar_audio_input_path: str, processing_audio_path: str) -> str: """Separate vocal from audio""" demucs_output_folder = os.path.splitext( os.path.basename(ultrastar_audio_input_path) )[0] audio_separation_path = os.path.join( - cache_path, "separated", "htdemucs", demucs_output_folder + cache_folder_path, "separated", "htdemucs", demucs_output_folder ) vocals_path = os.path.join(audio_separation_path, "vocals.wav") @@ -564,7 +513,7 @@ def separate_vocal_from_audio( ) if settings.skip_cache_vocal_separation or not cache_available: separate_audio( - ultrastar_audio_input_path, cache_path, settings.pytorch_device + ultrastar_audio_input_path, cache_folder_path, settings.pytorch_device ) else: print(f"{ULTRASINGER_HEAD} {green_highlighted('cache')} reusing cached separated vocals") @@ -574,22 +523,21 @@ def separate_vocal_from_audio( else: input_path = ultrastar_audio_input_path - convert_audio_to_mono_wav(input_path, process_data.process_data_paths.processing_audio_path) + convert_audio_to_mono_wav(input_path, processing_audio_path) return audio_separation_path def calculate_score_points( - pitched_data: PitchedData, - ultrastar_class: UltrastarTxtValue, + processed_data: ProcessData, ultrastar_file_output: str, ): """Calculate score points""" if not settings.ignore_audio: - ultrastar_class = ultrastar_parser.parse_ultrastar_txt(ultrastar_file_output) + ultrastar_txt = ultrastar_parser.parse_ultrastar_txt(ultrastar_file_output) ( simple_score, accurate_score, - ) = ultrastar_score_calculator.calculate_score(pitched_data, ultrastar_class) + ) = ultrastar_score_calculator.calculate_score(processed_data.pitched_data, ultrastar_txt) ultrastar_score_calculator.print_score_calculation(simple_score, accurate_score) else: print( @@ -598,29 +546,31 @@ def calculate_score_points( ( simple_score, accurate_score, - ) = ultrastar_score_calculator.calculate_score(pitched_data, ultrastar_class) + ) = ultrastar_score_calculator.calculate_score(processed_data.pitched_data, processed_data.parsed_file) ultrastar_score_calculator.print_score_calculation(simple_score, accurate_score) print( f"{ULTRASINGER_HEAD} {blue_highlighted('Score of re-pitched Ultrastar txt')}" ) - ultrastar_class = ultrastar_parser.parse_ultrastar_txt(ultrastar_file_output) + ultrastar_txt = ultrastar_parser.parse_ultrastar_txt(ultrastar_file_output) ( simple_score, accurate_score, - ) = ultrastar_score_calculator.calculate_score(pitched_data, ultrastar_class) + ) = ultrastar_score_calculator.calculate_score(processed_data.pitched_data, ultrastar_txt) ultrastar_score_calculator.print_score_calculation(simple_score, accurate_score) - return ultrastar_class, simple_score, accurate_score + return ultrastar_txt, simple_score, accurate_score def create_ultrastar_txt_from_ultrastar_data( song_output: str, - ultrastar_class: UltrastarTxtValue, - ultrastar_note_numbers: list[int], + title: str, + midi_segments: list[MidiSegment], ) -> str: """Create Ultrastar txt from Ultrastar data""" output_repitched_ultrastar = os.path.join( - song_output, ultrastar_class.title + ".txt" + song_output, title + ".txt" ) + ultrastar_note_numbers = convert_midi_notes_to_ultrastar_notes(midi_segments) + ultrastar_writer.create_repitched_txt_from_ultrastar_data( settings.input_file_path, ultrastar_note_numbers, @@ -634,8 +584,7 @@ def create_ultrastar_txt_from_automation( song_output: str, transcribed_data: list[TranscribedData], ultrastar_audio_input_path: str, - ultrastar_note_numbers: list[int], - language: str, + midi_segments: list[MidiSegment], media_info: MediaInfo ): """Create Ultrastar txt from automation""" @@ -646,7 +595,7 @@ def create_ultrastar_txt_from_automation( ultrastar_header.vocals = basename + " [Vocals].mp3" ultrastar_header.instrumental = basename + " [Instrumental].mp3" ultrastar_header.video = basename + ".mp4" - ultrastar_header.language = language + ultrastar_header.language = media_info.language cover = basename + " [CO].jpg" ultrastar_header.cover = ( cover if os_helper.check_file_exists(os.path.join(song_output, cover)) else None @@ -666,6 +615,8 @@ def create_ultrastar_txt_from_automation( if media_info.genre is not None: ultrastar_header.genre = format_separated_string(media_info.genre) + ultrastar_note_numbers = convert_midi_notes_to_ultrastar_notes(midi_segments) + real_bpm = get_bpm_from_file(ultrastar_audio_input_path) # todo: Wrong place ultrastar_file_output = os.path.join(song_output, basename + ".txt") ultrastar_writer.create_ultrastar_txt_from_automation( @@ -742,7 +693,7 @@ def infos_from_audio_input_file() -> tuple[str, str, str, MediaInfo]: extension = os.path.splitext(basename)[1] basename = f"{basename_without_ext}{extension}" - song_output = os.path.join(settings.output_file_path, basename_without_ext) + song_output = os.path.join(settings.output_folder_path, basename_without_ext) song_output = get_unused_song_output_dir(song_output) os_helper.create_folder(song_output) os_helper.copy(settings.input_file_path, song_output) @@ -750,6 +701,7 @@ def infos_from_audio_input_file() -> tuple[str, str, str, MediaInfo]: os.path.join(song_output, os.path.basename(settings.input_file_path)), os.path.join(song_output, basename), ) + # Todo: Read ID3 tags ultrastar_audio_input_path = os.path.join(song_output, basename) return ( basename_without_ext, @@ -787,46 +739,52 @@ def download_from_youtube() -> tuple[str, str, str, MediaInfo]: basename_without_ext = sanitize_filename(f"{artist} - {title}") basename = basename_without_ext + ".mp3" - song_output = os.path.join(settings.output_file_path, basename_without_ext) + song_output = os.path.join(settings.output_folder_path, basename_without_ext) song_output = get_unused_song_output_dir(song_output) os_helper.create_folder(song_output) download_youtube_audio(settings.input_file_path, basename_without_ext, song_output) download_youtube_video(settings.input_file_path, basename_without_ext, song_output) - download_youtube_thumbnail( + thumbnail_url = download_youtube_thumbnail( settings.input_file_path, basename_without_ext, song_output ) - ultrastar_audio_input_path = os.path.join(song_output, basename) + audio_file_path = os.path.join(song_output, basename) return ( basename_without_ext, song_output, - ultrastar_audio_input_path, - MediaInfo(artist=artist, title=title, year=year_info, genre=genre_info), + audio_file_path, + MediaInfo(artist=artist, title=title, year=year_info, genre=genre_info, youtube_thumbnail_url=thumbnail_url), ) -def parse_ultrastar_txt() -> tuple[str, float, str, str, UltrastarTxtValue]: +def parse_ultrastar_txt() -> tuple[str, str, str, UltrastarTxtValue]: """Parse Ultrastar txt""" ultrastar_class = ultrastar_parser.parse_ultrastar_txt(settings.input_file_path) - real_bpm = ultrastar_converter.ultrastar_bpm_to_real_bpm( - float(ultrastar_class.bpm.replace(",", ".")) - ) - ultrastar_mp3_name = ultrastar_class.mp3 - basename_without_ext = f"{ultrastar_class.artist.strip()} - {ultrastar_class.title.strip()}" + if ultrastar_class.mp3: + ultrastar_mp3_name = ultrastar_class.mp3 + elif ultrastar_class.audio: + ultrastar_mp3_name = ultrastar_class.audio + else: + print( + f"{ULTRASINGER_HEAD} {red_highlighted('Error!')} The provided text file does not have a reference to " + f"an audio file." + ) + exit(1) + dirname = os.path.dirname(settings.input_file_path) - ultrastar_audio_input_path = os.path.join(dirname, ultrastar_mp3_name) song_output = os.path.join( - settings.output_file_path, + settings.output_folder_path, ultrastar_class.artist.strip() + " - " + ultrastar_class.title.strip(), ) song_output = get_unused_song_output_dir(str(song_output)) os_helper.create_folder(song_output) + basename_without_ext = f"{ultrastar_class.artist.strip()} - {ultrastar_class.title.strip()}" + audio_file_path = os.path.join(dirname, ultrastar_mp3_name) return ( - str(basename_without_ext), - real_bpm, + basename_without_ext, song_output, - str(ultrastar_audio_input_path), + str(audio_file_path), ultrastar_class, ) @@ -834,35 +792,36 @@ def parse_ultrastar_txt() -> tuple[str, float, str, str, UltrastarTxtValue]: def create_midi_file( real_bpm: float, song_output: str, - ultrastar_class: UltrastarTxtValue, + midi_segments: list[MidiSegment], basename_without_ext: str, ) -> None: """Create midi file""" print(f"{ULTRASINGER_HEAD} Creating Midi with {blue_highlighted('pretty_midi')}") + # voice_instrument = [ + # convert_ultrastar_to_midi_instrument(ultrastar_class) + # ] voice_instrument = [ - convert_ultrastar_to_midi_instrument(ultrastar_class) + create_midi_instrument(midi_segments) ] + midi_output = os.path.join(song_output, f"{basename_without_ext}.mid") - instruments_to_midi(voice_instrument, real_bpm, midi_output, ultrastar_class.UltrastarNoteLines) + instruments_to_midi(voice_instrument, real_bpm, midi_output, midi_segments) def pitch_audio( - transcribed_data: list[TranscribedData], - ultrastar_class: UltrastarTxtValue, - cache_path: str -) -> tuple[list[MidiSegment], PitchedData, list[int], list[TranscribedData]]: + process_data_paths: ProcessDataPaths) -> PitchedData: """Pitch audio""" # todo: chunk pitching as option? # midi_notes = pitch_each_chunk_with_crepe(chunk_folder_name) pitching_config = f"crepe_{settings.ignore_audio}_{settings.crepe_model_capacity}_{settings.crepe_step_size}_{settings.tensorflow_device}" - pitched_data_path = os.path.join(cache_path, f"{pitching_config}.json") + pitched_data_path = os.path.join(process_data_paths.cache_folder_path, f"{pitching_config}.json") cache_available = check_file_exists(pitched_data_path) if settings.skip_cache_transcription or not cache_available: pitched_data = get_pitch_with_crepe_file( - process_data.process_data_paths.processing_audio_path, + process_data_paths.processing_audio_path, settings.crepe_model_capacity, settings.crepe_step_size, settings.tensorflow_device, @@ -877,43 +836,17 @@ def pitch_audio( json = file.read() pitched_data = PitchedData.from_json(json) - start_times = [] - end_times = [] - words = [] - if not settings.ignore_audio: - - for i, midi_segment in enumerate(transcribed_data): - start_times.append(midi_segment.start) - end_times.append(midi_segment.end) - words.append(midi_segment.word) - else: - for i, note_lines in enumerate(ultrastar_class.UltrastarNoteLines): - start_times.append(note_lines.startTime) - end_times.append(note_lines.endTime) - words.append(note_lines.word) - - midi_segments = create_midi_notes_from_pitched_data(start_times, end_times, words, pitched_data) - - # fixme: should be in UltraStar - ultrastar_note_numbers = convert_midi_notes_to_ultrastar_notes(midi_segments) - - # fixme: TrnscribedData in pitch_audio?? - new_transcribed_data = [] - for i, midi_segment in enumerate(midi_segments): - transcribed_midi_data = TranscribedData(word= midi_segment.word, start= midi_segment.start, end= midi_segment.end, is_hyphen= None, confidence= 1) - new_transcribed_data.append(transcribed_midi_data) - - return midi_segments, pitched_data, ultrastar_note_numbers, new_transcribed_data + return pitched_data def create_audio_chunks( - cache_path: str, + cache_folder_path: str, transcribed_data: list[TranscribedData], ultrastar_audio_input_path: str, ultrastar_class: UltrastarTxtValue ) -> None: """Create audio chunks""" - audio_chunks_path = os.path.join(cache_path, settings.audio_chunk_folder_name) + audio_chunks_path = os.path.join(cache_folder_path, settings.audio_chunk_folder_name) os_helper.create_folder(audio_chunks_path) if not settings.ignore_audio: # and csv csv_filename = os.path.join(audio_chunks_path, "_chunks.csv") @@ -934,7 +867,6 @@ def denoise_vocal_audio(input_path: str, output_path: str) -> None: else: print(f"{ULTRASINGER_HEAD} {green_highlighted('cache')} reusing cached denoised audio") - def main(argv: list[str]) -> None: """Main function""" print_version() @@ -942,9 +874,9 @@ def main(argv: list[str]) -> None: run() sys.exit() -def remove_cache_folder(cache_path: str) -> None: +def remove_cache_folder(cache_folder_path: str) -> None: """Remove cache folder""" - os_helper.remove_folder(cache_path) + os_helper.remove_folder(cache_folder_path) def init_settings(argv: list[str]) -> None: """Init settings""" @@ -960,7 +892,7 @@ def init_settings(argv: list[str]) -> None: elif opt in ("-i", "--ifile"): settings.input_file_path = arg elif opt in ("-o", "--ofile"): - settings.output_file_path = arg + settings.output_folder_path = arg elif opt in ("--whisper"): settings.transcriber = "whisper" settings.whisper_model = arg @@ -1009,16 +941,18 @@ def init_settings(argv: list[str]) -> None: settings.keep_cache = arg elif opt in ("--musescore_path"): settings.musescore_path = arg - if settings.output_file_path == "": + if settings.output_folder_path == "": if settings.input_file_path.startswith("https:"): dirname = os.getcwd() else: dirname = os.path.dirname(settings.input_file_path) - settings.output_file_path = os.path.join(dirname, "output") + settings.output_folder_path = os.path.join(dirname, "output") if not settings.force_cpu: settings.tensorflow_device, settings.pytorch_device = check_gpu_support() + return settings + def arg_options(): short = "hi:o:amv:" @@ -1048,6 +982,5 @@ def arg_options(): ] return long, short - if __name__ == "__main__": main(sys.argv[1:]) diff --git a/src/modules/Audio/youtube.py b/src/modules/Audio/youtube.py index 07c1cab..ce79094 100644 --- a/src/modules/Audio/youtube.py +++ b/src/modules/Audio/youtube.py @@ -41,7 +41,7 @@ def download_youtube_audio(url: str, clear_filename: str, output_path: str): start_download(ydl_opts, url) -def download_youtube_thumbnail(url: str, clear_filename: str, output_path: str): +def download_youtube_thumbnail(url: str, clear_filename: str, output_path: str) -> str: """Download thumbnail from YouTube""" print(f"{ULTRASINGER_HEAD} Downloading thumbnail") @@ -50,10 +50,11 @@ def download_youtube_thumbnail(url: str, clear_filename: str, output_path: str): "writethumbnail": True, } - download_and_convert_thumbnail(ydl_opts, url, clear_filename, output_path) + thumbnail_url = download_and_convert_thumbnail(ydl_opts, url, clear_filename, output_path) + return thumbnail_url -def download_and_convert_thumbnail(ydl_opts, url: str, clear_filename: str, output_path: str) -> None: +def download_and_convert_thumbnail(ydl_opts, url: str, clear_filename: str, output_path: str) -> str: """Download and convert thumbnail from YouTube""" with yt_dlp.YoutubeDL(ydl_opts) as ydl: @@ -67,6 +68,9 @@ def download_and_convert_thumbnail(ydl_opts, url: str, clear_filename: str, outp image_path = os.path.join(output_path, clear_filename + " [CO].jpg") image.save(image_path, "JPEG") crop_image_to_square(image_path) + return thumbnail_url + else: + return "" def download_youtube_video(url: str, clear_filename: str, output_path: str) -> None: diff --git a/src/modules/Midi/MidiSegment.py b/src/modules/Midi/MidiSegment.py new file mode 100644 index 0000000..44f2a39 --- /dev/null +++ b/src/modules/Midi/MidiSegment.py @@ -0,0 +1,9 @@ +from dataclasses import dataclass + + +@dataclass +class MidiSegment: + note: str + start: float + end: float + word: str diff --git a/src/modules/Midi/midi_creator.py b/src/modules/Midi/midi_creator.py index 7a81350..263e3c4 100644 --- a/src/modules/Midi/midi_creator.py +++ b/src/modules/Midi/midi_creator.py @@ -6,8 +6,8 @@ from collections import Counter import librosa import numpy as np import pretty_midi -from dataclasses import dataclass +from modules.Midi.MidiSegment import MidiSegment from modules.Pitcher.pitcher import get_frequencies_with_high_confidence from modules.Ultrastar.ultrastar_converter import ( midi_note_to_ultrastar_note, @@ -20,6 +20,21 @@ from modules.Ultrastar.ultrastar_txt import UltrastarTxtValue, UltrastarNoteLine from modules.Pitcher.pitched_data import PitchedData +def create_midi_instrument(midi_segments: list[MidiSegment]) -> object: + """Converts an Ultrastar data to a midi instrument""" + + print(f"{ULTRASINGER_HEAD} Creating midi instrument") + + instrument = pretty_midi.Instrument(program=0, name="Vocals") + velocity = 100 + + for i, midi_segment in enumerate(midi_segments): + note = pretty_midi.Note(velocity, midi_segment.note, midi_segment.start, midi_segment.end) + instrument.notes.append(note) + + return instrument + +# Todo: delete? def convert_ultrastar_to_midi_instrument(ultrastar_class: UltrastarTxtValue) -> object: """Converts an Ultrastar data to a midi instrument""" @@ -35,14 +50,14 @@ def convert_ultrastar_to_midi_instrument(ultrastar_class: UltrastarTxtValue) -> return instrument -def instruments_to_midi(instruments: list[object], bpm: float, midi_output: str, ultrastar_note_line: UltrastarNoteLine) -> None: +def instruments_to_midi(instruments: list[object], bpm: float, midi_output: str, midi_segments: list[MidiSegment]) -> None: """Write instruments to midi file""" print(f"{ULTRASINGER_HEAD} Creating midi file -> {midi_output}") midi_data = pretty_midi.PrettyMIDI(initial_tempo=bpm) - for i, note_line in enumerate(ultrastar_note_line): - midi_data.lyrics.append(pretty_midi.Lyric(text=note_line.word, time=note_line.startTime)) + for i, midi_segment in enumerate(midi_segments): + midi_data.lyrics.append(pretty_midi.Lyric(text=midi_segment.word, time=midi_segment.start)) for instrument in instruments: midi_data.instruments.append(instrument) midi_data.write(midi_output) @@ -77,15 +92,8 @@ def find_nearest_index(array: list[float], value: float) -> int: return idx -@dataclass -class MidiSegment: - note: str - start: float - end: float - word: str - - -def create_midi_notes_from_pitched_data(start_times: list[float], end_times: list[float], words: list[str], pitched_data: PitchedData) -> list[MidiSegment]: +def create_midi_notes_from_pitched_data(start_times: list[float], end_times: list[float], words: list[str], pitched_data: PitchedData) -> list[ + MidiSegment]: """Create midi notes from pitched data""" print(f"{ULTRASINGER_HEAD} Creating midi notes from pitched data") diff --git a/src/modules/ProcessData.py b/src/modules/ProcessData.py index f81d3c8..0d893f4 100644 --- a/src/modules/ProcessData.py +++ b/src/modules/ProcessData.py @@ -1,15 +1,19 @@ from dataclasses import dataclass, field from modules.Speech_Recognition.TranscribedData import TranscribedData from modules.Pitcher.pitched_data import PitchedData +from modules.Ultrastar.ultrastar_txt import UltrastarTxtValue +from modules.Ultrastar import ultrastar_converter +from modules.Midi.MidiSegment import MidiSegment from typing import Optional, List @dataclass class ProcessDataPaths: # Process data Paths processing_audio_path: Optional[str] = "" - cache_path: Optional[str] = "" - song_output: Optional[str] = "" - # ultrastar_audio_input_path: Optional[str] = "" + cache_folder_path: Optional[str] = "" + audio_output_file_path: Optional[str] = "" # Output audio file path + vocals_audio_file_path: Optional[str] = "" # Separated vocals audio file path + instrumental_audio_file_path: Optional[str] = "" # Separated instrumental audio file path @dataclass class MediaInfo: @@ -20,6 +24,7 @@ class MediaInfo: year: Optional[str] = None genre: Optional[str] = None language: Optional[str] = None + youtube_thumbnail_url: Optional[str] = None @dataclass class ProcessData: @@ -29,3 +34,22 @@ class ProcessData: media_info: Optional[MediaInfo] = None transcribed_data: Optional[List[TranscribedData]] = field(default_factory=list) pitched_data: Optional[PitchedData] = None + midi_segments: Optional[List[MidiSegment]] = field(default_factory=list) + parsed_file: Optional[UltrastarTxtValue] = None + + +def from_ultrastar_txt(ultrastar_txt: UltrastarTxtValue) -> ProcessData: + """Converts an Ultrastar txt to ProcessData""" + process_data = ProcessData() + process_data.parsed_file = ultrastar_txt + process_data.media_info = MediaInfo( + title=ultrastar_txt.title, + artist=ultrastar_txt.artist, + year=ultrastar_txt.year, + genre=ultrastar_txt.genre, + language=ultrastar_txt.language + ) + process_data.media_info.bpm = ultrastar_converter.ultrastar_bpm_to_real_bpm(float(ultrastar_txt.bpm.replace(",", "."))) + process_data.midi_segments = ultrastar_converter.ultrastar_to_midi_segments(ultrastar_txt) + + return process_data diff --git a/src/modules/Ultrastar/ultrastar_converter.py b/src/modules/Ultrastar/ultrastar_converter.py index 4912aed..87b59e1 100644 --- a/src/modules/Ultrastar/ultrastar_converter.py +++ b/src/modules/Ultrastar/ultrastar_converter.py @@ -1,7 +1,7 @@ """Ultrastar Converter""" - +import librosa from modules.Ultrastar.ultrastar_txt import UltrastarTxtValue - +from modules.Midi.MidiSegment import MidiSegment def real_bpm_to_ultrastar_bpm(real_bpm: float) -> float: """Converts real BPM to UltraStar BPM""" # The UltraStar BPM info is a fourth beat of the real BPM @@ -81,4 +81,19 @@ def get_end_time(gap: str, ultrastar_bpm: str, startBeat: float, duration: float ) + gap ) - return end_time \ No newline at end of file + return end_time + +def ultrastar_to_midi_segments(ultrastar_txt: UltrastarTxtValue) -> list[MidiSegment]: + """Converts an Ultrastar txt to Midi segments""" + midi_segments = [] + for i, data in enumerate(ultrastar_txt.UltrastarNoteLines): + start_time = get_start_time_from_ultrastar(ultrastar_txt, i) + end_time = get_end_time_from_ultrastar(ultrastar_txt, i) + midi_segments.append( + MidiSegment(librosa.midi_to_note(ultrastar_note_to_midi_note(data.pitch)), + start_time, + end_time, + data.word, + ) + ) + return midi_segments \ No newline at end of file diff --git a/src/modules/help_print.py b/src/modules/help_print.py new file mode 100644 index 0000000..498b581 --- /dev/null +++ b/src/modules/help_print.py @@ -0,0 +1,75 @@ +from modules.console_colors import ULTRASINGER_HEAD, gold_highlighted, light_blue_highlighted + + +def print_help() -> None: + """Print help text""" + help_string = """ + UltraSinger.py [opt] [mode] [transcription] [pitcher] [extra] + + [opt] + -h This help text. + -i Ultrastar.txt + audio like .mp3, .wav, youtube link + -o Output folder + + [mode] + ## INPUT is audio ## + default Creates all + + # Single file creation selection is in progress, you currently getting all! + (-u Create ultrastar txt file) # In Progress + (-m Create midi file) # In Progress + (-s Create sheet file) # In Progress + + ## INPUT is ultrastar.txt ## + default Creates all + + # Single selection is in progress, you currently getting all! + (-r repitch Ultrastar.txt (input has to be audio)) # In Progress + (-p Check pitch of Ultrastar.txt input) # In Progress + (-m Create midi file) # In Progress + + [transcription] + # Default is whisper + --whisper Multilingual model > tiny|base|small|medium|large-v1|large-v2 >> ((default) is large-v2 + English-only model > tiny.en|base.en|small.en|medium.en + --whisper_align_model Use other languages model for Whisper provided from huggingface.co + --language Override the language detected by whisper, does not affect transcription but steps after transcription + --whisper_batch_size Reduce if low on GPU mem >> ((default) is 16) + --whisper_compute_type Change to "int8" if low on GPU mem (may reduce accuracy) >> ((default) is "float16" for cuda devices, "int8" for cpu) + + [pitcher] + # Default is crepe + --crepe tiny|full >> ((default) is full) + --crepe_step_size unit is miliseconds >> ((default) is 10) + + [extra] + --hyphenation True|False >> ((default) is True) + --disable_separation True|False >> ((default) is False) + --disable_karaoke True|False >> ((default) is False) + --create_audio_chunks True|False >> ((default) is False) + --keep_cache True|False >> ((default) is False) + --plot True|False >> ((default) is False) + --format_version 0.3.0|1.0.0|1.1.0 >> ((default) is 1.0.0) + --musescore_path path to MuseScore executable + + [device] + --force_cpu True|False >> ((default) is False) All steps will be forced to cpu + --force_whisper_cpu True|False >> ((default) is False) Only whisper will be forced to cpu + --force_crepe_cpu True|False >> ((default) is False) Only crepe will be forced to cpu + """ + print(help_string) + + +def print_support() -> None: + """Print support text""" + print() + print( + f"{ULTRASINGER_HEAD} {gold_highlighted('Do you like UltraSinger? Want it to be even better? Then help with your')} {light_blue_highlighted('support')}{gold_highlighted('!')}" + ) + print( + f"{ULTRASINGER_HEAD} See project page -> https://github.com/rakuri255/UltraSinger" + ) + print( + f"{ULTRASINGER_HEAD} {gold_highlighted('This will help a lot to keep this project alive and improved.')}" + ) diff --git a/src/modules/plot.py b/src/modules/plot.py index 49f63fa..d278a68 100644 --- a/src/modules/plot.py +++ b/src/modules/plot.py @@ -13,7 +13,7 @@ from modules.console_colors import ULTRASINGER_HEAD from modules.Pitcher.pitched_data import PitchedData from modules.Pitcher.pitcher import get_pitched_data_with_high_confidence from modules.Speech_Recognition.TranscribedData import TranscribedData -from modules.Midi.midi_creator import MidiSegment +from modules.Midi.MidiSegment import MidiSegment @dataclass diff --git a/src/modules/sheet.py b/src/modules/sheet.py index 1e65b92..589ae42 100644 --- a/src/modules/sheet.py +++ b/src/modules/sheet.py @@ -2,7 +2,7 @@ import os.path import re from music21 import stream, note, duration, environment, metadata, tempo -from modules.Midi.midi_creator import MidiSegment +from modules.Midi.MidiSegment import MidiSegment from modules.console_colors import ULTRASINGER_HEAD, red_highlighted, blue_highlighted from modules.os_helper import move from modules.ProcessData import MediaInfo @@ -15,7 +15,7 @@ def add_metadata_to_stream(stream, artist: str, title: str, bpm: int): stream.insert(0, metronome_mark) -def add_midi_segments_to_stream(stream, midi_segments: MidiSegment): +def add_midi_segments_to_stream(stream, midi_segments: list[MidiSegment]): for segment in midi_segments: # Convert the note name to a music21 note m21_note = note.Note(replace_unsupported_accidentals(segment.note)) @@ -31,7 +31,7 @@ def add_midi_segments_to_stream(stream, midi_segments: MidiSegment): stream.append(m21_note) -def create_sheet(midi_segments: MidiSegment, +def create_sheet(midi_segments: list[MidiSegment], settings, filename: str, media_info: MediaInfo,