# makeglossquiz.py by Bruce_Landon@douglas.bc.ca 10-22-06
import string #module in the standard library
import os     #module in the standard library use to call external programs

topofscript="""
# quiztalker.py with inserted items by Bruce_Landon@douglas.bc.ca 10-22-06
# works with display only once then close and restart IDLE
# this should work most easily with glossary style questions
from ccm.env.objects import *
import random
import pyTTS

tts = pyTTS.Create()
#set the speech rate
tts.Rate = 5
#set the speech volume percentage (0-100%)
tts.Volume = 60
#get a list of all the available voice actors
#print tts.GetVoiceNames()
#explicitly set a voice from MS standard voices
#tts.SetVoiceByName('MSSam')
#tts.SetVoiceByName('MSMike')
#tts.SetVoiceByName('MSMary')
#explicitly set a voice from additional voices added
#tts.SetVoiceByName('CMUKal')
tts.SetVoiceByName('VW Kate')
#tts.SetVoiceByName('VW Paul')
#speak the text
#tts.Speak('This is the sound of my voice.')

instructions='You will now be shown a series\\nof questions.  Answer each one\\n'
instructions=instructions + 'by pressing the appropriate letter.\\n\\n'
instructions=instructions + 'Press any key to start.\\n'

questions=[
"""
# questions are reformatted and inserted here by code below
endofscript=""""
]


class MultipleChoiceEnvironment(ObjectEnvironment):
    def start(self):
        self.text=Object(isa='text',x=0.5,y=0.5)
        self.text.value=instructions
        tts.Speak(instructions)     # add voice
        self.currentQuestion=None
        self.answers=[]
        yield 'key'                 # wait for any key to be pressed
        self.text.value=None
        yield 0.5
        x=str(questions[0])
        # split into stem and choices
        stem=''
        choiceA=''
        choiceB=''
        choiceC=''
        choiceD=''
        choiceE=''
        stem=x[0:(x.find('\\nA)'))]
        choiceA=x[(x.find('\\nA)')):(x.find('\\nB)'))]
        choiceB=x[(x.find('\\nB)')):(x.find('\\nC)'))]
        choiceC=x[(x.find('\\nC)')):(x.find('\\nD)'))]
        if choiceD.find('\\nE)') > 0 :
            choiceD=x[(x.find('\\nD)')):(x.find('\\nE)'))]
            choiceE=x[(x.find('\\nD')):]
        else :
            choiceD=x[(x.find('\\nD')):]
          
        self.text.value=questions[0]     # show the first question
        # say stem - translated in memory
        tts.Speak(stem)                  # add voice
        self.currentQuestion=0           # remember what question we are on
        # model makes a choice
        # say choices - checking in memory for closeness to translated stem
        if choiceA != '' :
            tts.Speak(choiceA)
        if choiceB != '' :
            tts.Speak(choiceB)
        if choiceC != '' :
            tts.Speak(choiceC)
        if choiceD != '' :
            tts.Speak(choiceD)
        if choiceE != '' :
            tts.Speak(choiceE)

    @ccm.parallelize
    def press(self,key): #fix to add in model
        if self.currentQuestion is None: return    # make sure we are waiting
                                                   # for a response
        if key not in 'abcdeABCDE': return      # make sure it's a valid key        

        self.answers.append(key)         # remember the answer
        self.text.value=None
        nextQuestion=self.currentQuestion+1
        self.currentQuestion=None
        if nextQuestion<len(questions):      # more questions to ask?
            yield 0.5 # wait 0.5 seconds
            x=str(questions[nextQuestion])
            # split into stem and choices
            stem=''
            choiceA=''
            choiceB=''
            choiceC=''
            choiceD=''
            choiceE=''
            stem=x[0:(x.find('\\nA)'))]
            choiceA=x[(x.find('\\nA)')):(x.find('\\nB)'))]
            choiceB=x[(x.find('\\nB)')):(x.find('\\nC)'))]
            choiceC=x[(x.find('\\nC)')):(x.find('\\nD)'))]
            if choiceD.find('\\nE)') > 0 :
                choiceD=x[(x.find('\\nD)')):(x.find('\\nE)'))]
                choiceE=x[(x.find('\\nD')):]
            else :
                choiceD=x[(x.find('\\nD')):]
                      
            self.text.value=questions[nextQuestion]  # show the next question
            # say stem - translated in memory
            tts.Speak(stem)     # add voice
            # brief pause
            self.currentQuestion=nextQuestion
            # model makes a choice
            if choiceA != '' :
                tts.Speak(choiceA)
            if choiceB != '' :
                tts.Speak(choiceB)
            if choiceC != '' :
                tts.Speak(choiceC)
            if choiceD != '' :
                tts.Speak(choiceD)
            if choiceE != '' :
                tts.Speak(choiceE)
        else:
            log.answers=self.answers  # record the answers
            self.stop()


######### actr model for reading and making a choice ##########################

log=ccm.log()
env=MultipleChoiceEnvironment(log=log)

import ccm.display
ccm.display.Display(env)
env.run(rate=1)  # to run at real-time
env.stop()
#env.run() #does not work as text in IDLE

"""
########################## working parts of this script #######################
def reader(quizfile): 
	""" read xamtool test text file into a list for actr processing """
	print quizfile # debug
	if quizfile[len(quizfile)-4:] != ".txt" :
		quizfile = quizfile + ".txt"

	try:
		f = open(quizfile, "r")
		w = f.readlines()
		f.close()
		ww = ''
		for i in range(0, len(w)):
                        myline = w[i][:-1]
                        # replace quote marks in items
                        myline = myline.replace('"','`')
                        myline = myline.replace("'","`")
                        #print myline
                        if myline == '' :
                            ww=ww + '""",' + '\n'
                            ww=ww + '"""' + '\n'
                        else :
                            w[i] = wrapline(myline, wraplen=50)
                            print w[i] #debug
                            ww = ww + w[i] + '\n'

                return ww
	except:
		return "read file name error - command failed"


def wrapline(myline, wraplen = 50):
    """add newline to a text line to simulate line wrapping for quiz format"""
    if len(myline) <= wraplen :
        return myline
    x = 0
    j = 0
    while x != -1 :
	x = myline.rfind(" ", j, (j + wraplen))
        if x >= j :
            myline = myline[0:x] + "\n" + myline[x:]
            if (x + wraplen) < len(myline) :
                j = x
            else :
                return myline
        else :
            return myline


################ need to manually enter approriate file names #################
quizfile = 'pretest.txt'  # xamtools formatted source test file
glosstest = 'quizgloss01.py'  # destination file name
x=topofscript             # top of pythonactr script
y=reader(quizfile)        # fix the formatting into a list
print str(y)              # show the reformatted items
x=x + '"""' + str(y)[:-7] # trim off extra quotes
x=x + endofscript         # pythonactr model and run commands
f=open(glosstest, "a")    # open for append
f.write(x)                # adds to the file - problem is not empty
f.close()                 # finish up
############### end of script #################################################

