speech-scoring/tts_samplegen.py

233 lines
7.2 KiB
Python
Raw Normal View History

2017-10-04 12:21:24 +00:00
import objc
2017-10-25 08:06:41 +00:00
from AppKit import NSSpeechSynthesizer, NSSpeechInputModeProperty
from AppKit import NSSpeechModePhoneme
from Foundation import NSURL
2017-10-04 12:21:24 +00:00
import json
import random
2017-10-04 12:21:24 +00:00
import os
import re
import subprocess
2017-10-26 09:57:22 +00:00
import progressbar
2017-10-04 12:21:24 +00:00
2017-10-27 13:23:22 +00:00
from generate_similar import similar_phonemes,similar_word
2017-10-26 12:36:14 +00:00
2017-10-26 09:57:22 +00:00
OUTPUT_NAME = 'story_sents'
2017-10-25 08:06:41 +00:00
dest_dir = os.path.abspath('.') + '/outputs/' + OUTPUT_NAME + '/'
dest_file = './outputs/' + OUTPUT_NAME + '.csv'
2017-10-26 09:57:22 +00:00
def prog_bar(title):
2017-10-26 12:36:14 +00:00
widgets = [title, progressbar.Counter(), 'th entry - ', progressbar.FormatLabel(
2017-10-26 10:48:17 +00:00
''), ' [', progressbar.Bar(), '] - ', progressbar.ETA()]
2017-10-26 09:57:22 +00:00
prog = progressbar.ProgressBar(widgets=widgets)
def update_prog(current):
2017-10-26 10:48:17 +00:00
widgets[3] = progressbar.FormatLabel(current)
2017-10-26 09:57:22 +00:00
prog.update()
return (update_prog, prog)
def create_dir(direc):
2017-10-05 11:24:41 +00:00
if not os.path.exists(direc):
2017-10-26 09:57:22 +00:00
os.makedirs(direc)
2017-10-04 12:21:24 +00:00
2017-10-25 08:06:41 +00:00
2017-10-26 09:57:22 +00:00
def dest_filename(w, v, r, t):
return '{}-{}-{}-{}-{}.aiff'.format(w, v, r, t, str(random.randint(0, 10000)))
2017-10-25 08:06:41 +00:00
def dest_path(v, r, n):
2017-10-26 10:28:25 +00:00
rel = v + '/' + str(r) + '/' + n
2017-10-26 10:48:17 +00:00
return (dest_dir + rel), rel
2017-10-25 08:06:41 +00:00
def cli_gen_audio(speech_cmd, rate, voice, out_path):
subprocess.call(
['say', '-v', voice, '-r',
str(rate), '-o', out_path, speech_cmd])
class SynthFile(object):
"""docstring for SynthFile."""
2017-10-25 08:06:41 +00:00
2017-10-26 12:36:14 +00:00
def __init__(self, word, phon, filename, voice, voice_lang, rate, operation):
super(SynthFile, self).__init__()
self.word = word
self.phoneme = phon
self.filename = filename
self.voice = voice
2017-10-26 12:36:14 +00:00
self.voice_lang = voice_lang
self.rate = rate
self.variant = operation
2017-10-04 12:21:24 +00:00
def get_json(self):
2017-10-25 08:06:41 +00:00
return {
'filename': self.filename,
'voice': self.voice,
'rate': self.rate,
'operation': self.operation
}
def get_csv(self):
2017-10-26 12:36:14 +00:00
cols = [self.word, self.phoneme, self.voice,
self.voice_lang, self.rate, self.variant,
self.filename]
return ','.join([str(c) for c in cols])+'\n'
2017-10-25 08:06:41 +00:00
class SynthVariant(object):
"""docstring for SynthVariant."""
2017-10-25 08:06:41 +00:00
2017-10-26 09:57:22 +00:00
def __init__(self, identifier, voice, lang, rate):
super(SynthVariant, self).__init__()
self.synth = NSSpeechSynthesizer.alloc().initWithVoice_(identifier)
self.synth.setVolume_(100)
self.synth.setRate_(rate)
2017-10-25 08:06:41 +00:00
self.phone_synth = NSSpeechSynthesizer.alloc().initWithVoice_(
identifier)
self.phone_synth.setVolume_(100)
self.phone_synth.setRate_(rate)
2017-10-25 08:06:41 +00:00
self.phone_synth.setObject_forProperty_error_(
NSSpeechModePhoneme, NSSpeechInputModeProperty, None)
self.identifier = identifier
self.rate = rate
2017-10-26 09:57:22 +00:00
self.name = voice
self.lang = lang
self.phoneme_capable = self.is_phoneme_capable()
2017-10-26 12:36:14 +00:00
if self.phoneme_capable:
create_dir(dest_dir + self.name + '/' + str(self.rate))
def __repr__(self):
2017-10-26 09:57:22 +00:00
return 'Synthesizer[{} - {}]'.format(self.name, self.rate)
def is_phoneme_capable(self):
orig_phon = self.synth.phonemesFromText_('water')
return orig_phon != ''
2017-10-25 08:06:41 +00:00
def generate_audio(self, word, variant):
orig_phon, phoneme, phon_cmd = self.synth.phonemesFromText_(
word), '', word
if variant == 'low':
# self.synth.startSpeakingString_toURL_(word,d_url)
phoneme = orig_phon
elif variant == 'medium':
2017-10-27 13:23:22 +00:00
phoneme = similar_phoneme(orig_phon)
2017-10-25 08:06:41 +00:00
phon_cmd = '[[inpt PHON]] ' + phoneme
elif variant == 'high':
2017-10-27 13:23:22 +00:00
phoneme = similar_word(word)
phon_cmd = phoneme
# elif variant == 'long':
2017-10-25 08:06:41 +00:00
# if phon != '':
# self.phone_synth.startSpeakingString_toURL_(phon,d_url)
# else:
# self.synth.startSpeakingString_toURL_(word,d_url)
2017-10-26 09:57:22 +00:00
fname = dest_filename(word, self.name, self.rate, variant)
2017-10-26 10:28:25 +00:00
d_path, r_path = dest_path(self.name, self.rate, fname)
2017-10-25 08:06:41 +00:00
# d_url = NSURL.fileURLWithPath_(d_path)
cli_gen_audio(phon_cmd, self.rate, self.name, d_path)
2017-10-26 12:36:14 +00:00
return SynthFile(word, phoneme, r_path, self.name, self.lang, self.rate, variant)
2017-10-27 13:23:22 +00:00
@staticmethod
def voices_for_lang(lang):
voices_installed = NSSpeechSynthesizer.availableVoices()
voice_attrs = [
NSSpeechSynthesizer.attributesForVoice_(v) for v in voices_installed
]
# sk = [k for k in voice_attrs[0].keys() if k not in [
# 'VoiceIndividuallySpokenCharacters', 'VoiceSupportedCharacters']]
# s_attrs = [[v[i] for i in sk] for v in voice_attrs if 'VoiceShowInFullListOnly' in v
# and 'VoiceRelativeDesirability' in v]
return [
(v['VoiceIdentifier'],
v['VoiceName'],
v['VoiceLanguage']) for v in voice_attrs
if v['VoiceLanguage'] == lang
and v['VoiceGender'] != 'VoiceGenderNeuter'
]
@classmethod
def synth_with(cls,voice_params,rate=180):
identifier,voice,lang = voice_params
return cls(identifier,voice,lang,rate)
def synth_generator():
2017-10-27 13:23:22 +00:00
us_voices_ids = SynthVariant.voices_for_lang('en-US')
2017-10-25 08:06:41 +00:00
voice_rates = [150, 180, 210, 250]
voice_synths = []
create_dir(dest_dir)
2017-10-27 13:23:22 +00:00
for vp in us_voices_ids:
for r in voice_rates:
2017-10-27 13:23:22 +00:00
s = SynthVariant.synth_with(vp,r)
if s.phoneme_capable:
print('Adding ', s)
voice_synths.append(s)
else:
print('Discarding phoneme incapable ', s)
2017-10-25 08:06:41 +00:00
2017-10-26 10:28:25 +00:00
def synth_for_words(words, writer):
2017-10-26 10:48:17 +00:00
prog_title = "Synthesizing {} words : ".format(len(words))
2017-10-26 09:57:22 +00:00
(update, prog) = prog_bar(prog_title)
for w in prog(words):
for s in voice_synths:
2017-10-25 08:06:41 +00:00
for v in ['low', 'medium', 'high']:
2017-10-26 09:57:22 +00:00
update('"{}" with {} variant ({})'.format(w, s, v))
2017-10-26 10:28:25 +00:00
synthed = s.generate_audio(w, v)
writer(synthed)
return synth_for_words
2017-10-25 08:06:41 +00:00
def write_synths(synth_list, fname, csv=False):
f = open(fname, 'w')
if csv:
for s in synth_list:
f.write(s.get_csv())
else:
2017-10-25 08:06:41 +00:00
json.dump([s.get_json() for s in synth_list], f)
f.close()
2017-10-04 12:21:24 +00:00
2017-10-25 08:06:41 +00:00
2017-10-26 10:28:25 +00:00
def synth_logger(fname, csv=False):
f = open(fname, 'w')
def csv_writer(s):
f.write(s.get_csv())
synth_list = []
def json_writer(s):
synth_list.append(s)
def close_file():
if csv:
f.close()
else:
json.dump([s.get_json() for s in synth_list], f)
f.close()
if csv:
return csv_writer, close_file
else:
return json_writer, close_file
2017-10-04 12:21:24 +00:00
def generate_audio_for_stories():
2017-10-27 13:23:22 +00:00
story_file = './inputs/all_stories_hs.json'
# story_file = './inputs/all_stories.json'
2017-10-26 09:57:22 +00:00
stories_data = json.load(open(story_file))
2017-10-27 13:23:22 +00:00
word_list = [t[0] for i in stories_data.values() for t in i]
# word_list = [i for g in stories_data.values() for i in g]
2017-10-26 10:28:25 +00:00
(writer, closer) = synth_logger(dest_file, csv=True)
synth_for_words = synth_generator()
try:
synth_for_words(word_list, writer)
except:
import traceback
import sys
traceback.print_exc(file=sys.stdout)
pass
closer()
2017-10-04 12:21:24 +00:00
2017-10-26 12:36:14 +00:00
if __name__ == '__main__':
generate_audio_for_stories()