Adapt whisper

This commit is contained in:
Vadim committed 2023-02-04 01:12:52 +01:00
1 parent 7c4d1fcb89
commit 3ba96ffae2
9 files changed
+135 -86

No files matched your search

+43 -20
View File
@@ -20,60 +20,58 @@ You need FFmpeg installed.
_Not all options working now!_
```commandline
this.py [opt] [mode] [rec model] [pitcher] [extra]
UltraSinger.py [opt] [mode] [transcription] [rec model] [pitcher] [extra]
[opt]
-h This help text.
-i Ultrastar.txt
audio like .mp3, .wav, youtube link
-o Output folder
[mode]
## INPUT is audio ##
-a Is default
Creates all
default Creates all
(-u Create ultrastar txt file) # In Progress
(-m Create midi file) # In Progress
(-s Create sheet file) # In Progress
## INPUT is ultrastar.txt ##
-a Is default
Creates all
default Creates 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)
(-m Create midi file) # In Progress
[transcription]
--whisper (default) tiny|base|small|medium|large
--vosk Needs model
[rec model]
-v vosk model path
(-k Keep audio chunks) # In Progress
[extra]
(-k Keep audio chunks) # In Progress
-k Keep audio chunks
[pitcher]
-crepe default
--crepe_model tiny|small|medium|large|full
--crepe (default) tiny|small|medium|large|full
'''
```
### Input
#### Audio
For audio it uses Vosk transcription model. This model is not included. You can download it here [Link](https://alphacephei.com/vosk/models).
Make sure you take the right language. Also consider that a bigger model is more accurate, but also takes longer to transcribe.
For the first test run, use the `small model`, to be accurate use the `gigaspeech model`
##### Local file
```commandline
-i "input/music.mp3" -v "models\vosk-model-en-us-0.42-gigaspeech"
-i "input/music.mp3"
```
##### Youtube
```commandline
-i https://www.youtube.com/watch?v=BaW_jenozKc -v "models\vosk-model-en-us-0.42-gigaspeech"
-i https://www.youtube.com/watch?v=BaW_jenozKc
```
#### UltraStar
@@ -84,13 +82,38 @@ This re-pitch the audio and creates a new txt file.
-i "input/ultrastar.txt"
```
### Transcriber
For transcription, `whisper` is used by default. It is more accurate than the other even with the `tiny` model.
And it finds the language automatically.
But anyway, it depends! Try the other one if `Whisper` does not suit you.
Also keep in mind that while a larger model is more accurate, it also takes longer to transcribe.
#### Whisper
For the first test run, use the `tiny`, to be accurate use the `large` model
```commandline
-i XYZ --whisper large
```
#### Vosk
If you want to use `Vosk` than you need the model. It is not included. You can download it here [Link](https://alphacephei.com/vosk/models).
Make sure you take the right language.
For the first test run, use the `small model`, to be accurate use the `gigaspeech` model
```commandline
-i "input/music.mp3" -v "models\vosk-model-en-us-0.42-gigaspeech"
```
### Pitcher
Pitching is done with the crepe model.
Pitching is done with the `crepe` model.
Also consider that a bigger model is more accurate, but also takes longer to pitch.
For just testing you should use `tiny`, which is currently default.
If you want solid accurate, then use the `full` model.
```commandline
-i XYZ --crepe_model full
-i XYZ --crepe full
```
+13 -3
View File
@@ -5,11 +5,21 @@ class Settings:
input_file_path = ''
output_file_path = ''
audio_chunk_folder_name = 'audio-chunks'
vosk_model_path = '' # "models/vosk-model-small-en-us-0.15"
mono_audio_path = ''
crepe_model_capacity = 'tiny' # tiny|small|medium|large|full
# Transcribe
audio_chunk_folder_name = 'audio-chunks'
# Whisper
transcriber = 'whisper' # whisper|vosk
whisper_model = 'tiny' # Multilingual model tiny|base|small|medium|large
# English-only model tiny.en|base.en|small.en|medium.en
#Vosk
vosk_model_path = '' # "models/vosk-model-small-en-us-0.15"
# Pitch
crepe_model_capacity = 'tiny' # tiny|small|medium|large|full
crepe_step_size = 10
+36 -28
View File
@@ -19,7 +19,7 @@ from matplotlib import pyplot as plt
from collections import Counter
from Settings import Settings
from moduls.Audio.youtube import download_youtube_video, download_youtube_audio, get_youtube_title
from moduls.Speech_Recognition.Whisper import transcribe
from moduls.Speech_Recognition.Whisper import transcribe_with_whisper
settings = Settings()
@@ -148,39 +148,41 @@ def correct_words(recognized_words, word_list_file):
def print_help():
m = '''
UltraSinger.py [opt] [mode] [rec model] [pitcher] [extra]
UltraSinger.py [opt] [mode] [transcription] [rec model] [pitcher] [extra]
[opt]
-h This help text.
-i Ultrastar.txt
audio like .mp3, .wav, youtube link
-o Output folder
[mode]
## INPUT is audio ##
-a Is default
Creates all
-u Create ultrastar txt file
-m Create midi file
-s Create sheet file
default Creates all
(-u Create ultrastar txt file) # In Progress
(-m Create midi file) # In Progress
(-s Create sheet file) # In Progress
## INPUT is ultrastar.txt ##
-a Is default
Creates all
-r repitch Ultrastar.txt (input has to be audio)
-p Check pitch of Ultrastar.txt input
-m Create midi file
default Creates 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]
--whisper (default) tiny|base|small|medium|large
--vosk Needs model
[rec model]
-v vosk model path
(-k Keep audio chunks) # In Progress
[extra]
-k Keep audio chunks
[pitcher]
-crepe default
--crepe (default) tiny|small|medium|large|full
'''
print(m)
@@ -273,15 +275,17 @@ def do_audio_stuff():
convert_audio_to_mono_wav(ultrastar_audio_input_path, settings.mono_audio_path)
# Audio transcription
v = transcribe(settings.mono_audio_path)
vosk_transcribed_data = transcribe_with_vosk(settings.mono_audio_path, settings.vosk_model_path)
if settings.transcriber == "whisper":
transcribed_data = transcribe_with_whisper(settings.mono_audio_path, settings.whisper_model)
else: # vosk
transcribed_data = transcribe_with_vosk(settings.mono_audio_path, settings.vosk_model_path)
if settings.create_audio_chunks:
audio_chunks_path = cache_path + '/' + settings.audio_chunk_folder_name
create_folder(audio_chunks_path)
csv_filename = audio_chunks_path + "/_chunks.csv"
export_chunks_from_vosk_data(settings.mono_audio_path, vosk_transcribed_data, audio_chunks_path)
export_vosk_data_to_csv(vosk_transcribed_data, csv_filename)
export_chunks_from_vosk_data(settings.mono_audio_path, transcribed_data, audio_chunks_path)
export_vosk_data_to_csv(transcribed_data, csv_filename)
# todo: do we need to correct words?
# lyric = 'input/faber_lyric.txt'
@@ -295,20 +299,20 @@ def do_audio_stuff():
start_times = []
end_times = []
for i in range(len(vosk_transcribed_data)):
start_times.append(vosk_transcribed_data[i].start)
end_times.append(vosk_transcribed_data[i].end)
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)
ultrastar_note_numbers = convert_ultrastar_note_numbers(midi_notes)
if settings.create_plot:
plot(ultrastar_audio_input_path, vosk_transcribed_data, midi_notes)
plot(ultrastar_audio_input_path, transcribed_data, midi_notes)
# Ultrastar txt creation
real_bpm = get_bpm_from_file(ultrastar_audio_input_path)
ultrastar_file_output = song_output + '/' + basename_without_ext + '.txt'
ultrastar_writer.create_txt_from_transcription(vosk_transcribed_data, ultrastar_note_numbers, ultrastar_file_output,
ultrastar_writer.create_txt_from_transcription(transcribed_data, ultrastar_note_numbers, ultrastar_file_output,
basename_without_ext, real_bpm)
if settings.create_midi:
@@ -320,7 +324,7 @@ def do_audio_stuff():
def main(argv):
short = "hi:o:amv:"
long = ["ifile=", "ofile=", "crepe_model="]
long = ["ifile=", "ofile=", "crepe_model=", "vosk=", "whisper="]
opts, args = getopt.getopt(argv, short, long)
@@ -336,9 +340,13 @@ def main(argv):
settings.input_file_path = arg
elif opt in ("-o", "--ofile"):
settings.output_file_path = arg
elif opt in ("-v"):
elif opt in ("--whisper"):
settings.transcriber = "whisper"
settings.whisper_model = arg
elif opt in ("--vosk"):
settings.transcriber = 'vosk'
settings.vosk_model_path = arg
elif opt in ("--crepe_model"):
elif opt in ("--crepe"):
settings.crepe_model_capacity = arg
if settings.output_file_path == '':
-3
View File
@@ -12,9 +12,6 @@ from pydub import AudioSegment
def convert_audio_to_mono_wav(input_file, output_file):
"""Convert audio to mono wav"""
# Fixme: ffmpeg path in settings
AudioSegment.converter = 'C:\\Users\\vadim.rangnau\\Desktop\\Projekts\\UltraSinger\\bin\\ffmpeg.exe'
if '.mp3' in input_file:
sound = AudioSegment.from_mp3(input_file)
elif '.wav' in input_file:
@@ -0,0 +1,11 @@
class TranscribedData:
""" 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))
# Vosk = word, Whisper = text
self.word = transcribed_json.get("word", transcribed_json.get("text", None))
self.end = transcribed_json["end"]
self.start = transcribed_json["start"]
+2 -2
View File
@@ -3,7 +3,7 @@ import json
import csv
from vosk import Model, KaldiRecognizer
from moduls.Speech_Recognition.VoskTranscribedData import VoskTranscribedData
from moduls.Speech_Recognition.TranscribedData import TranscribedData
from moduls.Audio.vocal_chunks import remove_silence_from_vosk_data
@@ -56,7 +56,7 @@ def transcribe_with_vosk(audio_filename, model_path):
# {'text': ''}
continue
for obj in sentence['result']:
vtd = VoskTranscribedData(obj) # create custom Word object
vtd = TranscribedData(obj) # create custom Word object
vosk_transcribed_data.append(vtd) # and add it to list
# Todo: remove silent part from each word
@@ -1,23 +0,0 @@
class VoskTranscribedData:
""" A class representing a word from the JSON format for vosk speech recognition API """
# Code from here: https://towardsdatascience.com/speech-recognition-with-timestamps-934ede4234b2
def __init__(self, dict):
'''
Parameters:
dict (dict) dictionary from JSON, containing:
conf (float): degree of confidence, from 0 to 1
end (float): end time of the pronouncing the word, in seconds
start (float): start time of the pronouncing the word, in seconds
word (str): recognized word
'''
self.conf = dict["conf"]
self.end = dict["end"]
self.start = dict["start"]
self.word = dict["word"]
def to_string(self):
''' Returns a string describing this instance '''
return "{:20} from {:.2f} sec to {:.2f} sec, confidence is {:.2f}%".format(
self.word, self.start, self.end, self.conf*100)
+29 -6
View File
@@ -1,12 +1,35 @@
import whisper_timestamped as whisper
import json
from moduls.Speech_Recognition.TranscribedData import TranscribedData
def transcribe(audio):
def transcribe_with_whisper(audio, model):
model = whisper.load_model(model, device="cpu")
# load audio and pad/trim it to fit 30 seconds
audio = whisper.load_audio(audio)
model = whisper.load_model("tiny", device="cpu")
result = whisper.transcribe(model, audio, language="en")
audio_30 = whisper.pad_or_trim(audio)
print(json.dumps(result, indent=2, ensure_ascii=False))
return json.dumps(result, indent=2, ensure_ascii=False)
# make log-Mel spectrogram and move to the same device as the model
mel = whisper.log_mel_spectrogram(audio_30).to(model.device)
# detect the spoken language
_, probs = model.detect_language(mel)
language = max(probs, key=probs.get)
print(f"Detected language: {language}")
results = whisper.transcribe(model, audio, language=language)
transcribed_data = []
for segment in results["segments"]:
# todo:
#if sentence != 'segments':
# continue
# to class
for obj in segment["words"]:
vtd = TranscribedData(obj) # create custom Word object
transcribed_data.append(vtd) # and add it to list
return transcribed_data
+1 -1
View File
@@ -7,6 +7,6 @@ scipy==1.10.0
vosk==0.3.45
tensorflow==2.11.0
matplotlib~=3.6.3
numpy~=1.22.4
numpy~=1.23.5
yt_dlp~=2023.1.6
git+https://github.com/linto-ai/whisper-timestamped