Debian Codegraph @

dwtools/SpeechSynthesizer_and_TextGrid.cpp

raw symbols SCIP
1 /* SpeechSynthesizer_and_TextGrid.cpp
2 *
3 * Copyright (C) 2011-2019,2023 David Weenink, 2024,2025 Paul Boersma
4 *
5 * This code is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or (at
8 * your option) any later version.
9 *
10 * This code is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this work. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include "DTW.h"
20 #include "Sounds_to_DTW.h"
21 #include "Sound_extensions.h"
22 #include "SpeechSynthesizer_and_TextGrid.h"
23 #include "CCs_to_DTW.h"
24 #include "DTW_and_TextGrid.h"
25 #include "NUMmachar.h"
26
27 // prototypes
28 static void IntervalTier_splitInterval (IntervalTier me, double time, conststring32 leftLabel, integer interval, double precision);
29 static autoIntervalTier IntervalTier_IntervalTier_cutPartsMatchingLabel (IntervalTier me, IntervalTier thee, conststring32 label, double precision);
30 static autoIntervalTier IntervalTiers_patch_noBoundaries (IntervalTier me, IntervalTier thee, conststring32 patchLabel, double precision);
31
32 static void IntervalTier_checkRange (IntervalTier me, integer startInterval, integer endinterval) {
33 Melder_require (startInterval <= endinterval,
34 U"The interval range end number should not be smaller than the interval range start number.");
35 Melder_require (startInterval > 0,
36 U"The specified interval range start number is ", startInterval, U", but should be at least 1.");
37 Melder_require (endinterval <= my intervals.size,
38 U"The specified interval range end number (", endinterval, U") exceeds the number of intervals (", my intervals.size, U") in this tier.");
39 }
40
41 autoSound SpeechSynthesizer_TextInterval_to_Sound (SpeechSynthesizer me, TextInterval thee, autoTextGrid *out_textgrid)
42 {
43 try {
44 Melder_require (thy text && thy text [0] != U'\0',
45 U"TextInterval should not be empty.");
46 autoSound him = SpeechSynthesizer_to_Sound (me, thy text.get(), out_textgrid, nullptr);
47 return him;
48 } catch (MelderError) {
49 Melder_throw (U"Sound not created from TextInterval.");
50 }
51 }
52
53 autoSound SpeechSynthesizer_TextGrid_to_Sound (SpeechSynthesizer me, TextGrid thee, integer tierNumber, integer iinterval, autoTextGrid *out_textgrid) {
54 try {
55 TextGrid_checkSpecifiedTierNumberWithinRange (thee, tierNumber);
56 const IntervalTier intervalTier = (IntervalTier) thy tiers->at [tierNumber];
57 Melder_require (intervalTier -> classInfo == classIntervalTier,
58 U"Tier ", tierNumber, U" is not an interval tier.");
59 Melder_require (iinterval > 0 && iinterval <= intervalTier -> intervals.size,
60 U"Interval ", iinterval, U" does not exist on tier ", tierNumber, U".");
61 return SpeechSynthesizer_TextInterval_to_Sound (me, intervalTier -> intervals.at [iinterval], out_textgrid);
62 } catch (MelderError) {
63 Melder_throw (U"Sound not created from textGrid.");
64 }
65 }
66
67 #if 0
68 static double TextGrid_getStartTimeOfFirstOccurrence (TextGrid thee, integer tierNumber, conststring32 label) {
69 TextGrid_checkSpecifiedTierNumberWithinRange (thee, tierNumber);
70 const IntervalTier intervalTier = (IntervalTier) thy tiers->at [tierNumber];
71 Melder_require (intervalTier -> classInfo == classIntervalTier,
72 U"Tier ", tierNumber, U" is not an interval tier.");
73 double start = undefined;
74 for (integer iint = 1; iint <= intervalTier -> intervals.size; iint ++) {
75 const TextInterval ti = intervalTier -> intervals.at [iint];
76 if (Melder_cmp (ti -> text, label) == 0) {
77 start = ti -> xmin;
78 break;
79 }
80 }
81 return start;
82 }
83
84 static double TextGrid_getEndTimeOfLastOccurrence (TextGrid thee, integer tierNumber, conststring32 label) {
85 TextGrid_checkSpecifiedTierNumberWithinRange (thee, tierNumber);
86 IntervalTier intervalTier = (IntervalTier) thy tiers->at [tierNumber];
87 Melder_require (intervalTier -> classInfo == classIntervalTier,
88 U"Tier ", tierNumber, U" is not an interval tier.");
89 double end = undefined;
90 for (integer iint = intervalTier -> intervals.size; iint > 0; iint --) {
91 const TextInterval ti = intervalTier -> intervals.at [iint];
92 if (Melder_equ (ti -> text, label)) {
93 end = ti -> xmax;
94 break;
95 }
96 }
97 return end;
98 }
99 #endif
100
101 static void IntervalTier_getLabelInfo (IntervalTier me, conststring32 label, double *labelDurations, integer *numberOfOccurences) {
102 *labelDurations = 0.0;
103 *numberOfOccurences = 0;
104 for (integer i = 1; i <= my intervals.size; i ++) {
105 const TextInterval ti = my intervals.at [i];
106 if (Melder_equ (ti -> text.get(), label)) {
107 *labelDurations += ti -> xmax - ti -> xmin;
108 (*numberOfOccurences) ++;
109 }
110 }
111 }
112
113 #define TIMES_ARE_CLOSE(x,y) (fabs((x)-(y)) < precision)
114 void IntervalTier_splitInterval (IntervalTier me, double time, conststring32 leftLabel, integer interval, double precision) {
115 try {
116 Melder_assert (interval > 0);
117 TextInterval ti = nullptr;
118 integer index = 0;
119 for (integer i = interval; i <= my intervals.size; i ++) {
120 ti = my intervals.at [i];
121 if (time < ti -> xmax + precision && time > ti -> xmin - precision) {
122 index = i;
123 break;
124 }
125 }
126 // TODO: if index == 0 then search left intervals??
127 if (index == 0 || TIMES_ARE_CLOSE(time, ti -> xmin) || TIMES_ARE_CLOSE(time, ti -> xmax))
128 return;
129 autoTextInterval newInterval = TextInterval_create (ti -> xmin, time, leftLabel);
130 /*
131 Make start of current and begin of new interval equal
132 */
133 ti -> xmin = time;
134 my intervals. addItem_move (newInterval.move());
135 } catch (MelderError) {
136 Melder_throw (U"Boundary not inserted.");
137 }
138 }
139
140 static autoTextTier TextTier_IntervalTier_cutPartsMatchingLabel (TextTier me, IntervalTier thee, conststring32 label, double precision) {
141 try {
142 Melder_require (my xmin == thy xmin && my xmax == thy xmax,
143 U"Domains should be equal.");
144 integer myIndex = 1;
145 double timeCut = 0.0;
146 autoTextTier him = TextTier_create (0.0, my xmax - my xmin);
147 for (integer j = 1; j <= thy intervals.size; j ++) {
148 const TextInterval cut = thy intervals.at [j];
149 if (Melder_equ (cut -> text.get(), label))
150 timeCut += cut -> xmax - cut -> xmin;
151 else {
152 while (myIndex <= my points.size) {
153 const TextPoint tp = my points.at [myIndex];
154 if (tp -> number < cut -> xmin - precision) {
155 // point is left of cut
156 myIndex ++;
157 } else if (tp -> number < cut -> xmax + precision) {
158 // point is in (no)cut
159 const double time = tp -> number - my xmin - timeCut;
160 TextTier_addPoint (him.get(), time, tp -> mark.get());
161 myIndex ++;
162 } else {
163 break;
164 }
165 }
166 }
167 }
168 his xmax -= timeCut;
169 return him;
170 } catch (MelderError) {
171 Melder_throw (me, U": parts not cut.");
172 }
173 }
174
175 // Cut parts from me marked by labels in thee
176 autoIntervalTier IntervalTier_IntervalTier_cutPartsMatchingLabel (IntervalTier me, IntervalTier thee, conststring32 label, double precision) {
177 try {
178 Melder_require (my xmin == thy xmin && my xmax != thy xmax,
179 U"Domains should be identical.");
180 autoVEC durations = raw_VEC (my intervals.size);
181 for (integer i = 1; i <= my intervals.size; i ++) {
182 const TextInterval ti = my intervals.at [i];
183 durations [i] = ti -> xmax - ti -> xmin;
184 }
185 integer myInterval = 1;
186 for (integer j = 1; j <= thy intervals.size; j ++) {
187 const TextInterval cut = thy intervals.at [j];
188 if (Melder_equ (cut -> text.get(), label)) { // trim
189 while (myInterval <= my intervals.size) {
190 const TextInterval ti = my intervals.at [myInterval];
191 if (ti -> xmin > cut -> xmin - precision && ti -> xmax < cut -> xmax + precision) {
192 /*
193 1. Interval completely within cut
194 */
195 durations [myInterval] = 0.0;
196 myInterval ++;
197 } else if (ti -> xmin < cut -> xmin + precision && cut -> xmin < ti -> xmax + precision) {
198 /*
199 2. Cut start is within interval
200 */
201 if (cut -> xmax > ti -> xmax - precision) {
202 /*
203 Interval end is in cut, interval start before
204 */
205 durations [myInterval] -= ti -> xmax - cut -> xmin;
206 myInterval ++;
207 } else {
208 /*
209 3. cut completely within interval
210 */
211 durations [myInterval] -= cut -> xmax - cut -> xmin;
212 break;
213 }
214 } else if (cut -> xmax > ti -> xmin - precision && cut -> xmin < ti -> xmax + precision) {
215 /*
216 1+2 : cut end is within interval, cut start before
217 */
218 durations [myInterval] -= cut -> xmax - ti -> xmin;
219 break;
220 } else if (ti -> xmax < cut -> xmin + precision) {
221 myInterval ++;
222 }
223 }
224 }
225 }
226 longdouble totalDuration = 0.0;
227 for (integer i = 1; i <= my intervals.size; i ++) {
228 if (durations [i] < precision)
229 durations [i] = 0.0;
230 totalDuration += durations [i];
231 }
232 autoIntervalTier him = IntervalTier_create (0, double (totalDuration));
233 double time = 0.0;
234 integer hisInterval = 1;
235 for (integer i = 1; i <= my intervals.size; i ++) {
236 if (durations [i] <= 0.0)
237 continue;
238 const TextInterval ti = my intervals.at [i];
239 time += durations [i];
240 if (fabs (time - totalDuration) > precision) {
241 IntervalTier_splitInterval (him.get(), time, ti -> text.get(), hisInterval, precision);
242 hisInterval ++;
243 } else { // last interval
244 const TextInterval histi = his intervals.at [hisInterval];
245 TextInterval_setText (histi, ti -> text.get());
246 }
247 }
248 return him;
249 } catch (MelderError) {
250 Melder_throw (me, U": parts not cut.");
251 }
252 }
253
254 autoTextGrid TextGrid_IntervalTier_cutPartsMatchingLabel (TextGrid me, IntervalTier thee, conststring32 label, double precision) {
255 try {
256 Melder_require (my xmin == thy xmin && my xmax == thy xmax,
257 U"Domains should be equal.");
258 double cutDurations = 0;
259 for (integer i = 1; i <= thy intervals.size; i ++) {
260 const TextInterval cut = thy intervals.at [i];
261 if (Melder_equ (cut -> text.get(), label))
262 cutDurations += cut -> xmax - cut -> xmin;
263 }
264 if (cutDurations <= precision) // Nothing to patch
265 return Data_copy (me);
266 autoTextGrid him = TextGrid_createWithoutTiers (0, thy xmax - thy xmin - cutDurations);
267 for (integer itier = 1; itier <= my tiers->size; itier ++) {
268 const Function anyTier = my tiers->at [itier];
269 if (anyTier -> classInfo == classIntervalTier) {
270 autoIntervalTier newTier = IntervalTier_IntervalTier_cutPartsMatchingLabel ((IntervalTier) anyTier, thee, label, precision);
271 his tiers -> addItem_move (newTier.move());
272 } else {
273 autoTextTier newTier = TextTier_IntervalTier_cutPartsMatchingLabel ((TextTier) anyTier, thee, label, precision);
274 his tiers -> addItem_move (newTier.move());
275 }
276 }
277 return him;
278 } catch (MelderError) {
279 Melder_throw (me, U": no parts cut.");
280 }
281 }
282
283 // Patch thy intervals that match patchLabel into my intervals
284 // The resulting IntervalTier has thy xmin as starting time and thy xmax as end time
285 autoIntervalTier IntervalTiers_patch_noBoundaries (IntervalTier me, IntervalTier thee, conststring32 patchLabel, double precision) {
286 try {
287 autoVEC durations = zero_VEC (my intervals.size + 1);
288 for (integer i = 1; i <= my intervals.size; i ++) {
289 const TextInterval myti = my intervals.at [i];
290 durations [i] = myti -> xmax - myti -> xmin;
291 }
292 integer myInterval = 1;
293 double xShift = thy xmin - my xmin, firstShift = 0.0;
294 for (integer interval = 1; interval <= thy intervals.size; interval ++) {
295 const TextInterval patch = thy intervals.at [interval];
296 if (Melder_equ (patch -> text.get(), patchLabel)) {
297 if (interval == 1)
298 xShift += firstShift = patch -> xmax - patch -> xmin;
299 else if (interval == thy intervals.size)
300 durations [my intervals.size + 1] = patch -> xmax - patch -> xmin;
301 else
302 while (myInterval <= my intervals.size) {
303 const TextInterval ti = my intervals.at [myInterval];
304 const double tixmin = ti -> xmin + xShift;
305 const double tixmax = ti -> xmax + xShift;
306 if ((patch -> xmin > tixmin - precision) && (patch -> xmin < tixmax + precision)) {
307 durations [myInterval] += patch -> xmax - patch -> xmin;
308 break;
309 }
310 myInterval++;
311 }
312 } else
313 while (myInterval <= my intervals.size) {
314 TextInterval ti = my intervals.at [myInterval];
315 double tixmax = ti -> xmax + xShift;
316 if (tixmax < patch -> xmin + precision)
317 myInterval ++;
318 else
319 break;
320 }
321 }
322 autoIntervalTier him = IntervalTier_create (thy xmin, thy xmax);
323 // first interval
324 double time = thy xmin + firstShift;
325 integer hisInterval = 1;
326 if (firstShift > 0.0) {
327 IntervalTier_splitInterval (him.get(), time , U"", hisInterval, precision);
328 hisInterval ++;
329 }
330 for (integer interval = 1; interval <= my intervals.size; interval ++) {
331 const TextInterval ti = my intervals.at [interval];
332 time += durations [interval];
333 IntervalTier_splitInterval (him.get(), time, ti -> text.get(), hisInterval, precision);
334 hisInterval ++;
335 }
336 if (durations [my intervals.size + 1] > 0.0) {
337 time += durations [my intervals.size + 1];
338 IntervalTier_splitInterval (him.get(), time , U"", hisInterval, precision);
339 }
340 return him;
341 } catch (MelderError) {
342 Melder_throw (me, U": not patched.");
343 }
344 }
345
346 #if 0
347 static autoIntervalTier IntervalTiers_patch (IntervalTier me, IntervalTier thee, conststring32 patchLabel, double precision) {
348 try {
349 utoIntervalTier him = IntervalTier_create (thy xmin, thy xmax);
350 integer myInterval = 1, hisInterval = 1;
351 double xmax = thy xmin;
352 for (integer i = 1; i <= thy intervals.size; i ++) {
353 TextInterval myti, ti = thy intervals.at [i];
354 if (Melder_equ (ti -> text, patchLabel)) {
355 bool splitInterval = false;
356 double endtime, split = 0.0;
357 BUG if (i > 0) {
358 while (myInterval <= my intervals.size) {
359 myti = my intervals.at [myInterval];
360 endtime = xmax + myti -> xmax - myti -> xmin;
361 if (endtime <= ti -> xmin + precision) {
362 xmax = endtime;
363 IntervalTier_splitInterval (him.get(), xmax, myti -> text, hisInterval, precision);
364 hisInterval ++;
365 } else {
366 if (xmax < ti -> xmin - precision) { // split interval ???
367 splitInterval = true;
368 xmax = ti -> xmin;
369 split = endtime - xmax;
370 IntervalTier_splitInterval (him.get(), xmax, myti -> text, hisInterval, precision);
371 hisInterval ++;
372 myInterval ++;
373 }
374 break;
375 }
376 myInterval ++;
377 }
378 }
379 xmax += ti -> xmax - ti -> xmin;
380 IntervalTier_splitInterval (him.get(), xmax, U"", hisInterval, precision);
381 hisInterval ++;
382 if (splitInterval) {
383 xmax += split;
384 IntervalTier_splitInterval (him.get(), xmax, myti -> text, hisInterval, precision);
385 hisInterval ++;
386 }
387 } else if (i == thy intervals.size) { // copy remaining if last interval doesn't match
388 while (myInterval <= my intervals.size) {
389 myti = my intervals.at [myInterval];
390 xmax += myti -> xmax - myti -> xmin;
391 IntervalTier_splitInterval (him.get(), xmax, myti -> text, hisInterval, precision);
392 hisInterval ++;
393 myInterval ++;
394 }
395 }
396 }
397 return him;
398 } catch (MelderError) {
399 Melder_throw (me, U": not patched.");
400 }
401 }
402 #endif
403
404 static autoTextTier TextTier_IntervalTier_patch (TextTier me, IntervalTier thee, conststring32 patchLabel, double precision) {
405 try {
406 integer myIndex = 1;
407 autoTextTier him = TextTier_create (thy xmin, thy xmax);
408 double xShift = thy xmin - my xmin;
409 for (integer i = 1; i <= thy intervals.size; i ++) {
410 const TextInterval ti = thy intervals.at [i];
411 if (Melder_equ (ti -> text.get(), patchLabel)) {
412 if (i > 1) {
413 while (myIndex <= my points.size) {
414 const TextPoint tp = my points.at [myIndex];
415 const double time = tp -> number + xShift;
416 if (time < ti -> xmin + precision) {
417 autoTextPoint newPoint = TextPoint_create (time, tp -> mark.get());
418 his points. addItem_move (newPoint.move());
419 } else {
420 break;
421 }
422 myIndex ++;
423 }
424 }
425 xShift += ti -> xmax - ti -> xmin;
426 } else if (i == thy intervals.size) {
427 while (myIndex <= my points.size) {
428 const TextPoint tp = my points.at [myIndex];
429 const double time = tp -> number + xShift;
430 if (time < ti -> xmin + precision) {
431 autoTextPoint newPoint = TextPoint_create (time, tp -> mark.get());
432 his points. addItem_move (newPoint.move());
433 }
434 myIndex ++;
435 }
436 }
437 }
438 return him;
439 } catch (MelderError) {
440 Melder_throw (me, U": cannot patch TextTier.");
441 }
442 }
443
444 autoTextGrid TextGrid_IntervalTier_patch (TextGrid me, IntervalTier thee, conststring32 patchLabel, double precision) {
445 try {
446 double patchDurations;
447 integer numberOfPatches;
448 IntervalTier_getLabelInfo (thee, patchLabel, & patchDurations, & numberOfPatches);
449 if (patchDurations <= 0 || my xmax - my xmin >= thy xmax - thy xmin ) // Nothing to patch
450 return Data_copy (me);
451 autoTextGrid him = TextGrid_createWithoutTiers (thy xmin, thy xmax);
452 for (integer itier = 1; itier <= my tiers->size; itier ++) {
453 const Function anyTier = my tiers->at [itier];
454 if (anyTier -> classInfo == classIntervalTier) {
455 //autoIntervalTier ait = IntervalTiers_patch ((IntervalTier) anyTier, thee, patchLabel, precision);
456 autoIntervalTier newTier = IntervalTiers_patch_noBoundaries ((IntervalTier) anyTier, thee, patchLabel, precision);
457 his tiers -> addItem_move (newTier.move());
458 } else {
459 autoTextTier newTier = TextTier_IntervalTier_patch ((TextTier) anyTier, thee, patchLabel, precision);
460 his tiers -> addItem_move (newTier.move());
461 }
462 }
463 return him;
464 } catch (MelderError) {
465 Melder_throw (me, U": not patched.");
466 }
467 }
468
469 // We assume that the Sound and the SpeechSynthesizer have the same samplingFrequency
470 autoTextGrid SpeechSynthesizer_Sound_TextInterval_align (
471 const SpeechSynthesizer me, const Sound thee, const TextInterval him,
472 const double silenceThreshold,
473 const double minSilenceDuration, const double minSoundingDuration
474 ) {
475 try {
476 Melder_require (thy xmin == his xmin && thy xmax == his xmax,
477 U"Domains of Sound and TextGrid should be equal.");
478 Melder_require (fabs (1.0 / thy dx - my d_samplingFrequency) < 1e-9,
479 U"The sampling frequencies of the SpeechSynthesizer and the Sound should be equal.");
480
481 //TRACE
482 trace(U"original sound: ", thy xmin, U" .. ", thy xmax);
483 trace(U"interval: ", his xmin, U" .. ", his xmax, U" ", his text.get());
484 autoSTRVEC tokens = splitByWhitespace_STRVEC (his text.get());
485 const integer numberOfTokens = tokens.size;
486 Melder_require (numberOfTokens > 0,
487 U"The interval should contain text.");
488 /*
489 Remove silent intervals from start and end of sounds because
490 1. it will improve the word rate guess
491 2. it will improve the DTW matching.
492 */
493 trace(2);
494 const double minPitch = 200.0, timeStep = 0.005, precision = thy dx;
495 double startTimeOfSounding, endTimeOfSounding;
496 autoSound soundTrimmed;
497 {// scope
498 autoMelderWarningOff nowarn;
499 soundTrimmed = Sound_trimSilencesAtStartAndEnd (thee, 0.0, minPitch, timeStep,
500 silenceThreshold, minSilenceDuration, minSoundingDuration, & startTimeOfSounding, & endTimeOfSounding);
501 }
502 trace (U"- silence-trimmed: ", soundTrimmed -> xmin, U" .. ", soundTrimmed -> xmax);
503 const double duration_soundTrimmed = soundTrimmed -> xmax - soundTrimmed -> xmin;
504 Melder_require (duration_soundTrimmed > 0.0,
505 soundTrimmed.get(), U" is silent, so we cannot align it with text.");
506 const bool hasSilence_sound = fabs (startTimeOfSounding - thy xmin) > precision || fabs (endTimeOfSounding - thy xmax) > precision;
507 trace(3);
508
509 if (my d_estimateSpeechRate && duration_soundTrimmed != 0.0) {
510 /*
511 Estimate speaking rate with the number of words per minute from the text
512 */
513 Melder_assert (duration_soundTrimmed != 0.0);
514 const double wordsPerMinute_rawTokens = 60.0 * numberOfTokens / duration_soundTrimmed;
515 /*
516 Compensation for long words: 5 characters / word
517 */
518 const double wordsPerMinute_rawText = 60.0 * (Melder_length (his text.get()) / 5.0) / duration_soundTrimmed;
519 my d_wordsPerMinute = Melder_ifloor (0.5 * (wordsPerMinute_rawTokens + wordsPerMinute_rawText));
520 }
521 trace(4);
522
523 autoTextGrid textgrid_synth, textgrid_synth_sounding;
524 autoSound synth = SpeechSynthesizer_TextInterval_to_Sound (me, him, & textgrid_synth);
525 /*
526 For the synthesizer the silence threshold has to be < -30 dB, otherwise fricatives will not
527 be found as sounding! This is ok since silences are almost at zero amplitudes for synthesized sounds.
528 We also have to decrease the minimum silence and minimum sounding duration to catch, for example,
529 the final plosive "t" from the synthesized sound "text".
530 */
531 const double silenceThreshold_synth = -40.0, minSilenceDuration_synth = 0.05;
532 const double minSoundingDuration_synth = 0.05;
533 double startTimeOfSounding_synth, endTimeOfSounding_synth;
534 autoSound synthTrimmed;
535 {// scope
536 autoMelderWarningOff nowarn;
537 synthTrimmed = Sound_trimSilencesAtStartAndEnd (synth.get(), 0.0, minPitch, timeStep, silenceThreshold_synth,
538 minSilenceDuration_synth, minSoundingDuration_synth, & startTimeOfSounding_synth, & endTimeOfSounding_synth);
539 }
540 const double synthTrimmed_duration = synthTrimmed -> xmax - synthTrimmed -> xmin;
541 trace (U"synthesized sound: ", synth -> xmin, U" .. ", synth -> xmax);
542 trace (U"- silence-trimmed: ", synthTrimmed -> xmin, U" .. ", synthTrimmed -> xmax);
543 trace (U"- sounding: ", startTimeOfSounding_synth, U" .. ", endTimeOfSounding_synth);
544 const bool hasSilence_synth = fabs (startTimeOfSounding_synth - synth -> xmin) > precision ||
545 fabs (endTimeOfSounding_synth - synth -> xmax) > precision;
546 trace(5);
547
548 if (hasSilence_synth)
549 textgrid_synth_sounding = TextGrid_extractPart (textgrid_synth.get(), startTimeOfSounding_synth, endTimeOfSounding_synth, true);
550 /*
551 Compare the durations of the two sounds to get an indication of the slope constraint needed for the DTW
552 */
553 Melder_assert (synthTrimmed_duration != 0.0);
554 double slope = duration_soundTrimmed / synthTrimmed_duration;
555 Melder_assert (slope != 0.0);
556 slope = ( slope > 1.0 ? slope : 1.0 / slope );
557 const int constraint = ( slope < 1.5 ? 4 : slope < 2.0 ? 3 : slope < 3.0 ? 2 : 1 ); // TODO enums
558
559 trace(6);
560 trace (hasSilence_sound, hasSilence_synth);
561 const double analysisWidth = 0.02, dt = 0.005, band = 0.0;
562 autoDTW dtw = Sounds_to_DTW ((hasSilence_sound ? soundTrimmed.get() : thee),
563 (hasSilence_synth ? synthTrimmed.get() : synth.get()), analysisWidth, dt, band, constraint);
564 trace(7);
565
566 autoTextGrid result = DTW_TextGrid_to_TextGrid (dtw.get(), (hasSilence_synth ? textgrid_synth_sounding.get() : textgrid_synth.get()), precision);
567 trace(8);
568 if (hasSilence_sound) {
569 if (startTimeOfSounding > thy xmin) {
570 trace (U"Have to set earlier start time ", thy xmin);
571 TextGrid_setEarlierStartTime (result.get(), thy xmin, U"", U"");
572 }
573 if (endTimeOfSounding < thy xmax || result -> xmax < thy xmax) {
574 trace (U"Have to set later end time ", thy xmax);
575 TextGrid_setLaterEndTime (result.get(), thy xmax, U"", U"");
576 }
577 }
578 trace(9);
579 return result;
580 } catch (MelderError) {
581 Melder_throw (U"SpeechSynthesizer & Sound & TextInterval: not aligned.");
582 }
583 }
584 /*
585 typedef struct structAlignmentOfSoundAndTextStruct {
586 double windowLength, timeStep; // analysis
587 double f1_mel, fmax_mel, df_mel; // MelFilter
588 integer numberOfMFCCCoefficients; // MFCC
589 double dtw_cepstralWeight, dtw_logEnergyWeight; // MFCC -> DTW
590 double dtw_regressionWeight, dtw_regressionlogEnergyWeight;
591 double dtw_regressionWindowLength;
592 double dtw_sakoeChibaBand, dtw_constraint;
593 double silenceThreshold, minSilenceDuration, minSoundingDuration, trimDuration; // silence detection
594 integer language, voicevariant, pitchAdjustment, pitchRange, wordsPerMinute; // synthesizer
595 bool interpretPhonemeCodes, ipa, set_wordsPerMinute;
596 double wordgap; // synthesizer
597 } *SpeechSynthesizer_alignmentStruct;*/
598
599 static autoTextGrid SpeechSynthesizer_Sound_TextInterval_align2 (SpeechSynthesizer me, Sound thee, TextInterval him, double silenceThreshold, double minSilenceDuration, double minSoundingDuration, double trimDuration) {
600 try {
601 Melder_require (thy xmin == his xmin && thy xmax == his xmax,
602 U"Domains of Sound and TextGrid should be equal.");
603 Melder_require (fabs (1.0 / thy dx - my d_samplingFrequency) < 1e-9,
604 U"The sampling frequencies of the SpeechSynthesizer and the Sound should be equal.");
605
606 const conststring32 trimLabel = U"trim";
607 /*
608 1. Trim the silences of the sound
609
610 For the synthesizer the silence threshold has to be < -30 dB, otherwise fricatives
611 will not be found as sounding! This is ok since silences are almost at zero amplitudes
612 We also have to decrease the minimum silence and minimum sounding duration to catch,
613 for example, the final plosive "t" from the word "text"
614 */
615 const double minPitch = 200, timeStep = 0.005, precision = thy dx;
616 autoTextGrid thee_trimmer;
617 autoSound thee_trimmed;
618 {// scope
619 autoMelderWarningOff nowarn;
620 thee_trimmed = Sound_trimSilences (thee, trimDuration, false, minPitch, timeStep, silenceThreshold, minSilenceDuration, minSoundingDuration, & thee_trimmer, trimLabel);
621 }
622 /*
623 2. Synthesize the sound from the TextInterval
624 */
625 autoTextGrid tg_syn;
626 autoSound synth = SpeechSynthesizer_TextInterval_to_Sound (me, him, &tg_syn);
627 /*
628 3. There should be no silences in the synthesized sound except at the start and finish.
629 Set the wordwarp parameter to a small value like 0.001 s.
630
631 4. Get DTW from the two sounds
632 */
633 const double analysisWidth = 0.02, dt = 0.005, band = 0.0;
634 const int constraint = 4;
635 autoDTW dtw = Sounds_to_DTW (thee_trimmed.get(), synth.get(), analysisWidth, dt, band, constraint);
636 /*
637 6. Warp the synthesis TextGrid
638 First make domains equal, otherwise the warper protests
639 */
640 autoTextGrid warp = DTW_TextGrid_to_TextGrid (dtw.get(), tg_syn.get(), precision);
641 /*
642 6. Patch the trimmed intervals back into the warped TextGrid
643 */
644 autoTextGrid result = TextGrid_IntervalTier_patch (warp.get(), (IntervalTier) thee_trimmer -> tiers->at [1], U"trim", 2 * thy dx);
645
646 return result;
647 } catch (MelderError) {
648 Melder_throw (thee, U": sound and TextInterval not aligned.");
649 }
650 }
651
652 autoTextGrid SpeechSynthesizer_Sound_IntervalTier_align (SpeechSynthesizer me, Sound thee, IntervalTier him, integer istart, integer iend, double silenceThreshold, double minSilenceDuration, double minSoundingDuration) {
653 try {
654 IntervalTier_checkRange (him, istart, iend);
655 const TextInterval tib = his intervals.at [istart];
656 const TextInterval tie = his intervals.at [iend];
657 Melder_require (tib -> xmin >= thy xmin && tie -> xmax <= thy xmax,
658 U"The chosen interval(s) must lie within the sound.");
659 OrderedOf<structTextGrid> textgrids;
660 autoTextGrid result = TextGrid_create (tib -> xmin, tie -> xmax, U"sentence clause word phoneme", U"");
661 for (integer iint = istart; iint <= iend; iint ++) {
662 const TextInterval ti = his intervals.at [iint];
663 if (ti -> text && ti -> text [0] != U'\0') {
664 autoSound sound = Sound_extractPart (thee, ti -> xmin, ti -> xmax, kSound_windowShape::RECTANGULAR, 1, true);
665 autoTextGrid grid = SpeechSynthesizer_Sound_TextInterval_align (me, sound.get(), ti, silenceThreshold, minSilenceDuration, minSoundingDuration);
666 textgrids. addItem_move (grid.move());
667 }
668 }
669 Melder_require (textgrids.size > 0,
670 U"Nothing could be aligned. Was your IntervalTier empty?");
671 autoTextGrid aligned = TextGrids_to_TextGrid_appendContinuous (& textgrids, true);
672 return aligned;
673 } catch (MelderError) {
674 Melder_throw (U"No aligned TextGrid created.");
675 }
676 }
677
678 static autoTextGrid SpeechSynthesizer_Sound_IntervalTier_align2 (SpeechSynthesizer me, Sound thee, IntervalTier him, integer istart, integer iend, double silenceThreshold, double minSilenceDuration, double minSoundingDuration, double trimDuration) {
679 try {
680 IntervalTier_checkRange (him, istart, iend);
681 const TextInterval tb = his intervals.at [istart];
682 const TextInterval te = his intervals.at [iend];
683 autoTextGrid result = TextGrid_create (tb -> xmin, te -> xmax, U"sentence clause word phoneme", U"");
684 OrderedOf<structTextGrid> textgrids;
685 for (integer iint = istart; iint <= iend; iint ++) {
686 const TextInterval ti = his intervals.at [iint];
687 if (ti -> text && ti -> text [0] != U'\0') {
688 autoSound sound = Sound_extractPart (thee, ti -> xmin, ti -> xmax, kSound_windowShape::RECTANGULAR, 1, true);
689 autoTextGrid grid = SpeechSynthesizer_Sound_TextInterval_align2 (me, sound.get(), ti, silenceThreshold, minSilenceDuration, minSoundingDuration, trimDuration);
690 textgrids. addItem_move (grid.move());
691 }
692 }
693 Melder_require (textgrids.size > 0, U"Nothing could be aligned. Was your IntervalTier empty?");
694
695 autoTextGrid aligned = TextGrids_to_TextGrid_appendContinuous (& textgrids, true);
696 return aligned;
697 } catch (MelderError) {
698 Melder_throw (U"No aligned TextGrid created.");
699 }
700 }
701
702 autoTextGrid SpeechSynthesizer_Sound_TextGrid_align (SpeechSynthesizer me, Sound thee, TextGrid him, integer tierNumber, integer istart, integer iend, double silenceThreshold, double minSilenceDuration, double minSoundingDuration) {
703 try {
704 Melder_require (thy xmin == his xmin && thy xmax == his xmax,
705 U"The domains of the Sound and the TextGrid must be equal.");
706 const IntervalTier tier = TextGrid_checkSpecifiedTierIsIntervalTier (him, tierNumber);
707 autoTextGrid grid = SpeechSynthesizer_Sound_IntervalTier_align (me, thee, tier, istart, iend, silenceThreshold, minSilenceDuration, minSoundingDuration);
708 return grid;
709 } catch (MelderError) {
710 Melder_throw (me, U", ", thee, U", ", him, U": Cannot align.");
711 }
712 }
713
714
715 autoTextGrid SpeechSynthesizer_Sound_TextGrid_align2 (SpeechSynthesizer me, Sound thee, TextGrid him, integer tierNumber, integer istart, integer iend, double silenceThreshold, double minSilenceDuration, double minSoundingDuration, double trimDuration) {
716 try {//TODO: check not empty tier
717 const IntervalTier tier = TextGrid_checkSpecifiedTierIsIntervalTier (him, tierNumber);
718 autoTextGrid grid = SpeechSynthesizer_Sound_IntervalTier_align2 (me, thee, tier, istart, iend, silenceThreshold, minSilenceDuration, minSoundingDuration, trimDuration);
719 return grid;
720 } catch (MelderError) {
721 Melder_throw (U"");
722 }
723 }
724
725 static autoStrings IntervalTier_to_Strings_withOriginData (IntervalTier me, INTVEC from) {
726 try {
727 autoStrings thee = Thing_new (Strings);
728 thy strings = autoSTRVEC (my intervals.size);
729 for (integer i = 1; i <= my intervals.size; i ++) {
730 const TextInterval ti = my intervals.at [i];
731 if (ti -> text && ti -> text [0] != U'\0') {
732 thy strings [++ thy numberOfStrings] = Melder_dup (ti -> text.get());
733 from [thy numberOfStrings] = i;
734 }
735 }
736 return thee;
737 } catch (MelderError) {
738 Melder_throw (me, U": no Strings created.");
739 }
740 }
741
742 static autoTable IntervalTiers_to_Table_textAlignment (IntervalTier target, IntervalTier source, EditCostsTable costs) {
743 try {
744 const integer numberOfTargetIntervals = target -> intervals.size;
745 const integer numberOfSourceIntervals = source -> intervals.size;
746 autoINTVEC targetOrigin = zero_INTVEC (numberOfTargetIntervals);
747 autoINTVEC sourceOrigin = zero_INTVEC (numberOfSourceIntervals);
748 autoStrings targets = IntervalTier_to_Strings_withOriginData (target, targetOrigin.get());
749 autoStrings sources = IntervalTier_to_Strings_withOriginData (source, sourceOrigin.get());
750 autoEditDistanceTable edit = EditDistanceTable_create (targets.get(), sources.get());
751 if (costs) {
752 EditDistanceTable_setEditCosts (edit.get(), costs);
753 EditDistanceTable_findPath (edit.get(), nullptr);
754 }
755 const integer pathLength = edit -> pathLength;
756 const conststring32 columnNames [] = {
757 U"targetInterval", U"targetText", U"targetStart", U"targetEnd",
758 U"sourceInterval", U"sourceText", U"sourceStart", U"sourceEnd",
759 U"operation"
760 };
761 autoTable thee = Table_createWithColumnNames (pathLength - 1, ARRAY_TO_STRVEC (columnNames));
762 for (integer i = 2; i <= pathLength; i++) {
763 const structPairOfInteger p = edit -> path [i];
764 const structPairOfInteger p1 = edit -> path [i - 1];
765 double targetStart = undefined, targetEnd = undefined;
766 double sourceStart = undefined, sourceEnd = undefined;
767 conststring32 targetText = U"", sourceText = U"";
768 const integer targetInterval = ( p.y > 1 ? targetOrigin [p.y - 1] : 0 );
769 const integer sourceInterval = ( p.x > 1 ? sourceOrigin [p.x - 1] : 0 );
770 if (targetInterval > 0) {
771 const TextInterval ti = target -> intervals.at [targetInterval];
772 targetStart = ti -> xmin;
773 targetEnd = ti -> xmax;
774 targetText = ti -> text.get();
775 }
776 if (sourceInterval > 0) {
777 const TextInterval ti = source -> intervals.at [sourceInterval];
778 sourceStart = ti -> xmin;
779 sourceEnd = ti -> xmax;
780 sourceText = ti -> text.get();
781 }
782 const integer irow = i - 1;
783 if (p.y == p1.y) { // deletion
784 Table_setNumericValue (thee.get(), irow, 1, 0);
785 Table_setStringValue (thee.get(), irow, 2, U"");
786 Table_setNumericValue (thee.get(), irow, 3, undefined);
787 Table_setNumericValue (thee.get(), irow, 4, undefined);
788 Table_setNumericValue (thee.get(), irow, 5, sourceInterval);
789 Table_setStringValue (thee.get(), irow, 6, sourceText);
790 Table_setNumericValue (thee.get(), irow, 7, sourceStart);
791 Table_setNumericValue (thee.get(), irow, 8, sourceEnd);
792 Table_setStringValue (thee.get(), irow, 9, U"d");
793 } else if (p.x == p1.x) { // insertion
794 Table_setNumericValue (thee.get(), irow, 1, targetInterval);
795 Table_setStringValue (thee.get(), irow, 2, targetText);
796 Table_setNumericValue (thee.get(), irow, 3, targetStart);
797 Table_setNumericValue (thee.get(), irow, 4, targetEnd);
798 Table_setNumericValue (thee.get(), irow, 5, 0);
799 Table_setStringValue (thee.get(), irow, 6, U"");
800 Table_setNumericValue (thee.get(), irow, 7, undefined);
801 Table_setNumericValue (thee.get(), irow, 8, undefined);
802 Table_setStringValue (thee.get(), irow, 9, U"i");
803 } else { // substitution ?
804 Table_setNumericValue (thee.get(), irow, 1, targetInterval);
805 Table_setStringValue (thee.get(), irow, 2, targetText);
806 Table_setNumericValue (thee.get(), irow, 3, targetStart);
807 Table_setNumericValue (thee.get(), irow, 4, targetEnd);
808 Table_setNumericValue (thee.get(), irow, 5, sourceInterval);
809 Table_setStringValue (thee.get(), irow, 6, sourceText);
810 Table_setNumericValue (thee.get(), irow, 7, sourceStart);
811 Table_setNumericValue (thee.get(), irow, 8, sourceEnd);
812 Table_setStringValue (thee.get(), irow, 9, Melder_equ (targetText, sourceText) ? U" " : U"s");
813 }
814 }
815 return thee;
816 } catch (MelderError) {
817 Melder_throw (target, U" and ", source, U" not aligned.");
818 }
819 }
820
821 autoTable TextGrids_to_Table_textAlignment (TextGrid target, integer ttier, TextGrid source, integer stier, EditCostsTable costs) {
822 try {
823 const IntervalTier targetTier = TextGrid_checkSpecifiedTierIsIntervalTier (target, ttier);
824 const IntervalTier sourceTier = TextGrid_checkSpecifiedTierIsIntervalTier (source, stier);
825 return IntervalTiers_to_Table_textAlignment (targetTier, sourceTier, costs);
826 } catch (MelderError) {
827 Melder_throw (U"No text alignment table created from TextGrids ", target, U" and ", source, U".");
828 }
829 }
830
831 // End of file TextGrid_and_SpeechSynthesizer.cpp