Adapted patch to Praat 5.3.55
[sgc2.git] / InitialiseSGC2.praat
blobefbe3f358193956c34e400ca5998fff42d311bbc
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$'/log")
195         .dirPath$ > '.dirPath$'/log/directory.txt
196         createDirectory("'.dirPath$'/TTS")
197         .dirPath$ > '.dirPath$'/TTS/directory.txt
198 endproc
201 # Retrieve and store setting between sessions
203 procedure read_preferences .preferencesFile$
204         if not fileReadable(.preferencesFile$)
205                 .preferencesFile$ = preferencesAppDir$+"/sgc2rc.txt"
206         endif
207         if fileReadable(.preferencesFile$)
208                 Read from file... 'preferencesAppDir$'/sgc2rc.txt
209                 .preferenceTable$ = selected$("Table")
210                 .numPrefKeys = Get number of rows
211                 for .row to .numPrefKeys
212                         .variableName$ = Get value... '.row' Key
213                         if variableExists(.variableName$)
214                                 .variableValue = Get value... '.row' Value
215                                 if .variableValue <> undefined
216                                         '.variableName$' = '.variableValue'
217                                 endif
218                         elsif variableExists(.variableName$+"$")
219                                 .variableValue$ = Get value... '.row' Value
220                                 .variableName$ = .variableName$+"$"
221                                 '.variableName$' = "'.variableValue$'"
222                         endif
223                 endfor
224                 
225                 select Table '.preferenceTable$'
226                 Remove
227         endif
228 endproc
230 procedure write_preferences .preferencesFile$
231         Create Table with column names... Preferences 0 Key Value
232         if index_regex(.preferencesFile$, "[a-zA-Z0-9]") <= 0
233                 .preferencesFile$ = preferencesAppDir$ + "/sgc2rc.txt"
234         endif
235         .row = 0
236         
237         for .tableNum from 1 to 2
238                 if .tableNum = 1
239                         .table$ = "Config"
240                 elsif .tableNum = 2
241                         .table$ = "MainPage"
242                 endif
243                 .varPrefix$ = replace_regex$(.table$, "^(.)", "\l\1", 0)
245                 select Table '.table$'
246                 .numTableRows = Get number of rows
247                 for .tablerow to .numTableRows
248                         select Table '.table$'
249                         .label$ = Get value... '.tablerow' Label
250                         .variableName$ = .varPrefix$+"."+(replace_regex$(.label$, "^(.)", "\l\1", 0))
251                         .keyName$ = .variableName$
252                         .value$ = ""
253                         if variableExists(.variableName$)
254                                 .value = '.variableName$'
255                                 .value$ = "'.value'"
256                         elsif variableExists(.variableName$ + "$")
257                                 .variableName$ = .variableName$ + "$"
258                                 .value$ = '.variableName$'
259                         elsif index(.variableName$, "_") > 0
260                                 .variableName$ = left$(.variableName$, rindex(.variableName$, "_") - 1) 
261                                 .keyName$ = .variableName$
262                                 select Table Preferences
263                                 .prefRow = Search column... Key '.keyName$'
264                                 if .prefRow <= 0
265                                         if variableExists(.variableName$)
266                                            .value = '.variableName$'
267                                            .value$ = "'.value'"
268                                         elsif variableExists(.variableName$ + "$")
269                                            .variableName$ = .variableName$ + "$"
270                                            .value$ = '.variableName$'
271                                         endif
272                                 endif
273                         endif
275                         if .value$ <> ""
276                                 select Table Preferences
277                                 Append row
278                                 .row += 1
279                                 Set string value... '.row' Key '.keyName$'
280                                 Set string value... '.row' Value '.value$'
281                         endif
282                 endfor
283         endfor
284         
285         # Some extra settings
286         select Table Preferences
287         Append row
288         .row += 1
289         Set string value... '.row' Key wordlistDir
290         Set string value... '.row' Value 'localWordlistDir$'
292         select Table Preferences
293         Append row
294         .row += 1
295         Set string value... '.row' Key wordlistName
296         Set string value... '.row' Value 'wordlistName$'
298         select Table Preferences
299         Write to table file... '.preferencesFile$'
300         Remove
302 endproc
304 ###############################################################
306 # TTS (speech synthesis). Place commands in user info
308 # Prerequisites
309 # speakCommandDir$ = "'preferencesAppDir$'/TTS"
310 # speakCommandFile$ = ""
312 # Make sure sgc2.synthesizer is set!
313 procedure create_default_TTS .language$ .voice$ .samplefreq .gap .pitch_adj .pitch_range .words_per_minute .use_data$ .espeak_phones$
314         sgc2.synthesizer = Create SpeechSynthesizer... '.language$' '.voice$'
315         Set speech output settings... .samplefreq .gap .pitch_adj .pitch_range .words_per_minute '.use_data$' '.espeak_phones$'
316 endproc
318 procedure set_up_TTS
319         if sgc2.synthesizer > 0
320                 select sgc2.synthesizer
321                 Remove
322                 sgc2.synthesizer = -1
323         endif
324         # Note, the TTScommand must set sgc2.synthesizer!
325         if config.strict
326                 'sgc2.advancedTTScommand$'
327         else
328                 'sgc2.normalTTScommand$'
329         endif
331         if macintosh
332                 .ttscommand$ = "speak"
333                 .osName$ = "OSX"
334                 .quote$ = ""
335         elsif unix
336                 .ttscommand$ = "espeak"
337                 .osName$ = "UNIX"
338                 .quote$ = ""
339         elsif windows
340                 .ttscommand$ = "C:/Program Files/eSpeak/command_line/espeak.exe"
341                 .osName$ = "WIN"
342                 .quote$ = """"
343         endif
344         # Global TTS command has precedence
345         if fileReadable("'globalTTSdir$'/TTS_'.osName$'_command.txt")
346                 speakCommandFile$ = "'globalTTSdir$'/TTS_'.osName$'_command.txt"
347                 if config.synthesis$ = "_DISABLED_"
348                         # Default is ON
349                         config.synthesis$ = "eSpeak"
350                 endif
351         endif
353         # Local TTS command, if there is no global one
354         # Command does not exist yet, create it if eSpeak is installed
355         # Make sure to quote the path!
356         if speakCommandFile$ = ""
357                 # Autodetect synthesizer command
358 #               if not fileReadable("'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt")
359 #                       .command_path$ = ""
360 #                       if macintosh
361 #                               system_nocheck  PATH=${PATH}:/opt/local/bin; bash -c -- 'which '.ttscommand$' > "'speakCommandDir$'/command_path.txt"'
362 #                               .command_path$ < 'speakCommandDir$'/command_path.txt
363 #                       elsif unix
364 #                               system_nocheck  PATH=${PATH};bash -c -- 'which '.ttscommand$' > "'speakCommandDir$'/command_path.txt"'
365 #                               .command_path$ < 'speakCommandDir$'/command_path.txt
366 #                       elsif windows
367 #                               if fileReadable(.ttscommand$)
368 #                                       .command_path$ = .ttscommand$
369 #                               endif
370 #                       endif
371 #                       # Remove any newlines
372 #                       .command_path$ = replace$(.command_path$, "'newline$'", "", 0)
374 #                       # Command path found
375 #                       if sgc2.synthesizer <= 0 and .command_path$ <> "" and fileReadable(.command_path$)
376 #                               deleteFile("'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt")
377 #                               fileappend "'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt"  
378 #                               ...'.quote$''.ttscommand$''.quote$' -v zh+f4 -s 100 'newline$'
379 #                               speakCommandFile$ = "'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt"
380 #                       endif
381 #               endif
382 #               if fileReadable("'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt")
383                         speakCommandFile$ = "'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt"
384                 endif
385                 deleteFile("'speakCommandDir$'/command_path.txt")
386         endif
387         
388         # Close off (other TTS maybe a later option)
389         if sgc2.synthesizer > 0 or (speakCommandFile$ <> "" and fileReadable(speakCommandFile$))
390                 config.synthesis$ = "eSpeak"
391         endif
392 endproc
394 ###############################################################
396 # Evaluation tables
398 # Prerequisites
399 # initialiseSGC2.toneevaluation_table$ = ""
400 procedure initialize_toneevaluation_tables
401         # Remove old table
402         if initialiseSGC2.toneevaluation_table$ != ""
403                 select Table 'initialiseSGC2.toneevaluation_table$'
404                 Remove
405         endif
406         initialiseSGC2.toneevaluation_table$ = ""
407         
408         # Create new table
409         Create Table with column names... Performance 0 Tones Correct Wrong Total High Low Wide Narrow Unknown Commented
410         initialiseSGC2.toneevaluation_table$ = "Performance"
411         call get_toneevaluation_row Total
412 endproc
414 procedure get_toneevaluation_row .tones$
415         select Table 'initialiseSGC2.toneevaluation_table$'
416     .row = Search column... Tones '.tones$'
417         if .row < 1
418                 Append row
419                 .row = Get number of rows
420                 Set string value... '.row' Tones '.tones$'
421                 Set numeric value... '.row' Correct 0
422                 Set numeric value... '.row' Wrong 0
423                 Set numeric value... '.row' Total 0
424                 Set numeric value... '.row' High 0
425                 Set numeric value... '.row' Low 0
426                 Set numeric value... '.row' Wide 0
427                 Set numeric value... '.row' Narrow 0
428                 Set numeric value... '.row' Unknown 0
429                 Set numeric value... '.row' Commented 0
430                 Sort rows... Tones
431         .row = Search column... Tones '.tones$'
432         endif
433 endproc
435 procedure increment_toneevaluation_in_row .row .column$
436         select Table 'initialiseSGC2.toneevaluation_table$'
437         .tmp = Get value... '.row' '.column$'
438         .tmp += 1
439         Set numeric value... '.row' '.column$' '.tmp'
440 endproc
442 procedure increment_toneevaluation_value .tones$ .column$
443         call get_toneevaluation_row '.tones$'
444         .row = get_toneevaluation_row.row
445         call increment_toneevaluation_in_row '.row' '.column$'
446         
447         call get_toneevaluation_row Total
448         .row = get_toneevaluation_row.row
449         call increment_toneevaluation_in_row '.row' '.column$'
450 endproc
452 procedure add_feedback_to_toneevaluation .table$
453     select Table '.table$'
454     .line1$ = Get value... 1 Text
455     .line2$ = Get value... 2 Text
456     .label$ = Get value... 3 Text
457         if .label$ = "6"
458                 .label$ = "Unknown"
459         endif
460         
461         .tones$ = replace_regex$(left$(.line1$, rindex(.line1$, ":")), "[^0-9]", "", 0)
462         .recognized$ = replace_regex$(right$(.line1$, length(.line1$)-rindex(.line1$, ":")), "[^0-9]", "", 0)
463         
464         # Set evaluation
465         call increment_toneevaluation_value '.tones$' Total
466         if .tones$ = .recognized$
467                 call increment_toneevaluation_value '.tones$' Correct
468         else
469                 call increment_toneevaluation_value '.tones$' Wrong
470         endif
471         if index_regex(.label$, "(Correct|Wrong)") <= 0
472                 call increment_toneevaluation_value '.tones$' '.label$'
473                 call increment_toneevaluation_value '.tones$' Commented
474         endif
475 endproc
477 procedure CreateSummaryToneEvaluation
478         .font$ = "Helvetica"
479         # Summarize tone evaluation
480         Create Table with column names... SummaryToneEvaluation 0 Total Correct Problematic
481         # Create texts
482         call get_toneevaluation_row Total
483         .row = get_toneevaluation_row.row
484         select Table 'initialiseSGC2.toneevaluation_table$'
485         .total = Get value... '.row' Total
486         .correct = Get value... '.row' Correct
487         if .total > 0
488                 .correctPerc = 100 * .correct / .total
489         else
490                 .correctPerc = 0
491         endif
492         .problematic = Get value... '.row' Commented
493         if .total > 0
494                 .problematicPerc = 100 * .problematic / .total
495         else
496                 .problematicPerc = 0
497         endif
499         select Table SummaryToneEvaluation
500         Append row
501         Set numeric value... 1 Total '.total'
502         Set numeric value... 1 Correct '.correctPerc'
503         Set numeric value... 1 Problematic '.problematicPerc'
504 endproc
506 ###############################################################
508 # Miscelaneous procedures
510 ###############################################################
512 # Create a file 'preferencesAppDir$'/log/logPerformance
513 # This file contains the path to the target directory where logging
514 # is to be stored.
515 # Note that this procedure is nowhere used in SGC2. It has to
516 # be explicitely called in a separate script.
518 procedure activate_sgc2_logging .targetDirectory$
519         createDirectory("'preferencesAppDir$'")
520         preferencesAppDir$ > 'preferencesAppDir$'/directory.txt
521         createDirectory("'preferencesLogDir$'")
522         preferencesLogDir$ > 'preferencesLogDir$'/directory.txt
523         
524         if startsWith(.targetDirectory$, "~")
525                 .targetDirectory$ = replace$(.targetDirectory$, "~", homeDirectory$, 1)
526         endif
527         
528         .targetDirectory$ > 'preferencesLogDir$'/logPerformance.txt
529         newline$ >> 'preferencesLogDir$'/logPerformance.txt
530 endproc
532 # TTS synthesis
533 procedure synthesize_sound .pinyin$
534         .command$ = ""
535         if speakCommandFile$ <> "" and fileReadable(speakCommandFile$)
536                 .command$ < 'speakCommandFile$'
537                 .command$ = replace$(.command$, "'newline$'", " ", 0)
538                 if macintosh
539                         system_nocheck PATH=${PATH}:/usr/local/bin:/opt/local/bin; bash -rc -- ''.command$' "'.pinyin$'"'
540                 elsif unix
541                         system_nocheck bash -rc -- ''.command$' "'.pinyin$'"'
542                 elsif windows
543                         system_nocheck call '.command$' "'.pinyin$'"'
544                 endif
545         elsif sgc2.synthesizer > 0
546                 select sgc2.synthesizer
547                 Play text... '.pinyin$'
548         endif
549 endproc
551 procedure align_recordedSound .pinyin$
552         if 0 and sgc2.synthesizer > 0 and recordedSound$ <> ""
553                 select Sound 'recordedSound$'
554                 .recordedTextGrid = To TextGrid... pinyin
555                 Set interval text... 1 1 '.pinyin$'
556                 select sgc2.synthesizer
557                 plus Sound 'recordedSound$'
558                 plus .recordedTextGrid
559                 sgc2.alignedTextGrid = nowarn noprogress To TextGrid (align,trim)... 1 1 1 -35 0.1 0.1 0.08
560                 Rename... AlignedTextGrid
561                 select .recordedTextGrid
562                 Remove
563         endif
564 endproc