comparison cherryFxTest_1mains.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
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 return welcome_templ %cherrypy.session['sid']
112
113
114 def doStart(self, pageId, sessionId, startButton, uinfo00=None, uinfo01=None, uinfo02=None, info1=None, info2=None, info3=None, info4=None, info5=None):
115
116
117 if cherrypy.session['page'] != int(pageId):
118 print "################################# BACK BUTTON PRESSED #################################"
119
120
121 if cherrypy.session['sid'] != str(sessionId):
122 return TestPage.sessionError(self)
123 #cherrypy.session['page'] = int(pageId)
124
125
126
127
128 cherrypy.session['userinfobox'] = str([str(uinfo00), str(uinfo01), str(uinfo02), int(info1), int(info2), int(info3), int(info4), int(info5)]) + '\n'
129 cherrypy.session['sessionId'] = sessionId
130 #print "sid:"
131 #print TestPage.sid
132 #print sessionId
133 if cherrypy.session['sid'] != str(cherrypy.session['sessionId']):
134 return TestPage.sessionError(self)
135 else:
136 return TestPage.index2(self)
137
138
139
140 def index2(self):
141 #try: print testvar
142 #except: pass
143
144 cherrypy.session['page'] = 1
145 cherrypy.session['pages'] = 7
146 cherrypy.session['tests'] = len(cherrypy.session['audio_pairs']) #should be 66 #10 * cherrypy.session['pages']
147 cherrypy.session['results'] = []
148 for cherrypy.session['n'] in xrange(cherrypy.session['tests']): cherrypy.session['results'].append([None,0,0,0,0])
149
150 # create tuple to fill template
151 cherrypy.session['ts'] = []
152 for cherrypy.session['k'] in xrange(40):
153 cherrypy.session['ts'].append(0)
154
155 return audiotempl%TestPage.makeTuple(self, 10)
156
157 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):
158 #print attribute1 + ' ' + attribute2
159 # Error check
160
161 print "################################# %s" %pageId
162 #_pageId = int(pageId) - 1
163
164 if cherrypy.session['page'] != int(pageId):
165 print "################################# BACK BUTTON PRESSED #################################"
166
167 cherrypy.session['page'] = int(pageId)
168
169 if cherrypy.session['sid'] != str(sessionId):
170 return TestPage.sessionError(self)
171
172 #store results
173
174 cherrypy.session['pos'] = 10 * (cherrypy.session['page'] - 1)
175
176 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)]
177 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)]
178 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)]
179 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)]
180 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)]
181 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)]
182 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)]
183 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)]
184 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)]
185 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)]
186
187
188 resString = cherrypy.session['ip'] + '\n' + cherrypy.session['sid'] + '\n' + cherrypy.session['userinfobox'] + '\n' + ',\n'.join(str(x) for x in cherrypy.session['results'])
189
190 #f = open(TestPage.sid_filename, 'w')
191 #f.write(resString)
192 #f.close()
193
194 cherrypy.session.write_data(resString,'%s.txt'%cherrypy.session['sid'])
195
196 #if cherrypy.session['page'] < cherrypy.session['pages'] - 1:
197 cherrypy.session['page'] += 1
198 # create tuple to fill template
199 cherrypy.session['ts'] = []
200 cherrypy.session['npos'] = cherrypy.session['pos'] + 10
201
202 if cherrypy.session['page'] < cherrypy.session['pages']:
203 cherrypy.session['m'] = 10
204 else:
205 cherrypy.session['m'] = 6
206
207 for cherrypy.session['k'] in xrange(cherrypy.session['m']):
208 for cherrypy.session['i'] in xrange(4):
209 #print cherrypy.session['k']
210 #print cherrypy.session['i']
211 cherrypy.session['ts'].append(cherrypy.session['results'][cherrypy.session['npos']+cherrypy.session['k']][cherrypy.session['i']+1])
212
213 if cherrypy.session['page'] < cherrypy.session['pages']:
214 return audiotempl%TestPage.makeTuple(self, cherrypy.session['m'])
215 else:
216 return audiotemplast%TestPage.makeTuple(self, cherrypy.session['m'])
217
218
219 index.exposed = True
220 doAttrib.exposed = True
221 index2.exposed = True
222 doStart.exposed = True
223
224
225 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):
226 #print attribute1 + ' ' + attribute2
227 # Error check
228
229 print "################################# %s" %pageId
230 #_pageId = int(pageId) - 1
231
232 if cherrypy.session['page'] != int(pageId):
233 print "################################# BACK BUTTON PRESSED #################################"
234
235 cherrypy.session['page'] = int(pageId)
236
237 if cherrypy.session['sid'] != str(sessionId):
238 return TestPage.sessionError(self)
239
240 #store results
241
242 cherrypy.session['pos'] = 10 * (cherrypy.session['page'] - 1)
243
244 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)]
245 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)]
246 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)]
247 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)]
248 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)]
249 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)]
250
251
252
253 resString = cherrypy.session['ip'] + '\n' + cherrypy.session['sid'] + '\n' + cherrypy.session['userinfobox'] + '\n' + ',\n'.join(str(x) for x in cherrypy.session['results'])
254
255 #f = open(TestPage.sid_filename, 'w')
256 #f.write(resString)
257 #f.close()
258
259 cherrypy.session.write_data(resString,'%s.txt'%cherrypy.session['sid'])
260
261
262 print cherrypy.session['results']
263 #_results = []
264
265 cherrypy.session['templ'] = ''
266 for cherrypy.session['n'] in xrange(cherrypy.session['tests']):
267 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
268 #print cherrypy.session['n']
269 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])
270 cherrypy.session['templ'] += cherrypy.session['_templ']
271
272 #TestPage.pageComplete += 1
273 try:
274 #print 'skipping email'
275 TestPage.sendMail(self)
276 except:
277 print "WARNING: COULD NOT SEND RESULTS"
278 pass
279 cherrypy.session['sid'] = None
280 return endtempl%cherrypy.session['templ']
281 #return lastpage
282
283
284 index.exposed = True
285 doAttrib.exposed = True
286 doAttrib2.exposed = True
287 index2.exposed = True
288 doStart.exposed = True
289
290
291 def makeTuple(TestPage, nr):
292 cherrypy.session['nr'] = nr
293 cherrypy.session['ts'].append(cherrypy.session['page'])
294 cherrypy.session['ts'].append(cherrypy.session['pages'])
295 for cherrypy.session['k'] in xrange(cherrypy.session['nr']):
296 pos = 10 * (cherrypy.session['page'] - 1) + cherrypy.session['k']
297 #print pos
298 for n in xrange(3): cherrypy.session['ts'].append(cherrypy.session['audio_pairs'][pos][1])
299 for n in xrange(3): cherrypy.session['ts'].append(cherrypy.session['audio_pairs'][pos][2])
300 cherrypy.session['ts'].append(cherrypy.session['page'])
301 cherrypy.session['ts'].append(cherrypy.session['sid'])
302 cherrypy.session['ts'] = tuple(cherrypy.session['ts'])
303 print cherrypy.session['ts']
304 return cherrypy.session['ts']
305
306 def sessionError(TestPage):
307 print "################################# SESSION ERROR #################################"
308 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'])
309 cherrypy.session['resString'] += '\n\nERROR: SESSION CONFUSION'
310 #f = open(TestPage.sid_filename, 'w')
311 #f.write(resString)
312 #f.close()
313 cherrypy.session.write_data(cherrypy.session['resString'],'%s.txt'%cherrypy.session['sid'])
314
315 return '''
316 <p>
317 <a href="/test/">oh noes! there is something wrong with your session, please start again or go for a coffee!</a>
318 </p>'''
319
320
321 def sendMail(TestPage):
322 cherrypy.session['file'] = './sessions/%s/%s.txt'%(cherrypy.session['sid'], cherrypy.session['sid'])
323 username = 'eecsqmul@gmail.com'
324 password = 'perceptual'
325 fro = 'FX-Test <eecsqmul@gmail.com>'
326 to = ['thomas.wilmering@eecs.qmul.ac.uk', 'gyorgy.fazekas@eecs.qmul.ac.uk']
327 msg = MIMEMultipart()
328 msg['From'] = fro
329 msg['To'] = COMMASPACE.join(to)
330 msg['Date'] = formatdate(localtime=True)
331 msg['Subject'] = 'fx perceptual listening test'
332 msg.attach( MIMEText('Attached are new results from the listening test.'))
333 part = MIMEBase('application', "octet-stream")
334 part.set_payload( open(cherrypy.session['file'],"rb").read() )
335 Encoders.encode_base64(part)
336 part.add_header('Content-Disposition', 'attachment; filename="%s"' % cherrypy.session['file'])
337 msg.attach(part)
338 server = smtplib.SMTP('smtp.gmail.com:587')
339 server.starttls()
340 server.login(username,password)
341 server.sendmail(fro, to, msg.as_string() )
342 server.close()
343
344
345 class OutPage:
346 def index(self):
347 return '''
348 <html>
349 <body>
350 <div id="video">
351 <embed id="roll-video" src="http://www.dafk.net/what/ilovethe80s.swf" width="400" height="300"></embed>
352 </div>
353 </body>
354 </html>
355
356 '''
357 index.exposed = True
358
359
360 # # Of course we can also mount request handler objects right here!
361 # root = HomePage()
362 # root.test = TestPage()
363 # root.out = OutPage()
364 # #root = TestPage()
365 #
366 # tutconf = os.path.join(os.path.dirname(__file__), 'conf.conf')
367
368
369 def startFxTest(args):
370
371 # check local switch
372 if args.count('-local') :
373 local = True; args.remove('-local');
374 print 'Startup: Local mode.'
375 conf = os.path.join(os.path.dirname(__file__), 'local.conf')
376 else:
377 conf = os.path.join(os.path.dirname(__file__), 'server.conf')
378 local = False
379
380 # check string encoding
381 print "Startup: String encoding = '%s'" %(str(sys.getdefaultencoding()))
382
383 # check ip switch
384 ip = ''
385 if args.count('-ip') :
386 try :
387 # here we just see if it's numeric, parsing is done by the server wrapper
388 if args[args.index('-ip')+1].replace('.','').replace(':','').isdigit() :
389 ip = args[args.index('-ip')+1]
390 else :
391 print "Startup: Invalid service IP address. Use format: sawa.py -ip 127.0.0.1:8080"
392 os._exit(-1)
393 except :
394 print "Startup: Invalid service IP address. (Insufficient arguments.) Use format: cherryFxTest.py -ip 127.0.0.1:8080"
395 os._exit(-1)
396 args.remove(args[args.index('-ip')+1]);
397 args.remove('-ip')
398
399
400 # old command:
401 # cherrypy.quickstart(root, config=conf)
402
403 # Of course we can also mount request handler objects right here!
404 root = HomePage()
405 root.test = TestPage()
406 root.out = OutPage()
407 #root = TestPage()
408
409 server = CherryPyServer(ServerConfig(root=root,local=local,conf=conf))
410 # if local :
411 # server = CherryPyServer(ServerConfig(root=root,local=local,conf=conf))
412 # else :
413 # server = CherryPyServer(ServerConfig(root=False,local=local,conf=conf))
414 server.mount(root,path_name='')
415 server.quickstart(ip)
416
417
418 if __name__ == '__main__':
419 # CherryPy always starts with app.root when trying to map request URIs
420 # to objects, so we need to mount a request handler root. A request
421 # to '/' will be mapped to HelloWorld().index().
422 # cherrypy.quickstart(root, config=tutconf)
423 import sys
424 startFxTest(sys.argv[1:])
425 else:
426 # This branch is for the test suite; you can ignore it.
427 cherrypy.tree.mount(root, config=tutconf)
428