Added a way to select a new wordlist in the Words window
[sgc2.git] / InitialiseSGC2.praat
blob180edef7501da646005b905048c3b5a62e2d0222
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 # Do not store these variables as preferences
30 sgc.nonPreferences$ = " config.savePerf config.openPerf config.clearSummary config.audioName "
32 # Information for logging activity
33 currentDate$ = date$()
34 dateYear$ = right$(currentDate$, length(currentDate$) - rindex(currentDate$, " "))
35 logtimeStamp$ = replace_regex$(currentDate$, "[^a-zA-Z0-9\-_]", "-", 0)
36 currentLogDirectory$ = ""
37 feedbackTablePrefix$ = "Feedback"
38 feedbackTableName$ = ""
39 evaluationTablePrefix$ = "Evaluation"
40 evaluationTableName$ = ""
41 performanceTableName$ = "Performance"
43 # Define canvas
44 viewportMargin = 5
45 yWordlist = 11
46 yFeedback = yWordlist + 5
47 yPinyin = yFeedback + 10
48 yContour = yPinyin + 15
49 wipeContourArea$ = "demo Paint rectangle... White 20 80 'yContour' 100"
50 wipePinyinArea$ = "demo Paint rectangle... White 20 80 'yPinyin' 'yContour'"
51 wipeFeedbackArea$ = "demo Paint rectangle... White 0 100 'yFeedback' 'yPinyin'"
52 wipeWordlistArea$ = "demo Paint rectangle... White 20 80 'yWordlist' 'yFeedback'"
54 # Pop-Up window colors
55 sgc2.popUp_bordercolor$ = "{0.5,0.5,1}"
56 sgc2.popUp_backgroundcolor$ = "{0.9,0.9,1}"
58 # Initialize parameters
59 alertText$ = ""
60 sgc.currentWord = 1
61 sgc.currentWordlist = -1
62 sgc.numberOfWords = 0
63 sgc.currentWordNum = 1
64 sgc.numberOfDisplayedWords = 0
65 sgc.recordedSound = 0
66 sgc.saveAudioOn = 0
67 sgc.writeAll = 0
68 sgc.customLanguage$ = ""
69 pinyin$ = ""
70 sgc.pinyin$ = ""
71 character$ = ""
72 buttons$ = ""
73 config$ = ""
74 wordlistNum = 1
75 wordlistName$ = ""
76 wordlist$ = ""
77 sgc.failedAttempts = 0
78 mainPage.play = -1
79 config.deleteWordlist = -1
80 config.displayNumbers = 1
81 config.displayPinyin = 1
82 config.displayChar = 0
83 config.displayTrans = 1
84 config.useSoundExample = 1
85 config.synthesis$ = "_DISABLED_"
86 config.input$ = "Microphone"
87 config.showBackground = 1
88 sgc2.noiseThresshold = -30
89 config.strict$ = "1"
90 sgc.highestLevel = 3
91 config.voice = 4
92 config.voice$ = "f4"
93 config.voicesTTS$ = "default f1 f2 f3 f4 f5 m1 m2 m3 m4 m5 m6 m7"
94 sgc.lastVoice = 12
95 sgc.nativeOSXTTScommand$ = "say -vTing-Ting  --rate=95"
96 sgc.nativeLinuxTTScommand$ = "spd-say -l zh -t female1 -r -60"
97 #sgc.nativeWindowsTTScommand$ = "mshta.exe vbscript:Execute(""CreateObject(""""SAPI.SpVoice"""").Speak """"<voice gender='female' xml:lang='zh-CN'><rate speed='-5'>$$$</rate></voice>"""":Close"")"
98 sgc.nativeWindowsTTScommand$ = "mshta.exe vbscript:Execute(""CreateObject(""""SAPI.SpVoice"""").Speak """"<voice gender='female' xml:lang='zh-CN'><rate speed='-5'><pron sym='@@@'/></rate></voice>"""":Close"")"
99 sgc.nativeTTScommand$ = ""
100 config.savePerf = 0
101 config.openPerf = 0
102 config.clearSummary = 0
103 config.audioName$ = ""
104 sgc.savePerf$ = ""
105 sgc.saveAudio$ = ""
106 mainPage.saveAudio$ = ""
107 sgc.allWordLists = -1
109 sgc_ToneProt.minimumPitch = 40
110 sgc_ToneProt.maximumPitch = 600
112 # Platform dependent settings
113 if macintosh or windows
114         config.displayChar = 1
115         config.displayNumbers = 0
116 endif
117 if windows and endsWith(build_SHA$, " XP")
118         config.displayChar = 0
119         config.displayNumbers = 0
120 endif
121 if unix
122         config.displayChar = 0
123         config.displayNumbers = 1
124 endif
126 if unix
127         samplingFrequency = 44100
128 elsif macintosh
129         samplingFrequency = 44100
130 elsif windows
131         samplingFrequency = 44100
132 endif
133 recordingTime = 2
135 # Be careful: Logging and Replaying can have side-effects
136 # sgc2.logging$ = "call saveLogOfActivity"
137 sgc2.logging$ = "# "
138 # When this is not "# ", the command 'replaySGC2Log$' will be run!
139 if not variableExists("replaySGC2Log$")
140         replaySGC2Log$ = "# "
141 endif
143 config.language$ = "EN"
144 config.register = 249
145 preferencesAppFile$ = preferencesAppDir$+"/sgc2rc.txt"
146 preferencesLogDir$ = "'preferencesAppDir$'/log"
147 preferencesTableDir$ = "'preferencesAppDir$'/GUI"
148 sgc2wordlists$ = "'preferencesAppDir$'/wordlists"
149 localWordlistDir$ = sgc2wordlists$
151 # Global word lists must be installed BY THE ADMINISTRATOR
152 # This means, create the directory 'globalwordlists$' and
153 # fill it with wordlist directories containing wordlist.Table
154 # and audio files. They can be copied from a local directory.
155 globalwordlists$ = ""
156 globaltablelists$ = ""
157 globalTTSdir$ = ""
158 if unix
159         globalwordlists$ = "/etc/'sgc2.demoAppName$'/wordlists"
160         globaltablelists$ = "/etc/'sgc2.demoAppName$'/GUI"      
161         globalTTSdir$ = "/etc/'sgc2.demoAppName$'/TTS"  
162 elsif macintosh
163         globalwordlists$ = "/Library/Preferences/'sgc2.demoAppName$'/wordlists"
164         globaltablelists$ = "/Library/Preferences/'sgc2.demoAppName$'/GUI"
165         globalTTSdir$ = "/Library/Preferences/'sgc2.demoAppName$'/TTS"  
166 elsif windows
167         globalwordlists$ = "C:/Documents and Settings/All Users/Application Data/'sgc2.demoAppName$'/wordlists"
168         globaltablelists$ = "C:/Documents and Settings/All Users/Application Data/'sgc2.demoAppName$'/GUI"
169         globalTTSdir$ = "C:/Documents and Settings/All Users/Application Data/'sgc2.demoAppName$'/TTS"
170 endif
171 sgc2.synthesizer = -1
172 sgc.alignedTextGrid = -1
174 ##############################################################
176 config.shuffleLists = 1
177 config.adaptiveLists = 0
178 defaultFontSize = 12
179 defaultFont$ = "Helvetica"
180 defaultLineWidth = 1
182 # Set up directories if they do not exist already
183 call set_up_directories
185 # Get saved preferences
186 call read_preferences ""
188 # Set up TTS system
189 speakCommandDir$ = "'preferencesAppDir$'/TTS"
190 speakCommandFile$ = ""
191 # Define a Praat TTS command that will set sgc2.synthesizer
192 call set_TTS_parameters
193 call set_up_TTS
194 sgc.recordCommandFile$ = ""
195 sgc.playCommandFile$ = ""
196 if windows
197         sgc.scratchAudioDir$ = "'preferencesAppDir$'\audio\"
198 else
199         sgc.scratchAudioDir$ = "/tmp/SpeakGoodChinese/"
200 endif
201 sgc.useAlternativeRecorder = 0
202 call set_up_recorder
203 sgc.useAlternativePlayer = 0
204 call set_up_player
206 # Set inital language
207 call set_language 'config.language$'
209 # Get the word-list
210 call load_word_list "'localWordlistDir$'" 0
212 # Set up evaluation table
213 initialiseSGC2.toneevaluation_table$ = ""
214 call initialize_toneevaluation_tables
216 # Draw inital window
217 call init_window
219 ###############################################################
221 # Obligatory procedures
223 ###############################################################
224 # Initialize Demo Window
225 procedure init_window
226     demo Erase all
227         demo Line width... 'defaultLineWidth'
228         demo 'defaultFont$'
229         call set_font_size 'defaultFontSize'
230         demo Black
231         
232         # If there is no recorded sound, try to read stored recording
233         if recordedSound$ = "" and sgc.saveAudio$ <> ""
234                 sgc.pinyin$ = ""
235                 select sgc.currentWordlist
236                 if sgc.currentWord > 0 and sgc.currentWord <= sgc.numberOfWords
237                         call readPinyin 'sgc.currentWord'
238                         sgc.pinyin$ = readPinyin.pinyin$
239                         sgc.character$ = readPinyin.character$
240                         .outputName$ = "'sgc.saveAudio$'/'sgc.pinyin$'.wav"
241                         if fileReadable(.outputName$)
242                                 sgc.recordedSound = Read from file: .outputName$
243                                 recordedSound$ = selected$("Sound")
244                                 call recognizeTone
245                                 # See feedback on earl;ier recorded words
246                                 if fileReadable("'sgc.saveAudio$'/TestSpeakGoodChinese2.txt")
247                                         call write_feedback Feedback
248                                 endif
249                                 select Table Feedback
250                                 Remove
251                                 
252                                 # Set config.audioName
253                                 .tmp$ = replace_regex$(sgc.saveAudio$, "[^/\\]+[/\\]?$", "", 0)
254                                 config.audioName$ = replace$(sgc.saveAudio$, .tmp$, "", 0)
255                                 
256                         endif
257                 endif
258         endif
259         
260         # Set mainPage.saveAudio$ grade
261         call set_grade_display 'sgc.pinyin$'
262         
263         # Update screen
264         call reset_viewport
265         .windowTitle$ = replace$(wordlistName$, "_", " ", 0)
266         call set_window_title 'buttons$' '.windowTitle$'
267         # Display the word-list
268         call write_word_list
269     # Wipe screen and draw background
270     call wipeArea 'wipeContourArea$'
271         if config.showBackground
272                 call draw_background Background
273         endif
274     # Define buttons in a table
275     call init_buttons
276     # Set Play button
277         call Set_Play_Button
278     
279         # Draw the contour
280         call draw_tone_contour
281         # SaveAudio light
282         call paint_saveAudio_light
283         # Set play button
284         
285         sgc.failedAttempts = 0
286 endproc
288 # Make sure all Preferences directories are available
289 procedure set_up_directories
290         .dirPath$ = "'preferencesAppDir$'"
291         createDirectory(.dirPath$)
292         .dirPath$ > '.dirPath$'/directory.txt
293         createDirectory("'.dirPath$'/wordlists")
294         .dirPath$ > '.dirPath$'/wordlists/directory.txt
295         createDirectory("'.dirPath$'/pitchmodels")
296         .dirPath$ > '.dirPath$'/pitchmodels/directory.txt
297         createDirectory("'.dirPath$'/log")
298         .dirPath$ > '.dirPath$'/log/directory.txt
299         createDirectory("'.dirPath$'/TTS")
300         .dirPath$ > '.dirPath$'/TTS/directory.txt
301 endproc
304 # Retrieve and store setting between sessions
306 procedure read_preferences .preferencesFile$
307         if not fileReadable(.preferencesFile$)
308                 .preferencesFile$ = preferencesAppFile$
309         endif
310         if fileReadable(.preferencesFile$)
311                 Read from file... 'preferencesAppFile$'
312                 .preferenceTable$ = selected$("Table")
313                 .numPrefKeys = Get number of rows
314                 for .row to .numPrefKeys
315                         .variableName$ = Get value... '.row' Key
316                         if variableExists(.variableName$)
317                                 .variableValue = Get value... '.row' Value
318                                 if .variableValue <> undefined
319                                         '.variableName$' = '.variableValue'
320                                 endif
321                         elsif variableExists(.variableName$+"$")
322                                 .variableValue$ = Get value... '.row' Value
323                                 .variableName$ = .variableName$+"$"
324                                 '.variableName$' = "'.variableValue$'"
325                         endif
326                 endfor
327                 
328                 select Table '.preferenceTable$'
329                 Remove
330         endif
331 endproc
333 procedure write_preferences .preferencesFile$
334         Create Table with column names... Preferences 0 Key Value
335         if index_regex(.preferencesFile$, "[a-zA-Z0-9]") <= 0
336                 .preferencesFile$ = preferencesAppFile$
337         endif
338         .row = 0
339         
340         for .tableNum from 1 to 2
341                 if .tableNum = 1
342                         .table$ = "Config"
343                 elsif .tableNum = 2
344                         .table$ = "MainPage"
345                 endif
346                 .varPrefix$ = replace_regex$(.table$, "^(.)", "\l\1", 0)
348                 select Table '.table$'
349                 .numTableRows = Get number of rows
350                 for .tablerow to .numTableRows
351                         select Table '.table$'
352                         .label$ = Get value... '.tablerow' Label
353                         .variableName$ = .varPrefix$+"."+(replace_regex$(.label$, "^(.)", "\l\1", 0))
354                         .keyName$ = .variableName$
355                         .value$ = ""
356                         if sgc.nonPreferences$ <> "" and index(sgc.nonPreferences$, " '.variableName$' ")
357                                 .value$ = ""
358                         elsif variableExists(.variableName$)
359                                 .value = '.variableName$'
360                                 .value$ = "'.value'"
361                         elsif variableExists(.variableName$ + "$")
362                                 .variableName$ = .variableName$ + "$"
363                                 .value$ = '.variableName$'
364                         elsif index(.variableName$, "_") > 0
365                                 .variableName$ = left$(.variableName$, rindex(.variableName$, "_") - 1) 
366                                 .keyName$ = .variableName$
367                                 select Table Preferences
368                                 .prefRow = Search column... Key '.keyName$'
369                                 if .prefRow <= 0
370                                         if variableExists(.variableName$)
371                                            .value = '.variableName$'
372                                            .value$ = "'.value'"
373                                         elsif variableExists(.variableName$ + "$")
374                                            .variableName$ = .variableName$ + "$"
375                                            .value$ = '.variableName$'
376                                         endif
377                                 endif
378                         endif
380                         if .value$ <> ""
381                                 select Table Preferences
382                                 Append row
383                                 .row += 1
384                                 Set string value... '.row' Key '.keyName$'
385                                 Set string value... '.row' Value '.value$'
386                         endif
387                 endfor
388         endfor
389         
390         # Some extra settings
391         select Table Preferences
392         Append row
393         .row += 1
394         Set string value... '.row' Key wordlistDir
395         Set string value... '.row' Value 'localWordlistDir$'
397         select Table Preferences
398         Append row
399         .row += 1
400         Set string value... '.row' Key wordlistName
401         Set string value... '.row' Value 'wordlistName$'
403         select Table Preferences
404         Write to table file... '.preferencesFile$'
405         Remove
407 endproc
409 ###############################################################
411 # TTS (speech synthesis). Place commands in user info
413 # Prerequisites
414 # speakCommandDir$ = "'preferencesAppDir$'/TTS"
415 # speakCommandFile$ = ""
417 # Make sure sgc2.synthesizer is set!
418 procedure create_default_TTS .language$ .voice$ .samplefreq .gap .pitch_adj .pitch_range .words_per_minute .use_data$ .espeak_phones$
419         sgc2.synthesizer = Create SpeechSynthesizer... '.language$' '.voice$'
420         Set speech output settings... .samplefreq .gap .pitch_adj .pitch_range .words_per_minute '.use_data$' '.espeak_phones$'
421 endproc
423 procedure set_up_TTS
424         if sgc2.synthesizer > 0
425                 select sgc2.synthesizer
426                 Remove
427                 sgc2.synthesizer = -1
428         endif
429         # Note, the TTScommand must set sgc2.synthesizer!
430         if config.strict$ = "'sgc.highestLevel'"
431                 'sgc2.advancedTTScommand$'
432         else
433                 'sgc2.normalTTScommand$'
434         endif
436         if macintosh
437                 .ttscommand$ = "speak"
438                 .osName$ = "OSX"
439                 .quote$ = ""
440         elsif unix
441                 .ttscommand$ = "espeak"
442                 .osName$ = "UNIX"
443                 .quote$ = ""
444         elsif windows
445                 .ttscommand$ = "C:/Program Files/eSpeak/command_line/espeak.exe"
446                 .osName$ = "WIN"
447                 .quote$ = """"
448         endif
449         # Global TTS command has precedence
450         if fileReadable("'globalTTSdir$'/TTS_'.osName$'_command.txt")
451                 speakCommandFile$ = "'globalTTSdir$'/TTS_'.osName$'_command.txt"
452                 if config.synthesis$ = "_DISABLED_"
453                         # Default is ON
454                         config.synthesis$ = "eSpeak"
455                 endif
456         endif
458         # Local TTS command, if there is no global one
459         # Command does not exist yet, create it if eSpeak is installed
460         # Make sure to quote the path!
461         if speakCommandFile$ = ""
462                 # Autodetect synthesizer command
463 #               if not fileReadable("'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt")
464 #                       .command_path$ = ""
465 #                       if macintosh
466 #                               system_nocheck  PATH=${PATH}:/opt/local/bin; bash -c -- 'which '.ttscommand$' > "'speakCommandDir$'/command_path.txt"'
467 #                               .command_path$ < 'speakCommandDir$'/command_path.txt
468 #                       elsif unix
469 #                               system_nocheck  PATH=${PATH};bash -c -- 'which '.ttscommand$' > "'speakCommandDir$'/command_path.txt"'
470 #                               .command_path$ < 'speakCommandDir$'/command_path.txt
471 #                       elsif windows
472 #                               if fileReadable(.ttscommand$)
473 #                                       .command_path$ = .ttscommand$
474 #                               endif
475 #                       endif
476 #                       # Remove any newlines
477 #                       .command_path$ = replace$(.command_path$, "'newline$'", "", 0)
479 #                       # Command path found
480 #                       if sgc2.synthesizer <= 0 and .command_path$ <> "" and fileReadable(.command_path$)
481 #                               deleteFile("'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt")
482 #                               fileappend "'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt"  
483 #                               ...'.quote$''.ttscommand$''.quote$' -v zh+f4 -s 100 'newline$'
484 #                               speakCommandFile$ = "'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt"
485 #                       endif
486 #               endif
487                 if fileReadable("'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt")
488                         speakCommandFile$ = "'speakCommandDir$'/TTS_'.osName$'_eSpeak_command.txt"
489                 endif
490                 deleteFile("'speakCommandDir$'/command_path.txt")
491         endif
492         
493         # Close off (other TTS maybe a later option)
494         if sgc2.synthesizer > 0 or (speakCommandFile$ <> "" and fileReadable(speakCommandFile$))
495                 config.synthesis$ = "eSpeak"
496         endif
497 endproc
499 procedure set_TTS_parameters
500         if config.voice > 0
501                 .voice$ = replace_regex$(config.voicesTTS$, "^(\S+\s+){'config.voice'}(\S+)(\s+.*)?$", "\2", 0)
502         else
503                 .voice$ = replace_regex$(config.voicesTTS$, "^(\S+)(\s+.*)?$", "\1", 0)
504         endif
505         if .voice$ <> "" and index_regex(.voice$, "\s") <= 0
506                 if .voice$ = "default"
507                         config.voice$ = "*"
508                 else
509                         config.voice$ = replace_regex$(.voice$, ".", "\u&", 0)
510                 endif
511                 sgc2.normalTTScommand$ = "call create_default_TTS Mandarin '.voice$' 10000 0.01 50 100 95 no IPA"
512                 sgc2.advancedTTScommand$ = "call create_default_TTS Mandarin '.voice$' 10000 0.01 50 70 125 no IPA"
513         endif
514         if macintosh and fileReadable("/usr/bin/say")
515                 sgc.nativeTTScommand$ = sgc.nativeOSXTTScommand$
516         elsif unix and fileReadable("/usr/bin/spd-say")
517                 sgc.nativeTTScommand$ = sgc.nativeLinuxTTScommand$
518         elsif windows
519                 sgc.nativeTTScommand$ = sgc.nativeWindowsTTScommand$
520         endif
521 endproc
523 # Alternative audio recorder
524 procedure set_up_recorder
525         if macintosh
526                 .osName$ = "OSX"
527                 .quote$ = ""
528         elsif unix
529                 .osName$ = "UNIX"
530                 .quote$ = ""
531         elsif windows
532                 .osName$ = "WIN"
533                 .quote$ = """"
534         endif
535         # Global TTS command has precedence
536         sgc.useAlternativeRecorder = 0
537         if fileReadable("'globalTTSdir$'/TTS_'.osName$'_record_command.txt")
538                 createDirectory(sgc.scratchAudioDir$)
539                 sgc.recordCommandFile$ = "'globalTTSdir$'/TTS_'.osName$'_record_command.txt"
540                 sgc.useAlternativeRecorder = 1
541         elsif fileReadable("'speakCommandDir$'/TTS_'.osName$'_record_command.txt")
542                 createDirectory(sgc.scratchAudioDir$)
543                 sgc.recordCommandFile$ = "'speakCommandDir$'/TTS_'.osName$'_record_command.txt"
544                 sgc.useAlternativeRecorder = 1
545         endif
546 endproc
548 # Alternative audio player
549 procedure set_up_player
550         if macintosh
551                 .osName$ = "OSX"
552                 .quote$ = ""
553         elsif unix
554                 .osName$ = "UNIX"
555                 .quote$ = ""
556         elsif windows
557                 .osName$ = "WIN"
558                 .quote$ = """"
559         endif
560         # Global TTS command has precedence
561         sgc.useAlternativePlayer = 0
562         if fileReadable("'globalTTSdir$'/TTS_'.osName$'_play_command.txt")
563                 createDirectory(sgc.scratchAudioDir$)
564                 sgc.playCommandFile$ = "'globalTTSdir$'/TTS_'.osName$'_play_command.txt"
565                 sgc.useAlternativePlayer = 1
566         elsif fileReadable("'speakCommandDir$'/TTS_'.osName$'_play_command.txt")
567                 createDirectory(sgc.scratchAudioDir$)
568                 sgc.playCommandFile$ = "'speakCommandDir$'/TTS_'.osName$'_play_command.txt"
569                 sgc.useAlternativePlayer = 1
570         endif
571 endproc
573 ###############################################################
575 # Evaluation tables
577 # Prerequisites
578 # initialiseSGC2.toneevaluation_table$ = ""
579 procedure initialize_toneevaluation_tables
580         # Remove old table
581         if initialiseSGC2.toneevaluation_table$ != ""
582                 select sgc2.performanceTable
583                 Remove
584         endif
585         initialiseSGC2.toneevaluation_table$ = ""
586         # Get the name of the table
587         call get_evaluation_table_labels 'config.language$'
588         performanceTableName$ = eval.performance$
589         
590         if sgc.savePerf$ <> "" and fileReadable(sgc.savePerf$)
591                 sgc2.performanceTable = Read Table from tab-separated file: sgc.savePerf$
592                 Rename: performanceTableName$
593                 # Check to make sure all columns are initialized, but only if Pinyin exists!
594                 select sgc2.performanceTable
595                 .column = Get column index: eval.pinyin$
596                 if .column <= 0
597                         select sgc2.performanceTable
598                         Remove
599                         sgc2.performanceTable = Create Table with column names... "'performanceTableName$'" 0 'eval.pinyin$' 'eval.correct$' 'eval.wrong$' 'eval.total$' 'eval.high$' 'eval.low$' 'eval.wide$' 'eval.narrow$' 'eval.unknown$' 'eval.commented$' 'eval.level$' 'eval.time$' 'eval.wordlist$'
600                 endif
601                 .columnNameList$ = "'eval.correct$' 'eval.wrong$' 'eval.total$' 'eval.high$' 'eval.low$' 'eval.wide$' 'eval.narrow$' 'eval.unknown$' 'eval.commented$' 'eval.level$' 'eval.time$' 'eval.wordlist$'"
602                 while index_regex(.columnNameList$, "\S")
603                         .columnNameList$ = replace_regex$(.columnNameList$, "^\s+", "", 1)
604                         .columnHeader$ = extractWord$(.columnNameList$, "")
605                         .columnNameList$ = replace_regex$(.columnNameList$, "^\s*'.columnHeader$'\s*", "", 1)
606                         # Initialize header
607                         select sgc2.performanceTable
608                         .column = Get column index: .columnHeader$
609                         if .column <= 0
610                                 select sgc2.performanceTable
611                                 Append column: .columnHeader$
612                         endif
613                         
614                 endwhile
615                 
616                 # Performance table has been read. Set the wordlist to the first row
617                 select sgc2.performanceTable
618                 wordlistName$ = Get value: 1, eval.wordlist$
619                 call load_word_list: localWordlistDir$, 0
620         else
621                 # Create new table
622                 sgc2.performanceTable = Create Table with column names... "'performanceTableName$'" 0 'eval.pinyin$' 'eval.correct$' 'eval.wrong$' 'eval.total$' 'eval.high$' 'eval.low$' 'eval.wide$' 'eval.narrow$' 'eval.unknown$' 'eval.commented$' 'eval.level$' 'eval.time$' 'eval.wordlist$'
623         endif
624         initialiseSGC2.toneevaluation_table$ = performanceTableName$
625         call get_toneevaluation_row 'eval.total$'
626 endproc
628 procedure get_toneevaluation_row .pinyin$
629         select sgc2.performanceTable
630     .row = Search column... "'eval.pinyin$'" '.pinyin$'
631         if .row < 1
632                 Append row
633                 .row = Get number of rows
634                 Set string value... '.row' "'eval.pinyin$'" '.pinyin$'
635                 Set numeric value... '.row' 'eval.correct$' 0
636                 Set numeric value... '.row' 'eval.wrong$' 0
637                 Set numeric value... '.row' 'eval.total$' 0
638                 Set numeric value... '.row' 'eval.high$' 0
639                 Set numeric value... '.row' 'eval.low$' 0
640                 Set numeric value... '.row' 'eval.wide$' 0
641                 Set numeric value... '.row' 'eval.narrow$' 0
642                 Set numeric value... '.row' 'eval.unknown$' 0
643                 Set numeric value... '.row' 'eval.commented$' 0
644                 Set numeric value... '.row' 'eval.level$' 0
645                 Set numeric value... '.row' 'eval.time$' 0
646                 Set string value... '.row' 'eval.wordlist$' 'wordlistName$'
647                 Sort rows... 'eval.pinyin$'
648         .row = Search column... "'eval.pinyin$'" '.pinyin$'
649         endif
650 endproc
652 procedure increment_toneevaluation_in_row .row .column$
653         select sgc2.performanceTable
654         .tmp = Get value... '.row' '.column$'
655         if .tmp = undefined
656                 .tmp = 0
657         endif
658         .tmp += 1
659         Set numeric value... '.row' '.column$' '.tmp'
660         
661         # Set Level
662         Set string value: .row, eval.level$, config.strict$
663         
664         # Set time stamp and wordlist
665         .dateTime$ = date$()
666         Set string value: .row, eval.time$, .dateTime$
667         Set string value: .row, eval.wordlist$, wordlistName$
668         
669 endproc
671 # Update existing performance file with toneevaluation
672 procedure update_toneevaluation_file
673         if sgc.savePerf$ <> "" and fileReadable(sgc.savePerf$) and initialiseSGC2.toneevaluation_table$ <> ""
674                 select sgc2.performanceTable
675                 Write to table file... 'sgc.savePerf$'
676         endif
677 endproc
679 procedure increment_toneevaluation_value .pinyin$ .column$
680         call get_toneevaluation_row '.pinyin$'
681         .row = get_toneevaluation_row.row
682         call increment_toneevaluation_in_row '.row' '.column$'
683         
684         call get_toneevaluation_row 'eval.total$'
685         .row = get_toneevaluation_row.row
686         call increment_toneevaluation_in_row '.row' '.column$'
687 endproc
689 procedure add_feedback_to_toneevaluation .table$
690     select Table '.table$'
691     .line1$ = Get value... 1 Text
692     .line2$ = Get value... 2 Text
693     .label$ = Get value... 3 Text
694         if .label$ = "6"
695                 .label$ = "'eval.unknown$'"
696         endif
697         
698         .tones$ = replace_regex$(left$(.line1$, rindex(.line1$, ":")), "[^0-9]", "", 0)
699         .recognized$ = replace_regex$(right$(.line1$, length(.line1$)-rindex(.line1$, ":")), "[^0-9]", "", 0)
700         
701         # Set evaluation
702         call increment_toneevaluation_value 'sgc.pinyin$' 'eval.total$'
703         if .tones$ = .recognized$
704                 call increment_toneevaluation_value 'sgc.pinyin$' 'eval.correct$'
705                 .result = 1
706         else
707                 call increment_toneevaluation_value 'sgc.pinyin$' 'eval.wrong$'
708                 .result = 0
709         endif
710         if index_regex(.label$, "(Correct|Wrong)") <= 0
711                 if .label$ = "Correct"
712                         .label$ = eval.correct$
713                 else
714                         .label$ = eval.wrong$
715                 endif
716                 call increment_toneevaluation_value 'sgc.pinyin$' '.label$'
717                 call increment_toneevaluation_value 'sgc.pinyin$' 'eval.commented$'
718                 .result = 0
719         endif
720         
721         # Update performance table when SaveAudio is on
722         if sgc.saveAudioOn
723                 call update_toneevaluation_file
724         endif
725 endproc
727 procedure setGrade .grade$
728         select sgc.currentWordlist
729         if recordedSound$ <> "" and sgc.pinyin$ <> ""           
730                 call get_toneevaluation_row 'sgc.pinyin$'
731                 .row = get_toneevaluation_row.row
732                 select sgc2.performanceTable
733                 .col = Get column index... Grade
734                 if .col <= 0
735                         Insert column... 2 Grade
736                 endif
737                         
738                 Set numeric value: .row, "Grade", '.grade$'
739                 .numRows = Get number of rows
740                 .sumGrade = 0
741                 .sumN = 0
742                 for .r from 2 to .numRows
743                         .tmp = Get value: .r, "Grade"
744                         if .tmp <> undefined
745                                 .sumGrade += .tmp
746                                 .sumN += 1
747                         endif
748                 endfor
749                 .meanGrade = -1
750                 if .sumN > 0
751                         .meanGrade = .sumGrade / .sumN
752                 endif
753                 Set numeric value: 1, "Grade", .meanGrade
754                 
755                 # Store current performance table
756                 call update_toneevaluation_file
757         endif
758 endproc
760 # Set mainPage.saveAudio$ to Grade
761 procedure set_grade_display .pinyin$
762         mainPage.saveAudio$ = ""
763         select sgc2.performanceTable
764         .grade$ = ""
765         .col = Get column index: "Grade"
766         if .pinyin$ <> "" and .col > 0
767                 call get_toneevaluation_row '.pinyin$'
768                 .row = get_toneevaluation_row.row
769                 if .row > 0
770                         .grade$ = Get value: .row, "Grade"
771                         if index_regex(.grade$, "[0-9]") <= 0
772                                 .grade$ = ""
773                         endif
774                 endif
775         endif
776         if .grade$ <> ""
777                 mainPage.saveAudio$ = .grade$
778         endif
779 endproc
780         
781 ###############################################################
783 # Miscelaneous procedures
785 ###############################################################
787 # TTS synthesis
788 procedure synthesize_sound .pinyin$ .character$
789         .pinyin$ = replace_regex$(.pinyin$, "(^""|""$)", "", 0)
790         .character$ = replace_regex$(.character$, "(^""|""$)", "", 0)
791         .pinyinText$ = replace_regex$(.pinyin$, "0", "5", 0)
792         .pinyinExpanded$ = replace_regex$(.pinyin$, "([0-5])", " \1 - ", 0)
793         .pinyinExpanded$ = replace_regex$(.pinyinExpanded$, " - $", "", 0)
794         
795         if .character$ = "-" or .character$ = "" or .character$ = "?"
796                 .character$ = .pinyinText$
797         endif
798         .currentCommand$ = ""
799         # Files need more checks!
800         if speakCommandFile$ <> "" and fileReadable(speakCommandFile$)
801                 .currentCommand$ < 'speakCommandFile$'
802                 .currentCommand$ = replace$(.currentCommand$, "'newline$'", " ", 0)
803                 if index(.currentCommand$, "$$$") and .character$ <> .pinyinText$
804                         # Find the character representation
805                         .currentCommand$ = replace$(.currentCommand$, "$$$", .character$, 0)
806                 elsif index(.currentCommand$, "&&&")
807                         # Find the character representation
808                         .currentCommand$ = replace$(.currentCommand$, "&&&", .pinyinText$, 0)
809                 elsif index(sgc.nativeTTScommand$, "@@@")
810                         .currentCommand$ = replace$(sgc.nativeTTScommand$, "@@@", .pinyinExpanded$, 0)
811                 else
812                         .currentCommand$ = .currentCommand$ + " ""'.pinyinText$'"""
813                 endif
814                 if macintosh
815                         system_nocheck PATH=${PATH}:/usr/local/bin:/opt/local/bin; bash -rc -- ''.currentCommand$''
816                 elsif unix
817                         system_nocheck bash -rc -- ''.currentCommand$''
818                 elsif windows
819                         runSystem_nocheck: .currentCommand$
820                 endif
821         elsif sgc.nativeTTScommand$ <> "" and config.voice <= 0
822                 # Get the pinyin text on the correct place
823                 if index(sgc.nativeTTScommand$, "$$$")
824                         .currentCommand$ = replace$(sgc.nativeTTScommand$, "$$$", .character$, 0)
825                 elsif index(sgc.nativeTTScommand$, "&&&")
826                         .currentCommand$ = replace$(sgc.nativeTTScommand$, "&&&", .pinyinText$, 0)
827                 elsif index(sgc.nativeTTScommand$, "@@@")
828                         .currentCommand$ = replace$(sgc.nativeTTScommand$, "@@@", .pinyinExpanded$, 0)
829                 else
830                         .currentCommand$ = sgc.nativeTTScommand$ + " ""'.pinyinText$'"""
831                 endif
832                 runSystem_nocheck: .currentCommand$
833         elsif sgc2.synthesizer > 0
834                 select sgc2.synthesizer
835                 Play text... '.pinyin$'
836         endif
837 endproc
839 procedure align_recordedSound .pinyin$
840         if 0 and sgc2.synthesizer > 0 and recordedSound$ <> ""
841                 select Sound 'recordedSound$'
842                 .recordedTextGrid = To TextGrid... pinyin
843                 Set interval text... 1 1 '.pinyin$'
844                 select sgc2.synthesizer
845                 plus Sound 'recordedSound$'
846                 plus .recordedTextGrid
847                 sgc.alignedTextGrid = nowarn noprogress To TextGrid (align,trim)... 1 1 1 -35 0.1 0.1 0.08
848                 Rename... AlignedTextGrid
849                 select .recordedTextGrid
850                 Remove
851         endif
852 endproc