Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

recording_gui.py 21 KB
Raw

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
  1. # -*- coding: utf-8 -*-
  2. import sounddevice as sd
  3. from psychopy import gui, visual, core, event
  4. import numpy as np
  5. import scipy.io.wavfile as wavfile
  6. import datetime
  7. import os
  8. import sys
  9. import util
  10. class ProgressBar():
  11. """
  12. Class to visualize a progress bar on a psychopy window object
  13. """
  14. def __init__(self, window, fillup=0.0, msg= None, autoDraw = False, pos = [0.0, 0.0],
  15. relWidth = 0.9, relHeight = 0.05, lineColor = (1,1,1),
  16. fillColor = (1,1,1), backgoundColor = (-0.9, -0.9, -0.9)):
  17. """
  18. Parameters:
  19. -----------
  20. window: psychopy.visual.Window
  21. fillup: float
  22. Initial progress of progress bar, must be in [0,1].
  23. msg: string
  24. Message to show.
  25. autoDraw: boolean
  26. If True, progess bar is shown with every frame flip. If false,
  27. progress bar is not visible.
  28. pos: x,y tuple
  29. Coordinates of center of progress bar
  30. relWidth: float
  31. Width of progressbar relative to screen width
  32. relHeigth: float
  33. Height of progressbar relative to screen height
  34. lineColor: RGB tuple
  35. Color of progressbar contours
  36. fillColor: RGB tuple
  37. Color of filling of progressbar
  38. backgroundcolor: RGB tuple
  39. Color of non-filled progressbar
  40. """
  41. self.window = window
  42. self.relWidth = relWidth
  43. self.fillColor = fillColor
  44. self.x0 = pos[0] - self.relWidth
  45. self.x1 = pos[0] + self.relWidth
  46. self.y0 = pos[1] - relHeight
  47. self.y1 = pos[1] + relHeight
  48. # current progress
  49. x_progress = self.x0 + fillup*self.relWidth
  50. # "static" progress bar frame
  51. self.backBar = visual.ShapeStim(self.window,
  52. pos = pos,
  53. vertices = [(self.x0, self.y0),
  54. (self.x0, self.y1),
  55. (self.x1, self.y1),
  56. (self.x1, self.y0)],
  57. closeShape = True,
  58. lineColor = lineColor,
  59. fillColor = backgoundColor,
  60. autoDraw = autoDraw,
  61. units = 'norm')
  62. # "dynamic" bar of the progress bar, width and height are zero at init,
  63. # the correct positions of all vertices are set in set_progress()
  64. self.progBar = visual.Rect(self.window,
  65. pos = pos,
  66. width = 0,
  67. height = 0,
  68. lineColor = lineColor,
  69. fillColor = self.fillColor,
  70. autoDraw = autoDraw,
  71. units = 'norm')
  72. # percentage number which may be displayed additionally
  73. self.msgPrompt = visual.TextStim(self.window,
  74. text = msg if msg != None else str(fillup),
  75. pos = (pos[0], 2*self.y1),
  76. height = 0.05,
  77. units = 'norm')
  78. # there is no autoDraw parameter in TextStim constructor, so set manually
  79. self.msgPrompt.setAutoDraw(autoDraw)
  80. def set_progress(self, fillup, msg=None):
  81. """
  82. Method to update current progress.
  83. Parameters:
  84. -----------
  85. fillup: float
  86. Current progress, must be in [0,1].
  87. msg: string (or None)
  88. If a string is passed, it will be displayed.
  89. """
  90. x_progress = self.x0 + fillup*(2*self.relWidth)
  91. self.progBar.setVertices([(self.x0, self.y0),
  92. (self.x0, self.y1),
  93. (x_progress, self.y1),
  94. (x_progress, self.y0)])
  95. self.progBar.closeShape = True
  96. if msg != None:
  97. self.msgPrompt.setText(msg)
  98. else:
  99. self.msgPrompt.setText("{:.1f} %".format(fillup*100))
  100. def set_message(self, msg):
  101. """
  102. Method to display messages.
  103. Parameters:
  104. -----------
  105. msg: string
  106. Message to display.
  107. """
  108. self.msgPrompt.setText(msg)
  109. def set_AutoDraw(self, flag):
  110. """
  111. Method to toggle autodraw of progressbar.
  112. See documentation of psychopy for further explanation of the autodraw
  113. functionality.
  114. Parameters:
  115. -----------
  116. flag: boolean
  117. Set autodraw to True or to False.
  118. """
  119. self.backBar.setAutoDraw(flag)
  120. self.progBar.setAutoDraw(flag)
  121. self.msgPrompt.setAutoDraw(flag)
  122. def set_color(self, color):
  123. """
  124. Method to set color of progess of progressbar.
  125. Parameters:
  126. -----------
  127. color: RGB tuple
  128. """
  129. self.progBar.setFillColor(color)
  130. class SubjectMessageScreen():
  131. """
  132. Class to display a message dialog
  133. """
  134. def __init__(self, msg):
  135. """
  136. Parameters:
  137. -----------
  138. msg: string
  139. Message to show.
  140. """
  141. self.window = gui.Dlg(title='Message dialog')
  142. self.window.addText(msg)
  143. def show(self):
  144. """
  145. Call this method to show this SubjectMessageScreen.
  146. """
  147. self.window.show()
  148. if self.window.OK:
  149. return True
  150. else:
  151. return False
  152. class SubjectDataScreen(gui.DlgFromDict):
  153. """
  154. Class for entering subject data.
  155. """
  156. def __init__(self,
  157. dictionary,
  158. title='Subject information',
  159. order = ['alias','age','origin','accent','native speaker','gender','recordingdate'],
  160. fixed=['recordingdate']):
  161. """
  162. Parameters:
  163. -----------
  164. dictionary: dict
  165. Dictionary with keys 'alias','age','origin','accent',
  166. 'native speaker','gender','recordingdate'
  167. title: string
  168. Window title
  169. order: list of strings
  170. List of keys, specifying their order on screen
  171. fixed: list of strings
  172. List of keys whose value is immutable on screen.
  173. """
  174. # call the constructor of the base class
  175. gui.DlgFromDict.__init__(self,
  176. dictionary = dictionary,
  177. title = title,
  178. order = order,
  179. fixed = fixed)
  180. # There is no show method as gui.DlgFromDict does not need one.
  181. class DataRecordingScreen():
  182. """
  183. Class for audio data recording.
  184. """
  185. def __init__(self, SUBJECT, SETTINGS, SAMPLES, window=None, auto_cut=False):
  186. """
  187. Parameters:
  188. -----------
  189. SUBJECT: dict
  190. SETTINGS: dict
  191. SAMPLES: dict
  192. See main.py for examples of SUBJECT, SETTINGS and SAMPLES.
  193. """
  194. # define temporary variables
  195. displayWidth = 0.8
  196. frameRate = 60.
  197. secBetweenDigits = 0.
  198. # define object variables
  199. self.SUBJECT = SUBJECT
  200. self.SETTINGS = SETTINGS
  201. self.SAMPLES = SAMPLES
  202. self.nAtOnce = 10
  203. self.auto_cut = auto_cut
  204. assert (frameRate * SETTINGS['seconds']) % 1 == 0, \
  205. "Number of frames per digit must be a natural number"
  206. assert (frameRate * secBetweenDigits) % 1 == 0, \
  207. "Number of frames between digits must be a natural number"
  208. assert (frameRate * SETTINGS['pause']) % 1 == 0, \
  209. "Number of frames for break must be a natural number"
  210. assert ((self.nAtOnce * SETTINGS['seconds'] + \
  211. SETTINGS['pause']) * SETTINGS['samplerate']) % 1 == 0, \
  212. "number of audio samples must be a natural number"
  213. # define color definitions
  214. self.col_background = (-0.7, -0.7, -0.7)
  215. self.col_inactive = (0.4, 0.4, 0.5)
  216. self.col_active = (0.0, 0.5, 0)
  217. self.col_pause = (-0.1, -0.1, -0.1)
  218. self.col_rejected = (-1, -1, -0.5)
  219. self.col_instructions=(0.3,0.3,0.3)
  220. self.col_testmessage= (0.6,0.6,0.)
  221. # define keys
  222. self.KEY_REJECT = 'return'
  223. self.KEY_REJECT_PREVIOUS = 'x'
  224. self.KEY_PAUSE = 'space'
  225. self.KEY_PLAYBACK = 'p'
  226. if type(window) == visual.window.Window:
  227. self.win = window
  228. else:
  229. self.win = visual.Window(color = self.col_background,
  230. fullscr = True,
  231. allowGUI = True,
  232. units = 'norm',
  233. name = 'Spoken numbers recording',
  234. waitBlanking = False)
  235. # compute temporary varibles
  236. spacing = 2*displayWidth / (self.nAtOnce+2)
  237. # compute object variables
  238. self.framesPerDigit = int(frameRate * SETTINGS['seconds'])
  239. self.framesBetweenDigits = int(frameRate * secBetweenDigits)
  240. self.framesPause = int(frameRate * SETTINGS['pause'])
  241. self.digitStims = []
  242. self.controls = visual.TextStim(self.win,
  243. text = '<SPACE>\tto (UN)PAUSE after sample\n<ENTER>\tto REJECT sample',
  244. pos = (-0.5, -0.85),
  245. height = 0.05,
  246. color = self.col_instructions,
  247. wrapWidth = 1000)
  248. self.controls.setAutoDraw(True)
  249. self.test_prompt = visual.TextStim(self.win,
  250. text = 'TEST RUN',
  251. pos = (0, 0.2),
  252. height = 0.05,
  253. color = self.col_testmessage)
  254. # session progress bar
  255. self.sessProg = ProgressBar(self.win,
  256. pos = (0, 0.3),
  257. autoDraw = True,
  258. backgoundColor = self.col_background,
  259. fillColor = self.col_inactive,
  260. lineColor = self.col_inactive)
  261. # progess bar for breaks between series of digits
  262. self.pauseProg = ProgressBar(self.win,
  263. pos = (0, -0.3),
  264. autoDraw = True,
  265. backgoundColor = self.col_background,
  266. fillColor = self.col_inactive,
  267. lineColor = self.col_inactive)
  268. # create placeholders for digits
  269. for d in range(self.nAtOnce+2):
  270. self.digitStims.append(visual.TextStim(self.win,
  271. text = '>' if d <= 1 else '_',
  272. pos = (-displayWidth + spacing * d, 0),
  273. height = 0.12,
  274. units = 'norm',
  275. color = self.col_inactive))
  276. self.digitStims[d].setAutoDraw(False)
  277. def show(self, istest = False, noMic = False):
  278. """
  279. Method to display audio recording setup on screen. There will be 10
  280. digits presented as a series which should be read out loud when they
  281. turn green. The script will attempt to cut the recordings into 10
  282. records, one per digit. If this fails, as for instance the break
  283. between to articulations is too short or there was too much noise,
  284. the recording will be saved with the suffix 'unableToCut' and the
  285. series is repeated at the end of the experiment.
  286. Parameters:
  287. istest: boolean
  288. If True a single test run will be shown. No data will be saved
  289. for this run. If False, the entire audio recording will be
  290. carried out.
  291. noMic: boolean
  292. Select True if no microphone is connected to the computer.
  293. Recordings will not be saved.
  294. """
  295. if istest:
  296. self.test_prompt.setAutoDraw(True)
  297. else:
  298. self.test_prompt.setAutoDraw(False)
  299. REJECT_TRIGGER = False
  300. PAUSE_TRIGGER = False
  301. REJECT_PREVIOUS_TRIGGER = False
  302. self.sessProg.set_progress(0)
  303. self.sessProg.set_AutoDraw(True)
  304. self.pauseProg.set_progress(0, "Get Ready")
  305. self.pauseProg.set_AutoDraw(True)
  306. wavpath_previous = None
  307. saveRec = True
  308. leaveTest = False
  309. seriesIdx = 0
  310. numSeries = float(len(self.SAMPLES) / self.nAtOnce)
  311. nAudioSamples = int(((self.nAtOnce + 1) * self.SETTINGS["seconds"] + self.SETTINGS["pause"])) * self.SETTINGS["samplerate"]
  312. samplesToRepeat = []
  313. while (len(self.SAMPLES) > 0 and not leaveTest) or PAUSE_TRIGGER:
  314. if not PAUSE_TRIGGER:
  315. # get new set of samples to display
  316. if seriesIdx != 0 and not REJECT_TRIGGER:
  317. samples_previous = currentSamples[:] # creates a copy
  318. currentSamples = self.SAMPLES[0:self.nAtOnce]
  319. self.SAMPLES = self.SAMPLES[self.nAtOnce:]
  320. # set digits on screen
  321. self.digitStims[0].setColor(self.col_active)
  322. for stimIdx, stim in enumerate(self.digitStims[2:]):
  323. stim.setText(currentSamples[stimIdx][0])
  324. # if first time, activate all stimuli
  325. if seriesIdx == 0:
  326. stim.setAutoDraw(True)
  327. if stimIdx == 0:
  328. self.digitStims[0].setAutoDraw(True)
  329. self.digitStims[1].setAutoDraw(True)
  330. # display pause progress bar
  331. for fIdx in range(self.framesPause):
  332. self.pauseProg.set_progress(fillup = (fIdx+1)/float(self.framesPause), msg = "Get Ready")
  333. self.win.flip()
  334. # write out record
  335. if seriesIdx != 0:
  336. if noMic or istest or not saveRec:
  337. print(("auto - " if istest or noMic else "") +"rejected:", wavpath)
  338. seriesIdx -= 1
  339. saveRec = True
  340. REJECT_TRIGGER = False
  341. else:
  342. if self.auto_cut:
  343. if not util.cutSeries(recording, samples_previous, self.SETTINGS, self.SUBJECT, os.path.join(self.SETTINGS["data_folder"], "cut")):
  344. print("Series could not be cut")
  345. samplesToRepeat.extend(samples_previous)
  346. wavpath = wavpath.rstrip(".wav") + "_unableToCut.wav"
  347. else:
  348. print("Successfully cut.")
  349. util.add_to_log(self.SETTINGS, wavpath)
  350. print('writing',wavpath)
  351. wavfile.write(wavpath, self.SETTINGS['samplerate'], recording)
  352. wavpath_previous = wavpath
  353. # start new record
  354. recording = np.zeros((nAudioSamples, self.SETTINGS['channels']), dtype=np.int16)
  355. if not noMic:
  356. sd.rec(nAudioSamples,
  357. samplerate=self.SETTINGS['samplerate'],
  358. channels=self.SETTINGS['channels'],
  359. dtype=np.int16,
  360. device=self.SETTINGS['device_index'],
  361. out=recording)
  362. # deactivate first > symbol
  363. self.digitStims[0].setColor(self.col_inactive)
  364. # loop through digits
  365. for stimIdx, stim in enumerate(self.digitStims[1:]):
  366. # paint digit in active color
  367. stim.setColor(self.col_active)
  368. # set progress (take only digits into account)
  369. if stimIdx >= 1:
  370. self.sessProg.set_progress(seriesIdx / (numSeries) + (stimIdx)/(numSeries * float(self.nAtOnce)))
  371. # display digit for specified number of frames
  372. for _ in range(self.framesPerDigit):
  373. self.win.flip()
  374. # paint digit in inactive color
  375. stim.setColor(self.col_inactive)
  376. if len(event.getKeys(['return'])) > 0:
  377. REJECT_TRIGGER = True
  378. break
  379. pressedKeys = event.getKeys([self.KEY_PAUSE, self.KEY_REJECT, self.KEY_REJECT_PREVIOUS])
  380. if (self.KEY_REJECT in pressedKeys or REJECT_TRIGGER) and saveRec:
  381. REJECT_TRIGGER = True
  382. saveRec = False
  383. self.pauseProg.set_color(self.col_rejected)
  384. self.sessProg.set_progress(seriesIdx / numSeries)
  385. for fRejIdx in range(self.framesPause):
  386. self.pauseProg.set_progress((fRejIdx+1)/float(self.framesPause), "REJECTED")
  387. self.win.flip()
  388. self.pauseProg.set_color(self.col_inactive)
  389. self.SAMPLES.extend(currentSamples)
  390. if self.KEY_PAUSE in pressedKeys:
  391. PAUSE_TRIGGER = not PAUSE_TRIGGER
  392. if self.KEY_REJECT_PREVIOUS in pressedKeys:
  393. REJECT_PREVIOUS_TRIGGER = True
  394. if PAUSE_TRIGGER:
  395. if REJECT_TRIGGER:
  396. self.pauseProg.set_color(self.col_rejected)
  397. self.pauseProg.set_message("PAUSE - REJECTED")
  398. else:
  399. self.pauseProg.set_color(self.col_pause)
  400. self.pauseProg.set_message("PAUSE")
  401. self.win.flip()
  402. if not PAUSE_TRIGGER:
  403. if REJECT_PREVIOUS_TRIGGER:
  404. fileToRemove = util.get_full_series_path(self.SETTINGS, self.SUBJECT, samples_previous)
  405. if os.path.isfile(fileToRemove):
  406. util.remove_recordings([fileToRemove], self.SETTINGS)
  407. else:
  408. print("Cannot remove previous: {} does not exist. \
  409. \n Perhaps it has already been removed before?".format(fileToRemove))
  410. self.SAMPLES.extend(samples_previous)
  411. seriesIdx -= 1
  412. self.sessProg.set_progress(seriesIdx/numSeries)
  413. REJECT_PREVIOUS_TRIGGER = False
  414. self.pauseProg.set_color(self.col_inactive)
  415. wavpath = util.get_full_series_path(self.SETTINGS, self.SUBJECT, currentSamples)
  416. # increase series counter
  417. seriesIdx += 1
  418. # leave test after one series of digits
  419. if istest:
  420. self.SAMPLES.extend(currentSamples)
  421. leaveTest = True
  422. if not REJECT_TRIGGER:
  423. samples_previous = currentSamples[:]
  424. for fIdx in range(self.framesPause):
  425. self.pauseProg.set_progress(fillup = (fIdx+1)/float(self.framesPause), msg = "Complete")
  426. self.win.flip()
  427. # write out last record
  428. if not istest and not noMic:# and not noMic:
  429. if self.auto_cut:
  430. if not util.cutSeries(recording, samples_previous, self.SETTINGS, self.SUBJECT, os.path.join(self.SETTINGS["data_folder"], "cut")):
  431. print("Series could not be cut")
  432. samplesToRepeat.extend(samples_previous)
  433. wavpath = wavpath.rstrip(".wav") + "_unableToCut.wav"
  434. else:
  435. print("Successfully cut.")
  436. util.add_to_log(self.SETTINGS, wavpath)
  437. print('writing',wavpath)
  438. wavfile.write(wavpath, self.SETTINGS['samplerate'], recording)
  439. wavpath_previous = wavpath
  440. return samplesToRepeat
  441. def close(self):
  442. self.win.close()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...