comparison cherryFxTest.py @ 0:032bc65ebafc

added core components
author George Fazekas <gyorgy.fazekas@eecs.qmul.ac.uk>
date Wed, 06 Mar 2013 15:45:48 +0000
parents
children 9ab73065952b
comparison
equal deleted inserted replaced
-1:000000000000 0:032bc65ebafc
1
2 import cherrypy, os, random, smtplib, string
3 from cherrypy.lib.static import serve_file
4 from templates import *
5
6 from DirectorySession import DirectorySession
7 from ServerWrapper import ServerWrapper as CherryPyServer
8 from ServerWrapper import Config as ServerConfig
9
10 from email.MIMEBase import MIMEBase
11 from email.MIMEText import MIMEText
12 from email.MIMEMultipart import MIMEMultipart
13 from email.Utils import COMMASPACE, formatdate
14 from email import Encoders
15
16 from pprint import pprint
17
18 PATH = os.path.abspath(os.path.dirname(__file__))
19
20 #audiodir = './audio'
21 #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']))]
22 #cherrypy.session['fxs'].remove('dry')
23 #print cherrypy.session['fxs']
24
25 class Root(object): pass
26
27
28 class HomePage:
29 def index(self):
30
31 return "move along, nothing to see here!"
32
33 index.exposed = True
34
35
36
37 class TestPage:
38
39 def getFiles(self):
40 audiodir = './audio'
41 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']))]
42 cherrypy.session['fxs'].remove('dry')
43 print cherrypy.session['fxs']
44
45 def index(self):
46 TestPage.getFiles(self)
47 cherrypy.session['sid'] = None
48
49 cherrypy.session['sid_filename'] = None
50
51
52 if cherrypy.request.headers.has_key("X-Forwarded-For"):
53 cherrypy.session['ip'] = cherrypy.request.headers["X-Forwarded-For"]
54 elif cherrypy.request.headers.has_key("Remote-Addr"):
55 cherrypy.session['ip'] = cherrypy.request.headers["Remote-Addr"]
56 else :
57 cherrypy.session['ip'] = None
58
59 cherrypy.session['test'] = None
60 cherrypy.session['results'] = None
61 cherrypy.session['tests'] = None
62 cherrypy.session['test_nr'] = None
63 cherrypy.session['audio_pairs'] = None
64 cherrypy.session['page'] = 0
65 cherrypy.session['pages'] = 6
66 cherrypy.session['userinfobox'] = None
67 cherrypy.session['ts'] = None
68 #return '''
69 # <p>
70 # <a href="/test/">start test</a>
71 # </p>'''
72
73 #take 2 examples for each effect
74
75 cherrypy.session['audio_pairs'] = []
76
77 # get effected files:
78
79 for cherrypy.session['fx'] in cherrypy.session['fxs']:
80 cherrypy.session['dirlist'] = os.listdir('./audio/%s/'%cherrypy.session['fx'])
81 cherrypy.session['filelist'] = []
82 for cherrypy.session['item'] in cherrypy.session['dirlist']:
83 if cherrypy.session['item'].split('.')[-1] == 'mp3':
84 cherrypy.session['filelist'].append(cherrypy.session['item'].split('.')[0])
85
86 # create audio pairs for this fx
87
88 cherrypy.session['first'] = cherrypy.session['second'] = random.choice(cherrypy.session['filelist'])
89 while cherrypy.session['first'] == cherrypy.session['second']:
90 cherrypy.session['second'] = random.choice(cherrypy.session['filelist'])
91
92 cherrypy.session['dry1'] = 'dry/%s' %cherrypy.session['first'].split('_%s'%cherrypy.session['fx'])[0]
93 cherrypy.session['fx1'] = '%s/%s' %(cherrypy.session['fx'], cherrypy.session['first'])
94 cherrypy.session['dry2'] = 'dry/%s' %cherrypy.session['second'].split('_%s'%cherrypy.session['fx'])[0]
95 cherrypy.session['fx2'] = '%s/%s' %(cherrypy.session['fx'], cherrypy.session['second'])
96 cherrypy.session['audio_pairs'].append([cherrypy.session['fx'], cherrypy.session['dry1'], cherrypy.session['fx1']])
97 cherrypy.session['audio_pairs'].append([cherrypy.session['fx'], cherrypy.session['dry2'], cherrypy.session['fx2']])
98
99 #print TestPage.audio_pairs
100 random.shuffle(cherrypy.session['audio_pairs'])
101
102 print "NUMBER OF TESTS:"
103 print len(cherrypy.session['audio_pairs'])
104
105 cherrypy.session['sid'] = cherrypy.session.get_session_path().split('/')[1]
106 print cherrypy.session['sid']
107
108 #print cherrypy.session['audio_pairs']
109 pprint(cherrypy.session['audio_pairs'])
110
111
112 TestPage.outfileid = '%s' %cherrypy.session['sid']
113 ida = 0
114 while os.path.exists('./sessions/%s/%s.txt' %(cherrypy.session['sid'], TestPage.outfileid)):
115 TestPage.outfileid += '_%s' %ida
116 ida += 1
117
118
119 return welcome_templ %cherrypy.session['sid']
120
121
122 def doStart(self, pageId, sessionId, startButton, uinfo00=None, uinfo01=None, uinfo02=None, info1=None, info2=None, info3=None, info4=None, info5=None):
123
124
125
126 if cherrypy.session['page'] != int(pageId):
127 print "################################# BACK BUTTON PRESSED #################################"
128
129
130 if cherrypy.session['sid'] != str(sessionId):
131 return TestPage.sessionError(self)
132 #cherrypy.session['page'] = int(pageId)
133
134
135
136
137 cherrypy.session['userinfobox'] = str([str(uinfo00), str(uinfo01), str(uinfo02), int(info1), int(info2), int(info3), int(info4), int(info5)]) + '\n'
138 cherrypy.session['sessionId'] = sessionId
139 #print "sid:"
140 #print TestPage.sid
141 #print sessionId
142 if cherrypy.session['sid'] != str(cherrypy.session['sessionId']):
143 return TestPage.sessionError(self)
144 else:
145 return TestPage.index2(self)
146
147
148
149 def index2(self):
150 #try: print testvar
151 #except: pass
152
153 cherrypy.session['page'] = 1
154 cherrypy.session['pages'] = 7
155 cherrypy.session['tests'] = len(cherrypy.session['audio_pairs']) #should be 66 #10 * cherrypy.session['pages']
156 cherrypy.session['results'] = []
157 for cherrypy.session['n'] in xrange(cherrypy.session['tests']): cherrypy.session['results'].append([None,0,0,0,0])
158
159 # create tuple to fill template
160 cherrypy.session['ts'] = []
161 for cherrypy.session['k'] in xrange(40):
162 cherrypy.session['ts'].append(0)
163
164 return audiotempl%TestPage.makeTuple(self, 10)
165
166 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):
167 #print attribute1 + ' ' + attribute2
168 # Error check
169
170 print "################################# %s" %pageId
171 #_pageId = int(pageId) - 1
172
173 if cherrypy.session['page'] != int(pageId):
174 print "################################# BACK BUTTON PRESSED #################################"
175
176 cherrypy.session['page'] = int(pageId)
177
178 if cherrypy.session['sid'] != str(sessionId):
179 return TestPage.sessionError(self)
180
181 #store results
182
183 cherrypy.session['pos'] = 10 * (cherrypy.session['page'] - 1)
184
185 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)]
186 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)]
187 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)]
188 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)]
189 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)]
190 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)]
191 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)]
192 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)]
193 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)]
194 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)]
195
196
197 resString = cherrypy.session['ip'] + '\n' + TestPage.outfileid + '\n' + cherrypy.session['userinfobox'] + '\n' + ',\n'.join(str(x) for x in cherrypy.session['results'])
198
199 #f = open(TestPage.sid_filename, 'w')
200 #f.write(resString)
201 #f.close()
202
203 cherrypy.session.write_data(resString,'%s.txt'%TestPage.outfileid)
204
205 #if cherrypy.session['page'] < cherrypy.session['pages'] - 1:
206 cherrypy.session['page'] += 1
207 # create tuple to fill template
208 cherrypy.session['ts'] = []
209 cherrypy.session['npos'] = cherrypy.session['pos'] + 10
210
211 if cherrypy.session['page'] < cherrypy.session['pages']:
212 cherrypy.session['m'] = 10
213 else:
214 cherrypy.session['m'] = 6
215
216 for cherrypy.session['k'] in xrange(cherrypy.session['m']):
217 for cherrypy.session['i'] in xrange(4):
218 #print cherrypy.session['k']
219 #print cherrypy.session['i']
220 cherrypy.session['ts'].append(cherrypy.session['results'][cherrypy.session['npos']+cherrypy.session['k']][cherrypy.session['i']+1])
221
222 if cherrypy.session['page'] < cherrypy.session['pages']:
223 return audiotempl%TestPage.makeTuple(self, cherrypy.session['m'])
224 else:
225 return audiotemplast%TestPage.makeTuple(self, cherrypy.session['m'])
226
227
228 index.exposed = True
229 doAttrib.exposed = True
230 index2.exposed = True
231 doStart.exposed = True
232
233
234 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):
235 #print attribute1 + ' ' + attribute2
236 # Error check
237
238 print "################################# %s" %pageId
239 #_pageId = int(pageId) - 1
240
241 if cherrypy.session['page'] != int(pageId):
242 print "################################# BACK BUTTON PRESSED #################################"
243
244 cherrypy.session['page'] = int(pageId)
245
246 if cherrypy.session['sid'] != str(sessionId):
247 return TestPage.sessionError(self)
248
249 #store results
250
251 cherrypy.session['pos'] = 10 * (cherrypy.session['page'] - 1)
252
253 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)]
254 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)]
255 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)]
256 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)]
257 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)]
258 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)]
259
260
261
262 resString = cherrypy.session['ip'] + '\n' + cherrypy.session['sid'] + '\n' + cherrypy.session['userinfobox'] + '\n' + ',\n'.join(str(x) for x in cherrypy.session['results'])
263
264 #f = open(TestPage.sid_filename, 'w')
265 #f.write(resString)
266 #f.close()
267 #os.path.exists()
268
269 cherrypy.session.write_data(resString,'%s.txt'%TestPage.outfileid)
270
271
272 print cherrypy.session['results']
273 #_results = []
274
275 cherrypy.session['templ'] = ''
276 for cherrypy.session['n'] in xrange(cherrypy.session['tests']):
277 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
278 #print cherrypy.session['n']
279 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])
280 cherrypy.session['templ'] += cherrypy.session['_templ']
281
282 #TestPage.pageComplete += 1
283 try:
284 #print 'skipping email'
285 TestPage.sendMail(self)
286 except:
287 print "WARNING: COULD NOT SEND RESULTS"
288 pass
289 cherrypy.session['sid'] = None
290 return endtempl%cherrypy.session['templ']
291 #return lastpage
292
293
294 index.exposed = True
295 doAttrib.exposed = True
296 doAttrib2.exposed = True
297 index2.exposed = True
298 doStart.exposed = True
299
300
301 def makeTuple(TestPage, nr):
302 cherrypy.session['nr'] = nr
303 cherrypy.session['ts'].append(cherrypy.session['page'])
304 cherrypy.session['ts'].append(cherrypy.session['pages'])
305 for cherrypy.session['k'] in xrange(cherrypy.session['nr']):
306 pos = 10 * (cherrypy.session['page'] - 1) + cherrypy.session['k']
307 #print pos
308 for n in xrange(3): cherrypy.session['ts'].append(cherrypy.session['audio_pairs'][pos][1])
309 for n in xrange(3): cherrypy.session['ts'].append(cherrypy.session['audio_pairs'][pos][2])
310 cherrypy.session['ts'].append(cherrypy.session['page'])
311 cherrypy.session['ts'].append(cherrypy.session['sid'])
312 cherrypy.session['ts'] = tuple(cherrypy.session['ts'])
313 print cherrypy.session['ts']
314 return cherrypy.session['ts']
315
316 def sessionError(TestPage):
317 print "################################# SESSION ERROR #################################"
318 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'])
319 cherrypy.session['resString'] += '\n\nERROR: SESSION CONFUSION'
320 #f = open(TestPage.sid_filename, 'w')
321 #f.write(resString)
322 #f.close()
323 cherrypy.session.write_data(cherrypy.session['resString'],'%s.txt'%TestPage.outfileid)
324
325 return '''
326 <p>
327 <a href="/test/">oh noes! there is something wrong with your session, please start again or go for a coffee!</a>
328 </p>'''
329
330
331 def sendMail(TestPage):
332 cherrypy.session['file'] = './sessions/%s/%s.txt'%(cherrypy.session['sid'], TestPage.outfileid)
333 username = 'eecsqmul@gmail.com'
334 password = 'perceptual'
335 fro = 'FX-Test <eecsqmul@gmail.com>'
336 to = ['thomas.wilmering@eecs.qmul.ac.uk', 'gyorgy.fazekas@eecs.qmul.ac.uk']
337 msg = MIMEMultipart()
338 msg['From'] = fro
339 msg['To'] = COMMASPACE.join(to)
340 msg['Date'] = formatdate(localtime=True)
341 msg['Subject'] = 'fx perceptual listening test'
342 msg.attach( MIMEText('Attached are new results from the listening test.'))
343 part = MIMEBase('application', "octet-stream")
344 part.set_payload( open(cherrypy.session['file'],"rb").read() )
345 Encoders.encode_base64(part)
346 part.add_header('Content-Disposition', 'attachment; filename="%s"' % cherrypy.session['file'])
347 msg.attach(part)
348 server = smtplib.SMTP('smtp.gmail.com:587')
349 server.starttls()
350 server.login(username,password)
351 server.sendmail(fro, to, msg.as_string() )
352 server.close()
353
354
355 class OutPage:
356 def index(self):
357 return '''
358 <html>
359 <body>
360 <div id="video">
361 <embed id="roll-video" src="http://www.dafk.net/what/ilovethe80s.swf" width="400" height="300"></embed>
362 </div>
363 </body>
364 </html>
365
366 '''
367 index.exposed = True
368
369
370 # # Of course we can also mount request handler objects right here!
371 # root = HomePage()
372 # root.test = TestPage()
373 # root.out = OutPage()
374 # #root = TestPage()
375 #
376 # tutconf = os.path.join(os.path.dirname(__file__), 'conf.conf')
377
378
379 def startFxTest(args):
380
381 # check local switch
382 if args.count('-local') :
383 local = True; args.remove('-local');
384 print 'Startup: Local mode.'
385 conf = os.path.join(os.path.dirname(__file__), 'local.conf')
386 else:
387 conf = os.path.join(os.path.dirname(__file__), 'server.conf')
388 local = False
389
390 # check string encoding
391 print "Startup: String encoding = '%s'" %(str(sys.getdefaultencoding()))
392
393 # check ip switch
394 ip = ''
395 if args.count('-ip') :
396 try :
397 # here we just see if it's numeric, parsing is done by the server wrapper
398 if args[args.index('-ip')+1].replace('.','').replace(':','').isdigit() :
399 ip = args[args.index('-ip')+1]
400 else :
401 print "Startup: Invalid service IP address. Use format: sawa.py -ip 127.0.0.1:8080"
402 os._exit(-1)
403 except :
404 print "Startup: Invalid service IP address. (Insufficient arguments.) Use format: cherryFxTest.py -ip 127.0.0.1:8080"
405 os._exit(-1)
406 args.remove(args[args.index('-ip')+1]);
407 args.remove('-ip')
408
409
410 # old command:
411 # cherrypy.quickstart(root, config=conf)
412
413 # Of course we can also mount request handler objects right here!
414 root = HomePage()
415 root.test = TestPage()
416 root.out = OutPage()
417 #root = TestPage()
418
419 server = CherryPyServer(ServerConfig(root=root,local=local,conf=conf))
420 # if local :
421 # server = CherryPyServer(ServerConfig(root=root,local=local,conf=conf))
422 # else :
423 # server = CherryPyServer(ServerConfig(root=False,local=local,conf=conf))
424 server.mount(root,path_name='')
425 server.quickstart(ip)
426
427
428 if __name__ == '__main__':
429 # CherryPy always starts with app.root when trying to map request URIs
430 # to objects, so we need to mount a request handler root. A request
431 # to '/' will be mapped to HelloWorld().index().
432 # cherrypy.quickstart(root, config=tutconf)
433 import sys
434 startFxTest(sys.argv[1:])
435 else:
436 # This branch is for the test suite; you can ignore it.
437 cherrypy.tree.mount(root, config=tutconf)
438