Adapted to praat 5.3.64
[sgc2.git] / InitialiseSGC2.praat
blobee01533e29b4776d63d475a8a3deeed6a56cb6c4
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 te.currentWord = 1
53 te.numberOfWords = 0
54 te.recordedSound = 0
55 pinyin$ = ""
56 character$ = ""
57 buttons$ = ""
58 config$ = ""
59 wordlistNum = 1
60 wordlistName$ = ""
61 wordlist$ = ""
62 config.deleteWordlist = -1
63 config.displayNumbers = 1
64 config.displayPinyin = 1
65 config.displayChar = 0
66 config.displayTrans = 1
67 config.useSoundExample = 1
68 config.synthesis$ = "_DISABLED_"
69 config.input$ = "Microphone"
70 config.showBackground = 1
71 sgc2.noiseThresshold = -30
72 config.strict = 0
74 sgc_ToneProt.minimumPitch = 40
75 sgc_ToneProt.maximumPitch = 600
77 # Platform dependent settings
78 if macintosh or windows
79         config.displayChar = 1
80         config.displayNumbers = 0
81 endif
82 if windows and endsWith(build_SHA$, " XP")
83         config.displayChar = 0
84         config.displayNumbers = 0
85 endif
86 if unix
87         config.displayChar = 0
88         config.displayNumbers = 1
89 endif
91 if unix
92         samplingFrequency = 44100
93 elsif macintosh
94         samplingFrequency = 44100
95 elsif windows
96         samplingFrequency = 44100
97 endif
98 recordingTime = 2
100 logging = 0
101 config.language$ = "EN"
102 config.register = 249
103 config.logPerformance = 0
104 preferencesLogDir$ = "'preferencesAppDir$'/log"
105 preferencesTableDir$ = "'preferencesAppDir$'/Data"
106 sgc2wordlists$ = "'preferencesAppDir$'/wordlists"
107 localWordlistDir$ = sgc2wordlists$
109 # Global word lists must be installed BY THE ADMINISTRATOR
110 # This means, create the directory 'globalwordlists$' and
111 # fill it with wordlist directories containing wordlist.Table
112 # and audio files. They can be copied from a local directory.
113 globalwordlists$ = ""
114 globaltablelists$ = ""
115 globalTTSdir$ = ""
116 if unix
117         globalwordlists$ = "/etc/'sgc2.demoAppName$'/wordlists"
118         globaltablelists$ = "/etc/'sgc2.demoAppName$'/Data"     
119         globalTTSdir$ = "/etc/'sgc2.demoAppName$'/TTS"  
120 elsif macintosh
121         globalwordlists$ = "/Library/Preferences/'sgc2.demoAppName$'/wordlists"
122         globaltablelists$ = "/Library/Preferences/'sgc2.demoAppName$'/Data"
123         globalTTSdir$ = "/Library/Preferences/'sgc2.demoAppName$'/TTS"  
124 elsif windows
125         globalwordlists$ = "C:/Documents and Settings/All Users/Application Data/'sgc2.demoAppName$'/wordlists"
126         globaltablelists$ = "C:/Documents and Settings/All Users/Application Data/'sgc2.demoAppName$'/Data"
127         globalTTSdir$ = "C:/Documents and Settings/All Users/Application Data/'sgc2.demoAppName$'/TTS"
128 endif
129 sgc2.synthesizer = -1
130 # Define a Praat TTS command that will set sgc2.synthesizer
131 sgc2.normalTTScommand$ = "call create_default_TTS Mandarin f4 10000 0.01 50 100 95 no IPA"
132 sgc2.advancedTTScommand$ = "call create_default_TTS Mandarin f4 10000 0.01 50 70 125 no IPA"
133 sgc2.alignedTextGrid = -1
135 ##############################################################
137 config.shuffleLists = 1
138 defaultFontSize = 12
139 defaultFont$ = "Helvetica"
140 defaultLineWidth = 1
142 # Set up directories if they do not exist already
143 call set_up_directories
145 # Get saved preferences
146 call read_preferences ""
148 # Set up TTS system
149 speakCommandDir$ = "'preferencesAppDir$'/TTS"
150 speakCommandFile$ = ""
151 call set_up_TTS
153 # Set inital language
154 call set_language 'config.language$'
156 # Get the word-list
157 call load_word_list "'localWordlistDir$'" 0
159 # Set up evaluation table
160 initialiseSGC2.toneevaluation_table$ = ""
161 call initialize_toneevaluation_tables
163 # Draw inital window
164 call init_window
166 ###############################################################
168 # Obligatory procedures
170 ###############################################################
171 # Initialize Demo Window
172 procedure init_window
173     demo Erase all
174         demo Line width... 'defaultLineWidth'
175         demo 'defaultFont$'
176         call set_font_size 'defaultFontSize'
177         demo Black
178         call reset_viewport
179         .windowTitle$ = replace$(wordlistName$, "_", " ", 0)
180         call set_window_title 'buttons$' '.windowTitle$'
181         # Display the word-list
182         call write_word_list
183     # Wipe screen and draw background
184     call wipeArea 'wipeContourArea$'
185         if config.showBackground
186                 call draw_background Background
187         endif
188     # Define buttons in a table
189     call init_buttons
190         # Draw the contour
191         call draw_tone_contour
192         # Logging light
193         call paint_logging_light
194 endproc
196 # Make sure all Preferences directories are available
197 procedure set_up_directories
198         .dirPath$ = "'preferencesAppDir$'"
199         createDirectory(.dirPath$)
200         .dirPath$ > '.dirPath$'/directory.txt
201         createDirectory("'.dirPath$'/wordlists")
202         .dirPath$ > '.dirPath$'/wordlists/directory.txt
203         createDirectory("'.dirPath$'/pitchmodels")
204         .dirPath$ > '.dirPath$'/pitchmodels/directory.txt
205         createDirectory("'.dirPath$'/log")
206         .dirPath$ > '.dirPath$'/log/directory.txt
207         createDirectory("'.dirPath$'/TTS")
208         .dirPath$ > '.dirPath$'/TTS/directory.txt
209 endproc
212 # Retrieve and store setting between sessions
214 procedure read_preferences .preferencesFile$
215         if not fileReadable(.preferencesFile$)
216                 .preferencesFile$ = preferencesAppDir$+"/sgc2rc.txt"
217         endif
218         if fileReadable(.preferencesFile$)
219                 Read from file... 'preferencesAppDir$'/sgc2rc.txt
220                 .preferenceTable$ = selected$("Table")
221                 .numPrefKeys = Get number of rows
222                 for .row to .numPrefKeys
223                         .variableName$ = Get value... '.row' Key
224                         if variableExists(.variableName$)
225                                 .variableValue = Get value... '.row' Value
226                                 if .variableValue <> undefined
227                                         '.variableName$' = '.variableValue'
228                                 endif
229                         elsif variableExists(.variableName$+"$")
230                                 .variableValue$ = Get value... '.row' Value
231                                 .variableName$ = .variableName$+"$"
232                                 '.variableName$' = "'.variableValue$'"
233                         endif
234                 endfor
235                 
236                 select Table '.preferenceTable$'
237                 Remove
238         endif
239 endproc
241 procedure write_preferences .preferencesFile$
242         Create Table with column names... Preferences 0 Key Value
243         if index_regex(.preferencesFile$, "[a-zA-Z0-9]") <= 0
244                 .preferencesFile$ = preferencesAppDir$ + "/sgc2rc.txt"
245         endif
246         .row = 0
247         
248         for .tableNum from 1 to 2
249                 if .tableNum = 1
250                         .table$ = "Config"
251                 elsif .tableNum = 2
252                         .table$ = "MainPage"
253                 endif
254                 .varPrefix$ = replace_regex$(.table$, "^(.)", "\l\1", 0)
256                 select Table '.table$'
257                 .numTableRows = Get number of rows
258                 for .tablerow to .numTableRows
259                         select Table '.table$'
260                         .label$ = Get value... '.tablerow' Label
261                         .variableName$ = .varPrefix$+"."+(replace_regex$(.label$, "^(.)", "\l\1", 0))
262                         .keyName$ = .variableName$
263                         .value$ = ""
264                         if variableExists(.variableName$)
265                                 .value = '.variableName$'
266                                 .value$ = "'.value'"
267                         elsif variableExists(.variableName$ + "$")
268                                 .variableName$ = .variableName$ + "$"
269                                 .value$ = '.variableName$'
270                         elsif index(.variableName$, "_") > 0
271                                 .variableName$ = left$(.variableName$, rindex(.variableName$, "_") - 1) 
272                                 .keyName$ = .variableName$
273                                 select Table Preferences
274                                 .prefRow = Search column... Key '.keyName$'
275                                 if .prefRow <= 0
276                                         if variableExists(.variableName$)
277                                            .value = '.variableName$'
278                                            .value$ = "'.value'"
279                                         elsif variableExists(.variableName$ + "$")
280                                            .variableName$ = .variableName$ + "$"
281                                            .value$ = '.variableName$'
282                                         endif
283                                 endif
284                         endif
286                         if .value$ <> ""
287                                 select Table Preferences
288                                 Append row
289                                 .row += 1
290                                 Set string value... '.row' Key '.keyName$'
291                                 Set string value... '.row' Value '.value$'
292                         endif
293                 endfor
294         endfor
295         
296         # Some extra settings
297         select Table Preferences
298         Append row
299         .row += 1
300         Set string value... '.row' Key wordlistDir
301         Set string value... '.row' Value 'localWordlistDir$'
303         select Table Preferences
304         Append row
305         .row += 1
306         Set string value... '.row' Key wordlistName
307         Set string value... '.row' Value 'wordlistName$'
309         select Table Preferences
310         Write to table file... '.preferencesFile$'
311         Remove
313 endproc
315 ###############################################################
317 # TTS (speech synthesis). Place commands in user info
319 # Prerequisites
320 # speakCommandDir$ = "'preferencesAppDir$'/TTS"
321 # speakCommandFile$ = ""
323 # Make sure sgc2.synthesizer is set!
324 procedure create_default_TTS .language$ .voice$ .samplefreq .gap .pitch_adj .pitch_range .words_per_minute .use_data$ .espeak_phones$
325         sgc2.synthesizer = Create SpeechSynthesizer... '.language$' '.voice$'
326         Set speech output settings... .samplefreq .gap .pitch_adj .pitch_range .words_per_minute '.use_data$' '.espeak_phones$'
327 endproc
329 procedure set_up_TTS
330         if sgc2.synthesizer > 0
331                 select sgc2.synthesizer
332                 Remove
333                 sgc2.synthesizer = -1
334         endif
335         # Note, the TTScommand must set sgc2.synthesizer!
336         if config.strict
337                 'sgc2.advancedTTScommand$'
338         else
339                 'sgc2.normalTTScommand$'
340         endif
342         if macintosh
343                 .ttscommand$ = "speak"
344                 .osName$ = "OSX"
345                 .quote$ = ""
346         elsif unix
347                 .ttscommand$ = "espeak"
348                 .osName$ = "UNIX"
349                 .quote$ = ""
350         elsif windows
351                 .ttscommand$ = "C:/Program Files/eSpeak/command_line/espeak.exe"
352                 .osName$ = "WIN"
353                 .quote$ = """"
354         endif
355         # Global TTS command has precedence
356         if fileReadable("'globalTTSdir$'/TTS_'.osName$'_command.txt")
357                 speakCommandFile$ = "'globalTTSdir$'/TTS_'.osName$'_command.txt"
358                 if config.synthesis$ = "_DISABLED_"
359                         # Default is ON
360                         config.synthesis$ = "eSpeak"
361                 endif
362         endif
364         # Local TTS command, if there is no global one
365         # Command does not exist yet, create it if eSpeak is installed
366         # Make sure to quote the path!
367         if speakCommandFile$ = ""
368                 # Autodetect synthesizer command
369 #               if not fileReadable("'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt")
370 #                       .command_path$ = ""
371 #                       if macintosh
372 #                               system_nocheck  PATH=${PATH}:/opt/local/bin; bash -c -- 'which '.ttscommand$' > "'speakCommandDir$'/command_path.txt"'
373 #                               .command_path$ < 'speakCommandDir$'/command_path.txt
374 #                       elsif unix
375 #                               system_nocheck  PATH=${PATH};bash -c -- 'which '.ttscommand$' > "'speakCommandDir$'/command_path.txt"'
376 #                               .command_path$ < 'speakCommandDir$'/command_path.txt
377 #                       elsif windows
378 #                               if fileReadable(.ttscommand$)
379 #                                       .command_path$ = .ttscommand$
380 #                               endif
381 #                       endif
382 #                       # Remove any newlines
383 #                       .command_path$ = replace$(.command_path$, "'newline$'", "", 0)
385 #                       # Command path found
386 #                       if sgc2.synthesizer <= 0 and .command_path$ <> "" and fileReadable(.command_path$)
387 #                               deleteFile("'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt")
388 #                               fileappend "'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt"  
389 #                               ...'.quote$''.ttscommand$''.quote$' -v zh+f4 -s 100 'newline$'
390 #                               speakCommandFile$ = "'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt"
391 #                       endif
392 #               endif
393 #               if fileReadable("'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt")
394                         speakCommandFile$ = "'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt"
395                 endif
396                 deleteFile("'speakCommandDir$'/command_path.txt")
397         endif
398         
399         # Close off (other TTS maybe a later option)
400         if sgc2.synthesizer > 0 or (speakCommandFile$ <> "" and fileReadable(speakCommandFile$))
401                 config.synthesis$ = "eSpeak"
402         endif
403 endproc
405 ###############################################################
407 # Evaluation tables
409 # Prerequisites
410 # initialiseSGC2.toneevaluation_table$ = ""
411 procedure initialize_toneevaluation_tables
412         # Remove old table
413         if initialiseSGC2.toneevaluation_table$ != ""
414                 select Table 'initialiseSGC2.toneevaluation_table$'
415                 Remove
416         endif
417         initialiseSGC2.toneevaluation_table$ = ""
418         
419         # Create new table
420         Create Table with column names... Performance 0 Tones Correct Wrong Total High Low Wide Narrow Unknown Commented
421         initialiseSGC2.toneevaluation_table$ = "Performance"
422         call get_toneevaluation_row Total
423 endproc
425 procedure get_toneevaluation_row .tones$
426         select Table 'initialiseSGC2.toneevaluation_table$'
427     .row = Search column... Tones '.tones$'
428         if .row < 1
429                 Append row
430                 .row = Get number of rows
431                 Set string value... '.row' Tones '.tones$'
432                 Set numeric value... '.row' Correct 0
433                 Set numeric value... '.row' Wrong 0
434                 Set numeric value... '.row' Total 0
435                 Set numeric value... '.row' High 0
436                 Set numeric value... '.row' Low 0
437                 Set numeric value... '.row' Wide 0
438                 Set numeric value... '.row' Narrow 0
439                 Set numeric value... '.row' Unknown 0
440                 Set numeric value... '.row' Commented 0
441                 Sort rows... Tones
442         .row = Search column... Tones '.tones$'
443         endif
444 endproc
446 procedure increment_toneevaluation_in_row .row .column$
447         select Table 'initialiseSGC2.toneevaluation_table$'
448         .tmp = Get value... '.row' '.column$'
449         .tmp += 1
450         Set numeric value... '.row' '.column$' '.tmp'
451 endproc
453 procedure increment_toneevaluation_value .tones$ .column$
454         call get_toneevaluation_row '.tones$'
455         .row = get_toneevaluation_row.row
456         call increment_toneevaluation_in_row '.row' '.column$'
457         
458         call get_toneevaluation_row Total
459         .row = get_toneevaluation_row.row
460         call increment_toneevaluation_in_row '.row' '.column$'
461 endproc
463 procedure add_feedback_to_toneevaluation .table$
464     select Table '.table$'
465     .line1$ = Get value... 1 Text
466     .line2$ = Get value... 2 Text
467     .label$ = Get value... 3 Text
468         if .label$ = "6"
469                 .label$ = "Unknown"
470         endif
471         
472         .tones$ = replace_regex$(left$(.line1$, rindex(.line1$, ":")), "[^0-9]", "", 0)
473         .recognized$ = replace_regex$(right$(.line1$, length(.line1$)-rindex(.line1$, ":")), "[^0-9]", "", 0)
474         
475         # Set evaluation
476         call increment_toneevaluation_value '.tones$' Total
477         if .tones$ = .recognized$
478                 call increment_toneevaluation_value '.tones$' Correct
479         else
480                 call increment_toneevaluation_value '.tones$' Wrong
481         endif
482         if index_regex(.label$, "(Correct|Wrong)") <= 0
483                 call increment_toneevaluation_value '.tones$' '.label$'
484                 call increment_toneevaluation_value '.tones$' Commented
485         endif
486 endproc
488 procedure CreateSummaryToneEvaluation
489         .font$ = "Helvetica"
490         # Summarize tone evaluation
491         Create Table with column names... SummaryToneEvaluation 0 Total Correct Problematic
492         # Create texts
493         call get_toneevaluation_row Total
494         .row = get_toneevaluation_row.row
495         select Table 'initialiseSGC2.toneevaluation_table$'
496         .total = Get value... '.row' Total
497         .correct = Get value... '.row' Correct
498         if .total > 0
499                 .correctPerc = 100 * .correct / .total
500         else
501                 .correctPerc = 0
502         endif
503         .problematic = Get value... '.row' Commented
504         if .total > 0
505                 .problematicPerc = 100 * .problematic / .total
506         else
507                 .problematicPerc = 0
508         endif
510         select Table SummaryToneEvaluation
511         Append row
512         Set numeric value... 1 Total '.total'
513         Set numeric value... 1 Correct '.correctPerc'
514         Set numeric value... 1 Problematic '.problematicPerc'
515 endproc
517 ###############################################################
519 # Miscelaneous procedures
521 ###############################################################
523 # Create a file 'preferencesAppDir$'/log/logPerformance
524 # This file contains the path to the target directory where logging
525 # is to be stored.
526 # Note that this procedure is nowhere used in SGC2. It has to
527 # be explicitely called in a separate script.
529 procedure activate_sgc2_logging .targetDirectory$
530         createDirectory("'preferencesAppDir$'")
531         preferencesAppDir$ > 'preferencesAppDir$'/directory.txt
532         createDirectory("'preferencesLogDir$'")
533         preferencesLogDir$ > 'preferencesLogDir$'/directory.txt
534         
535         if startsWith(.targetDirectory$, "~")
536                 .targetDirectory$ = replace$(.targetDirectory$, "~", homeDirectory$, 1)
537         endif
538         
539         .targetDirectory$ > 'preferencesLogDir$'/logPerformance.txt
540         newline$ >> 'preferencesLogDir$'/logPerformance.txt
541 endproc
543 # TTS synthesis
544 procedure synthesize_sound .pinyin$
545         .command$ = ""
546         if speakCommandFile$ <> "" and fileReadable(speakCommandFile$)
547                 .command$ < 'speakCommandFile$'
548                 .command$ = replace$(.command$, "'newline$'", " ", 0)
549                 if macintosh
550                         system_nocheck PATH=${PATH}:/usr/local/bin:/opt/local/bin; bash -rc -- ''.command$' "'.pinyin$'"'
551                 elsif unix
552                         system_nocheck bash -rc -- ''.command$' "'.pinyin$'"'
553                 elsif windows
554                         system_nocheck call '.command$' "'.pinyin$'"'
555                 endif
556         elsif sgc2.synthesizer > 0
557                 select sgc2.synthesizer
558                 Play text... '.pinyin$'
559         endif
560 endproc
562 procedure align_recordedSound .pinyin$
563         if 0 and sgc2.synthesizer > 0 and recordedSound$ <> ""
564                 select Sound 'recordedSound$'
565                 .recordedTextGrid = To TextGrid... pinyin
566                 Set interval text... 1 1 '.pinyin$'
567                 select sgc2.synthesizer
568                 plus Sound 'recordedSound$'
569                 plus .recordedTextGrid
570                 sgc2.alignedTextGrid = nowarn noprogress To TextGrid (align,trim)... 1 1 1 -35 0.1 0.1 0.08
571                 Rename... AlignedTextGrid
572                 select .recordedTextGrid
573                 Remove
574         endif
575 endproc