catiR
commited on
Commit
•
5c7029b
1
Parent(s):
e6c2cf8
queries only sentences at least 10 speakers
Browse files- README.md +1 -1
- human_data/SQL1adult10s_metadata.tsv +0 -0
- scripts/ctcalign.py +274 -0
- scripts/runSQ.py +221 -0
- scripts/tapi.py +69 -0
README.md
CHANGED
@@ -1,5 +1,5 @@
|
|
1 |
---
|
2 |
-
title:
|
3 |
emoji: ⚡
|
4 |
colorFrom: pink
|
5 |
colorTo: pink
|
|
|
1 |
---
|
2 |
+
title: Prosody clustering and evaluation
|
3 |
emoji: ⚡
|
4 |
colorFrom: pink
|
5 |
colorTo: pink
|
human_data/SQL1adult10s_metadata.tsv
ADDED
The diff for this file is too large to render.
See raw diff
|
|
scripts/ctcalign.py
ADDED
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
|
2 |
+
import torch
|
3 |
+
import numpy as np
|
4 |
+
import soundfile as sf
|
5 |
+
from dataclasses import dataclass
|
6 |
+
|
7 |
+
|
8 |
+
# read wav audio, make mono and 16khz if necessary
|
9 |
+
def wav16m(sound_path):
|
10 |
+
aud, sr = sf.read(sound_path, dtype=np.float32)
|
11 |
+
if len(aud.shape) == 2:
|
12 |
+
aud = aud.mean(1)
|
13 |
+
if sr != 16000:
|
14 |
+
alen = int(aud.shape[0] / sr * 16000)
|
15 |
+
aud = signal.resample(aud, alen)
|
16 |
+
return aud
|
17 |
+
|
18 |
+
|
19 |
+
def aligner(model_path,model_word_separator = '|', model_blank_token = '[PAD]'):
|
20 |
+
|
21 |
+
# build labels dict from a processor where it is not directly accessible
|
22 |
+
def get_processor_labels(processor,word_sep,max_labels=100):
|
23 |
+
ixs = sorted(list(range(max_labels)),reverse=True)
|
24 |
+
return {processor.tokenizer.decode(n) or word_sep:n for n in ixs}
|
25 |
+
|
26 |
+
#------------------------------------------
|
27 |
+
# setup wav2vec2
|
28 |
+
#------------------------------------------
|
29 |
+
|
30 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
31 |
+
torch.random.manual_seed(0)
|
32 |
+
max_labels = 100 # any reasonable number higher than vocab + extra + special tokens in any language used
|
33 |
+
|
34 |
+
|
35 |
+
model = Wav2Vec2ForCTC.from_pretrained(model_path).to(device)
|
36 |
+
processor = Wav2Vec2Processor.from_pretrained(model_path)
|
37 |
+
labels_dict = get_processor_labels(processor,model_word_separator)
|
38 |
+
blank_id = labels_dict[model_blank_token]
|
39 |
+
|
40 |
+
|
41 |
+
#convert frame-numbers to timestamps in seconds
|
42 |
+
# w2v2 step size is about 20ms, or 50 frames per second
|
43 |
+
def f2s(fr):
|
44 |
+
return fr/50
|
45 |
+
|
46 |
+
|
47 |
+
|
48 |
+
#------------------------------------------
|
49 |
+
# forced alignment with ctc decoder
|
50 |
+
# based on implementation of
|
51 |
+
# https://pytorch.org/audio/main/tutorials/forced_alignment_tutorial.html
|
52 |
+
#------------------------------------------
|
53 |
+
|
54 |
+
|
55 |
+
# return the label class probability of each audio frame
|
56 |
+
# wav is the wav data already read in, NOT the file path.
|
57 |
+
def get_frame_probs(wav):
|
58 |
+
with torch.inference_mode(): # similar to with torch.no_grad():
|
59 |
+
input_values = processor(wav,sampling_rate=16000).input_values[0]
|
60 |
+
input_values = torch.tensor(input_values, device=device).unsqueeze(0)
|
61 |
+
emits = model(input_values).logits
|
62 |
+
emits = torch.log_softmax(emits, dim=-1)
|
63 |
+
return emits[0].cpu().detach()
|
64 |
+
|
65 |
+
|
66 |
+
def get_trellis(emission, tokens, blank_id):
|
67 |
+
|
68 |
+
num_frame = emission.size(0)
|
69 |
+
num_tokens = len(tokens)
|
70 |
+
trellis = torch.empty((num_frame + 1, num_tokens + 1))
|
71 |
+
trellis[0, 0] = 0
|
72 |
+
trellis[1:, 0] = torch.cumsum(emission[:, 0], 0) # len of this slice of trellis is len of audio frames)
|
73 |
+
trellis[0, -num_tokens:] = -float("inf") # len of this slice of trellis is len of transcript tokens
|
74 |
+
trellis[-num_tokens:, 0] = float("inf")
|
75 |
+
for t in range(num_frame):
|
76 |
+
trellis[t + 1, 1:] = torch.maximum(
|
77 |
+
# Score for staying at the same token
|
78 |
+
trellis[t, 1:] + emission[t, blank_id],
|
79 |
+
# Score for changing to the next token
|
80 |
+
trellis[t, :-1] + emission[t, tokens],
|
81 |
+
)
|
82 |
+
return trellis
|
83 |
+
|
84 |
+
|
85 |
+
|
86 |
+
@dataclass
|
87 |
+
class Point:
|
88 |
+
token_index: int
|
89 |
+
time_index: int
|
90 |
+
score: float
|
91 |
+
|
92 |
+
@dataclass
|
93 |
+
class Segment:
|
94 |
+
label: str
|
95 |
+
start: int
|
96 |
+
end: int
|
97 |
+
score: float
|
98 |
+
|
99 |
+
@property
|
100 |
+
def mfaform(self):
|
101 |
+
return f"{f2s(self.start)},{f2s(self.end)},{self.label}"
|
102 |
+
|
103 |
+
@property
|
104 |
+
def length(self):
|
105 |
+
return self.end - self.start
|
106 |
+
|
107 |
+
|
108 |
+
|
109 |
+
def backtrack(trellis, emission, tokens, blank_id):
|
110 |
+
# Note:
|
111 |
+
# j and t are indices for trellis, which has extra dimensions
|
112 |
+
# for time and tokens at the beginning.
|
113 |
+
# When referring to time frame index `T` in trellis,
|
114 |
+
# the corresponding index in emission is `T-1`.
|
115 |
+
# Similarly, when referring to token index `J` in trellis,
|
116 |
+
# the corresponding index in transcript is `J-1`.
|
117 |
+
j = trellis.size(1) - 1
|
118 |
+
t_start = torch.argmax(trellis[:, j]).item()
|
119 |
+
|
120 |
+
path = []
|
121 |
+
for t in range(t_start, 0, -1):
|
122 |
+
# 1. Figure out if the current position was stay or change
|
123 |
+
# `emission[J-1]` is the emission at time frame `J` of trellis dimension.
|
124 |
+
# Score for token staying the same from time frame J-1 to T.
|
125 |
+
stayed = trellis[t - 1, j] + emission[t - 1, blank_id]
|
126 |
+
# Score for token changing from C-1 at T-1 to J at T.
|
127 |
+
changed = trellis[t - 1, j - 1] + emission[t - 1, tokens[j - 1]]
|
128 |
+
|
129 |
+
# 2. Store the path with frame-wise probability.
|
130 |
+
prob = emission[t - 1, tokens[j - 1] if changed > stayed else 0].exp().item()
|
131 |
+
# Return token index and time index in non-trellis coordinate.
|
132 |
+
path.append(Point(j - 1, t - 1, prob))
|
133 |
+
|
134 |
+
# 3. Update the token
|
135 |
+
if changed > stayed:
|
136 |
+
j -= 1
|
137 |
+
if j == 0:
|
138 |
+
break
|
139 |
+
else:
|
140 |
+
raise ValueError("Failed to align")
|
141 |
+
return path[::-1]
|
142 |
+
|
143 |
+
|
144 |
+
def merge_repeats(path,transcript):
|
145 |
+
i1, i2 = 0, 0
|
146 |
+
segments = []
|
147 |
+
while i1 < len(path):
|
148 |
+
while i2 < len(path) and path[i1].token_index == path[i2].token_index: # while both path steps point to the same token index
|
149 |
+
i2 += 1
|
150 |
+
score = sum(path[k].score for k in range(i1, i2)) / (i2 - i1)
|
151 |
+
segments.append( # when i2 finally switches to a different token,
|
152 |
+
Segment(
|
153 |
+
transcript[path[i1].token_index],# to the list of segments, append the token from i1
|
154 |
+
path[i1].time_index, # time of the first path-point of that token
|
155 |
+
path[i2 - 1].time_index + 1, # time of the final path-point for that token.
|
156 |
+
score,
|
157 |
+
)
|
158 |
+
)
|
159 |
+
i1 = i2
|
160 |
+
return segments
|
161 |
+
|
162 |
+
|
163 |
+
|
164 |
+
def merge_words(segments, separator):
|
165 |
+
words = []
|
166 |
+
i1, i2 = 0, 0
|
167 |
+
while i1 < len(segments):
|
168 |
+
if i2 >= len(segments) or segments[i2].label == separator:
|
169 |
+
if i1 != i2:
|
170 |
+
segs = segments[i1:i2]
|
171 |
+
word = "".join([seg.label for seg in segs])
|
172 |
+
score = sum(seg.score * seg.length for seg in segs) / sum(seg.length for seg in segs)
|
173 |
+
words.append(Segment(word, segments[i1].start, segments[i2 - 1].end, score))
|
174 |
+
i1 = i2 + 1
|
175 |
+
i2 = i1
|
176 |
+
else:
|
177 |
+
i2 += 1
|
178 |
+
return words
|
179 |
+
|
180 |
+
|
181 |
+
|
182 |
+
|
183 |
+
#------------------------------------------
|
184 |
+
# handle, i/o, etc.
|
185 |
+
#------------------------------------------
|
186 |
+
|
187 |
+
|
188 |
+
# generate mfa format for character (phone) and word alignments
|
189 |
+
# skip the word separator as it is not a phone
|
190 |
+
def mfalike(chars,wds,wsep):
|
191 |
+
hed = ['Begin,End,Label,Type,Speaker\n']
|
192 |
+
wlines = [f'{w.mfaform},words,000\n' for w in wds]
|
193 |
+
slines = [f'{ch.mfaform},phones,000\n' for ch in chars if ch.label != wsep]
|
194 |
+
return (''.join(hed+wlines+slines))
|
195 |
+
|
196 |
+
# generate basic exportable list format for character OR word alignments
|
197 |
+
# skip the word separator as it is not a phone
|
198 |
+
def basic(segs,wsep="|"):
|
199 |
+
return [[s.label,f2s(s.start),f2s(s.end)] for s in segs if s.label != wsep]
|
200 |
+
|
201 |
+
|
202 |
+
# generate numbered dicts to use in dtw
|
203 |
+
# alignment is given in numbered frames, not converted to timestamps
|
204 |
+
def fordtw(words,segments):
|
205 |
+
|
206 |
+
# index i, and word/seg, startframe, endframe
|
207 |
+
# preppend the index i to the word or seg
|
208 |
+
def _ix(i,elem):
|
209 |
+
return [f'{i:03d}__{elem.label}', elem.start, elem.end]
|
210 |
+
|
211 |
+
w_al = [_ix(i,wse) for i,wse in enumerate(words)] # from tuple to list
|
212 |
+
|
213 |
+
wsegdict = {}
|
214 |
+
for w,s,e in w_al:
|
215 |
+
nlett = len(w.split('__')[1])
|
216 |
+
wsegs = segments[:nlett]
|
217 |
+
wstart = s
|
218 |
+
wsegs = [_ix(i,cse) for i,cse in enumerate(wsegs)]
|
219 |
+
wsegs = [[seg, ss-s, se-s] for seg,ss,se in wsegs]
|
220 |
+
wsegdict[w] = wsegs
|
221 |
+
segments = segments[nlett:]
|
222 |
+
|
223 |
+
return w_al, wsegdict
|
224 |
+
|
225 |
+
|
226 |
+
# basic cleaning
|
227 |
+
# skip with is_normed=True
|
228 |
+
# if transcript was already normalised externally
|
229 |
+
def normalise_transcript(xcp):
|
230 |
+
xcp = xcp.lower()
|
231 |
+
xcp = xcp.replace('-','')
|
232 |
+
while ' ' in xcp:
|
233 |
+
xcp = xcp.replace(' ', ' ')
|
234 |
+
return xcp
|
235 |
+
|
236 |
+
|
237 |
+
# needs pad labels added to correctly time first segment
|
238 |
+
# and therefore add word sep character as placeholder in transcript
|
239 |
+
def prep_transcript(xcp,is_normed):
|
240 |
+
if not is_normed:
|
241 |
+
xcp = normalise_transcript(xcp)
|
242 |
+
xcp = xcp.replace(' ',model_word_separator)
|
243 |
+
label_ids = [labels_dict[c] for c in xcp]
|
244 |
+
label_ids = [blank_id] + label_ids + [blank_id]
|
245 |
+
xcp = f'{model_word_separator}{xcp}{model_word_separator}'
|
246 |
+
return xcp,label_ids
|
247 |
+
|
248 |
+
|
249 |
+
def _align(wav_data,transcript,is_normed=False):
|
250 |
+
|
251 |
+
norm_transcript,rec_label_ids = prep_transcript(transcript,is_normed)
|
252 |
+
emit = get_frame_probs(wav_data)
|
253 |
+
trellis = get_trellis(emit, rec_label_ids, blank_id)
|
254 |
+
path = backtrack(trellis, emit, rec_label_ids, blank_id)
|
255 |
+
|
256 |
+
segments = merge_repeats(path,norm_transcript)
|
257 |
+
words = merge_words(segments, model_word_separator)
|
258 |
+
|
259 |
+
#return fordtw(words,model_word_separator), basic(segments,model_word_separator)
|
260 |
+
return basic(words,model_word_separator)
|
261 |
+
|
262 |
+
return _align
|
263 |
+
|
264 |
+
|
265 |
+
# usage:
|
266 |
+
# from ctcalign import aligner, wav16m
|
267 |
+
# model_path ="/home/caitlinr/work/models/LVL/wav2vec2-large-xlsr-53-icelandic-ep10-1000h"
|
268 |
+
# model_word_sep = '|'
|
269 |
+
# model_blank_tk = '[PAD]'
|
270 |
+
# caligner = aligner(model_path,model_word_sep,model_blank_tk)
|
271 |
+
# word_aln, seg_aln = caligner(wav16m(wav_path),transcript_string)
|
272 |
+
|
273 |
+
|
274 |
+
|
scripts/runSQ.py
ADDED
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from ctcalign import aligner, wav16m
|
3 |
+
from tapi import tiro
|
4 |
+
|
5 |
+
# given a Sentence string,
|
6 |
+
# using a metadata file of SQ, // SQL1adult_metadata.tsv
|
7 |
+
# get every file from SQ of a L1 adult with that sentence
|
8 |
+
# report how many, or if 0.
|
9 |
+
|
10 |
+
|
11 |
+
def run():
|
12 |
+
sentence = 'hvaða sjúkdómar geta fylgt óbeinum reykingum'
|
13 |
+
voices = ['Alfur','Dilja','Karl', 'Dora']
|
14 |
+
# On tts.tiro.is speech marks are only available
|
15 |
+
# for the voices: Alfur, Dilja, Karl and Dora.
|
16 |
+
|
17 |
+
corpus_meta = 'human_data/SQL1adult_metadata.tsv'
|
18 |
+
speech_dir = 'human_data/audio/squeries/'
|
19 |
+
speech_aligns = 'human_data/aligns/squeries/'
|
20 |
+
speech_f0 = 'human_data/f0/squeries/'
|
21 |
+
align_model_path ="carlosdanielhernandezmena/wav2vec2-large-xlsr-53-icelandic-ep10-1000h"
|
22 |
+
|
23 |
+
tts_dir = 'tts_data/'
|
24 |
+
|
25 |
+
|
26 |
+
meta = get_recordings(sentence, corpus_meta)
|
27 |
+
if meta:
|
28 |
+
align_human(meta,speech_aligns,speech_dir,align_model_path)
|
29 |
+
f0_human(meta, speech_f0, speech_dir, 'TODO path to reaper')
|
30 |
+
if voices:
|
31 |
+
get_tts(sentence,voices,tts_dir)
|
32 |
+
f0_tts(sentence, voices, tts_dir, 'TODO path to reaper')
|
33 |
+
|
34 |
+
|
35 |
+
# find all the recordings of a given sentence
|
36 |
+
# listed in the corpus metadata.
|
37 |
+
# sentence should be provided lowercase without punctuation
|
38 |
+
def get_recordings(sentence, corpusdb):
|
39 |
+
with open(corpusdb,'r') as handle:
|
40 |
+
meta = handle.read().splitlines()
|
41 |
+
meta = [l.split('\t') for l in meta[1:]]
|
42 |
+
|
43 |
+
# column index 4 of db is normalised sentence text
|
44 |
+
smeta = [l for l in meta if l[4] == sentence]
|
45 |
+
|
46 |
+
if len(smeta) < 10:
|
47 |
+
if len(smeta) < 1:
|
48 |
+
print('This sentence does not exist in the corpus')
|
49 |
+
else:
|
50 |
+
print('Under 10 copies of the sentence: skipping.')
|
51 |
+
return []
|
52 |
+
else:
|
53 |
+
print(f'{len(smeta)} recordings of sentence <{sentence}>')
|
54 |
+
return smeta
|
55 |
+
|
56 |
+
|
57 |
+
|
58 |
+
# check if word alignments exist for a set of human speech recordings
|
59 |
+
# if not, warn, and make them with ctcalign.
|
60 |
+
def align_human(meta,align_dir,speech_dir,model_path):
|
61 |
+
|
62 |
+
model_word_sep = '|'
|
63 |
+
model_blank_tk = '[PAD]'
|
64 |
+
|
65 |
+
no_align = []
|
66 |
+
|
67 |
+
for rec in meta:
|
68 |
+
apath = align_dir + rec[2].replace('.wav','.tsv')
|
69 |
+
if not os.path.exists(apath):
|
70 |
+
no_align.append(rec)
|
71 |
+
|
72 |
+
if no_align:
|
73 |
+
print(f'Need to run alignment for {len(no_align)} files')
|
74 |
+
caligner = aligner(model_path,model_word_sep,model_blank_tk)
|
75 |
+
for rec in no_align:
|
76 |
+
wav_path = f'{speech_dir}{rec[1]}/{rec[2]}'
|
77 |
+
word_aln = caligner(wav16m(wav_path),rec[4],is_normed=True)
|
78 |
+
apath = align_dir + rec[2].replace('.wav','.tsv')
|
79 |
+
word_aln = [[str(x) for x in l] for l in word_aln]
|
80 |
+
with open(apath,'w') as handle:
|
81 |
+
handle.write(''.join(['\t'.join(l)+'\n' for l in word_aln]))
|
82 |
+
else:
|
83 |
+
print('All alignments existed')
|
84 |
+
|
85 |
+
|
86 |
+
|
87 |
+
# check if f0s exist for all of those files.
|
88 |
+
# if not, warn, and make them with TODO reaper
|
89 |
+
def f0_human(meta, f0_dir, speech_dir, reaper_path):
|
90 |
+
no_f0 = []
|
91 |
+
|
92 |
+
for rec in meta:
|
93 |
+
fpath = f0_dir + rec[2].replace('.wav','.f0')
|
94 |
+
if not os.path.exists(fpath):
|
95 |
+
no_f0.append(rec)
|
96 |
+
|
97 |
+
if no_f0:
|
98 |
+
print(f'Need to estimate pitch for {len(no_f0)} recordings')
|
99 |
+
#TODO
|
100 |
+
|
101 |
+
else:
|
102 |
+
print('All speech pitch trackings existed')
|
103 |
+
|
104 |
+
|
105 |
+
|
106 |
+
# # # # # # # # #
|
107 |
+
#################
|
108 |
+
# TODO
|
109 |
+
# IMPLEMENT GOOD 2 STEP PITCH ESTIMATION
|
110 |
+
# TODO
|
111 |
+
#################
|
112 |
+
# # # # # # # # #
|
113 |
+
|
114 |
+
|
115 |
+
|
116 |
+
|
117 |
+
# check if the TTS wavs + align jsons exist for this sentence
|
118 |
+
# if not, warn and make them with TAPI ******
|
119 |
+
def get_tts(sentence,voices,ttsdir):
|
120 |
+
|
121 |
+
# assume the first 64 chars of sentence are enough
|
122 |
+
dpath = sentence.replace(' ','_')[:65]
|
123 |
+
|
124 |
+
no_voice = []
|
125 |
+
|
126 |
+
for v in voices:
|
127 |
+
wpath = f'{ttsdir}{dpath}/{v}.wav'
|
128 |
+
jpath = f'{ttsdir}{dpath}/{v}.json'
|
129 |
+
if not (os.path.exists(wpath) and os.path.exists(jpath)):
|
130 |
+
no_voice.append(v)
|
131 |
+
|
132 |
+
if no_voice:
|
133 |
+
print(f'Need to generate TTS for {len(no_voice)} voices')
|
134 |
+
if not os.path.exists(f'{ttsdir}{dpath}'):
|
135 |
+
os.mkdir(f'{ttsdir}{dpath}')
|
136 |
+
for v in voices:
|
137 |
+
wf, af = tiro(sentence,v,save=f'{ttsdir}{dpath}/')
|
138 |
+
|
139 |
+
else:
|
140 |
+
print('TTS for all voices existed')
|
141 |
+
|
142 |
+
|
143 |
+
|
144 |
+
# check if the TTS f0s exist
|
145 |
+
# if not warn + make
|
146 |
+
# TODO collapse functions
|
147 |
+
def f0_tts(sentence, voices, ttsdir, reaper_path):
|
148 |
+
|
149 |
+
# assume the first 64 chars of sentence are enough
|
150 |
+
dpath = sentence.replace(' ','_')[:65]
|
151 |
+
|
152 |
+
no_f0 = []
|
153 |
+
|
154 |
+
for v in voices:
|
155 |
+
fpath = f'{ttsdir}{dpath}/{v}.f0'
|
156 |
+
if not os.path.exists(fpath):
|
157 |
+
no_f0.append(v)
|
158 |
+
|
159 |
+
if no_f0:
|
160 |
+
print(f'Need to estimate pitch for {len(no_f0)} voices')
|
161 |
+
#TODO
|
162 |
+
|
163 |
+
else:
|
164 |
+
print('All TTS pitch trackings existed')
|
165 |
+
|
166 |
+
|
167 |
+
|
168 |
+
|
169 |
+
|
170 |
+
|
171 |
+
run()
|
172 |
+
|
173 |
+
|
174 |
+
|
175 |
+
|
176 |
+
|
177 |
+
|
178 |
+
# https://colab.research.google.com/drive/1RApnJEocx3-mqdQC2h5SH8vucDkSlQYt?authuser=1#scrollTo=410ecd91fa29bc73
|
179 |
+
|
180 |
+
# CLUSTER the humans
|
181 |
+
# - read energy and pitch, to alignments
|
182 |
+
# - dtw based with selected chunking ? code should exist.
|
183 |
+
|
184 |
+
# ... experimental variants?
|
185 |
+
# ** 1 dimension at a time vs 2 on top of each other
|
186 |
+
# ** 25 points resampling (euclidean, kmeans, i guess....) vs all points dtw kmediods
|
187 |
+
# +/or maybe some intermediate parts of that??? like 25 points dtw medoids particularly **
|
188 |
+
# --different normings for pitch? different settings for energy (tbqh i hope not too much?)
|
189 |
+
# TODO '''replacement with a constant low value''' ********
|
190 |
+
# errrrrrrrm duration?
|
191 |
+
# duration feature vector will have a different length than the others, BUT,
|
192 |
+
# besides the single clustering,,
|
193 |
+
# i SUPPOSE one could TRY assigning the phone's 'speech rate' value to every frame of the phone, so it doesn't change while the other 2 values do change.... like it would still VAGUELY represent that 2 people elongating the same vowel/syllable are doing similar things with duration while someone eliding that vowel is doing a different durational thing right there?
|
194 |
+
# might want to z-score this dimension across ALL speakers tho not within a speaker
|
195 |
+
# try doing it both ways at least. bc not sure to what extent i want absolute vs. relative rate info here.
|
196 |
+
#(note - unless chengs dur metric is of a kind where only rel makes sense in the first place. idr.)
|
197 |
+
|
198 |
+
|
199 |
+
|
200 |
+
|
201 |
+
# GRAPH the humans.
|
202 |
+
# - probably modify this code a bit to centre on boundary.
|
203 |
+
# - idk.
|
204 |
+
|
205 |
+
|
206 |
+
# TEST each TTS
|
207 |
+
# - structure its features
|
208 |
+
# - find its avg dist for each human cluster
|
209 |
+
# - find the lowest dist cluster
|
210 |
+
# - report the dist for i guess this and all clusters
|
211 |
+
# - GRAPH the tts with its best cluster
|
212 |
+
|
213 |
+
|
214 |
+
|
215 |
+
# EVALUATION
|
216 |
+
# - of the tts
|
217 |
+
# - of the method: consistency? coherency / interpretability of 'best' voice across different features; alt. ability to recover good & problematic features from a combined method if that is chosen as the best?
|
218 |
+
# - how similar are the results across different sentences? are any voices consistently good or bad; if multiple are good, are they good in the same way or good in different ways; do humans agree.
|
219 |
+
# >> bc hey THAT could at least be an argument for the method, u might have to take time for human judgement once but then you can keep re using it free for new voices. or to select among alternative generations given you might know a context and know what you're going for in that context. etc.
|
220 |
+
|
221 |
+
|
scripts/tapi.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json, os, requests, warnings, wave
|
2 |
+
warnings.filterwarnings("ignore")
|
3 |
+
|
4 |
+
|
5 |
+
|
6 |
+
# synthesise speech
|
7 |
+
# save 16khz mono wav file
|
8 |
+
# and word-level timestamps
|
9 |
+
# return paths to wave and alignment files
|
10 |
+
def tiro(text,voice,save='./'):
|
11 |
+
|
12 |
+
# endpoint working 2023
|
13 |
+
url = 'https://tts.tiro.is/v0/speech'
|
14 |
+
headers = {'Content-Type': 'application/json'}
|
15 |
+
|
16 |
+
|
17 |
+
# synthesis
|
18 |
+
payload_tts = {
|
19 |
+
"Engine": "standard",
|
20 |
+
"LanguageCode": "is-IS",
|
21 |
+
"OutputFormat": "pcm",
|
22 |
+
"SampleRate":"16000",
|
23 |
+
"Text": text,
|
24 |
+
"VoiceId": voice
|
25 |
+
}
|
26 |
+
|
27 |
+
# word time alignments
|
28 |
+
payload_aln = {
|
29 |
+
"Engine": "standard",
|
30 |
+
"LanguageCode": "is-IS",
|
31 |
+
"OutputFormat": "json",
|
32 |
+
"SpeechMarkTypes": ["word"],
|
33 |
+
"Text": text,
|
34 |
+
"VoiceId": voice
|
35 |
+
}
|
36 |
+
|
37 |
+
|
38 |
+
tts_data = requests.post(url, headers=headers, json=payload_tts, verify=False)
|
39 |
+
aln_data = requests.post(url, headers=headers, json=payload_aln, verify=False)
|
40 |
+
|
41 |
+
|
42 |
+
#fname = save+text.replace(':','').replace('/','-')
|
43 |
+
#wname = fname+'.wav'
|
44 |
+
#aname = fname+'.json'
|
45 |
+
wname = save+voice+'.wav'
|
46 |
+
aname = save+voice+'.json'
|
47 |
+
|
48 |
+
with wave.open(wname,'wb') as f:
|
49 |
+
f.setnchannels(1)
|
50 |
+
f.setframerate(16000)
|
51 |
+
f.setsampwidth(2)
|
52 |
+
f.writeframes(tts_data.content)
|
53 |
+
|
54 |
+
with open(aname,'w') as f:
|
55 |
+
f.write('{"alignments": [')
|
56 |
+
f.write(aln_data.content.decode().replace('}\n{','},\n {'))
|
57 |
+
f.write(']}')
|
58 |
+
|
59 |
+
return(os.path.abspath(wname),os.path.abspath(aname))
|
60 |
+
|
61 |
+
|
62 |
+
|
63 |
+
|
64 |
+
#sentence = "Hæ hæ hæ hæ! Ég heiti Gervimaður Finnland, en þú?"
|
65 |
+
#voice = "Alfur"
|
66 |
+
|
67 |
+
#wf, af = tiro(sentence,voice)
|
68 |
+
|
69 |
+
#print(wf, af)
|