Cherry refactorings from evaluation PR

This commit is contained in:
Vadim committed 2024-07-04 23:40:51 +02:00
1 parent 398027b724
commit 4b86e7a86b
19 files changed
+421 -259

No files matched your search

+14 -9
View File
@@ -1,7 +1,10 @@
"""Separate vocals from audio"""
import os
import shlex
import subprocess
import demucs.separate
from modules.console_colors import (
ULTRASINGER_HEAD,
blue_highlighted,
@@ -10,16 +13,18 @@ from modules.console_colors import (
from modules.os_helper import current_executor_path, move, path_join
def separate_audio(input_file_path: str, output_file: str, device="cpu") -> None:
def separate_audio(input_file_path: str, output_folder: str, device="cpu") -> None:
"""Separate vocals from audio with demucs."""
print(
f"{ULTRASINGER_HEAD} Separating vocals from audio with {blue_highlighted('demucs')} and {red_highlighted(device)} as worker."
)
# Model selection?
# -n htdemucs_ft
subprocess.run(
["demucs", "-d", device, "--two-stems=vocals", "--float32", input_file_path]
)
separated_folder = path_join(current_executor_path(), "separated")
move(separated_folder, output_file)
# subprocess.run(
# ["demucs", "-d", device, "--two-stems=vocals", "--float32", input_file_path]
# )
# separated_folder = path_join(current_executor_path(), "separated")
# move(separated_folder, output_file)
# fixme "--float32" is missing
demucs.separate.main(shlex.split(f'--two-stems vocals -d {device} --out "{os.path.join(output_folder, "separated")}" "{input_file_path}"'))
+1 -1
View File
@@ -63,7 +63,7 @@ def remove_silence(silence_parts_list: list[tuple[float, float]], transcribed_da
split_word = "~ "
is_word_end = True
split_data = TranscribedData({"conf": data.conf, "word": split_word, "end": split_end, "start": silence_end, "is_word_end": is_word_end})
split_data = TranscribedData({"confidence": data.confidence, "word": split_word, "end": split_end, "start": silence_end, "is_word_end": is_word_end})
if not was_split:
data.end = silence_start
+3
View File
@@ -1,7 +1,10 @@
"""Pitched data"""
from dataclasses import dataclass
from dataclasses_json import dataclass_json
@dataclass_json
@dataclass
class PitchedData:
"""Pitched data from crepe"""
+4
View File
@@ -30,6 +30,10 @@ def get_pitch_with_crepe(
times, frequencies, confidence, activation = crepe.predict(
audio, sample_rate, model_capacity, step_size=step_size, viterbi=True
)
# convert to native float for serialization
confidence = [float(x) for x in confidence]
return PitchedData(times, frequencies, confidence)
@@ -1,21 +1,29 @@
"""Docstring"""
from dataclasses import dataclass
from dataclasses_json import dataclass_json
@dataclass_json
@dataclass
class TranscribedData:
"""Transcribed data from json file"""
def __init__(self, transcribed_json = None):
if transcribed_json is None:
return
# Vosk = conf, Whisper = confidence
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.get("end", None)
self.start = transcribed_json.get("start", None)
self.is_hyphen = transcribed_json.get("is_hyphen", None)
self.is_word_end = transcribed_json.get("is_word_end", True)
confidence: float = 0
word: str = ""
start: float = 0
end: float = 0
is_hyphen: bool = False
is_word_end: bool = True
def from_whisper(whisper_dict) -> TranscribedData:
transcribed_data = TranscribedData()
if "score" in whisper_dict:
transcribed_data.confidence = whisper_dict["score"]
if "word" in whisper_dict:
transcribed_data.word = whisper_dict["word"]
if "start" in whisper_dict:
transcribed_data.start = whisper_dict["start"]
if "end" in whisper_dict:
transcribed_data.end = whisper_dict["end"]
return transcribed_data
@@ -0,0 +1,14 @@
from dataclasses import dataclass
from dataclasses_json import dataclass_json
from modules.Speech_Recognition.TranscribedData import TranscribedData
@dataclass_json
@dataclass
class TranscriptionResult:
"""Transcription result"""
transcribed_data: list[TranscribedData]
detected_language: str
+57 -52
View File
@@ -2,11 +2,16 @@
import sys
import torch
import whisperx
from torch.cuda import OutOfMemoryError
from modules.Speech_Recognition.TranscriptionResult import TranscriptionResult
from modules.console_colors import ULTRASINGER_HEAD, blue_highlighted, red_highlighted
from modules.Speech_Recognition.TranscribedData import TranscribedData
from modules.Speech_Recognition.TranscribedData import TranscribedData, from_whisper
MEMORY_ERROR_MESSAGE = f"{ULTRASINGER_HEAD} {blue_highlighted('whisper')} ran out of GPU memory; reduce --whisper_batch_size or force usage of cpu with --force_cpu"
def transcribe_with_whisper(
@@ -17,7 +22,7 @@ def transcribe_with_whisper(
batch_size: int = 16,
compute_type: str = None,
language: str = None,
) -> (list[TranscribedData], str):
) -> TranscriptionResult:
"""Transcribe with whisper"""
# Info: Regardless of the audio sampling rate used in the original audio file, whisper resample the audio signal to 16kHz (via ffmpeg). So the standard input from (44.1 or 48 kHz) should work.
@@ -32,9 +37,50 @@ def transcribe_with_whisper(
compute_type = "float16" if device == "cuda" else "int8"
try:
torch.cuda.empty_cache()
loaded_whisper_model = whisperx.load_model(
model, language=language, device=device, compute_type=compute_type
)
audio = whisperx.load_audio(audio_path)
print(f"{ULTRASINGER_HEAD} Transcribing {audio_path}")
result = loaded_whisper_model.transcribe(
audio, batch_size=batch_size, language=language
)
detected_language = result["language"]
if language is None:
language = detected_language
# load alignment model and metadata
try:
model_a, metadata = whisperx.load_align_model(
language_code=language, device=device, model_name=model_name
)
except ValueError as ve:
print(
f"{red_highlighted(f'{ve}')}"
f"\n"
f"{ULTRASINGER_HEAD} {red_highlighted('Error:')} Unknown language. "
f"Try add it with --align_model [huggingface]."
)
raise ve
# align whisper output
result_aligned = whisperx.align(
result["segments"],
model_a,
metadata,
audio,
device,
return_char_alignments=False,
)
transcribed_data = convert_to_transcribed_data(result_aligned)
return TranscriptionResult(transcribed_data, detected_language)
except ValueError as value_error:
if (
"Requested float16 compute type, but the target device or backend do not support efficient float16 computation."
@@ -44,68 +90,27 @@ def transcribe_with_whisper(
print(
f"{ULTRASINGER_HEAD} Your GPU does not support efficient float16 computation; run UltraSinger with '--whisper_compute_type int8'"
)
sys.exit(1)
raise value_error
except OutOfMemoryError as oom_exception:
print(oom_exception)
print(
f"{ULTRASINGER_HEAD} {blue_highlighted('whisper')} ran out of GPU memory; reduce --whisper_batch_size or force usage of cpu with --force_cpu"
)
sys.exit(1)
audio = whisperx.load_audio(audio_path)
print(f"{ULTRASINGER_HEAD} Transcribing {audio_path}")
result = loaded_whisper_model.transcribe(
audio, batch_size=batch_size, language=language
)
detected_language = result["language"]
if language is None:
language = detected_language
# load alignment model and metadata
try:
model_a, metadata = whisperx.load_align_model(
language_code=language, device=device, model_name=model_name
)
except ValueError as ve:
print(
f"{red_highlighted(f'{ve}')}"
f"\n"
f"{ULTRASINGER_HEAD} {red_highlighted('Error:')} Unknown language. "
f"Try add it with --align_model [huggingface]."
)
sys.exit(1)
# align whisper output
result_aligned = whisperx.align(
result["segments"],
model_a,
metadata,
audio,
device,
return_char_alignments=False,
)
transcribed_data = convert_to_transcribed_data(result_aligned)
return transcribed_data, detected_language
print(MEMORY_ERROR_MESSAGE)
raise oom_exception
except Exception as exception:
if "CUDA failed with error out of memory" in str(exception.args[0]):
print(exception)
print(MEMORY_ERROR_MESSAGE)
raise exception
def convert_to_transcribed_data(result_aligned):
transcribed_data = []
for segment in result_aligned["segments"]:
for obj in segment["words"]:
vtd = TranscribedData(obj) # create custom Word object
vtd = from_whisper(obj) # create custom Word object
vtd.word = vtd.word + " " # add space to end of word
if len(obj) < 4:
previous = transcribed_data[-1]
if not previous:
previous.end = 0
previous.end = ""
previous = transcribed_data[-1] if len(transcribed_data) != 0 else TranscribedData()
vtd.start = previous.end + 0.1
vtd.end = previous.end + 0.2
msg = f'Error: There is no timestamp for word: "{obj["word"]}". ' \
+9 -14
View File
@@ -48,30 +48,25 @@ def ultrastar_note_to_midi_note(ultrastar_note: int) -> int:
return midi_note
def get_start_time_from_ultrastar(ultrastar_class: UltrastarTxtValue, pos: int) -> float:
def get_start_time_from_ultrastar(
ultrastar_class: UltrastarTxtValue, pos: int
) -> float:
"""Calculates the start time from the Ultrastar txt"""
gap = int(ultrastar_class.gap) / 1000
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
)
gap = int(float(ultrastar_class.gap.replace(",", ".")) / 1000)
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: UltrastarTxtValue, pos: int) -> float:
"""Calculates the end time from the Ultrastar txt"""
gap = int(ultrastar_class.gap) / 1000
real_bpm = ultrastar_bpm_to_real_bpm(
float(ultrastar_class.bpm.replace(",", "."))
)
gap = int(float(ultrastar_class.gap.replace(",", ".")) / 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]),
int(ultrastar_class.startBeat[pos]) + int(ultrastar_class.durations[pos]),
real_bpm,
)
+ gap
+20 -3
View File
@@ -5,7 +5,13 @@ from modules.Ultrastar.ultrastar_converter import (
get_end_time_from_ultrastar,
get_start_time_from_ultrastar,
)
from modules.Ultrastar.ultrastar_txt import UltrastarTxtValue, UltrastarTxtTag, UltrastarTxtNoteTypeTag, FILE_ENCODING
from modules.Ultrastar.ultrastar_txt import (
UltrastarTxtValue,
UltrastarTxtTag,
UltrastarTxtNoteTypeTag,
FILE_ENCODING,
)
def parse_ultrastar_txt(input_file: str) -> UltrastarTxtValue:
"""Parse ultrastar txt file to UltrastarTxt class"""
@@ -35,12 +41,23 @@ def parse_ultrastar_txt(input_file: str) -> UltrastarTxtValue:
ultrastar_class.gap = line.split(":")[1].replace("\n", "")
elif line.startswith(f"#{UltrastarTxtTag.BPM}"):
ultrastar_class.bpm = line.split(":")[1].replace("\n", "")
elif line.startswith((
elif line.startswith(f"#{UltrastarTxtTag.VIDEO}"):
ultrastar_class.video = line.split(":")[1].replace("\n", "")
elif line.startswith(f"#{UltrastarTxtTag.VIDEOGAP}"):
ultrastar_class.videoGap = line.split(":")[1].replace("\n", "")
elif line.startswith(f"#{UltrastarTxtTag.COVER}"):
ultrastar_class.cover = line.split(":")[1].replace("\n", "")
elif line.startswith(f"#{UltrastarTxtTag.BACKGROUND}"):
ultrastar_class.background = line.split(":")[1].replace("\n", "")
elif line.startswith(
(
f"{UltrastarTxtNoteTypeTag.FREESTYLE} ",
f"{UltrastarTxtNoteTypeTag.NORMAL} ",
f"{UltrastarTxtNoteTypeTag.GOLDEN} ",
f"{UltrastarTxtNoteTypeTag.RAP} ",
f"{UltrastarTxtNoteTypeTag.RAP_GOLDEN} ")):
f"{UltrastarTxtNoteTypeTag.RAP_GOLDEN} ",
)
):
parts = line.split()
# [0] F : * R G
# [1] start beat
@@ -1,4 +1,7 @@
"""Ultrastar score calculator."""
from dataclasses import dataclass
from dataclasses_json import dataclass_json
import librosa
@@ -48,6 +51,8 @@ def add_point(note_type: str, points: Points) -> Points:
return points
@dataclass_json
@dataclass
class Score:
"""Docstring"""
+4 -2
View File
@@ -19,9 +19,11 @@ class UltrastarTxtTag(str, Enum):
GENRE = 'GENRE' # Multi-language support since v1.1.0
YEAR = 'YEAR' # Multi-language support since v1.1.0
COVER = 'COVER' # Path to cover. Should end with `*[CO].jpg`
BACKGROUND = 'BACKGROUND' # Path to background. Is shown when there is no video. Should end with `*[BG].jpg`
CREATOR = 'CREATOR' # Multi-language support since v1.1.0
COMMENT = 'COMMENT'
VIDEO = 'VIDEO'
VIDEOGAP = 'VIDEOGAP'
FILE_END = 'E'
LINEBREAK = '-'
@@ -32,8 +34,6 @@ class UltrastarTxtTag(str, Enum):
TAGS = 'TAGS' # Tags for the song. Can be used for filtering
# Unused 0.2.0
BACKGROUND = 'BACKGROUND' # Path to background. Is shown when there is no video. Should end with `*[BG].jpg`
VIDEOGAP = 'VIDEOGAP'
EDITION = 'EDITION' # Multi-language support since v1.1.0
START = 'START'
END = 'END'
@@ -84,10 +84,12 @@ class UltrastarTxtValue:
mp3 = ""
audio = ""
video = None
videoGap = None
gap = ""
bpm = ""
language = None
cover = None
background = None
vocals = None
instrumental = None
tags = None
+6 -1
View File
@@ -99,6 +99,8 @@ def create_ultrastar_txt_from_automation(
file.write(f"#{UltrastarTxtTag.GENRE}:{ultrastar_class.genre}\n")
if ultrastar_class.cover is not None:
file.write(f"#{UltrastarTxtTag.COVER}:{ultrastar_class.cover}\n")
if ultrastar_class.background is not None:
file.write(f"#{UltrastarTxtTag.BACKGROUND}:{ultrastar_class.background}\n")
file.write(f"#{UltrastarTxtTag.MP3}:{ultrastar_class.mp3}\n")
if version.parse(ultrastar_class.version) >= version.parse("1.1.0"):
file.write(f"#{UltrastarTxtTag.AUDIO}:{ultrastar_class.audio}\n")
@@ -108,7 +110,10 @@ def create_ultrastar_txt_from_automation(
file.write(f"#{UltrastarTxtTag.INSTRUMENTAL}:{ultrastar_class.instrumental}\n")
if ultrastar_class.tags is not None:
file.write(f"#{UltrastarTxtTag.TAGS}:{ultrastar_class.tags}\n")
file.write(f"#{UltrastarTxtTag.VIDEO}:{ultrastar_class.video}\n")
if ultrastar_class.video is not None:
file.write(f"#{UltrastarTxtTag.VIDEO}:{ultrastar_class.video}\n")
if ultrastar_class.videoGap is not None:
file.write(f"#{UltrastarTxtTag.VIDEOGAP}:{ultrastar_class.videoGap}\n")
file.write(f"#{UltrastarTxtTag.BPM}:{round(ultrastar_bpm, 2)}\n") # not the real BPM!
file.write(f"#{UltrastarTxtTag.GAP}:{int(gap * 1000)}\n")
file.write(f"#{UltrastarTxtTag.CREATOR}:{ultrastar_class.creator}\n")
+6
View File
@@ -8,6 +8,11 @@ def blue_highlighted(text: str) -> str:
return f"{Bcolors.blue}{text}{Bcolors.endc}"
def green_highlighted(text: str) -> str:
"""Returns a blue highlighted text"""
return f"{Bcolors.dark_green}{text}{Bcolors.endc}"
def gold_highlighted(text: str) -> str:
"""Returns a gold highlighted text"""
return f"{Bcolors.gold}{text}{Bcolors.endc}"
@@ -37,6 +42,7 @@ class Bcolors:
"""Colors for the console"""
blue = "\033[94m"
dark_green = "\033[32m"
red = "\033[91m"
light_blue = "\033[96m"
cyan = "\033[36m"
+1 -1
View File
@@ -20,7 +20,7 @@ def export_transcribed_data_to_csv(transcribed_data: list[TranscribedData], file
data.word,
data.start,
data.end,
data.conf,
data.confidence,
]
)