Added support for pitch models
[sgc2.git] / InitialiseSGC2.praat
blob657a6437b5f464935bce705dca973893e68a0e05
2 # SpeakGoodChinese 2.0
3
4 # Intializing Praat script
6 #     SpeakGoodChinese: InitializeSGC2.praat defines and sets the global variables
7 #     and loads general SGC2 code 
8 #     
9 #     Copyright (C) 2007-2010  R.J.J.H. van Son and 2010 the Netherlands Cancer Institute
10 #     The SpeakGoodChinese team are:
11 #     Guangqin Chen, Zhonyan Chen, Stefan de Koning, Eveline van Hagen, 
12 #     Rob van Son, Dennis Vierkant, David Weenink
13
14 #     This program is free software; you can redistribute it and/or modify
15 #     it under the terms of the GNU General Public License as published by
16 #     the Free Software Foundation; either version 2 of the License, or
17 #     (at your option) any later version.
18
19 #     This program is distributed in the hope that it will be useful,
20 #     but WITHOUT ANY WARRANTY; without even the implied warranty of
21 #     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 #     GNU General Public License for more details.
23
24 #     You should have received a copy of the GNU General Public License
25 #     along with this program; if not, write to the Free Software
26 #     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
27
29 # Information for logging
30 currentDate$ = date$()
31 dateYear$ = right$(currentDate$, length(currentDate$) - rindex(currentDate$, " "))
32 logtimeStamp$ = replace_regex$(currentDate$, "[^a-zA-Z0-9\-_]", "-", 0)
33 currentLogDirectory$ = ""
35 # Define canvas
36 viewportMargin = 5
37 yWordlist = 11
38 yFeedback = yWordlist + 5
39 yPinyin = yFeedback + 10
40 yContour = yPinyin + 15
41 wipeContourArea$ = "demo Paint rectangle... White 20 80 'yContour' 100"
42 wipePinyinArea$ = "demo Paint rectangle... White 20 80 'yPinyin' 'yContour'"
43 wipeFeedbackArea$ = "demo Paint rectangle... White 0 100 'yFeedback' 'yPinyin'"
44 wipeWordlistArea$ = "demo Paint rectangle... White 20 80 'yWordlist' 'yFeedback'"
46 # Pop-Up window colors
47 sgc2.popUp_bordercolor$ = "{0.5,0.5,1}"
48 sgc2.popUp_backgroundcolor$ = "{0.9,0.9,1}"
50 # Initialize parameters
51 alertText$ = ""
52 currentWord = 1
53 pinyin$ = ""
54 character$ = ""
55 buttons$ = ""
56 config$ = ""
57 wordlistNum = 1
58 wordlistName$ = ""
59 wordlist$ = ""
60 config.deleteWordlist = -1
61 config.displayNumbers = 1
62 config.displayPinyin = 1
63 config.displayChar = 0
64 config.displayTrans = 1
65 config.useSoundExample = 1
66 config.synthesis$ = "_DISABLED_"
67 config.input$ = "Microphone"
68 config.showBackground = 1
69 sgc2.noiseThresshold = -30
70 config.strict = 0
72 # Platform dependent settings
73 if macintosh or windows
74         config.displayChar = 1
75         config.displayNumbers = 0
76 endif
77 if windows and endsWith(build_SHA$, " XP")
78         config.displayChar = 0
79         config.displayNumbers = 0
80 endif
81 if unix
82         config.displayChar = 0
83         config.displayNumbers = 1
84 endif
86 if unix
87         samplingFrequency = 44100
88 elsif macintosh
89         samplingFrequency = 44100
90 elsif windows
91         samplingFrequency = 44100
92 endif
93 recordingTime = 2
95 logging = 0
96 config.language$ = "EN"
97 config.register = 249
98 config.logPerformance = 0
99 preferencesLogDir$ = "'preferencesAppDir$'/log"
100 preferencesTableDir$ = "'preferencesAppDir$'/Data"
101 sgc2wordlists$ = "'preferencesAppDir$'/wordlists"
102 localWordlistDir$ = sgc2wordlists$
104 # Global word lists must be installed BY THE ADMINISTRATOR
105 # This means, create the directory 'globalwordlists$' and
106 # fill it with wordlist directories containing wordlist.Table
107 # and audio files. They can be copied from a local directory.
108 globalwordlists$ = ""
109 globaltablelists$ = ""
110 globalTTSdir$ = ""
111 if unix
112         globalwordlists$ = "/etc/'sgc2.demoAppName$'/wordlists"
113         globaltablelists$ = "/etc/'sgc2.demoAppName$'/Data"     
114         globalTTSdir$ = "/etc/'sgc2.demoAppName$'/TTS"  
115 elsif macintosh
116         globalwordlists$ = "/Library/Preferences/'sgc2.demoAppName$'/wordlists"
117         globaltablelists$ = "/Library/Preferences/'sgc2.demoAppName$'/Data"
118         globalTTSdir$ = "/Library/Preferences/'sgc2.demoAppName$'/TTS"  
119 elsif windows
120         globalwordlists$ = "C:/Documents and Settings/All Users/Application Data/'sgc2.demoAppName$'/wordlists"
121         globaltablelists$ = "C:/Documents and Settings/All Users/Application Data/'sgc2.demoAppName$'/Data"
122         globalTTSdir$ = "C:/Documents and Settings/All Users/Application Data/'sgc2.demoAppName$'/TTS"
123 endif
124 sgc2.synthesizer = -1
125 # Define a Praat TTS command that will set sgc2.synthesizer
126 sgc2.normalTTScommand$ = "call create_default_TTS Mandarin f4 10000 0.01 50 100 95 no IPA"
127 sgc2.advancedTTScommand$ = "call create_default_TTS Mandarin f4 10000 0.01 50 70 125 no IPA"
128 sgc2.alignedTextGrid = -1
130 ##############################################################
132 config.shuffleLists = 1
133 defaultFontSize = 12
134 defaultFont$ = "Helvetica"
135 defaultLineWidth = 1
137 # Set up directories if they do not exist already
138 call set_up_directories
140 # Get saved preferences
141 call read_preferences ""
143 # Set up TTS system
144 speakCommandDir$ = "'preferencesAppDir$'/TTS"
145 speakCommandFile$ = ""
146 call set_up_TTS
148 # Set inital language
149 call set_language 'config.language$'
151 # Get the word-list
152 call load_word_list "'localWordlistDir$'" 0
154 # Set up evaluation table
155 initialiseSGC2.toneevaluation_table$ = ""
156 call initialize_toneevaluation_tables
158 # Draw inital window
159 call init_window
161 ###############################################################
163 # Obligatory procedures
165 ###############################################################
166 # Initialize Demo Window
167 procedure init_window
168     demo Erase all
169         if config.showBackground
170                 call draw_background Background
171         endif
172         demo Line width... 'defaultLineWidth'
173         demo 'defaultFont$'
174         call set_font_size 'defaultFontSize'
175         demo Black
176         call reset_viewport
177     # Define buttons in a table
178     call init_buttons
179         .windowTitle$ = replace$(wordlistName$, "_", " ", 0)
180         call set_window_title 'buttons$' '.windowTitle$'
181         # Display the word-list
182         call write_word_list
183         # Logging light
184         call paint_logging_light
185 endproc
187 # Make sure all Preferences directories are available
188 procedure set_up_directories
189         .dirPath$ = "'preferencesAppDir$'"
190         createDirectory(.dirPath$)
191         .dirPath$ > '.dirPath$'/directory.txt
192         createDirectory("'.dirPath$'/wordlists")
193         .dirPath$ > '.dirPath$'/wordlists/directory.txt
194         createDirectory("'.dirPath$'/pitchmodels")
195         .dirPath$ > '.dirPath$'/pitchmodels/directory.txt
196         createDirectory("'.dirPath$'/log")
197         .dirPath$ > '.dirPath$'/log/directory.txt
198         createDirectory("'.dirPath$'/TTS")
199         .dirPath$ > '.dirPath$'/TTS/directory.txt
200 endproc
203 # Retrieve and store setting between sessions
205 procedure read_preferences .preferencesFile$
206         if not fileReadable(.preferencesFile$)
207                 .preferencesFile$ = preferencesAppDir$+"/sgc2rc.txt"
208         endif
209         if fileReadable(.preferencesFile$)
210                 Read from file... 'preferencesAppDir$'/sgc2rc.txt
211                 .preferenceTable$ = selected$("Table")
212                 .numPrefKeys = Get number of rows
213                 for .row to .numPrefKeys
214                         .variableName$ = Get value... '.row' Key
215                         if variableExists(.variableName$)
216                                 .variableValue = Get value... '.row' Value
217                                 if .variableValue <> undefined
218                                         '.variableName$' = '.variableValue'
219                                 endif
220                         elsif variableExists(.variableName$+"$")
221                                 .variableValue$ = Get value... '.row' Value
222                                 .variableName$ = .variableName$+"$"
223                                 '.variableName$' = "'.variableValue$'"
224                         endif
225                 endfor
226                 
227                 select Table '.preferenceTable$'
228                 Remove
229         endif
230 endproc
232 procedure write_preferences .preferencesFile$
233         Create Table with column names... Preferences 0 Key Value
234         if index_regex(.preferencesFile$, "[a-zA-Z0-9]") <= 0
235                 .preferencesFile$ = preferencesAppDir$ + "/sgc2rc.txt"
236         endif
237         .row = 0
238         
239         for .tableNum from 1 to 2
240                 if .tableNum = 1
241                         .table$ = "Config"
242                 elsif .tableNum = 2
243                         .table$ = "MainPage"
244                 endif
245                 .varPrefix$ = replace_regex$(.table$, "^(.)", "\l\1", 0)
247                 select Table '.table$'
248                 .numTableRows = Get number of rows
249                 for .tablerow to .numTableRows
250                         select Table '.table$'
251                         .label$ = Get value... '.tablerow' Label
252                         .variableName$ = .varPrefix$+"."+(replace_regex$(.label$, "^(.)", "\l\1", 0))
253                         .keyName$ = .variableName$
254                         .value$ = ""
255                         if variableExists(.variableName$)
256                                 .value = '.variableName$'
257                                 .value$ = "'.value'"
258                         elsif variableExists(.variableName$ + "$")
259                                 .variableName$ = .variableName$ + "$"
260                                 .value$ = '.variableName$'
261                         elsif index(.variableName$, "_") > 0
262                                 .variableName$ = left$(.variableName$, rindex(.variableName$, "_") - 1) 
263                                 .keyName$ = .variableName$
264                                 select Table Preferences
265                                 .prefRow = Search column... Key '.keyName$'
266                                 if .prefRow <= 0
267                                         if variableExists(.variableName$)
268                                            .value = '.variableName$'
269                                            .value$ = "'.value'"
270                                         elsif variableExists(.variableName$ + "$")
271                                            .variableName$ = .variableName$ + "$"
272                                            .value$ = '.variableName$'
273                                         endif
274                                 endif
275                         endif
277                         if .value$ <> ""
278                                 select Table Preferences
279                                 Append row
280                                 .row += 1
281                                 Set string value... '.row' Key '.keyName$'
282                                 Set string value... '.row' Value '.value$'
283                         endif
284                 endfor
285         endfor
286         
287         # Some extra settings
288         select Table Preferences
289         Append row
290         .row += 1
291         Set string value... '.row' Key wordlistDir
292         Set string value... '.row' Value 'localWordlistDir$'
294         select Table Preferences
295         Append row
296         .row += 1
297         Set string value... '.row' Key wordlistName
298         Set string value... '.row' Value 'wordlistName$'
300         select Table Preferences
301         Write to table file... '.preferencesFile$'
302         Remove
304 endproc
306 ###############################################################
308 # TTS (speech synthesis). Place commands in user info
310 # Prerequisites
311 # speakCommandDir$ = "'preferencesAppDir$'/TTS"
312 # speakCommandFile$ = ""
314 # Make sure sgc2.synthesizer is set!
315 procedure create_default_TTS .language$ .voice$ .samplefreq .gap .pitch_adj .pitch_range .words_per_minute .use_data$ .espeak_phones$
316         sgc2.synthesizer = Create SpeechSynthesizer... '.language$' '.voice$'
317         Set speech output settings... .samplefreq .gap .pitch_adj .pitch_range .words_per_minute '.use_data$' '.espeak_phones$'
318 endproc
320 procedure set_up_TTS
321         if sgc2.synthesizer > 0
322                 select sgc2.synthesizer
323                 Remove
324                 sgc2.synthesizer = -1
325         endif
326         # Note, the TTScommand must set sgc2.synthesizer!
327         if config.strict
328                 'sgc2.advancedTTScommand$'
329         else
330                 'sgc2.normalTTScommand$'
331         endif
333         if macintosh
334                 .ttscommand$ = "speak"
335                 .osName$ = "OSX"
336                 .quote$ = ""
337         elsif unix
338                 .ttscommand$ = "espeak"
339                 .osName$ = "UNIX"
340                 .quote$ = ""
341         elsif windows
342                 .ttscommand$ = "C:/Program Files/eSpeak/command_line/espeak.exe"
343                 .osName$ = "WIN"
344                 .quote$ = """"
345         endif
346         # Global TTS command has precedence
347         if fileReadable("'globalTTSdir$'/TTS_'.osName$'_command.txt")
348                 speakCommandFile$ = "'globalTTSdir$'/TTS_'.osName$'_command.txt"
349                 if config.synthesis$ = "_DISABLED_"
350                         # Default is ON
351                         config.synthesis$ = "eSpeak"
352                 endif
353         endif
355         # Local TTS command, if there is no global one
356         # Command does not exist yet, create it if eSpeak is installed
357         # Make sure to quote the path!
358         if speakCommandFile$ = ""
359                 # Autodetect synthesizer command
360 #               if not fileReadable("'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt")
361 #                       .command_path$ = ""
362 #                       if macintosh
363 #                               system_nocheck  PATH=${PATH}:/opt/local/bin; bash -c -- 'which '.ttscommand$' > "'speakCommandDir$'/command_path.txt"'
364 #                               .command_path$ < 'speakCommandDir$'/command_path.txt
365 #                       elsif unix
366 #                               system_nocheck  PATH=${PATH};bash -c -- 'which '.ttscommand$' > "'speakCommandDir$'/command_path.txt"'
367 #                               .command_path$ < 'speakCommandDir$'/command_path.txt
368 #                       elsif windows
369 #                               if fileReadable(.ttscommand$)
370 #                                       .command_path$ = .ttscommand$
371 #                               endif
372 #                       endif
373 #                       # Remove any newlines
374 #                       .command_path$ = replace$(.command_path$, "'newline$'", "", 0)
376 #                       # Command path found
377 #                       if sgc2.synthesizer <= 0 and .command_path$ <> "" and fileReadable(.command_path$)
378 #                               deleteFile("'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt")
379 #                               fileappend "'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt"  
380 #                               ...'.quote$''.ttscommand$''.quote$' -v zh+f4 -s 100 'newline$'
381 #                               speakCommandFile$ = "'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt"
382 #                       endif
383 #               endif
384 #               if fileReadable("'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt")
385                         speakCommandFile$ = "'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt"
386                 endif
387                 deleteFile("'speakCommandDir$'/command_path.txt")
388         endif
389         
390         # Close off (other TTS maybe a later option)
391         if sgc2.synthesizer > 0 or (speakCommandFile$ <> "" and fileReadable(speakCommandFile$))
392                 config.synthesis$ = "eSpeak"
393         endif
394 endproc
396 ###############################################################
398 # Evaluation tables
400 # Prerequisites
401 # initialiseSGC2.toneevaluation_table$ = ""
402 procedure initialize_toneevaluation_tables
403         # Remove old table
404         if initialiseSGC2.toneevaluation_table$ != ""
405                 select Table 'initialiseSGC2.toneevaluation_table$'
406                 Remove
407         endif
408         initialiseSGC2.toneevaluation_table$ = ""
409         
410         # Create new table
411         Create Table with column names... Performance 0 Tones Correct Wrong Total High Low Wide Narrow Unknown Commented
412         initialiseSGC2.toneevaluation_table$ = "Performance"
413         call get_toneevaluation_row Total
414 endproc
416 procedure get_toneevaluation_row .tones$
417         select Table 'initialiseSGC2.toneevaluation_table$'
418     .row = Search column... Tones '.tones$'
419         if .row < 1
420                 Append row
421                 .row = Get number of rows
422                 Set string value... '.row' Tones '.tones$'
423                 Set numeric value... '.row' Correct 0
424                 Set numeric value... '.row' Wrong 0
425                 Set numeric value... '.row' Total 0
426                 Set numeric value... '.row' High 0
427                 Set numeric value... '.row' Low 0
428                 Set numeric value... '.row' Wide 0
429                 Set numeric value... '.row' Narrow 0
430                 Set numeric value... '.row' Unknown 0
431                 Set numeric value... '.row' Commented 0
432                 Sort rows... Tones
433         .row = Search column... Tones '.tones$'
434         endif
435 endproc
437 procedure increment_toneevaluation_in_row .row .column$
438         select Table 'initialiseSGC2.toneevaluation_table$'
439         .tmp = Get value... '.row' '.column$'
440         .tmp += 1
441         Set numeric value... '.row' '.column$' '.tmp'
442 endproc
444 procedure increment_toneevaluation_value .tones$ .column$
445         call get_toneevaluation_row '.tones$'
446         .row = get_toneevaluation_row.row
447         call increment_toneevaluation_in_row '.row' '.column$'
448         
449         call get_toneevaluation_row Total
450         .row = get_toneevaluation_row.row
451         call increment_toneevaluation_in_row '.row' '.column$'
452 endproc
454 procedure add_feedback_to_toneevaluation .table$
455     select Table '.table$'
456     .line1$ = Get value... 1 Text
457     .line2$ = Get value... 2 Text
458     .label$ = Get value... 3 Text
459         if .label$ = "6"
460                 .label$ = "Unknown"
461         endif
462         
463         .tones$ = replace_regex$(left$(.line1$, rindex(.line1$, ":")), "[^0-9]", "", 0)
464         .recognized$ = replace_regex$(right$(.line1$, length(.line1$)-rindex(.line1$, ":")), "[^0-9]", "", 0)
465         
466         # Set evaluation
467         call increment_toneevaluation_value '.tones$' Total
468         if .tones$ = .recognized$
469                 call increment_toneevaluation_value '.tones$' Correct
470         else
471                 call increment_toneevaluation_value '.tones$' Wrong
472         endif
473         if index_regex(.label$, "(Correct|Wrong)") <= 0
474                 call increment_toneevaluation_value '.tones$' '.label$'
475                 call increment_toneevaluation_value '.tones$' Commented
476         endif
477 endproc
479 procedure CreateSummaryToneEvaluation
480         .font$ = "Helvetica"
481         # Summarize tone evaluation
482         Create Table with column names... SummaryToneEvaluation 0 Total Correct Problematic
483         # Create texts
484         call get_toneevaluation_row Total
485         .row = get_toneevaluation_row.row
486         select Table 'initialiseSGC2.toneevaluation_table$'
487         .total = Get value... '.row' Total
488         .correct = Get value... '.row' Correct
489         if .total > 0
490                 .correctPerc = 100 * .correct / .total
491         else
492                 .correctPerc = 0
493         endif
494         .problematic = Get value... '.row' Commented
495         if .total > 0
496                 .problematicPerc = 100 * .problematic / .total
497         else
498                 .problematicPerc = 0
499         endif
501         select Table SummaryToneEvaluation
502         Append row
503         Set numeric value... 1 Total '.total'
504         Set numeric value... 1 Correct '.correctPerc'
505         Set numeric value... 1 Problematic '.problematicPerc'
506 endproc
508 ###############################################################
510 # Miscelaneous procedures
512 ###############################################################
514 # Create a file 'preferencesAppDir$'/log/logPerformance
515 # This file contains the path to the target directory where logging
516 # is to be stored.
517 # Note that this procedure is nowhere used in SGC2. It has to
518 # be explicitely called in a separate script.
520 procedure activate_sgc2_logging .targetDirectory$
521         createDirectory("'preferencesAppDir$'")
522         preferencesAppDir$ > 'preferencesAppDir$'/directory.txt
523         createDirectory("'preferencesLogDir$'")
524         preferencesLogDir$ > 'preferencesLogDir$'/directory.txt
525         
526         if startsWith(.targetDirectory$, "~")
527                 .targetDirectory$ = replace$(.targetDirectory$, "~", homeDirectory$, 1)
528         endif
529         
530         .targetDirectory$ > 'preferencesLogDir$'/logPerformance.txt
531         newline$ >> 'preferencesLogDir$'/logPerformance.txt
532 endproc
534 # TTS synthesis
535 procedure synthesize_sound .pinyin$
536         .command$ = ""
537         if speakCommandFile$ <> "" and fileReadable(speakCommandFile$)
538                 .command$ < 'speakCommandFile$'
539                 .command$ = replace$(.command$, "'newline$'", " ", 0)
540                 if macintosh
541                         system_nocheck PATH=${PATH}:/usr/local/bin:/opt/local/bin; bash -rc -- ''.command$' "'.pinyin$'"'
542                 elsif unix
543                         system_nocheck bash -rc -- ''.command$' "'.pinyin$'"'
544                 elsif windows
545                         system_nocheck call '.command$' "'.pinyin$'"'
546                 endif
547         elsif sgc2.synthesizer > 0
548                 select sgc2.synthesizer
549                 Play text... '.pinyin$'
550         endif
551 endproc
553 procedure align_recordedSound .pinyin$
554         if 0 and sgc2.synthesizer > 0 and recordedSound$ <> ""
555                 select Sound 'recordedSound$'
556                 .recordedTextGrid = To TextGrid... pinyin
557                 Set interval text... 1 1 '.pinyin$'
558                 select sgc2.synthesizer
559                 plus Sound 'recordedSound$'
560                 plus .recordedTextGrid
561                 sgc2.alignedTextGrid = nowarn noprogress To TextGrid (align,trim)... 1 1 1 -35 0.1 0.1 0.08
562                 Rename... AlignedTextGrid
563                 select .recordedTextGrid
564                 Remove
565         endif
566 endproc