view cherryFxTest.py @ 10:9ab73065952b

Changed local conf. file
author Daniele Barchiesi <daniele.barchiesi@eecs.qmul.ac.uk>
date Wed, 06 Mar 2013 18:01:13 +0000
parents 032bc65ebafc
children 15260ae0d6bc
line wrap: on
line source

import cherrypy, os, random, smtplib, string
from cherrypy.lib.static import serve_file
from templates import *

from DirectorySession import DirectorySession
from ServerWrapper import ServerWrapper as CherryPyServer
from ServerWrapper import Config as ServerConfig

from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.Utils import COMMASPACE, formatdate
from email import Encoders

from pprint import pprint

PATH = os.path.abspath(os.path.dirname(__file__))

#audiodir = './audio'
#cherrypy.session['fxs'] = [cherrypy.session['f'] for cherrypy.session['f'] in os.listdir(audiodir) if os.path.isdir(os.path.join(audiodir, cherrypy.session['f']))]
#cherrypy.session['fxs'].remove('dry')
#print cherrypy.session['fxs']
	
class Root(object): pass


class HomePage:
	def index(self):
		
		return "move along, nothing to see here!"

	index.exposed = True



class TestPage:

	def getFiles(self):
		audiodir = './audio'
		cherrypy.session['fxs'] = [cherrypy.session['f'] for cherrypy.session['f'] in os.listdir(audiodir) if os.path.isdir(os.path.join(audiodir, cherrypy.session['f']))]
		cherrypy.session['fxs'].remove('dry')
		print cherrypy.session['fxs']
	
	def index(self):
		TestPage.getFiles(self)
		cherrypy.session['sid'] = None
		
		cherrypy.session['sid_filename'] = None
		
		
		if cherrypy.request.headers.has_key("X-Forwarded-For"):
			cherrypy.session['ip'] = cherrypy.request.headers["X-Forwarded-For"]
		elif cherrypy.request.headers.has_key("Remote-Addr"):
			cherrypy.session['ip'] = cherrypy.request.headers["Remote-Addr"]
		else :
			cherrypy.session['ip'] = None
		
		cherrypy.session['test'] = None
		cherrypy.session['results'] = None
		cherrypy.session['tests'] = None
		cherrypy.session['test_nr'] = None
		cherrypy.session['audio_pairs'] = None
		cherrypy.session['page'] = 0
		cherrypy.session['pages'] = 6
		cherrypy.session['userinfobox'] = None
		cherrypy.session['ts'] = None
		#return '''
		#	<p>
		#	<a href="/test/">start test</a>
		#	</p>'''
		
		#take 2 examples for each effect

		cherrypy.session['audio_pairs'] = []
		
		# get effected files:
			
		for cherrypy.session['fx'] in cherrypy.session['fxs']:
			cherrypy.session['dirlist'] = os.listdir('./audio/%s/'%cherrypy.session['fx'])
			cherrypy.session['filelist'] = []
			for cherrypy.session['item'] in cherrypy.session['dirlist']:
				if cherrypy.session['item'].split('.')[-1] == 'mp3':
					cherrypy.session['filelist'].append(cherrypy.session['item'].split('.')[0])
			
			# create audio pairs for this fx
			
			cherrypy.session['first'] = cherrypy.session['second'] = random.choice(cherrypy.session['filelist'])
			while cherrypy.session['first'] == cherrypy.session['second']:
				cherrypy.session['second'] = random.choice(cherrypy.session['filelist'])

			cherrypy.session['dry1'] = 'dry/%s' %cherrypy.session['first'].split('_%s'%cherrypy.session['fx'])[0]
			cherrypy.session['fx1'] = '%s/%s' %(cherrypy.session['fx'], cherrypy.session['first'])
			cherrypy.session['dry2'] = 'dry/%s' %cherrypy.session['second'].split('_%s'%cherrypy.session['fx'])[0]
			cherrypy.session['fx2'] = '%s/%s' %(cherrypy.session['fx'], cherrypy.session['second'])
			cherrypy.session['audio_pairs'].append([cherrypy.session['fx'], cherrypy.session['dry1'], cherrypy.session['fx1']])
			cherrypy.session['audio_pairs'].append([cherrypy.session['fx'], cherrypy.session['dry2'], cherrypy.session['fx2']])
		
		#print TestPage.audio_pairs
		random.shuffle(cherrypy.session['audio_pairs'])
		
		print "NUMBER OF TESTS:"
		print len(cherrypy.session['audio_pairs'])
		
		cherrypy.session['sid'] = cherrypy.session.get_session_path().split('/')[1]
		print cherrypy.session['sid']
		
		#print cherrypy.session['audio_pairs']
		pprint(cherrypy.session['audio_pairs'])
		
		
		TestPage.outfileid = '%s' %cherrypy.session['sid']
		ida = 0
		while os.path.exists('./sessions/%s/%s.txt' %(cherrypy.session['sid'], TestPage.outfileid)):
			TestPage.outfileid += '_%s' %ida
			ida += 1
		
		
		return welcome_templ %cherrypy.session['sid']	

		
	def doStart(self, pageId, sessionId, startButton, uinfo00=None, uinfo01=None, uinfo02=None, info1=None, info2=None, info3=None, info4=None, info5=None):
		
		
		
		if cherrypy.session['page'] != int(pageId):
			print "################################# BACK BUTTON PRESSED #################################"

		
		if cherrypy.session['sid'] != str(sessionId):
			return TestPage.sessionError(self)
		#cherrypy.session['page'] = int(pageId)
		
		
		
		
		cherrypy.session['userinfobox'] = str([str(uinfo00), str(uinfo01), str(uinfo02), int(info1), int(info2), int(info3), int(info4), int(info5)]) + '\n'
		cherrypy.session['sessionId'] = sessionId
		#print "sid:"
		#print TestPage.sid
		#print sessionId
		if cherrypy.session['sid'] != str(cherrypy.session['sessionId']):
			return TestPage.sessionError(self)
		else:
			return TestPage.index2(self)

		

	def index2(self):
		#try: print testvar
		#except: pass
	
		cherrypy.session['page'] = 1
		cherrypy.session['pages'] = 7
		cherrypy.session['tests'] = len(cherrypy.session['audio_pairs']) #should be 66  #10 * cherrypy.session['pages']
		cherrypy.session['results'] = []
		for cherrypy.session['n'] in xrange(cherrypy.session['tests']): cherrypy.session['results'].append([None,0,0,0,0])

		# create tuple to fill template
		cherrypy.session['ts'] = []
		for cherrypy.session['k'] in xrange(40):
			cherrypy.session['ts'].append(0)
			
		return audiotempl%TestPage.makeTuple(self, 10)
		
	def doAttrib(self, pageId, sessionId, submitButton, attribute1_1=None, attribute1_2=None, attribute1_3=None, attribute1_4=None, attribute2_1=None, attribute2_2=None, attribute2_3=None, attribute2_4=None, attribute3_1=None, attribute3_2=None, attribute3_3=None, attribute3_4=None, attribute4_1=None, attribute4_2=None, attribute4_3=None, attribute4_4=None, attribute5_1=None, attribute5_2=None, attribute5_3=None, attribute5_4=None, attribute6_1=None, attribute6_2=None, attribute6_3=None, attribute6_4=None, attribute7_1=None, attribute7_2=None, attribute7_3=None, attribute7_4=None, attribute8_1=None, attribute8_2=None, attribute8_3=None, attribute8_4=None, attribute9_1=None, attribute9_2=None, attribute9_3=None, attribute9_4=None, attribute10_1=None, attribute10_2=None, attribute10_3=None, attribute10_4=None):
		#print attribute1 + ' ' + attribute2
		# Error check
 			
		print "################################# %s" %pageId
		#_pageId = int(pageId) - 1

		if cherrypy.session['page'] != int(pageId):
			print "################################# BACK BUTTON PRESSED #################################"

		cherrypy.session['page'] = int(pageId)
						
		if cherrypy.session['sid'] != str(sessionId):
			return TestPage.sessionError(self)
				
		#store results
		
		cherrypy.session['pos'] = 10 * (cherrypy.session['page'] - 1)		
	 
		cherrypy.session['results'][cherrypy.session['pos']] = [cherrypy.session['audio_pairs'][cherrypy.session['pos']][2].split('/')[-1], int(attribute1_1), int(attribute1_2), int(attribute1_3), int(attribute1_4)]
		cherrypy.session['results'][cherrypy.session['pos']+1] = [cherrypy.session['audio_pairs'][cherrypy.session['pos']+1][2].split('/')[-1], int(attribute2_1), int(attribute2_2), int(attribute2_3), int(attribute2_4)]
		cherrypy.session['results'][cherrypy.session['pos']+2] = [cherrypy.session['audio_pairs'][cherrypy.session['pos']+2][2].split('/')[-1], int(attribute3_1), int(attribute3_2), int(attribute3_3), int(attribute3_4)]
		cherrypy.session['results'][cherrypy.session['pos']+3] = [cherrypy.session['audio_pairs'][cherrypy.session['pos']+3][2].split('/')[-1], int(attribute4_1), int(attribute4_2), int(attribute4_3), int(attribute4_4)]
		cherrypy.session['results'][cherrypy.session['pos']+4] = [cherrypy.session['audio_pairs'][cherrypy.session['pos']+4][2].split('/')[-1], int(attribute5_1), int(attribute5_2), int(attribute5_3), int(attribute5_4)]
		cherrypy.session['results'][cherrypy.session['pos']+5] = [cherrypy.session['audio_pairs'][cherrypy.session['pos']+5][2].split('/')[-1], int(attribute6_1), int(attribute6_2), int(attribute6_3), int(attribute6_4)]
		cherrypy.session['results'][cherrypy.session['pos']+6] = [cherrypy.session['audio_pairs'][cherrypy.session['pos']+6][2].split('/')[-1], int(attribute7_1), int(attribute7_2), int(attribute7_3), int(attribute7_4)]
		cherrypy.session['results'][cherrypy.session['pos']+7] = [cherrypy.session['audio_pairs'][cherrypy.session['pos']+7][2].split('/')[-1], int(attribute8_1), int(attribute8_2), int(attribute8_3), int(attribute8_4)]
		cherrypy.session['results'][cherrypy.session['pos']+8] = [cherrypy.session['audio_pairs'][cherrypy.session['pos']+8][2].split('/')[-1], int(attribute9_1), int(attribute9_2), int(attribute9_3), int(attribute9_4)]
		cherrypy.session['results'][cherrypy.session['pos']+9] = [cherrypy.session['audio_pairs'][cherrypy.session['pos']+9][2].split('/')[-1], int(attribute10_1), int(attribute10_2), int(attribute10_3), int(attribute10_4)]
		
		
		resString = cherrypy.session['ip'] + '\n' + TestPage.outfileid + '\n' + cherrypy.session['userinfobox'] + '\n' + ',\n'.join(str(x) for x in cherrypy.session['results'])
		
		#f = open(TestPage.sid_filename, 'w')
		#f.write(resString)
		#f.close()
		
		cherrypy.session.write_data(resString,'%s.txt'%TestPage.outfileid)
		
		#if cherrypy.session['page'] < cherrypy.session['pages'] - 1:
		cherrypy.session['page'] += 1
		# create tuple to fill template
		cherrypy.session['ts'] = []
		cherrypy.session['npos'] = cherrypy.session['pos'] + 10
		
		if cherrypy.session['page'] < cherrypy.session['pages']:
			cherrypy.session['m'] = 10
		else:
			cherrypy.session['m'] = 6
		
		for cherrypy.session['k'] in xrange(cherrypy.session['m']):
			for cherrypy.session['i'] in xrange(4):
				#print cherrypy.session['k']
				#print cherrypy.session['i']
				cherrypy.session['ts'].append(cherrypy.session['results'][cherrypy.session['npos']+cherrypy.session['k']][cherrypy.session['i']+1])	
			
		if cherrypy.session['page'] < cherrypy.session['pages']:
			return audiotempl%TestPage.makeTuple(self, cherrypy.session['m'])
		else:
			return audiotemplast%TestPage.makeTuple(self, cherrypy.session['m'])

	
	index.exposed = True
	doAttrib.exposed = True
	index2.exposed = True
	doStart.exposed = True

	
	def doAttrib2(self, pageId, sessionId, submitButton, attribute1_1=None, attribute1_2=None, attribute1_3=None, attribute1_4=None, attribute2_1=None, attribute2_2=None, attribute2_3=None, attribute2_4=None, attribute3_1=None, attribute3_2=None, attribute3_3=None, attribute3_4=None, attribute4_1=None, attribute4_2=None, attribute4_3=None, attribute4_4=None, attribute5_1=None, attribute5_2=None, attribute5_3=None, attribute5_4=None, attribute6_1=None, attribute6_2=None, attribute6_3=None, attribute6_4=None):
		#print attribute1 + ' ' + attribute2
		# Error check
 			
		print "################################# %s" %pageId
		#_pageId = int(pageId) - 1

		if cherrypy.session['page'] != int(pageId):
			print "################################# BACK BUTTON PRESSED #################################"

		cherrypy.session['page'] = int(pageId)
						
		if cherrypy.session['sid'] != str(sessionId):
			return TestPage.sessionError(self)
				
		#store results
		
		cherrypy.session['pos'] = 10 * (cherrypy.session['page'] - 1)		
	 
		cherrypy.session['results'][cherrypy.session['pos']] = [cherrypy.session['audio_pairs'][cherrypy.session['pos']][2].split('/')[-1], int(attribute1_1), int(attribute1_2), int(attribute1_3), int(attribute1_4)]
		cherrypy.session['results'][cherrypy.session['pos']+1] = [cherrypy.session['audio_pairs'][cherrypy.session['pos']+1][2].split('/')[-1], int(attribute2_1), int(attribute2_2), int(attribute2_3), int(attribute2_4)]
		cherrypy.session['results'][cherrypy.session['pos']+2] = [cherrypy.session['audio_pairs'][cherrypy.session['pos']+2][2].split('/')[-1], int(attribute3_1), int(attribute3_2), int(attribute3_3), int(attribute3_4)]
		cherrypy.session['results'][cherrypy.session['pos']+3] = [cherrypy.session['audio_pairs'][cherrypy.session['pos']+3][2].split('/')[-1], int(attribute4_1), int(attribute4_2), int(attribute4_3), int(attribute4_4)]
		cherrypy.session['results'][cherrypy.session['pos']+4] = [cherrypy.session['audio_pairs'][cherrypy.session['pos']+4][2].split('/')[-1], int(attribute5_1), int(attribute5_2), int(attribute5_3), int(attribute5_4)]
		cherrypy.session['results'][cherrypy.session['pos']+5] = [cherrypy.session['audio_pairs'][cherrypy.session['pos']+5][2].split('/')[-1], int(attribute6_1), int(attribute6_2), int(attribute6_3), int(attribute6_4)]

		
		
		resString = cherrypy.session['ip'] + '\n' + cherrypy.session['sid'] + '\n' + cherrypy.session['userinfobox'] + '\n' + ',\n'.join(str(x) for x in cherrypy.session['results'])
		
		#f = open(TestPage.sid_filename, 'w')
		#f.write(resString)
		#f.close()
		#os.path.exists()
		
		cherrypy.session.write_data(resString,'%s.txt'%TestPage.outfileid)
		
	
		print cherrypy.session['results']
		#_results = []
		
		cherrypy.session['templ'] = ''
		for cherrypy.session['n'] in xrange(cherrypy.session['tests']):
			#print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
			#print cherrypy.session['n']
			cherrypy.session['_templ'] = endtempl2 %(cherrypy.session['results'][cherrypy.session['n']][0], cherrypy.session['results'][cherrypy.session['n']][1], cherrypy.session['results'][cherrypy.session['n']][2], cherrypy.session['results'][cherrypy.session['n']][3], cherrypy.session['results'][cherrypy.session['n']][4])
			cherrypy.session['templ'] += cherrypy.session['_templ'] 

		#TestPage.pageComplete += 1
		try: 
			#print 'skipping email'
			TestPage.sendMail(self)
		except:
			print "WARNING: COULD NOT SEND RESULTS"
			pass
		cherrypy.session['sid'] = None
		return endtempl%cherrypy.session['templ']
		#return lastpage
			
			
	index.exposed = True
	doAttrib.exposed = True
	doAttrib2.exposed = True
	index2.exposed = True
	doStart.exposed = True
	
	
	def makeTuple(TestPage, nr):
		cherrypy.session['nr'] = nr
		cherrypy.session['ts'].append(cherrypy.session['page'])
		cherrypy.session['ts'].append(cherrypy.session['pages'])
		for cherrypy.session['k'] in xrange(cherrypy.session['nr']):
			pos = 10 * (cherrypy.session['page'] - 1) + cherrypy.session['k']
			#print pos
			for n in xrange(3): cherrypy.session['ts'].append(cherrypy.session['audio_pairs'][pos][1])
			for n in xrange(3): cherrypy.session['ts'].append(cherrypy.session['audio_pairs'][pos][2])		
		cherrypy.session['ts'].append(cherrypy.session['page'])
		cherrypy.session['ts'].append(cherrypy.session['sid'])
		cherrypy.session['ts'] = tuple(cherrypy.session['ts'])
		print cherrypy.session['ts']
		return cherrypy.session['ts']
	
	def sessionError(TestPage):
		print "################################# SESSION ERROR #################################"
		cherrypy.session['resString'] = cherrypy.session['ip'] + '\n' + str(cherrypy.session['sid']) + '\n' + cherrypy.session['userinfobox'] + '\n' + ',\n'.join(str(x) for x in cherrypy.session['results'])
		cherrypy.session['resString'] += '\n\nERROR: SESSION CONFUSION'
		#f = open(TestPage.sid_filename, 'w')
		#f.write(resString)
		#f.close()
		cherrypy.session.write_data(cherrypy.session['resString'],'%s.txt'%TestPage.outfileid)
		
		return '''
			<p>
			<a href="/test/">oh noes! there is something wrong with your session, please start again or go for a coffee!</a>
			</p>'''
			

	def sendMail(TestPage):
		cherrypy.session['file'] = './sessions/%s/%s.txt'%(cherrypy.session['sid'], TestPage.outfileid)
		username = 'eecsqmul@gmail.com'	 
		password = 'perceptual'
		fro = 'FX-Test <eecsqmul@gmail.com>'
		to = ['thomas.wilmering@eecs.qmul.ac.uk', 'gyorgy.fazekas@eecs.qmul.ac.uk']
		msg = MIMEMultipart()
		msg['From'] = fro
		msg['To'] = COMMASPACE.join(to)
		msg['Date'] = formatdate(localtime=True)
		msg['Subject'] = 'fx perceptual listening test'
		msg.attach( MIMEText('Attached are new results from the listening test.'))
		part = MIMEBase('application', "octet-stream")
		part.set_payload( open(cherrypy.session['file'],"rb").read() )
		Encoders.encode_base64(part)
		part.add_header('Content-Disposition', 'attachment; filename="%s"' % cherrypy.session['file'])
		msg.attach(part)
		server = smtplib.SMTP('smtp.gmail.com:587')
		server.starttls()
		server.login(username,password)
		server.sendmail(fro, to, msg.as_string() )
		server.close()


class OutPage:
	def index(self):
		return '''
		<html>
		<body>
		<div id="video">
		<embed id="roll-video" src="http://www.dafk.net/what/ilovethe80s.swf" width="400" height="300"></embed>
		</div>
		</body>
		</html>
		
		'''
	index.exposed = True		
	

# # Of course we can also mount request handler objects right here!
# root = HomePage()
# root.test = TestPage()
# root.out = OutPage()
# #root = TestPage()
# 
# tutconf = os.path.join(os.path.dirname(__file__), 'conf.conf')


def startFxTest(args):
	
	# check local switch
	if args.count('-local') :
		local = True; args.remove('-local'); 
		print 'Startup: Local mode.'
		conf = os.path.join(os.path.dirname(__file__), 'local.conf')
	else:
		conf = os.path.join(os.path.dirname(__file__), 'server.conf')
		local = False
				
	# check string encoding
	print "Startup: String encoding = '%s'" %(str(sys.getdefaultencoding()))

	# check ip switch
	ip = ''
	if args.count('-ip') :
		try :
			# here we just see if it's numeric, parsing is done by the server wrapper
			if args[args.index('-ip')+1].replace('.','').replace(':','').isdigit() :
				ip = args[args.index('-ip')+1]
			else :
				print "Startup: Invalid service IP address. Use format: sawa.py -ip 127.0.0.1:8080"
				os._exit(-1)				
		except :
			print "Startup: Invalid service IP address. (Insufficient arguments.) Use format: cherryFxTest.py -ip 127.0.0.1:8080"
			os._exit(-1)
		args.remove(args[args.index('-ip')+1]); 
		args.remove('-ip')


	# old command:
	# cherrypy.quickstart(root, config=conf)	
	
	# Of course we can also mount request handler objects right here!
	root = HomePage()
	root.test = TestPage()
	root.daniele = TestPage()
	root.out = OutPage()
	#root = TestPage()	
	
	server = CherryPyServer(ServerConfig(root=root,local=local,conf=conf)) 
	# if local :
	# 	server = CherryPyServer(ServerConfig(root=root,local=local,conf=conf))  
	# else :
	# 	server = CherryPyServer(ServerConfig(root=False,local=local,conf=conf))  
	server.mount(root,path_name='')
	server.quickstart(ip)
	

if __name__ == '__main__':
	# CherryPy always starts with app.root when trying to map request URIs
	# to objects, so we need to mount a request handler root. A request
	# to '/' will be mapped to HelloWorld().index().	
	# cherrypy.quickstart(root, config=tutconf)
	import sys
	startFxTest(sys.argv[1:])
else:
	# This branch is for the test suite; you can ignore it.
	cherrypy.tree.mount(root, config=tutconf)