mirror of
https://github.com/rakuri255/UltraSinger.git
synced 2026-11-30 09:13:57 +09:00
Use black to format code.
This commit is contained in:
1 parent
60b7fec9e7
commit
dbd60d0172
22 files changed
+585
-299
No files matched your search
+12
-11
@@ -6,25 +6,26 @@ class Settings:
|
||||
use_separated_vocal = True
|
||||
create_karaoke = True
|
||||
|
||||
input_file_path = ''
|
||||
output_file_path = ''
|
||||
mono_audio_path = ''
|
||||
input_file_path = ""
|
||||
output_file_path = ""
|
||||
mono_audio_path = ""
|
||||
|
||||
# Transcribe
|
||||
audio_chunk_folder_name = 'audio-chunks'
|
||||
audio_chunk_folder_name = "audio-chunks"
|
||||
|
||||
# Whisper
|
||||
transcriber = 'whisper' # whisper|vosk
|
||||
whisper_model = 'large-v2' # Multilingual model tiny|base|small|medium|large-v1|large-v2
|
||||
# English-only model tiny.en|base.en|small.en|medium.en
|
||||
transcriber = "whisper" # whisper|vosk
|
||||
whisper_model = (
|
||||
"large-v2" # Multilingual model tiny|base|small|medium|large-v1|large-v2
|
||||
)
|
||||
# English-only model tiny.en|base.en|small.en|medium.en
|
||||
|
||||
# Vosk
|
||||
vosk_model_path = '' # "models/vosk-model-small-en-us-0.15"
|
||||
vosk_model_path = "" # "models/vosk-model-small-en-us-0.15"
|
||||
|
||||
# Pitch
|
||||
crepe_model_capacity = 'full' # tiny|small|medium|large|full
|
||||
crepe_model_capacity = "full" # tiny|small|medium|large|full
|
||||
crepe_step_size = 10
|
||||
|
||||
# Device
|
||||
device = 'cpu' # cpu|cuda|gpu
|
||||
|
||||
device = "cpu" # cpu|cuda|gpu
|
||||
+273
-111
@@ -12,31 +12,47 @@ from tqdm import tqdm
|
||||
from moduls import os_helper
|
||||
from moduls.Audio.denoise import ffmpeg_reduce_noise
|
||||
from moduls.Audio.separation import separate_audio
|
||||
from moduls.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 moduls.Audio.youtube import (download_youtube_audio,
|
||||
download_youtube_thumbnail,
|
||||
download_youtube_video, get_youtube_title)
|
||||
from moduls.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 moduls.Audio.youtube import (
|
||||
download_youtube_audio,
|
||||
download_youtube_thumbnail,
|
||||
download_youtube_video,
|
||||
get_youtube_title,
|
||||
)
|
||||
from moduls.DeviceDetection.device_detection import get_available_device
|
||||
from moduls.Log import (PRINT_ULTRASTAR, print_blue_highlighted_text,
|
||||
print_gold_highlighted_text,
|
||||
print_light_blue_highlighted_text,
|
||||
print_red_highlighted_text)
|
||||
from moduls.Log import (
|
||||
PRINT_ULTRASTAR,
|
||||
print_blue_highlighted_text,
|
||||
print_gold_highlighted_text,
|
||||
print_light_blue_highlighted_text,
|
||||
print_red_highlighted_text,
|
||||
)
|
||||
from moduls.Midi import midi_creator
|
||||
from moduls.Midi.midi_creator import (convert_frequencies_to_notes,
|
||||
create_midi_notes_from_pitched_data,
|
||||
most_frequent)
|
||||
from moduls.Pitcher.pitcher import (get_frequency_with_high_confidence,
|
||||
get_pitch_with_crepe_file)
|
||||
from moduls.Midi.midi_creator import (
|
||||
convert_frequencies_to_notes,
|
||||
create_midi_notes_from_pitched_data,
|
||||
most_frequent,
|
||||
)
|
||||
from moduls.Pitcher.pitcher import (
|
||||
get_frequency_with_high_confidence,
|
||||
get_pitch_with_crepe_file,
|
||||
)
|
||||
from moduls.Speech_Recognition.hyphenation import hyphenation, language_check
|
||||
from moduls.Speech_Recognition.Vosk import transcribe_with_vosk
|
||||
from moduls.Speech_Recognition.Whisper import transcribe_with_whisper
|
||||
from moduls.Ultrastar import (ultrastar_converter, ultrastar_parser,
|
||||
ultrastar_score_calculator, ultrastar_writer)
|
||||
from moduls.Ultrastar import (
|
||||
ultrastar_converter,
|
||||
ultrastar_parser,
|
||||
ultrastar_score_calculator,
|
||||
ultrastar_writer,
|
||||
)
|
||||
from moduls.Ultrastar.ultrastar_txt import UltrastarTxt
|
||||
from Settings import Settings
|
||||
|
||||
@@ -70,15 +86,23 @@ def convert_ultrastar_note_numbers(midi_notes):
|
||||
|
||||
|
||||
def pitch_each_chunk_with_crepe(directory):
|
||||
print(f"{PRINT_ULTRASTAR} Pitching each chunk with {print_blue_highlighted_text('crepe')}")
|
||||
print(
|
||||
f"{PRINT_ULTRASTAR} Pitching each chunk with {print_blue_highlighted_text('crepe')}"
|
||||
)
|
||||
|
||||
midi_notes = []
|
||||
for filename in sorted([f for f in os.listdir(directory) if f.endswith('.wav')],
|
||||
key=lambda x: int(x.split("_")[1])):
|
||||
for filename in sorted(
|
||||
[f for f in os.listdir(directory) if f.endswith(".wav")],
|
||||
key=lambda x: int(x.split("_")[1]),
|
||||
):
|
||||
filepath = os.path.join(directory, filename)
|
||||
# todo: stepsize = duration? then when shorter than "it" it should take the duration. Otherwise there a more notes
|
||||
pitched_data = get_pitch_with_crepe_file(filepath, settings.crepe_step_size, settings.crepe_model_capacity)
|
||||
conf_f = get_frequency_with_high_confidence(pitched_data.frequencies, pitched_data.confidence)
|
||||
pitched_data = get_pitch_with_crepe_file(
|
||||
filepath, settings.crepe_step_size, settings.crepe_model_capacity
|
||||
)
|
||||
conf_f = get_frequency_with_high_confidence(
|
||||
pitched_data.frequencies, pitched_data.confidence
|
||||
)
|
||||
|
||||
notes = convert_frequencies_to_notes(conf_f)
|
||||
note = most_frequent(notes)[0][0]
|
||||
@@ -104,7 +128,9 @@ def add_hyphen_to_data(transcribed_data, hyphen_words):
|
||||
for j in range(len(hyphen_words[i])):
|
||||
dup = copy.copy(transcribed_data[i])
|
||||
dup.start = next_start
|
||||
next_start = transcribed_data[i].end - chunk_duration * (len(hyphen_words[i]) - 1 - j)
|
||||
next_start = transcribed_data[i].end - chunk_duration * (
|
||||
len(hyphen_words[i]) - 1 - j
|
||||
)
|
||||
dup.end = next_start
|
||||
dup.word = hyphen_words[i][j]
|
||||
dup.is_hyphen = True
|
||||
@@ -117,7 +143,9 @@ def get_bpm_from_data(data, sr):
|
||||
onset_env = librosa.onset.onset_strength(y=data, sr=sr)
|
||||
wav_tempo = librosa.beat.tempo(onset_envelope=onset_env, sr=sr)
|
||||
|
||||
print(f"{PRINT_ULTRASTAR} BPM is {print_blue_highlighted_text(str(round(wav_tempo[0], 2)))}")
|
||||
print(
|
||||
f"{PRINT_ULTRASTAR} BPM is {print_blue_highlighted_text(str(round(wav_tempo[0], 2)))}"
|
||||
)
|
||||
return wav_tempo[0]
|
||||
|
||||
|
||||
@@ -127,7 +155,7 @@ def get_bpm_from_file(wav_file):
|
||||
|
||||
|
||||
def correct_words(recognized_words, word_list_file):
|
||||
with open(word_list_file, 'r') as f:
|
||||
with open(word_list_file, "r") as f:
|
||||
text = f.read()
|
||||
word_list = text.split()
|
||||
|
||||
@@ -135,14 +163,16 @@ def correct_words(recognized_words, word_list_file):
|
||||
if rec_word.word in word_list:
|
||||
continue
|
||||
else:
|
||||
closest_word = min(word_list, key=lambda x: Levenshtein.distance(rec_word.word, x))
|
||||
closest_word = min(
|
||||
word_list, key=lambda x: Levenshtein.distance(rec_word.word, x)
|
||||
)
|
||||
print(recognized_words[i].word + " - " + closest_word)
|
||||
recognized_words[i].word = closest_word
|
||||
return recognized_words
|
||||
|
||||
|
||||
def print_help():
|
||||
m = '''
|
||||
m = """
|
||||
UltraSinger.py [opt] [mode] [transcription] [pitcher] [extra]
|
||||
|
||||
[opt]
|
||||
@@ -178,12 +208,14 @@ def print_help():
|
||||
|
||||
[pitcher]
|
||||
--crepe (default) tiny|small|medium|large|full
|
||||
'''
|
||||
"""
|
||||
print(m)
|
||||
|
||||
|
||||
def plot(input_file, vosk_transcribed_data, midi_notes):
|
||||
pitched_data = get_pitch_with_crepe_file(input_file, settings.crepe_step_size, settings.crepe_model_capacity)
|
||||
pitched_data = get_pitch_with_crepe_file(
|
||||
input_file, settings.crepe_step_size, settings.crepe_model_capacity
|
||||
)
|
||||
t, f, c = get_confidence(pitched_data, 0.4)
|
||||
|
||||
plt.ylim(0, 600)
|
||||
@@ -193,24 +225,33 @@ def plot(input_file, vosk_transcribed_data, midi_notes):
|
||||
|
||||
for i in range(len(vosk_transcribed_data)):
|
||||
nf = librosa.note_to_hz(midi_notes[i])
|
||||
plt.plot([vosk_transcribed_data[i].start, vosk_transcribed_data[i].end], [nf, nf], linewidth=1, alpha=0.5)
|
||||
plt.plot(
|
||||
[vosk_transcribed_data[i].start, vosk_transcribed_data[i].end],
|
||||
[nf, nf],
|
||||
linewidth=1,
|
||||
alpha=0.5,
|
||||
)
|
||||
plt.savefig(os.path.join("test", "pit.png"), dpi=2000)
|
||||
|
||||
|
||||
def remove_unecessary_punctuations(transcribed_data):
|
||||
punctuation = ".,"
|
||||
for i in range(len(transcribed_data)):
|
||||
transcribed_data[i].word = transcribed_data[i].word.translate({ord(i): None for i in punctuation})
|
||||
transcribed_data[i].word = transcribed_data[i].word.translate(
|
||||
{ord(i): None for i in punctuation}
|
||||
)
|
||||
|
||||
|
||||
def hyphenate_each_word(language, transcribed_data):
|
||||
hyphenated_word = []
|
||||
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?')}")
|
||||
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?')}"
|
||||
)
|
||||
return None
|
||||
|
||||
sleep(.1)
|
||||
sleep(0.1)
|
||||
for i in tqdm(range(len(transcribed_data))):
|
||||
hyphenated_word.append(hyphenation(transcribed_data[i].word, lang_region))
|
||||
return hyphenated_word
|
||||
@@ -218,9 +259,15 @@ def hyphenate_each_word(language, transcribed_data):
|
||||
|
||||
def print_support():
|
||||
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('!')}")
|
||||
print(f"{PRINT_ULTRASTAR} 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.')}")
|
||||
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('!')}"
|
||||
)
|
||||
print(
|
||||
f"{PRINT_ULTRASTAR} 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.')}"
|
||||
)
|
||||
|
||||
|
||||
def run():
|
||||
@@ -230,20 +277,36 @@ def run():
|
||||
|
||||
if not isAudio: # Parse Ultrastar txt
|
||||
print(f"{PRINT_ULTRASTAR} {print_gold_highlighted_text('re-pitch mode')}")
|
||||
basename_without_ext, real_bpm, song_output, ultrastar_audio_input_path, ultrastar_class = parse_ultrastar_txt()
|
||||
elif settings.input_file_path.startswith('https:'): # Youtube
|
||||
(
|
||||
basename_without_ext,
|
||||
real_bpm,
|
||||
song_output,
|
||||
ultrastar_audio_input_path,
|
||||
ultrastar_class,
|
||||
) = parse_ultrastar_txt()
|
||||
elif settings.input_file_path.startswith("https:"): # Youtube
|
||||
print(f"{PRINT_ULTRASTAR} {print_gold_highlighted_text('full automatic mode')}")
|
||||
basename_without_ext, song_output, ultrastar_audio_input_path = download_from_youtube()
|
||||
(
|
||||
basename_without_ext,
|
||||
song_output,
|
||||
ultrastar_audio_input_path,
|
||||
) = download_from_youtube()
|
||||
else: # Audio File
|
||||
print(f"{PRINT_ULTRASTAR} {print_gold_highlighted_text('full automatic mode')}")
|
||||
basename_without_ext, song_output, ultrastar_audio_input_path = setup_audio_input_file()
|
||||
(
|
||||
basename_without_ext,
|
||||
song_output,
|
||||
ultrastar_audio_input_path,
|
||||
) = setup_audio_input_file()
|
||||
|
||||
cache_path = os.path.join(song_output, 'cache')
|
||||
settings.mono_audio_path = os.path.join(cache_path, basename_without_ext + '.wav')
|
||||
cache_path = os.path.join(song_output, "cache")
|
||||
settings.mono_audio_path = os.path.join(cache_path, basename_without_ext + ".wav")
|
||||
os_helper.create_folder(cache_path)
|
||||
|
||||
# Separate vocal from audio
|
||||
audio_separation_path = separate_vocal_from_audio(basename_without_ext, cache_path, ultrastar_audio_input_path)
|
||||
audio_separation_path = separate_vocal_from_audio(
|
||||
basename_without_ext, cache_path, ultrastar_audio_input_path
|
||||
)
|
||||
|
||||
# Denoise vocal audio
|
||||
denoise_vocal_audio(basename_without_ext, cache_path)
|
||||
@@ -254,7 +317,9 @@ def run():
|
||||
if isAudio:
|
||||
language, transcribed_data = transcribe_audio(transcribed_data)
|
||||
remove_unecessary_punctuations(transcribed_data)
|
||||
transcribed_data = remove_silence_from_transcribtion_data(settings.mono_audio_path, transcribed_data)
|
||||
transcribed_data = remove_silence_from_transcribtion_data(
|
||||
settings.mono_audio_path, transcribed_data
|
||||
)
|
||||
|
||||
if settings.hyphenation:
|
||||
hyphen_words = hyphenate_each_word(language, transcribed_data)
|
||||
@@ -267,10 +332,18 @@ def run():
|
||||
|
||||
# Create audio chunks
|
||||
if settings.create_audio_chunks:
|
||||
create_audio_chunks(cache_path, isAudio, transcribed_data, ultrastar_audio_input_path, ultrastar_class)
|
||||
create_audio_chunks(
|
||||
cache_path,
|
||||
isAudio,
|
||||
transcribed_data,
|
||||
ultrastar_audio_input_path,
|
||||
ultrastar_class,
|
||||
)
|
||||
|
||||
# Pitch the audio
|
||||
midi_notes, pitched_data, ultrastar_note_numbers = pitch_audio(isAudio, transcribed_data, ultrastar_class)
|
||||
midi_notes, pitched_data, ultrastar_note_numbers = pitch_audio(
|
||||
isAudio, transcribed_data, ultrastar_class
|
||||
)
|
||||
|
||||
# Create plot
|
||||
if isAudio and settings.create_plot:
|
||||
@@ -278,17 +351,24 @@ def run():
|
||||
|
||||
# Write Ultrastar txt
|
||||
if isAudio:
|
||||
real_bpm, ultrastar_file_output = create_ultrastar_txt_from_automation(audio_separation_path,
|
||||
basename_without_ext,
|
||||
song_output, transcribed_data,
|
||||
ultrastar_audio_input_path,
|
||||
ultrastar_note_numbers, language)
|
||||
real_bpm, ultrastar_file_output = create_ultrastar_txt_from_automation(
|
||||
audio_separation_path,
|
||||
basename_without_ext,
|
||||
song_output,
|
||||
transcribed_data,
|
||||
ultrastar_audio_input_path,
|
||||
ultrastar_note_numbers,
|
||||
language,
|
||||
)
|
||||
else:
|
||||
ultrastar_file_output = create_ultrastar_txt_from_ultrastar_data(song_output, ultrastar_class,
|
||||
ultrastar_note_numbers)
|
||||
ultrastar_file_output = create_ultrastar_txt_from_ultrastar_data(
|
||||
song_output, ultrastar_class, ultrastar_note_numbers
|
||||
)
|
||||
|
||||
# Calc Points
|
||||
ultrastar_class, simple_score, accurate_score = calculate_score_points(isAudio, pitched_data, ultrastar_class, ultrastar_file_output)
|
||||
ultrastar_class, simple_score, accurate_score = calculate_score_points(
|
||||
isAudio, pitched_data, ultrastar_class, ultrastar_file_output
|
||||
)
|
||||
|
||||
# Add calculated score to Ultrastar txt
|
||||
ultrastar_writer.add_score_to_ultrastar_txt(ultrastar_file_output, simple_score)
|
||||
@@ -313,24 +393,33 @@ def get_unused_song_output_dir(path):
|
||||
path = path.replace(f"({i - 1})", f"({i})")
|
||||
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.')}")
|
||||
print(
|
||||
f"{PRINT_ULTRASTAR} {print_red_highlighted_text('Error: Could not create output folder! (999) is the maximum number of tries.')}"
|
||||
)
|
||||
sys.exit(1)
|
||||
return path
|
||||
|
||||
|
||||
def transcribe_audio(transcribed_data):
|
||||
if settings.transcriber == "whisper":
|
||||
transcribed_data, language = transcribe_with_whisper(settings.mono_audio_path, settings.whisper_model,
|
||||
settings.device)
|
||||
transcribed_data, language = transcribe_with_whisper(
|
||||
settings.mono_audio_path, settings.whisper_model, settings.device
|
||||
)
|
||||
else: # vosk
|
||||
transcribed_data = transcribe_with_vosk(settings.mono_audio_path, settings.vosk_model_path)
|
||||
transcribed_data = transcribe_with_vosk(
|
||||
settings.mono_audio_path, settings.vosk_model_path
|
||||
)
|
||||
# todo: make language selectable
|
||||
language = 'en'
|
||||
language = "en"
|
||||
return language, transcribed_data
|
||||
|
||||
|
||||
def separate_vocal_from_audio(basename_without_ext, cache_path, ultrastar_audio_input_path):
|
||||
audio_separation_path = os.path.join(cache_path, "separated", "htdemucs", basename_without_ext)
|
||||
def separate_vocal_from_audio(
|
||||
basename_without_ext, cache_path, ultrastar_audio_input_path
|
||||
):
|
||||
audio_separation_path = os.path.join(
|
||||
cache_path, "separated", "htdemucs", basename_without_ext
|
||||
)
|
||||
if settings.use_separated_vocal or settings.create_karaoke:
|
||||
separate_audio(ultrastar_audio_input_path, cache_path)
|
||||
if settings.use_separated_vocal:
|
||||
@@ -341,32 +430,55 @@ def separate_vocal_from_audio(basename_without_ext, cache_path, ultrastar_audio_
|
||||
return audio_separation_path
|
||||
|
||||
|
||||
def calculate_score_points(isAudio, pitched_data, ultrastar_class, ultrastar_file_output):
|
||||
def calculate_score_points(
|
||||
isAudio, pitched_data, ultrastar_class, ultrastar_file_output
|
||||
):
|
||||
if isAudio:
|
||||
ultrastar_class = ultrastar_parser.parse_ultrastar_txt(ultrastar_file_output)
|
||||
simple_score, accurate_score = ultrastar_score_calculator.calculate_score(pitched_data, ultrastar_class)
|
||||
simple_score, accurate_score = ultrastar_score_calculator.calculate_score(
|
||||
pitched_data, ultrastar_class
|
||||
)
|
||||
ultrastar_score_calculator.print_score_calculation(simple_score, accurate_score)
|
||||
else:
|
||||
print(f"{PRINT_ULTRASTAR} {print_blue_highlighted_text('Score of original Ultrastar txt')}")
|
||||
simple_score, accurate_score = ultrastar_score_calculator.calculate_score(pitched_data, ultrastar_class)
|
||||
print(
|
||||
f"{PRINT_ULTRASTAR} {print_blue_highlighted_text('Score of original Ultrastar txt')}"
|
||||
)
|
||||
simple_score, accurate_score = ultrastar_score_calculator.calculate_score(
|
||||
pitched_data, ultrastar_class
|
||||
)
|
||||
ultrastar_score_calculator.print_score_calculation(simple_score, accurate_score)
|
||||
print(f"{PRINT_ULTRASTAR} {print_blue_highlighted_text('Score of re-pitched Ultrastar txt')}")
|
||||
print(
|
||||
f"{PRINT_ULTRASTAR} {print_blue_highlighted_text('Score of re-pitched Ultrastar txt')}"
|
||||
)
|
||||
ultrastar_class = ultrastar_parser.parse_ultrastar_txt(ultrastar_file_output)
|
||||
simple_score, accurate_score = ultrastar_score_calculator.calculate_score(pitched_data, ultrastar_class)
|
||||
simple_score, accurate_score = ultrastar_score_calculator.calculate_score(
|
||||
pitched_data, ultrastar_class
|
||||
)
|
||||
ultrastar_score_calculator.print_score_calculation(simple_score, accurate_score)
|
||||
return ultrastar_class, simple_score, accurate_score
|
||||
|
||||
|
||||
def create_ultrastar_txt_from_ultrastar_data(song_output, ultrastar_class, ultrastar_note_numbers):
|
||||
output_repitched_ultrastar = os.path.join(song_output, ultrastar_class.title + '.txt')
|
||||
ultrastar_writer.create_repitched_txt_from_ultrastar_data(settings.input_file_path, ultrastar_note_numbers,
|
||||
output_repitched_ultrastar)
|
||||
def create_ultrastar_txt_from_ultrastar_data(
|
||||
song_output, ultrastar_class, ultrastar_note_numbers
|
||||
):
|
||||
output_repitched_ultrastar = os.path.join(
|
||||
song_output, ultrastar_class.title + ".txt"
|
||||
)
|
||||
ultrastar_writer.create_repitched_txt_from_ultrastar_data(
|
||||
settings.input_file_path, ultrastar_note_numbers, output_repitched_ultrastar
|
||||
)
|
||||
return output_repitched_ultrastar
|
||||
|
||||
|
||||
def create_ultrastar_txt_from_automation(audio_separation_path, basename_without_ext, song_output,
|
||||
transcribed_data, ultrastar_audio_input_path, ultrastar_note_numbers,
|
||||
language):
|
||||
def create_ultrastar_txt_from_automation(
|
||||
audio_separation_path,
|
||||
basename_without_ext,
|
||||
song_output,
|
||||
transcribed_data,
|
||||
ultrastar_audio_input_path,
|
||||
ultrastar_note_numbers,
|
||||
language,
|
||||
):
|
||||
ultrastar_header = UltrastarTxt()
|
||||
ultrastar_header.title = basename_without_ext
|
||||
ultrastar_header.artist = basename_without_ext
|
||||
@@ -374,13 +486,19 @@ def create_ultrastar_txt_from_automation(audio_separation_path, basename_without
|
||||
ultrastar_header.video = basename_without_ext + ".mp4"
|
||||
ultrastar_header.language = language
|
||||
cover = basename_without_ext + " [CO].jpg"
|
||||
ultrastar_header.cover = cover if os_helper.check_file_exists(os.path.join(song_output, cover)) else None
|
||||
ultrastar_header.cover = (
|
||||
cover if os_helper.check_file_exists(os.path.join(song_output, cover)) else None
|
||||
)
|
||||
|
||||
real_bpm = get_bpm_from_file(ultrastar_audio_input_path)
|
||||
ultrastar_file_output = os.path.join(song_output, basename_without_ext + '.txt')
|
||||
ultrastar_writer.create_ultrastar_txt_from_automation(transcribed_data, ultrastar_note_numbers,
|
||||
ultrastar_file_output,
|
||||
ultrastar_header, real_bpm)
|
||||
ultrastar_file_output = os.path.join(song_output, basename_without_ext + ".txt")
|
||||
ultrastar_writer.create_ultrastar_txt_from_automation(
|
||||
transcribed_data,
|
||||
ultrastar_note_numbers,
|
||||
ultrastar_file_output,
|
||||
ultrastar_header,
|
||||
real_bpm,
|
||||
)
|
||||
if settings.create_karaoke:
|
||||
no_vocals_path = os.path.join(audio_separation_path, "no_vocals.wav")
|
||||
title = basename_without_ext + " [Karaoke]"
|
||||
@@ -390,9 +508,13 @@ def create_ultrastar_txt_from_automation(audio_separation_path, basename_without
|
||||
karaoke_audio_output_path = karaoke_output_path + ".mp3"
|
||||
convert_wav_to_mp3(no_vocals_path, karaoke_audio_output_path)
|
||||
karaoke_txt_output_path = karaoke_output_path + ".txt"
|
||||
ultrastar_writer.create_ultrastar_txt_from_automation(transcribed_data, ultrastar_note_numbers,
|
||||
karaoke_txt_output_path,
|
||||
ultrastar_header, real_bpm)
|
||||
ultrastar_writer.create_ultrastar_txt_from_automation(
|
||||
transcribed_data,
|
||||
ultrastar_note_numbers,
|
||||
karaoke_txt_output_path,
|
||||
ultrastar_header,
|
||||
real_bpm,
|
||||
)
|
||||
return real_bpm, ultrastar_file_output
|
||||
|
||||
|
||||
@@ -422,75 +544,106 @@ def sanitize_filename(fname: str) -> str:
|
||||
def download_from_youtube():
|
||||
title = get_youtube_title(settings.input_file_path)
|
||||
basename_without_ext = sanitize_filename(title)
|
||||
basename = basename_without_ext + '.mp3'
|
||||
basename = basename_without_ext + ".mp3"
|
||||
song_output = os.path.join(settings.output_file_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(settings.input_file_path, basename_without_ext, song_output)
|
||||
download_youtube_thumbnail(
|
||||
settings.input_file_path, basename_without_ext, song_output
|
||||
)
|
||||
ultrastar_audio_input_path = os.path.join(song_output, basename)
|
||||
return basename_without_ext, song_output, ultrastar_audio_input_path
|
||||
|
||||
|
||||
def 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(',', '.')))
|
||||
real_bpm = ultrastar_converter.ultrastar_bpm_to_real_bpm(
|
||||
float(ultrastar_class.bpm.replace(",", "."))
|
||||
)
|
||||
ultrastar_mp3_name = ultrastar_class.mp3
|
||||
basename_without_ext = os.path.splitext(ultrastar_mp3_name)[0]
|
||||
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, ultrastar_class.artist + ' - ' + ultrastar_class.title)
|
||||
song_output = os.path.join(
|
||||
settings.output_file_path,
|
||||
ultrastar_class.artist + " - " + ultrastar_class.title,
|
||||
)
|
||||
song_output = get_unused_song_output_dir(song_output)
|
||||
os_helper.create_folder(song_output)
|
||||
return basename_without_ext, real_bpm, song_output, ultrastar_audio_input_path, ultrastar_class
|
||||
return (
|
||||
basename_without_ext,
|
||||
real_bpm,
|
||||
song_output,
|
||||
ultrastar_audio_input_path,
|
||||
ultrastar_class,
|
||||
)
|
||||
|
||||
|
||||
def create_midi_file(isAudio, real_bpm, song_output, ultrastar_class):
|
||||
print(f"{PRINT_ULTRASTAR} Creating Midi with {print_blue_highlighted_text('pretty_midi')}")
|
||||
print(
|
||||
f"{PRINT_ULTRASTAR} Creating Midi with {print_blue_highlighted_text('pretty_midi')}"
|
||||
)
|
||||
if isAudio:
|
||||
voice_instrument = [midi_creator.convert_ultrastar_to_midi_instrument(ultrastar_class)]
|
||||
midi_output = os.path.join(song_output, ultrastar_class.title + '.mid')
|
||||
voice_instrument = [
|
||||
midi_creator.convert_ultrastar_to_midi_instrument(ultrastar_class)
|
||||
]
|
||||
midi_output = os.path.join(song_output, ultrastar_class.title + ".mid")
|
||||
midi_creator.instruments_to_midi(voice_instrument, real_bpm, midi_output)
|
||||
else:
|
||||
voice_instrument = [midi_creator.convert_ultrastar_to_midi_instrument(ultrastar_class)]
|
||||
midi_output = os.path.join(song_output, ultrastar_class.title + '.mid')
|
||||
voice_instrument = [
|
||||
midi_creator.convert_ultrastar_to_midi_instrument(ultrastar_class)
|
||||
]
|
||||
midi_output = os.path.join(song_output, ultrastar_class.title + ".mid")
|
||||
midi_creator.instruments_to_midi(voice_instrument, real_bpm, midi_output)
|
||||
|
||||
|
||||
def pitch_audio(isAudio, transcribed_data, ultrastar_class):
|
||||
# todo: chunk pitching as option?
|
||||
# midi_notes = pitch_each_chunk_with_crepe(chunk_folder_name)
|
||||
pitched_data = get_pitch_with_crepe_file(settings.mono_audio_path, settings.crepe_step_size,
|
||||
settings.crepe_model_capacity)
|
||||
pitched_data = get_pitch_with_crepe_file(
|
||||
settings.mono_audio_path,
|
||||
settings.crepe_step_size,
|
||||
settings.crepe_model_capacity,
|
||||
)
|
||||
if isAudio:
|
||||
start_times = []
|
||||
end_times = []
|
||||
for i in range(len(transcribed_data)):
|
||||
start_times.append(transcribed_data[i].start)
|
||||
end_times.append(transcribed_data[i].end)
|
||||
midi_notes = create_midi_notes_from_pitched_data(start_times, end_times, pitched_data)
|
||||
midi_notes = create_midi_notes_from_pitched_data(
|
||||
start_times, end_times, pitched_data
|
||||
)
|
||||
|
||||
else:
|
||||
midi_notes = create_midi_notes_from_pitched_data(ultrastar_class.startTimes, ultrastar_class.endTimes,
|
||||
pitched_data)
|
||||
midi_notes = create_midi_notes_from_pitched_data(
|
||||
ultrastar_class.startTimes, ultrastar_class.endTimes, pitched_data
|
||||
)
|
||||
ultrastar_note_numbers = convert_ultrastar_note_numbers(midi_notes)
|
||||
return midi_notes, pitched_data, ultrastar_note_numbers
|
||||
|
||||
|
||||
def create_audio_chunks(cache_path, isAudio, transcribed_data, ultrastar_audio_input_path, ultrastar_class):
|
||||
def create_audio_chunks(
|
||||
cache_path, isAudio, transcribed_data, ultrastar_audio_input_path, ultrastar_class
|
||||
):
|
||||
audio_chunks_path = os.path.join(cache_path, settings.audio_chunk_folder_name)
|
||||
os_helper.create_folder(audio_chunks_path)
|
||||
if isAudio: # and csv
|
||||
csv_filename = os.path.join(audio_chunks_path, "_chunks.csv")
|
||||
export_chunks_from_transcribed_data(settings.mono_audio_path, transcribed_data, audio_chunks_path)
|
||||
export_chunks_from_transcribed_data(
|
||||
settings.mono_audio_path, transcribed_data, audio_chunks_path
|
||||
)
|
||||
export_transcribed_data_to_csv(transcribed_data, csv_filename)
|
||||
else:
|
||||
export_chunks_from_ultrastar_data(ultrastar_audio_input_path, ultrastar_class, audio_chunks_path)
|
||||
export_chunks_from_ultrastar_data(
|
||||
ultrastar_audio_input_path, ultrastar_class, audio_chunks_path
|
||||
)
|
||||
|
||||
|
||||
def denoise_vocal_audio(basename_without_ext, cache_path):
|
||||
denoised_path = os.path.join(cache_path, basename_without_ext + '_denoised.wav')
|
||||
denoised_path = os.path.join(cache_path, basename_without_ext + "_denoised.wav")
|
||||
ffmpeg_reduce_noise(settings.mono_audio_path, denoised_path)
|
||||
settings.mono_audio_path = denoised_path
|
||||
|
||||
@@ -504,14 +657,23 @@ def main(argv):
|
||||
|
||||
def init_settings(argv):
|
||||
short = "hi:o:amv:"
|
||||
long = ["ifile=", "ofile=", "crepe=", "vosk=", "whisper=", "hyphenation=", "disable_separation=",
|
||||
"disable_karaoke=", "create_audio_chunks="]
|
||||
long = [
|
||||
"ifile=",
|
||||
"ofile=",
|
||||
"crepe=",
|
||||
"vosk=",
|
||||
"whisper=",
|
||||
"hyphenation=",
|
||||
"disable_separation=",
|
||||
"disable_karaoke=",
|
||||
"create_audio_chunks=",
|
||||
]
|
||||
opts, args = getopt.getopt(argv, short, long)
|
||||
if len(opts) == 0:
|
||||
print_help()
|
||||
sys.exit()
|
||||
for opt, arg in opts:
|
||||
if opt == '-h':
|
||||
if opt == "-h":
|
||||
print_help()
|
||||
sys.exit()
|
||||
elif opt in ("-i", "--ifile"):
|
||||
@@ -522,7 +684,7 @@ def init_settings(argv):
|
||||
settings.transcriber = "whisper"
|
||||
settings.whisper_model = arg
|
||||
elif opt in ("--vosk"):
|
||||
settings.transcriber = 'vosk'
|
||||
settings.transcriber = "vosk"
|
||||
settings.vosk_model_path = arg
|
||||
elif opt in ("--crepe"):
|
||||
settings.crepe_model_capacity = arg
|
||||
@@ -534,12 +696,12 @@ def init_settings(argv):
|
||||
settings.create_karaoke = not arg
|
||||
elif opt in ("--create_audio_chunks"):
|
||||
settings.create_audio_chunks = arg
|
||||
if settings.output_file_path == '':
|
||||
if settings.input_file_path.startswith('https:'):
|
||||
if settings.output_file_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_file_path = os.path.join(dirname, "output")
|
||||
settings.device = get_available_device()
|
||||
|
||||
|
||||
|
||||
@@ -14,11 +14,12 @@ def ffmpeg_reduce_noise(input_file_path, output_file):
|
||||
# track_noise, tn
|
||||
# Enable noise floor tracking. By default is disabled. With this enabled, noise floor is automatically adjusted.
|
||||
|
||||
print(f"{PRINT_ULTRASTAR} Reduce noise from vocal audio with {print_blue_highlighted_text('ffmpeg')}.")
|
||||
print(
|
||||
f"{PRINT_ULTRASTAR} Reduce noise from vocal audio with {print_blue_highlighted_text('ffmpeg')}."
|
||||
)
|
||||
(
|
||||
ffmpeg
|
||||
.input(input_file_path)
|
||||
.output(output_file, af='afftdn=nr=70:nf=-50:tn=1')
|
||||
ffmpeg.input(input_file_path)
|
||||
.output(output_file, af="afftdn=nr=70:nf=-50:tn=1")
|
||||
.overwrite_output()
|
||||
.run()
|
||||
)
|
||||
@@ -1,12 +1,17 @@
|
||||
import subprocess
|
||||
|
||||
from moduls.Log import (PRINT_ULTRASTAR, print_blue_highlighted_text,
|
||||
print_red_highlighted_text)
|
||||
from moduls.Log import (
|
||||
PRINT_ULTRASTAR,
|
||||
print_blue_highlighted_text,
|
||||
print_red_highlighted_text,
|
||||
)
|
||||
from moduls.os_helper import current_executor_path, move, path_join
|
||||
|
||||
|
||||
def separate_audio(input_file_path, output_file, device="cpu"):
|
||||
print(f"{PRINT_ULTRASTAR} Separating vocals from audio with {print_blue_highlighted_text('demucs')} and {print_red_highlighted_text(device)} as worker.")
|
||||
print(
|
||||
f"{PRINT_ULTRASTAR} Separating vocals from audio with {print_blue_highlighted_text('demucs')} and {print_red_highlighted_text(device)} as worker."
|
||||
)
|
||||
# Model selection?
|
||||
# -n mdx_q
|
||||
# -n htdemucs_ft
|
||||
|
||||
@@ -9,19 +9,21 @@ from pydub import AudioSegment
|
||||
from moduls.Log import PRINT_ULTRASTAR
|
||||
from moduls.os_helper import create_folder
|
||||
from moduls.Ultrastar.ultrastar_converter import (
|
||||
get_end_time_from_ultrastar, get_start_time_from_ultrastar)
|
||||
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:
|
||||
if ".mp3" in input_file:
|
||||
sound = AudioSegment.from_mp3(input_file)
|
||||
elif '.wav' in input_file:
|
||||
elif ".wav" in input_file:
|
||||
sound = AudioSegment.from_wav(input_file)
|
||||
else:
|
||||
raise ValueError('data format not supported')
|
||||
raise ValueError("data format not supported")
|
||||
|
||||
sound = sound.set_channels(1)
|
||||
sound.export(output_file, format="wav")
|
||||
@@ -36,7 +38,9 @@ class AudioManipulation:
|
||||
pass
|
||||
|
||||
|
||||
def export_chunks_from_transcribed_data(audio_filename, transcribed_data, output_folder_name):
|
||||
def export_chunks_from_transcribed_data(
|
||||
audio_filename, transcribed_data, output_folder_name
|
||||
):
|
||||
"""Export transcribed_data as vocal chunks wav files"""
|
||||
print(f"{PRINT_ULTRASTAR} Export transcribed data as vocal chunks wav files")
|
||||
|
||||
@@ -48,13 +52,17 @@ def export_chunks_from_transcribed_data(audio_filename, transcribed_data, output
|
||||
end_byte = int(transcribed_data[i].end * sr * n_channels)
|
||||
|
||||
chunk = get_chunk(end_byte, start_byte, wf)
|
||||
export_chunk_to_wav_file(chunk, output_folder_name, i, transcribed_data[i].word, wf)
|
||||
export_chunk_to_wav_file(
|
||||
chunk, output_folder_name, i, transcribed_data[i].word, wf
|
||||
)
|
||||
|
||||
wf.close()
|
||||
|
||||
|
||||
def remove_silence_from_transcribtion_data(audio_path, transcribed_data):
|
||||
print(f"{PRINT_ULTRASTAR} Removing silent start and ending, from transcription data")
|
||||
print(
|
||||
f"{PRINT_ULTRASTAR} Removing silent start and ending, from transcription data"
|
||||
)
|
||||
|
||||
y, sr = librosa.load(audio_path, sr=None)
|
||||
|
||||
@@ -68,7 +76,9 @@ def remove_silence_from_transcribtion_data(audio_path, transcribed_data):
|
||||
# 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)
|
||||
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:
|
||||
@@ -110,11 +120,12 @@ def export_chunks_from_ultrastar_data(audio_filename, ultrastar_data, folder_nam
|
||||
def export_chunk_to_wav_file(chunk, folder_name, i, word, wf):
|
||||
"""Export vocal chunks to wav file"""
|
||||
|
||||
clean_word = re.sub('[^A-Za-z0-9]+', '', word)
|
||||
clean_word = re.sub("[^A-Za-z0-9]+", "", word)
|
||||
# todo: Progress?
|
||||
# print(str(i) + ' ' + clean_word)
|
||||
with wave.open(os.path.join(folder_name, f"chunk_{i}_{clean_word}.wav"),
|
||||
"wb") as chunk_file:
|
||||
with wave.open(
|
||||
os.path.join(folder_name, f"chunk_{i}_{clean_word}.wav"), "wb"
|
||||
) as chunk_file:
|
||||
chunk_file.setparams(wf.getparams())
|
||||
chunk_file.writeframes(chunk)
|
||||
|
||||
@@ -135,11 +146,16 @@ 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', newline='') as csvfile:
|
||||
with open(filename, "w", newline="") as csvfile:
|
||||
writer = csv.writer(csvfile)
|
||||
header = ["word", "start", "end", "confidence"]
|
||||
writer.writerow(header)
|
||||
for i in range(len(transcribed_data)):
|
||||
writer.writerow(
|
||||
[transcribed_data[i].word, transcribed_data[i].start, transcribed_data[i].end,
|
||||
transcribed_data[i].conf])
|
||||
[
|
||||
transcribed_data[i].word,
|
||||
transcribed_data[i].start,
|
||||
transcribed_data[i].end,
|
||||
transcribed_data[i].conf,
|
||||
]
|
||||
)
|
||||
+10
-14
@@ -11,22 +11,18 @@ def get_youtube_title(url):
|
||||
ydl_opts = {}
|
||||
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
||||
result = ydl.extract_info(
|
||||
url,
|
||||
download=False # We just want to extract the info
|
||||
url, download=False # We just want to extract the info
|
||||
)
|
||||
|
||||
return result['title']
|
||||
return result["title"]
|
||||
|
||||
|
||||
def download_youtube_audio(url, clear_filename, output_path):
|
||||
print(f"{PRINT_ULTRASTAR} Downloading Audio")
|
||||
ydl_opts = {
|
||||
'format': 'bestaudio/best',
|
||||
'outtmpl': output_path + '/' + clear_filename,
|
||||
'postprocessors': [{
|
||||
'key': 'FFmpegExtractAudio',
|
||||
'preferredcodec': 'mp3'
|
||||
}]
|
||||
"format": "bestaudio/best",
|
||||
"outtmpl": output_path + "/" + clear_filename,
|
||||
"postprocessors": [{"key": "FFmpegExtractAudio", "preferredcodec": "mp3"}],
|
||||
}
|
||||
|
||||
start_download(ydl_opts, url)
|
||||
@@ -35,8 +31,8 @@ def download_youtube_audio(url, clear_filename, output_path):
|
||||
def download_youtube_thumbnail(url, clear_filename, output_path):
|
||||
print(f"{PRINT_ULTRASTAR} Downloading thumbnail")
|
||||
ydl_opts = {
|
||||
'skip_download': True,
|
||||
'writethumbnail': True,
|
||||
"skip_download": True,
|
||||
"writethumbnail": True,
|
||||
}
|
||||
|
||||
download_and_convert_thumbnail(ydl_opts, url, clear_filename, output_path)
|
||||
@@ -45,7 +41,7 @@ def download_youtube_thumbnail(url, clear_filename, output_path):
|
||||
def download_and_convert_thumbnail(ydl_opts, url, clear_filename, output_path):
|
||||
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
||||
info_dict = ydl.extract_info(url, download=False)
|
||||
thumbnail_url = info_dict.get('thumbnail')
|
||||
thumbnail_url = info_dict.get("thumbnail")
|
||||
if thumbnail_url:
|
||||
response = ydl.urlopen(thumbnail_url)
|
||||
image_data = response.read()
|
||||
@@ -56,8 +52,8 @@ def download_and_convert_thumbnail(ydl_opts, url, clear_filename, output_path):
|
||||
def download_youtube_video(url, clear_filename, output_path):
|
||||
print(f"{PRINT_ULTRASTAR} Downloading Video")
|
||||
ydl_opts = {
|
||||
'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4',
|
||||
'outtmpl': output_path + '/' + clear_filename + '.mp4'
|
||||
"format": "bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4",
|
||||
"outtmpl": output_path + "/" + clear_filename + ".mp4",
|
||||
}
|
||||
start_download(ydl_opts, url)
|
||||
|
||||
|
||||
@@ -4,10 +4,12 @@ from moduls.Log import PRINT_ULTRASTAR, print_red_highlighted_text
|
||||
|
||||
|
||||
def get_available_device():
|
||||
gpus = tf.config.list_physical_devices('GPU')
|
||||
gpus = tf.config.list_physical_devices("GPU")
|
||||
|
||||
if not gpus:
|
||||
print(f"{PRINT_ULTRASTAR} There are no GPUs available. Using {print_red_highlighted_text('cpu')}.")
|
||||
print(
|
||||
f"{PRINT_ULTRASTAR} There are no GPUs available. Using {print_red_highlighted_text('cpu')}."
|
||||
)
|
||||
return "cpu"
|
||||
|
||||
print(f"{PRINT_ULTRASTAR} Found available GPUs:")
|
||||
@@ -15,5 +17,7 @@ def get_available_device():
|
||||
print("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')}")
|
||||
print(
|
||||
f"{PRINT_ULTRASTAR} GPU usage are currently in development. Using {print_red_highlighted_text('cpu')}"
|
||||
)
|
||||
return "cpu"
|
||||
+7
-7
@@ -26,10 +26,10 @@ def print_cyan_highlighted_text(text):
|
||||
|
||||
|
||||
class Bcolors:
|
||||
BLUE = '\033[94m'
|
||||
RED = '\033[91m'
|
||||
LightBlue = '\033[96m'
|
||||
Cyan = '\033[36m'
|
||||
Gold = '\033[93m'
|
||||
Underline = '\033[4m'
|
||||
ENDC = '\033[0m'
|
||||
BLUE = "\033[94m"
|
||||
RED = "\033[91m"
|
||||
LightBlue = "\033[96m"
|
||||
Cyan = "\033[36m"
|
||||
Gold = "\033[93m"
|
||||
Underline = "\033[4m"
|
||||
ENDC = "\033[0m"
|
||||
@@ -8,8 +8,10 @@ import pretty_midi
|
||||
from moduls.Log import PRINT_ULTRASTAR
|
||||
from moduls.Pitcher.pitcher import get_frequency_with_high_confidence
|
||||
from moduls.Ultrastar.ultrastar_converter import (
|
||||
get_end_time_from_ultrastar, get_start_time_from_ultrastar,
|
||||
ultrastar_note_to_midi_note)
|
||||
get_end_time_from_ultrastar,
|
||||
get_start_time_from_ultrastar,
|
||||
ultrastar_note_to_midi_note,
|
||||
)
|
||||
|
||||
|
||||
def convert_ultrastar_to_midi_instrument(ultrastar_class):
|
||||
@@ -55,7 +57,10 @@ def most_frequent(ar):
|
||||
|
||||
def find_nearest_index(array, value):
|
||||
idx = np.searchsorted(array, value, side="left")
|
||||
if idx > 0 and (idx == len(array) or math.fabs(value - array[idx - 1]) < math.fabs(value - array[idx])):
|
||||
if idx > 0 and (
|
||||
idx == len(array)
|
||||
or math.fabs(value - array[idx - 1]) < math.fabs(value - array[idx])
|
||||
):
|
||||
return idx - 1
|
||||
else:
|
||||
return idx
|
||||
|
||||
+22
-13
@@ -3,35 +3,44 @@ import csv
|
||||
import crepe
|
||||
from scipy.io import wavfile
|
||||
|
||||
from moduls.Log import (PRINT_ULTRASTAR, print_blue_highlighted_text,
|
||||
print_red_highlighted_text)
|
||||
from moduls.Log import (
|
||||
PRINT_ULTRASTAR,
|
||||
print_blue_highlighted_text,
|
||||
print_red_highlighted_text,
|
||||
)
|
||||
from moduls.Pitcher.pitched_data import PitchedData
|
||||
|
||||
|
||||
def get_pitch_with_crepe_file(filename, step_size, model_capacity):
|
||||
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")
|
||||
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"
|
||||
)
|
||||
# Todo: add GPU support by using torchcrepe
|
||||
sr, audio = wavfile.read(filename)
|
||||
|
||||
pitched_data = PitchedData()
|
||||
pitched_data.times, pitched_data.frequencies, pitched_data.confidence, activation = crepe.predict(audio, sr,
|
||||
model_capacity,
|
||||
step_size=step_size,
|
||||
viterbi=True)
|
||||
(
|
||||
pitched_data.times,
|
||||
pitched_data.frequencies,
|
||||
pitched_data.confidence,
|
||||
activation,
|
||||
) = crepe.predict(audio, sr, model_capacity, step_size=step_size, viterbi=True)
|
||||
return pitched_data
|
||||
|
||||
|
||||
def get_pitch_with_crepe(y, sr, step_size, model_capacity):
|
||||
pitched_data = PitchedData()
|
||||
pitched_data.times, pitched_data.frequencies, pitched_data.confidence, activation = crepe.predict(y, sr,
|
||||
model_capacity,
|
||||
step_size=step_size,
|
||||
viterbi=True)
|
||||
(
|
||||
pitched_data.times,
|
||||
pitched_data.frequencies,
|
||||
pitched_data.confidence,
|
||||
activation,
|
||||
) = crepe.predict(y, sr, model_capacity, step_size=step_size, viterbi=True)
|
||||
return pitched_data
|
||||
|
||||
|
||||
def write_lists_to_csv(time, frequency, confidence, filename):
|
||||
with open(filename, 'w', newline='') as csvfile:
|
||||
with open(filename, "w", newline="") as csvfile:
|
||||
writer = csv.writer(csvfile)
|
||||
header = ["time", "frequency", "confidence"]
|
||||
writer.writerow(header)
|
||||
@@ -41,7 +50,7 @@ def write_lists_to_csv(time, frequency, confidence, filename):
|
||||
|
||||
def read_data_from_csv(filename):
|
||||
csv_data = []
|
||||
with open(filename, 'r') as csv_file:
|
||||
with open(filename, "r") as csv_file:
|
||||
csv_reader = csv.reader(csv_file)
|
||||
for line in csv_reader:
|
||||
csv_data.append(line)
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
class TranscribedData:
|
||||
""" Transcribed data from json file """
|
||||
"""Transcribed data from json file"""
|
||||
|
||||
def __init__(self, transcribed_json):
|
||||
# Vosk = conf, Whisper = confidence
|
||||
self.conf = transcribed_json.get("conf", transcribed_json.get("confidence", None))
|
||||
self.conf = transcribed_json.get(
|
||||
"conf", transcribed_json.get("confidence", None)
|
||||
)
|
||||
# Vosk = word, Whisper = text
|
||||
self.word = transcribed_json.get("word", transcribed_json.get("text", None))
|
||||
self.end = transcribed_json["end"]
|
||||
|
||||
@@ -11,7 +11,9 @@ from moduls.Speech_Recognition.TranscribedData import TranscribedData
|
||||
|
||||
def transcribe_with_vosk(audio_filename, model_path):
|
||||
# Code from here: https://towardsdatascience.com/speech-recognition-with-timestamps-934ede4234b2
|
||||
print(f"{PRINT_ULTRASTAR} Transcribing {audio_filename} with vosk and model {model_path}")
|
||||
print(
|
||||
f"{PRINT_ULTRASTAR} Transcribing {audio_filename} with vosk and model {model_path}"
|
||||
)
|
||||
|
||||
model = Model(model_path)
|
||||
wf = wave.open(audio_filename, "rb")
|
||||
@@ -41,9 +43,9 @@ def transcribe_with_vosk(audio_filename, model_path):
|
||||
# and it returns an empty dictionary
|
||||
# {'text': ''}
|
||||
continue
|
||||
for obj in sentence['result']:
|
||||
for obj in sentence["result"]:
|
||||
vtd = TranscribedData(obj) # create custom Word object
|
||||
vtd.word = vtd.word + ' '
|
||||
vtd.word = vtd.word + " "
|
||||
transcribed_data.append(vtd) # and add it to list
|
||||
|
||||
# Todo: remove silent part from each word
|
||||
|
||||
@@ -1,18 +1,27 @@
|
||||
import whisperx
|
||||
|
||||
from moduls.Log import (PRINT_ULTRASTAR, print_blue_highlighted_text,
|
||||
print_red_highlighted_text)
|
||||
from moduls.Log import (
|
||||
PRINT_ULTRASTAR,
|
||||
print_blue_highlighted_text,
|
||||
print_red_highlighted_text,
|
||||
)
|
||||
from moduls.Speech_Recognition.TranscribedData import TranscribedData
|
||||
|
||||
|
||||
def transcribe_with_whisper(audio_path, model, device="cpu"):
|
||||
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")
|
||||
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"
|
||||
)
|
||||
|
||||
batch_size = 16 # reduce if low on GPU mem
|
||||
compute_type = "float16" if device == "cuda" else "int8" # change to "int8" if low on GPU mem (may reduce accuracy)
|
||||
compute_type = (
|
||||
"float16" if device == "cuda" else "int8"
|
||||
) # change to "int8" if low on GPU mem (may reduce accuracy)
|
||||
|
||||
# transcribe with original whisper
|
||||
loaded_whisper_model = whisperx.load_model(model, device=device, compute_type=compute_type)
|
||||
loaded_whisper_model = whisperx.load_model(
|
||||
model, device=device, compute_type=compute_type
|
||||
)
|
||||
audio = whisperx.load_audio(audio_path)
|
||||
|
||||
print(f"{PRINT_ULTRASTAR} Transcribing {audio_path}")
|
||||
@@ -24,17 +33,26 @@ def transcribe_with_whisper(audio_path, model, device="cpu"):
|
||||
model_a, metadata = whisperx.load_align_model(language_code=language, device=device)
|
||||
|
||||
# align whisper output
|
||||
result_aligned = whisperx.align(result["segments"], model_a, metadata, audio, device, return_char_alignments=False)
|
||||
result_aligned = whisperx.align(
|
||||
result["segments"],
|
||||
model_a,
|
||||
metadata,
|
||||
audio,
|
||||
device,
|
||||
return_char_alignments=False,
|
||||
)
|
||||
|
||||
transcribed_data = []
|
||||
|
||||
for segment in result_aligned["segments"]:
|
||||
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']))}")
|
||||
print(
|
||||
f"{print_red_highlighted_text('Error: Skipping Word {}, because of missing timings'.format(obj['word']))}"
|
||||
)
|
||||
continue
|
||||
vtd = TranscribedData(obj) # create custom Word object
|
||||
vtd.word = vtd.word + ' '
|
||||
vtd.word = vtd.word + " "
|
||||
transcribed_data.append(vtd) # and add it to list
|
||||
|
||||
return transcribed_data, language
|
||||
@@ -2,11 +2,14 @@ import string
|
||||
|
||||
from hyphen import Hyphenator, dictools
|
||||
|
||||
from moduls.Log import (PRINT_ULTRASTAR, print_blue_highlighted_text,
|
||||
print_gold_highlighted_text)
|
||||
from moduls.Log import (
|
||||
PRINT_ULTRASTAR,
|
||||
print_blue_highlighted_text,
|
||||
print_gold_highlighted_text,
|
||||
)
|
||||
|
||||
|
||||
def language_check(language='en'):
|
||||
def language_check(language="en"):
|
||||
dict_langs = dictools.LANGUAGES
|
||||
|
||||
lang_region = None
|
||||
@@ -18,7 +21,9 @@ def language_check(language='en'):
|
||||
if lang_region is None:
|
||||
return None
|
||||
|
||||
print(f"{PRINT_ULTRASTAR} Hyphenate using language code: {print_blue_highlighted_text(lang_region)}")
|
||||
print(
|
||||
f"{PRINT_ULTRASTAR} Hyphenate using language code: {print_blue_highlighted_text(lang_region)}"
|
||||
)
|
||||
return lang_region
|
||||
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ from moduls.Log import PRINT_ULTRASTAR
|
||||
|
||||
# todo: Code from here: https://www.thepythoncode.com/article/using-speech-recognition-to-convert-speech-to-text-python
|
||||
|
||||
|
||||
def PrintText(wav_file):
|
||||
# English speach!
|
||||
r = sr.Recognizer()
|
||||
@@ -31,14 +32,15 @@ def get_large_audio_transcription(wav_file):
|
||||
sound = AudioSegment.from_wav(wav_file)
|
||||
|
||||
# split audio sound where silence is 700 miliseconds or more and get chunks
|
||||
chunks = split_on_silence(sound,
|
||||
# experiment with this value for your target audio file
|
||||
min_silence_len=500,
|
||||
# adjust this per requirement
|
||||
silence_thresh=sound.dBFS - 14,
|
||||
# keep the silence for 1 second, adjustable as well
|
||||
keep_silence=500,
|
||||
)
|
||||
chunks = split_on_silence(
|
||||
sound,
|
||||
# experiment with this value for your target audio file
|
||||
min_silence_len=500,
|
||||
# adjust this per requirement
|
||||
silence_thresh=sound.dBFS - 14,
|
||||
# keep the silence for 1 second, adjustable as well
|
||||
keep_silence=500,
|
||||
)
|
||||
|
||||
folder_name = "audio-chunks"
|
||||
# create a directory to store the audio chunks
|
||||
@@ -76,9 +78,13 @@ def transcribe_audio(audio_file):
|
||||
audio = recognizer.record(source)
|
||||
try:
|
||||
transcript = recognizer.recognize_google(audio, show_all=True)
|
||||
start_time = transcript['result'][0]['alternative'][0]['words'][0]['startTime']
|
||||
end_time = transcript['result'][0]['alternative'][0]['words'][-1]['endTime']
|
||||
return transcript['result'][0]['alternative'][0]['transcript'], start_time, end_time
|
||||
start_time = transcript["result"][0]["alternative"][0]["words"][0]["startTime"]
|
||||
end_time = transcript["result"][0]["alternative"][0]["words"][-1]["endTime"]
|
||||
return (
|
||||
transcript["result"][0]["alternative"][0]["transcript"],
|
||||
start_time,
|
||||
end_time,
|
||||
)
|
||||
except sr.UnknownValueError:
|
||||
print(f"{PRINT_ULTRASTAR} Could not understand audio")
|
||||
except sr.RequestError as e:
|
||||
|
||||
@@ -37,14 +37,19 @@ def ultrastar_note_to_midi_note(ultrastar_note):
|
||||
|
||||
def get_start_time_from_ultrastar(ultrastar_class, pos):
|
||||
gap = int(ultrastar_class.gap) / 1000
|
||||
real_bpm = ultrastar_bpm_to_real_bpm(float(ultrastar_class.bpm.replace(',', '.')))
|
||||
real_bpm = ultrastar_bpm_to_real_bpm(float(ultrastar_class.bpm.replace(",", ".")))
|
||||
start_time = beat_to_second(int(ultrastar_class.startBeat[pos]), real_bpm) + gap
|
||||
return start_time
|
||||
|
||||
|
||||
def get_end_time_from_ultrastar(ultrastar_class, pos):
|
||||
gap = int(ultrastar_class.gap) / 1000
|
||||
real_bpm = ultrastar_bpm_to_real_bpm(float(ultrastar_class.bpm.replace(',', '.')))
|
||||
end_time = beat_to_second(int(ultrastar_class.startBeat[pos]) + int(ultrastar_class.durations[pos]),
|
||||
real_bpm) + gap
|
||||
real_bpm = ultrastar_bpm_to_real_bpm(float(ultrastar_class.bpm.replace(",", ".")))
|
||||
end_time = (
|
||||
beat_to_second(
|
||||
int(ultrastar_class.startBeat[pos]) + int(ultrastar_class.durations[pos]),
|
||||
real_bpm,
|
||||
)
|
||||
+ gap
|
||||
)
|
||||
return end_time
|
||||
@@ -1,13 +1,15 @@
|
||||
from moduls.Log import PRINT_ULTRASTAR
|
||||
from moduls.Ultrastar.ultrastar_converter import (
|
||||
get_end_time_from_ultrastar, get_start_time_from_ultrastar)
|
||||
get_end_time_from_ultrastar,
|
||||
get_start_time_from_ultrastar,
|
||||
)
|
||||
from moduls.Ultrastar.ultrastar_txt import UltrastarTxt
|
||||
|
||||
|
||||
def parse_ultrastar_txt(input_file):
|
||||
print(f"{PRINT_ULTRASTAR} Parse ultrastar txt -> {input_file}")
|
||||
|
||||
file = open(input_file, 'r', encoding='utf8')
|
||||
file = open(input_file, "r", encoding="utf8")
|
||||
txt = file.readlines()
|
||||
|
||||
ultrastar_class = UltrastarTxt()
|
||||
@@ -16,18 +18,18 @@ def parse_ultrastar_txt(input_file):
|
||||
# Strips the newline character
|
||||
for line in txt:
|
||||
count += 1
|
||||
if line.startswith('#'):
|
||||
if line.startswith('#ARTIST'):
|
||||
ultrastar_class.artist = line.split(':')[1].replace('\n', '')
|
||||
elif line.startswith('#TITLE'):
|
||||
ultrastar_class.title = line.split(':')[1].replace('\n', '')
|
||||
elif line.startswith('#MP3'):
|
||||
ultrastar_class.mp3 = line.split(':')[1].replace('\n', '')
|
||||
elif line.startswith('#GAP'):
|
||||
ultrastar_class.gap = line.split(':')[1].replace('\n', '')
|
||||
elif line.startswith('#BPM'):
|
||||
ultrastar_class.bpm = line.split(':')[1].replace('\n', '')
|
||||
elif line.startswith(('F ', ': ', '* ', 'R ', 'G ')):
|
||||
if line.startswith("#"):
|
||||
if line.startswith("#ARTIST"):
|
||||
ultrastar_class.artist = line.split(":")[1].replace("\n", "")
|
||||
elif line.startswith("#TITLE"):
|
||||
ultrastar_class.title = line.split(":")[1].replace("\n", "")
|
||||
elif line.startswith("#MP3"):
|
||||
ultrastar_class.mp3 = line.split(":")[1].replace("\n", "")
|
||||
elif line.startswith("#GAP"):
|
||||
ultrastar_class.gap = line.split(":")[1].replace("\n", "")
|
||||
elif line.startswith("#BPM"):
|
||||
ultrastar_class.bpm = line.split(":")[1].replace("\n", "")
|
||||
elif line.startswith(("F ", ": ", "* ", "R ", "G ")):
|
||||
parts = line.split()
|
||||
# [0] F : * R G
|
||||
# [1] start beat
|
||||
@@ -39,12 +41,16 @@ def parse_ultrastar_txt(input_file):
|
||||
ultrastar_class.startBeat.append(parts[1])
|
||||
ultrastar_class.durations.append(parts[2])
|
||||
ultrastar_class.pitches.append(parts[3])
|
||||
ultrastar_class.words.append(parts[4] if len(parts) > 4 else '')
|
||||
ultrastar_class.words.append(parts[4] if len(parts) > 4 else "")
|
||||
|
||||
# do always as last
|
||||
pos = len(ultrastar_class.startBeat) - 1
|
||||
ultrastar_class.startTimes.append(get_start_time_from_ultrastar(ultrastar_class, pos))
|
||||
ultrastar_class.endTimes.append(get_end_time_from_ultrastar(ultrastar_class, pos))
|
||||
ultrastar_class.startTimes.append(
|
||||
get_start_time_from_ultrastar(ultrastar_class, pos)
|
||||
)
|
||||
ultrastar_class.endTimes.append(
|
||||
get_end_time_from_ultrastar(ultrastar_class, pos)
|
||||
)
|
||||
# todo: Progress?
|
||||
|
||||
return ultrastar_class
|
||||
@@ -1,14 +1,19 @@
|
||||
import librosa
|
||||
|
||||
from moduls.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 moduls.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 moduls.Midi.midi_creator import create_midi_note_from_pitched_data
|
||||
from moduls.Ultrastar.ultrastar_converter import (
|
||||
get_end_time_from_ultrastar, get_start_time_from_ultrastar,
|
||||
ultrastar_note_to_midi_note)
|
||||
get_end_time_from_ultrastar,
|
||||
get_start_time_from_ultrastar,
|
||||
ultrastar_note_to_midi_note,
|
||||
)
|
||||
|
||||
MAX_SONG_SCORE = 10000
|
||||
MAX_SONG_LINE_BONUS = 1000
|
||||
@@ -24,16 +29,17 @@ class Points:
|
||||
|
||||
|
||||
def add_point(noteType, points):
|
||||
if noteType == ':':
|
||||
if noteType == ":":
|
||||
points.notes += 1
|
||||
elif noteType == '*':
|
||||
elif noteType == "*":
|
||||
points.golden_notes += 2
|
||||
elif noteType == 'R':
|
||||
elif noteType == "R":
|
||||
points.rap += 1
|
||||
elif noteType == 'G':
|
||||
elif noteType == "G":
|
||||
points.golden_rap += 2
|
||||
return points
|
||||
|
||||
|
||||
class Score:
|
||||
max_score = 0
|
||||
notes = 0
|
||||
@@ -41,17 +47,25 @@ class Score:
|
||||
line_bonus = 0
|
||||
score = 0
|
||||
|
||||
|
||||
def get_score(points):
|
||||
score = Score()
|
||||
score.max_score = MAX_SONG_SCORE if points.line_bonus == 0 else MAX_SONG_SCORE - MAX_SONG_LINE_BONUS
|
||||
score.max_score = (
|
||||
MAX_SONG_SCORE
|
||||
if points.line_bonus == 0
|
||||
else MAX_SONG_SCORE - MAX_SONG_LINE_BONUS
|
||||
)
|
||||
score.notes = round(score.max_score * (points.notes + points.rap) / points.parts)
|
||||
score.golden = round(points.golden_notes + points.golden_rap)
|
||||
score.score = round(score.notes + points.line_bonus + score.golden)
|
||||
score.line_bonus = round(points.line_bonus)
|
||||
return score
|
||||
|
||||
|
||||
def print_score(score):
|
||||
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))}")
|
||||
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))}"
|
||||
)
|
||||
|
||||
|
||||
def calculate_score(pitched_data, ultrastar_class):
|
||||
@@ -66,7 +80,7 @@ def calculate_score(pitched_data, ultrastar_class):
|
||||
if ultrastar_class.words == "":
|
||||
continue
|
||||
|
||||
if ultrastar_class.noteType[i] == 'F':
|
||||
if ultrastar_class.noteType[i] == "F":
|
||||
continue
|
||||
|
||||
start_time = get_start_time_from_ultrastar(ultrastar_class, i)
|
||||
@@ -79,7 +93,9 @@ def calculate_score(pitched_data, ultrastar_class):
|
||||
accurate_part_line_bonus_points = 0
|
||||
simple_part_line_bonus_points = 0
|
||||
|
||||
ultrastar_midi_note = ultrastar_note_to_midi_note(int(ultrastar_class.pitches[i]))
|
||||
ultrastar_midi_note = ultrastar_note_to_midi_note(
|
||||
int(ultrastar_class.pitches[i])
|
||||
)
|
||||
ultrastar_note = librosa.midi_to_note(ultrastar_midi_note)
|
||||
|
||||
for p in range(parts):
|
||||
@@ -94,7 +110,9 @@ def calculate_score(pitched_data, ultrastar_class):
|
||||
|
||||
if pitch_note == ultrastar_note:
|
||||
# Octave high must be the same
|
||||
accurate_points = add_point(ultrastar_class.noteType[i], accurate_points)
|
||||
accurate_points = add_point(
|
||||
ultrastar_class.noteType[i], accurate_points
|
||||
)
|
||||
accurate_part_line_bonus_points += 1
|
||||
|
||||
accurate_points.parts += 1
|
||||
@@ -108,9 +126,14 @@ def calculate_score(pitched_data, ultrastar_class):
|
||||
|
||||
return get_score(simple_points), get_score(accurate_points)
|
||||
|
||||
|
||||
def print_score_calculation(simple_points, accurate_points):
|
||||
print(f"{PRINT_ULTRASTAR} {print_underlined_text('Simple (octave high ignored)')} points")
|
||||
print(
|
||||
f"{PRINT_ULTRASTAR} {print_underlined_text('Simple (octave high ignored)')} points"
|
||||
)
|
||||
print_score(simple_points)
|
||||
|
||||
print(f"{PRINT_ULTRASTAR} {print_underlined_text('Accurate (octave high matches)')} points:")
|
||||
print(
|
||||
f"{PRINT_ULTRASTAR} {print_underlined_text('Accurate (octave high matches)')} points:"
|
||||
)
|
||||
print_score(accurate_points)
|
||||
@@ -1,13 +1,13 @@
|
||||
class UltrastarTxt:
|
||||
artist = ''
|
||||
title = ''
|
||||
mp3 = ''
|
||||
gap = ''
|
||||
bpm = ''
|
||||
artist = ""
|
||||
title = ""
|
||||
mp3 = ""
|
||||
gap = ""
|
||||
bpm = ""
|
||||
cover = None
|
||||
creator = 'UltraSinger [GitHub]'
|
||||
fixer = 'YOUR NAME'
|
||||
comment = 'UltraSinger [GitHub]'
|
||||
creator = "UltraSinger [GitHub]"
|
||||
fixer = "YOUR NAME"
|
||||
comment = "UltraSinger [GitHub]"
|
||||
startBeat = []
|
||||
startTimes = []
|
||||
endTimes = []
|
||||
|
||||
@@ -3,8 +3,10 @@ import re
|
||||
import langcodes
|
||||
|
||||
from moduls.Log import PRINT_ULTRASTAR
|
||||
from moduls.Ultrastar.ultrastar_converter import (real_bpm_to_ultrastar_bpm,
|
||||
second_to_beat)
|
||||
from moduls.Ultrastar.ultrastar_converter import (
|
||||
real_bpm_to_ultrastar_bpm,
|
||||
second_to_beat,
|
||||
)
|
||||
|
||||
|
||||
def get_multiplier(real_bpm):
|
||||
@@ -23,36 +25,39 @@ def get_language_name(language):
|
||||
return langcodes.Language.make(language=language).display_name()
|
||||
|
||||
|
||||
def create_ultrastar_txt_from_automation(transcribed_data, note_numbers, ultrastar_file_output, ultrastar_class,
|
||||
bpm=120):
|
||||
def create_ultrastar_txt_from_automation(
|
||||
transcribed_data, note_numbers, ultrastar_file_output, ultrastar_class, bpm=120
|
||||
):
|
||||
print(f"{PRINT_ULTRASTAR} Creating {ultrastar_file_output} from transcription.")
|
||||
|
||||
real_bpm = real_bpm_to_ultrastar_bpm(bpm)
|
||||
multiplication = get_multiplier(real_bpm)
|
||||
ultrastar_bpm = real_bpm * get_multiplier(real_bpm)
|
||||
|
||||
with open(ultrastar_file_output, 'w', encoding='utf8') as f:
|
||||
with open(ultrastar_file_output, "w", encoding="utf8") as f:
|
||||
gap = transcribed_data[0].start
|
||||
|
||||
f.write(f'#ARTIST:{ultrastar_class.artist}\n')
|
||||
f.write(f'#TITLE:{ultrastar_class.title}\n')
|
||||
f.write(f'#CREATOR:{ultrastar_class.creator}\n')
|
||||
f.write(f'#FIXER:{ultrastar_class.fixer}\n')
|
||||
f.write(f"#ARTIST:{ultrastar_class.artist}\n")
|
||||
f.write(f"#TITLE:{ultrastar_class.title}\n")
|
||||
f.write(f"#CREATOR:{ultrastar_class.creator}\n")
|
||||
f.write(f"#FIXER:{ultrastar_class.fixer}\n")
|
||||
if ultrastar_class.language is not None:
|
||||
f.write(f'#LANGUAGE:{get_language_name(ultrastar_class.language)}\n')
|
||||
f.write(f"#LANGUAGE:{get_language_name(ultrastar_class.language)}\n")
|
||||
if ultrastar_class.cover is not None:
|
||||
f.write(f'#COVER:{ultrastar_class.cover}\n')
|
||||
f.write(f'#MP3:{ultrastar_class.mp3}\n')
|
||||
f.write(f'#VIDEO:{ultrastar_class.video}\n')
|
||||
f.write(f'#BPM:' + str(round(ultrastar_bpm, 2)) + '\n') # not the real BPM!
|
||||
f.write(f'#GAP:' + str(int(gap * 1000)) + '\n')
|
||||
f.write(f'#COMMENT:{ultrastar_class.comment}\n')
|
||||
f.write(f"#COVER:{ultrastar_class.cover}\n")
|
||||
f.write(f"#MP3:{ultrastar_class.mp3}\n")
|
||||
f.write(f"#VIDEO:{ultrastar_class.video}\n")
|
||||
f.write(f"#BPM:" + str(round(ultrastar_bpm, 2)) + "\n") # not the real BPM!
|
||||
f.write(f"#GAP:" + str(int(gap * 1000)) + "\n")
|
||||
f.write(f"#COMMENT:{ultrastar_class.comment}\n")
|
||||
|
||||
# Write the singing part
|
||||
previous_end_beat = 0
|
||||
for i in range(len(transcribed_data)):
|
||||
start_time = (transcribed_data[i].start - gap) * multiplication
|
||||
end_time = (transcribed_data[i].end - transcribed_data[i].start) * multiplication
|
||||
end_time = (
|
||||
transcribed_data[i].end - transcribed_data[i].start
|
||||
) * multiplication
|
||||
start_beat = round(second_to_beat(start_time, bpm))
|
||||
duration = round(second_to_beat(end_time, bpm))
|
||||
|
||||
@@ -67,12 +72,12 @@ def create_ultrastar_txt_from_automation(transcribed_data, note_numbers, ultrast
|
||||
# 'n2' duration at real beat
|
||||
# 'n3' pitch where 0 == C4
|
||||
# 'w' lyric
|
||||
f.write(': ')
|
||||
f.write(str(start_beat) + ' ')
|
||||
f.write(str(duration) + ' ')
|
||||
f.write(str(note_numbers[i]) + ' ')
|
||||
f.write(": ")
|
||||
f.write(str(start_beat) + " ")
|
||||
f.write(str(duration) + " ")
|
||||
f.write(str(note_numbers[i]) + " ")
|
||||
f.write(transcribed_data[i].word)
|
||||
f.write('\n')
|
||||
f.write("\n")
|
||||
|
||||
# detect silence between words
|
||||
if i < len(transcribed_data) - 1:
|
||||
@@ -84,27 +89,33 @@ def create_ultrastar_txt_from_automation(transcribed_data, note_numbers, ultrast
|
||||
# - 10
|
||||
# '-' end of current sing part
|
||||
# 'n1' show next at time in real beat
|
||||
f.write('- ')
|
||||
show_next = second_to_beat(transcribed_data[i].end - gap, bpm) * multiplication
|
||||
f.write("- ")
|
||||
show_next = (
|
||||
second_to_beat(transcribed_data[i].end - gap, bpm) * multiplication
|
||||
)
|
||||
f.write(str(round(show_next)))
|
||||
f.write('\n')
|
||||
f.write('E')
|
||||
f.write("\n")
|
||||
f.write("E")
|
||||
|
||||
|
||||
def create_repitched_txt_from_ultrastar_data(input_file, note_numbers, output_repitched_ultrastar):
|
||||
def create_repitched_txt_from_ultrastar_data(
|
||||
input_file, note_numbers, output_repitched_ultrastar
|
||||
):
|
||||
# todo: just add '_repitched' to input_file
|
||||
print("{PRINT_ULTRASTAR} Creating repitched ultrastar txt -> {input_file}_repitch.txt")
|
||||
print(
|
||||
"{PRINT_ULTRASTAR} Creating repitched ultrastar txt -> {input_file}_repitch.txt"
|
||||
)
|
||||
|
||||
# todo: to reader
|
||||
file = open(input_file, 'r')
|
||||
file = open(input_file, "r")
|
||||
txt = file.readlines()
|
||||
|
||||
i = 0
|
||||
# todo: just add '_repitched' to input_file
|
||||
with open(output_repitched_ultrastar, 'w', encoding='utf8') as f:
|
||||
with open(output_repitched_ultrastar, "w", encoding="utf8") as f:
|
||||
for line in txt:
|
||||
if line.startswith(':'):
|
||||
parts = re.findall(r'\S+|\s+', line)
|
||||
if line.startswith(":"):
|
||||
parts = re.findall(r"\S+|\s+", line)
|
||||
# between are whitespaces
|
||||
# [0] :
|
||||
# [2] start beat
|
||||
@@ -112,28 +123,36 @@ def create_repitched_txt_from_ultrastar_data(input_file, note_numbers, output_re
|
||||
# [6] pitch
|
||||
# [8] word
|
||||
parts[6] = str(note_numbers[i])
|
||||
delimiter = ''
|
||||
delimiter = ""
|
||||
f.write(delimiter.join(parts))
|
||||
i += 1
|
||||
else:
|
||||
f.write(line)
|
||||
|
||||
|
||||
def add_score_to_ultrastar_txt(ultrastar_file_output, score):
|
||||
with open(ultrastar_file_output, 'r', encoding='utf8') as f:
|
||||
with open(ultrastar_file_output, "r", encoding="utf8") as f:
|
||||
text = f.read()
|
||||
text = text.split('\n')
|
||||
text = text.split("\n")
|
||||
|
||||
for i in range(len(text)):
|
||||
if text[i].startswith("#COMMENT:"):
|
||||
text[i] = f"{text[i]} | Score: total: {score.score}, notes: {score.notes} line: {score.line_bonus}, golden: {score.golden}"
|
||||
text[
|
||||
i
|
||||
] = f"{text[i]} | Score: total: {score.score}, notes: {score.notes} line: {score.line_bonus}, golden: {score.golden}"
|
||||
break
|
||||
elif text[i].startswith(('F ', ': ', '* ', 'R ', 'G ')):
|
||||
text.insert(i, f"#COMMENT: UltraSinger [GitHub] | Score: total: {score.score}, notes: {score.notes} line: {score.line_bonus}, golden: {score.golden}")
|
||||
elif text[i].startswith(("F ", ": ", "* ", "R ", "G ")):
|
||||
text.insert(
|
||||
i,
|
||||
f"#COMMENT: UltraSinger [GitHub] | Score: total: {score.score}, notes: {score.notes} line: {score.line_bonus}, golden: {score.golden}",
|
||||
)
|
||||
break
|
||||
|
||||
text = '\n'.join(text)
|
||||
text = "\n".join(text)
|
||||
|
||||
with open(ultrastar_file_output, 'w', encoding='utf8') as f:
|
||||
with open(ultrastar_file_output, "w", encoding="utf8") as f:
|
||||
f.write(text)
|
||||
|
||||
|
||||
class UltraStarWriter:
|
||||
pass
|
||||
+1
-1
@@ -32,4 +32,4 @@ def check_file_exists(file_path):
|
||||
|
||||
|
||||
def check_if_folder_exists(song_output):
|
||||
return os.path.isdir(song_output)
|
||||
return os.path.isdir(song_output)
|
||||
@@ -17,3 +17,4 @@ langcodes~=3.3.0
|
||||
language-data~=1.1
|
||||
Pillow~=9.5.0
|
||||
isort==5.12
|
||||
black==23.3
|
||||
Reference in new issue
Block a user