-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroler.py
962 lines (733 loc) · 35 KB
/
controler.py
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
# To do: Handle {"error":"The MusicBrainz web server is currently busy. Please try again later."}
# update gui.py
import PyQt4.uic
with open('gui.py','w') as f:
PyQt4.uic.compileUi('gui.ui',f)
from PyQt4 import QtGui, QtCore, QtSql
import sys
from lastify_v6 import *
from Filter import *
import gui
from Writer import *
import threading
import pandas as pd
import sqlite3
import time
import re
# variables
path = r'd:\Dropbox\work\python\lastify'
db_path = '%s\\lastify.db' % path
createDB(db_path)
con = sqlite3.connect(db_path)
db_lock = threading.RLock()
class QTHR_LOCKOWNER(QtCore.QThread):
""" emits database lockownership every 2 seconds to be displayed in GUI"""
outsignal = QtCore.pyqtSignal('QString', name='outsignal')
def __init__(self):
super(QTHR_LOCKOWNER, self).__init__()
self.on = True
def run(self):
while self.on:
self.outsignal.emit(self.process_out())
time.sleep(2)
def process_out(self):
out = str(db_lock)
m = re.search('=(.+) ', out)
out = m.group().rstrip().lstrip('=')
if out.isdigit():
out='Qt Worker thread'
return str('Database access: %s' % out)
class QTHR_WORK_WRITER_TRACK(QtCore.QThread):
""" Worker thread to instantiate track writer, creates temp_view_track table in database using the filtered IDs
of the track filter manager
"""
def __init__(self, user):
super(QTHR_WORK_WRITER_TRACK, self).__init__()
self.user = user
self.con = sqlite3.connect(db_path)
self.lock = db_lock
def run(self):
self.writer = Writer(category='track', user=self.user, db_path=db_path, db_lock = self.lock)
def del_writer(self):
if self.isFinished():
del self.writer
def __del__(self): # this seems to make the thread more stable and prevent it from crashing
self.wait()
class QTHR_WORK_WRITER_ALBUM(QTHR_WORK_WRITER_TRACK):
""" Worker thread to instantiate album writer, creates temp_view_album table in database using the filtered IDs
of the album filter manager
"""
def __init__(self, user):
super(QTHR_WORK_WRITER_ALBUM, self).__init__(user=user)
def run(self):
self.writer = Writer(category='album', user=self.user, db_path=db_path, db_lock = self.lock)
pass
class QTHR_WORK_FILTER(QtCore.QThread):
""" Worker track to instantiate filter manager
"""
def __init__(self, user):
super(QTHR_WORK_FILTER, self).__init__()
self.user = user
def run(self):
cleanup_db_dates(db_path, db_lock)
calc_interest_score(self.user, db_path, db_lock)
self.filtman_track = FilterManager(db_path=db_path, user=self.user, category='track', thresh=0, db_lock=db_lock, freq_init= True)
self.filtman_album = FilterManager(db_path=db_path, user=self.user, category='album', thresh=0, db_lock=db_lock, freq_init= True)
def __del__(self): # this seems to make the thread more stable and prevent it from crashing
self.wait()
class QTHR_WORK_LOAD(QtCore.QThread):
'''starts loading and emits regular output signals
:user_input = tuple generated by get_input() method of MainWindow class'''
outsignal = QtCore.pyqtSignal('PyQt_PyObject', name='outsignal')
def __init__(self, user_input, db_path):
super(QTHR_WORK_LOAD, self).__init__()
self.user_input = user_input
self.db_path = db_path
def run(self):
out_vars, events = self.load(self.user_input, self.db_path)
self.emit_output(out_vars, events)
def emit_output(self, out_vars, events):
""" emits output to update Gui in regular 2s intervalls
:param out_vars: group of output_controler outputvariables passed from self.load() associated with the threads started therein
:param events: group of threding events passed from self.load() associated with the threads started therein
"""
while not all([event.isSet() for event in events]):
self.outsignal.emit(out_vars)
time.sleep(2)
self.outsignal.emit(out_vars)
def load(self, user_input, db_path):
""" established thread database connection and start threads loading data from various APIs and threads that control them
:param user_input: tuple passed from WindowApp
:param db_path: database path
:return: output variables of threads and relevant threading events
"""
con = sqlite3.connect(db_path)
user, lim_charts_artist, lim_charts_track, lim_charts_album, lim_similar_artist, lim_similar_track, lim_toptracks, \
lim_topalbums = user_input
# load charts
chart, attr = get_chart(attr={'category': 'artist'}, period='overall', limit=lim_charts_artist, user=user)
db_lock.acquire()
enter_chart(con, chart, attr)
chart, attr = get_chart(attr={'category': 'track'}, period='overall', limit=lim_charts_track, user=user)
enter_chart(con, chart, attr)
chart, attr = get_chart(attr={'category': 'album'}, period='overall', limit=lim_charts_album, user=user)
enter_chart(con, chart, attr)
db_lock.release()
print 'charts loaded'
# load output, call controlers
out_cont = output_controler(0.1) # output controler in combination with GUI serves only logging purposes
out_cont.start()
out_cont.output_stop()
lastfm_cont = call_controler(1500, 300, out_cont, 'LASTFM CONTROLLER\t')
lastfm_cont.start()
spotify_cont = call_controler(1500, 300, out_cont, 'SPOTIFY CONTROLLER\t')
spotify_cont.start()
mb_cont = call_controler(15, 20, out_cont, 'MUSICBRAINZ CONTROLLER\t')
mb_cont.start()
# create THREADS
thr_similar_artist = SIMILAR_ARTIST(db_path, 'SIMILAR_ARTIST', lastfm_cont, out_cont, db_lock, user,
lim_similar_artist, 5000)
thr_similar_track = SIMILAR_TRACK(db_path, 'SIMILAR_TRACK', lastfm_cont, out_cont, db_lock, user,
lim_similar_track, 5000)
thr_toptracks = TOPTRACKS(db_path, 'TOPTRACKS', lastfm_cont, out_cont, db_lock, lim_toptracks, 5000)
thr_topalbums = TOPALBUMS(db_path, 'TOPALBUMS', lastfm_cont, out_cont, db_lock, lim_topalbums, 5000)
thr_toptags_artist = TOPTAGS_ARTIST(db_path, 'TOPTAGS_ARTIST', lastfm_cont, out_cont, db_lock, 20000)
thr_toptags_album = TOPTAGS_ALBUM(db_path, 'TOPTAGS_ALBUM', lastfm_cont, out_cont, db_lock, 20000)
thr_toptags_track = TOPTAGS_TRACK(db_path, 'TOPTAGS_TRACK', lastfm_cont, out_cont, db_lock, 20000)
thr_mbinfo_album = MBINFO_ALBUM(db_path, 'MBINFO_ALBUM', mb_cont, out_cont, db_lock, 500)
thr_spotifyID_album = SPOTIFYID_ALBUM(db_path, 'SPOTIFYID ALBUM', spotify_cont, out_cont, db_lock, 1000)
thr_spotifyID_track = SPOTIFYID_TRACK(db_path, 'SPOTIFYID TRACK', spotify_cont, out_cont, db_lock, 1000)
# CONTROLER THREAD 1
# toptags tracks gets deactivated when SIMILAR_TRACK and TOPTRACKS are done
def f_1():
thr_toptags_track.deactivate()
thr_cont_toptags_track = CONTROLER([thr_similar_track.signal_event, thr_toptracks.signal_event],
f_1, name='TOPTAGS TRACK CONTROLER')
thr_cont_toptags_track.start()
# CONTROLER THREAD 2
# restarting threads are deactivated when all other track and album collecting threads are done
def f_2():
thr_mbinfo_album.deactivate()
thr_spotifyID_album.deactivate()
thr_spotifyID_track.deactivate()
thr_cont_restart = CONTROLER(
[thr_similar_track.signal_event, thr_toptracks.signal_event, thr_topalbums.signal_event],
f_2, name='RESTART CONTROLER')
thr_cont_restart.start()
# CONTROLER THREAD 3
# call and output controler are stopped when all threads are finished
def f_3():
lastfm_cont.stop()
spotify_cont.stop()
mb_cont.stop()
out_cont.stop()
thr_cont = CONTROLER([thr_spotifyID_album.signal_event, \
thr_spotifyID_track.signal_event, \
thr_mbinfo_album.signal_event, \
thr_toptags_artist.signal_event, \
thr_toptags_album.signal_event, \
thr_toptags_track.signal_event, ], \
f_3, name='THREAD CONTROLER ALL')
thr_cont.start()
# CONTROLER THREAD 4
def f_4():
thr_toptags_artist.deactivate()
thr_toptracks.deactivate()
thr_topalbums.deactivate()
thr_cont_sim_artist = CONTROLER([thr_similar_artist.signal_event, thr_similar_track.signal_event], \
f_4, name='THREAD CONTROLER TOPTAGS_ARTIST, TOPTRACKS, TOPALBUMS')
thr_cont_sim_artist.start()
# CONTROLER THREAD 5
def f_5():
thr_toptags_album.deactivate()
thr_cont_topalbum = CONTROLER([thr_topalbums.signal_event], \
f_5, name='THREAD CONTROLER TOPTAGS_ALBUM')
thr_cont_topalbum.start()
# activate starting threads
thr_similar_artist.activate()
thr_similar_track.activate()
thr_toptracks.activate()
thr_topalbums.activate()
thr_toptags_artist.activate()
thr_toptags_album.activate()
thr_toptags_track.activate()
thr_mbinfo_album.activate()
thr_spotifyID_album.activate()
thr_spotifyID_track.activate()
# start threads
thr_similar_artist.start()
thr_similar_track.start()
thr_toptracks.start()
thr_topalbums.start()
thr_toptags_artist.start()
thr_toptags_album.start()
thr_toptags_track.start()
thr_mbinfo_album.start()
thr_spotifyID_album.start()
thr_spotifyID_track.start()
# return
out_vars = (thr_similar_artist.out, \
thr_similar_track.out, \
thr_toptracks.out, \
thr_topalbums.out, \
thr_toptags_artist.out, \
thr_toptags_track.out, \
thr_toptags_album.out, \
thr_mbinfo_album.out, \
thr_spotifyID_track.out, \
thr_spotifyID_album.out, \
lastfm_cont.out, \
spotify_cont.out, \
mb_cont.out, \
)
events = [thr_spotifyID_album.signal_event, \
thr_spotifyID_track.signal_event, \
thr_mbinfo_album.signal_event, \
thr_toptags_artist.signal_event, \
thr_toptags_album.signal_event, \
thr_toptags_track.signal_event, ]
return out_vars, events
def __del__(self): # this seems to make the thread more stable and prevent it from crashing
self.wait()
class WindowApp(QtGui.QMainWindow, gui.Ui_MainWindow):
""" Main GUI Class
"""
def __init__(self):
super(WindowApp, self).__init__() # loads the constructors of the parent classes
self.setupUi(self) # setupUi is defined in the Gui.Ui_MainWindow class in the Gui.py module
self.user = str( self.in_txt_user.text() )
# connect lockowner thread
self.thr_lockowner = QTHR_LOCKOWNER()
self.thr_lockowner.outsignal.connect(self.set_lab_lockowner)
self.thr_lockowner.start()
# connect tab selection
self.tabWidget.currentChanged.connect(self.select_tab)
# connect load tab
self.btn_load.clicked.connect(self.load)
for category in ('track','album'):
self.select_list_category.addItem(category)
# connect write tab
self.select_list_sortby_asc.addItem('ASC')
self.select_list_sortby_asc.addItem('DSC')
self.select_list_rankby_asc.addItem('ASC')
self.select_list_rankby_asc.addItem('DSC')
self.home()
def home(self):
self.tabWidget.setCurrentIndex(0)
def add_filt_date(self):
""" creates date filter according to user settings, passes filter object to add_filt_final
"""
filtman = self.get_filtman()
category_list = filtman.category
category = self.select_date_category.currentText()
undated = self.checkbox_date.isChecked()
minim = self.in_box_date_min.value()
maxim = self.in_box_date_max.value()
name = '%s %d-%d %s' %(category, minim, maxim, undated)
self.set_lab_filter('adding date filter')
if minim > maxim:
minim = maxim
self.in_box_date_min.setValue(maxim)
if category == 'track' :
filt = FilterDateTrack(name=name, db_path=db_path, db_lock=db_lock, minim=minim, maxim=maxim, include_undated=undated)
if category == 'album' :
filt = FilterDateAlbum(name=name, db_path=db_path, db_lock=db_lock, minim=minim, maxim=maxim, include_undated=undated)
if category == 'artist' :
filt = FilterDateArtist(name=name, db_path=db_path, db_lock=db_lock, category=category_list, minim=minim, maxim=maxim, include_undated=undated)
self.add_filt_final(filt,name)
def add_filt_plays(self):
""" creates plays filter according to user settings, passes filter object to add_filt_final
"""
filtman = self.get_filtman()
category_list = filtman.category
category = str(self.select_plays_category.currentText())
user = str(self.select_user.currentText())
minim = int(self.in_box_plays_min.value())
maxim = int(self.in_box_plays_max.value())
name = '%s %s %d -%d plays' % (user, category, minim, maxim)
self.set_lab_filter('adding play filter')
if minim == 0 and maxim == 0:
return
if maxim and minim > maxim:
minim = maxim
self.in_box_plays_min.setValue(maxim)
if category == 'track' :
filt = FilterPlaysTrack(name=name, user=user, db_path=db_path, db_lock=db_lock, minim=minim, maxim=maxim)
if category == 'album' :
filt = FilterPlaysAlbum(name=name, user=user, db_path=db_path, db_lock=db_lock, minim=minim, maxim=maxim)
if category == 'artist' :
filt = FilterPlaysArtist(name=name, user=user, db_path=db_path, db_lock=db_lock, category=category_list, minim=minim, maxim=maxim)
self.add_filt_final(filt,name)
def add_filt_tag(self):
""" creates tags filter according to user settings, passes filter object to add_filt_final
"""
filtman = self.get_filtman()
tagscore = self.in_box_tagscore.value()
tag = str( self.select_tag.currentText() ).split('\t')[0].rstrip()
name = '%s\t%s' %(tag,tagscore)
list_category = self.select_list_category.currentText()
category = self.select_tag_category.currentText()
self.set_lab_filter('adding tag filter')
if category == 'artist':
filt = FilterArtistTag(name, tag, tagscore, list_category, db_path, db_lock)
if category == 'track' and list_category == 'track':
filt = FilterTrackTag(name, tag, tagscore, db_path, db_lock)
if category == 'album' and list_category == 'album':
filt = FilterAlbumTag(name, tag, tagscore, db_path, db_lock)
self.add_filt_final( filt= filt,name= name )
def add_filt_final(self, filt, name):
""" finalises filter addition to filtermanager and GUI list widget
:param filt: filter object from Writer.py
:param name: string name of filter object
"""
filtman = self.get_filtman()
if name in filtman.filter_log.keys() :
print 'name: %s already in filt log' % name
self.set_lab_filter('name: %s already in filt log' % name)
return
if len( filt.IDs ) == 0:
print 'no IDs in filter'
self.set_lab_filter('no IDs in filter')
return
filtman = self.get_filtman()
filtman.log_filter(filt)
item = QtGui.QListWidgetItem()
item.setText(name)
self.list_filt.addItem(item)
self.update_filtIDs_filtmanager()
self.set_lab_filter('filter added')
def del_filt(self):
""" deletes selected filters, calls refresh_tags
"""
filtman = self.get_filtman()
items = self.list_filt.selectedItems()
if items == None:
print 'no filter selected'
self.set_lab_filter('no filter selected')
return
self.set_lab_filter('deleting filter')
for item in items:
#get row of current item and take it out of the list
row = self.list_filt.row(item)
self.list_filt.takeItem(row)
#delete item from filtmanager
filtman.del_filter( filtman.filter_log[ str( item.text() ) ] )
del item
self.update_filtIDs_filtmanager()
self.set_lab_filter('filter deleted')
def apply_limit(self):
""" limits the number of items from the same artist by passing user settings to writer in writer worker thread,
which then updates temp_view table in database
"""
limit = int ( self.in_box_limit_items_per_artist.value() )
rank_by = str ( self.select_list_rankby.currentText() )
writer = self.get_writer()
asc = str(self.select_list_rankby_asc.currentText())
if asc == 'ASC':
asc=True
else:
asc=False
writer.limit(rank_by=rank_by, topX=limit, con=con, asc=asc)
self.set_view_model()
print 'limit applied'
self.set_lab_writer('limit applied')
def apply_sort(self):
""" sorts the playlist created by the writer by passing user settings to writer in writer worker thread, which then
updates temp_view in database
"""
sort_by = str( self.select_list_sortby.currentText() )
asc = str(self.select_list_sortby_asc.currentText())
writer = self.get_writer()
if asc == 'ASC':
asc=True
else:
asc=False
writer.sort(sort_by=sort_by,con=con, asc=asc)
self.set_view_model()
self.set_lab_writer('playlist sorted')
def connect_thr_filtman_finished(self):
""" establishes connections and runs functions that are supposed to be disabled as long as no filtermanager is created
"""
self.btn_add_filter_tag.clicked.connect(self.add_filt_tag)
self.btn_add_filter_date.clicked.connect(self.add_filt_date)
self.btn_add_filter_plays.clicked.connect(self.add_filt_plays)
self.btn_refresh_filtman.clicked.connect(self.refresh_filtman)
self.btn_del_filter.clicked.connect(self.del_filt)
self.btn_pass.clicked.connect(self.pass_2_writer)
self.select_tag_category.currentIndexChanged.connect(self.update_filtIDs_filtmanager)
self.lab_no_items.setText( str( len(self.get_filtman().unfiltered_IDs) ) )
self.refresh_tagfreq()
self.get_user(db_lock)
self.set_playlist_category()
self.select_list_category.currentIndexChanged.connect(self.set_playlist_category)
self.set_lab_filter('filter manager loaded')
def connect_thr_writer_finished(self):
""" establishes connections and runs function that are supposed to be disabled as long as no writer is created
"""
self.set_view_model()
self.select_list_sortby.currentIndexChanged.connect(self.apply_sort)
self.select_list_sortby_asc.currentIndexChanged.connect(self.apply_sort)
self.btn_wr_list.clicked.connect(self.write_list)
self.btn_apply_artist_limit.clicked.connect(self.apply_limit)
self.apply_sort()
self.set_lab_filter('items passed to writer')
self.set_lab_writer('items received')
def update_list_filt(self):
""" updates list according to filters in filter manager
"""
self.list_filt.clear()
filtman = self.get_filtman()
for filt in filtman.filter_log.keys():
item = QtGui.QListWidgetItem()
item.setText(filt)
self.list_filt.addItem(item)
def get_user(self,db_lock):
""" gets a list of all users in database and adds them to self.select_user
:param db_lock:
"""
db_lock.acquire()
df = pd.read_sql('SELECT userName FROM ID_user', con)
users = df['userName'].tolist()
[self.select_user.addItem(user) for user in users]
db_lock.release()
def get_filtman(self):
""" returns active filter manager according to user selection. If applicable function waits for filter manager to be loaded
"""
while not self.thr_select_tab_filter.isFinished():
time.sleep(1)
print 'waiting for filtman'
self.set_lab_filter('waiting for filtmanager to be loaded')
if self.select_list_category.currentText() == 'track':
return self.thr_select_tab_filter.filtman_track
if self.select_list_category.currentText() == 'album':
return self.thr_select_tab_filter.filtman_album
def get_writer(self):
""" returns active writer according to user selection. If applicable function waits for writer to be loaded
"""
category = self.select_list_category.currentText()
if category == 'track':
if hasattr(self, 'thr_writer_track'):
while self.thr_writer_track.isRunning():
time.sleep(1)
self.set_lab_writer('waiting for track writer to be loaded')
return self.thr_writer_track.writer
else:
print'no writer_track_thread'
self.set_lab_writer('pass items to track writer')
if category == 'album':
if hasattr(self, 'thr_writer_album'):
while self.thr_writer_album.isRunning():
time.sleep(1)
self.set_lab_writer('waiting for album writer to be loaded')
return self.thr_writer_album.writer
else:
print'no writer_album_thread'
self.set_lab_writer('pass items to album writer')
def get_input_load(self):
"""
:return: user input needed for running loading worker thread
"""
return (str(self.in_txt_user.text()), \
int(self.in_box_limit_charts_artist.value()), \
int(self.in_box_limit_charts_track.value()), \
int(self.in_box_limit_charts_album.value()), \
int(self.in_box_limit_similar_artist.value()), \
int(self.in_box_limit_similar_track.value()), \
int(self.in_box_limit_toptracks.value()), \
int(self.in_box_limit_topalbums.value())
)
def load(self):
""" instantiates loading worker thread and passes get_input_load(), connects outsignal of thread to GUI by connecting
it via manage_output()
"""
self.thr_loading = QTHR_WORK_LOAD(self.get_input_load(), db_path)
self.thr_loading.outsignal.connect(self.manage_output)
self.thr_loading.start()
def manage_output(self, out_vars):
""" links output variable passed by loading worker thread outsignal to various GUI elements
:param out_vars: output variables that are being passed by the loading worker thread outsignal
"""
bars = (self.bar_similar_artist, \
self.bar_similar_track, \
self.bar_toptracks, \
self.bar_topalbums, \
self.bar_toptags_artist, \
self.bar_toptags_track, \
self.bar_toptags_album, \
self.bar_mbinfo, \
self.bar_spotifyID_track, \
self.bar_spotifyID_album, \
self.bar_call_lastfm, \
self.bar_call_spotify, \
self.bar_call_mbinfo
)
labels = (self.lab_thr_status_similar_artist, \
self.lab_thr_status_similar_track, \
self.lab_thr_status_toptracks, \
self.lab_thr_status_topalbums, \
self.lab_thr_status_toptags_artist, \
self.lab_thr_status_toptags_track, \
self.lab_thr_status_toptags_album, \
self.lab_thr_status_mbinfo, \
self.lab_thr_status_spotifyID_track, \
self.lab_thr_status_spotifyID_album, \
self.lab_lastfm, \
self.lab_spotify, \
self.lab_mbinfo,
)
# Status loading threads
for tripplet in zip(out_vars[:10], bars[:10], labels[:10]):
outvar, bar, label = tripplet
text = outvar.read()
m = re.search('\d+.\d+', text)
if m:
bar.setValue(int(float(m.group())))
label.setText('%.3f %%' % float(m.group()))
else:
label.setText(outvar.out)
if 'finished' in outvar.out:
bar.setValue(100)
# Status call controlers which log and control number of API calls in a particular timeframe
for tripplet in zip(out_vars[10:], bars[10:], labels[10:]):
outvar, bar, label = tripplet
text = outvar.read()
text = text.replace('\t', '').replace('CONTROLLER', 'API')
label.setText(text)
if ':' in outvar.out:
m = re.search('\d+', text.split(':')[1])
bar.setValue(int(m.group()))
def pass_2_writer(self):
""" passes filtered items of filter manager to writer calls set_writer_selectionboxes
"""
category = self.select_list_category.currentText()
while self.thr_select_tab_filter.isRunning():
time.sleep(1)
if category == 'track':
if hasattr(self, 'thr_writer_track'):
if self.thr_writer_track.isRunning():
print 'writer is busy'
self.set_lab_writer('writer is busy')
return
self.set_lab_writer('passing items to track writer')
self.thr_writer_track.start()
else:
self.thr_writer_track = QTHR_WORK_WRITER_TRACK(user=self.user)
self.thr_writer_track.finished.connect(self.connect_thr_writer_finished)
self.set_lab_writer('passing items to track writer')
self.thr_writer_track.start()
if category == 'album':
if hasattr(self, 'thr_writer_album'):
if self.thr_writer_album.isRunning():
print 'writer is busy'
self.set_lab_writer('writer is busy')
return
self.set_lab_writer('passing items to track writer')
self.thr_writer_album.start()
else:
self.thr_writer_album = QTHR_WORK_WRITER_ALBUM(user=self.user)
self.thr_writer_album.finished.connect(self.connect_thr_writer_finished)
self.set_lab_writer('passing items to album writer')
self.thr_writer_album.start()
self.set_writer_selectionboxes()
def select_tab(self):
""" detects which tab is selected and runs appropriate functions, is connected to tab change signal
"""
#selecting filter tab creates filter manager
if self.tabWidget.currentWidget().objectName() == 'tab_filter':
print 'filter tab selected'
if not hasattr(self, 'thr_select_tab_filter'):
self.select_tag.addItem('loading')
self.set_lab_filter('loading filter manager')
self.thr_select_tab_filter = QTHR_WORK_FILTER(str(self.in_txt_user.text()))
self.thr_select_tab_filter.finished.connect(self.connect_thr_filtman_finished)
self.thr_select_tab_filter.start()
#selecting writer tab when filter manager has not started loading (eg filter tab has not been clicked),
#selects filer tab instead
if self.tabWidget.currentWidget().objectName() == 'tab_write':
print 'writer tab selected'
if not hasattr(self, 'thr_select_tab_filter'):
self.tabWidget.setCurrentIndex(1)
while not self.thr_select_tab_filter.isFinished():
time.sleep(1)
if self.tabWidget.currentWidget().objectName() == 'tab_stats':
print 'stats tab selected'
def update_filtIDs_filtmanager(self):
""" updates filtered IDs of current filtmanager calls refresh_tagfreq, can take long to execute
"""
filtman=self.get_filtman()
# if len(filtman.filtered_IDs) == 0:
# return
self.select_tag.clear()
self.select_tag.addItem('loading')
self.lab_no_items.setText('loading')
filtman.update_filterIDs(con=con)
if self.list_filt.count() > 0:
filtman.calc_freq_tag(artist=True, con=con)
filtman.calc_freq_tag(artist=False, con=con)
self.lab_no_items.setText( str( len(filtman.filtered_IDs) ) )
else:
self.lab_no_items.setText( str( len(filtman.unfiltered_IDs) ) )
self.refresh_tagfreq()
def refresh_tagfreq(self):
""" refreshes tagfrequencies as displayed in GUI
"""
self.select_tag.clear()
filtman = self.get_filtman()
if self.list_filt.count() == 0:
if self.select_tag_category.currentText() == 'artist':
tags = filtman.freq_tag_artist_init
else:
tags = filtman.freq_tag_init
else:
if self.select_tag_category.currentText() == 'artist':
tags = filtman.freq_tag_artist
else:
tags = filtman.freq_tag
tags = tags.sort_values('count', ascending=False)
for tup in tags.head(500).itertuples(index=False):
self.select_tag.addItem('%s\t%s' %(tup[0],tup[1]))
def refresh_filtman(self):
""" reloads filtmanager
"""
if not self.thr_select_tab_filter.isFinished():
return
self.select_tag.clear()
self.list_filt.clear()
self.select_tag.addItem('loading')
self.set_lab_filter('loading filter manager')
self.thr_select_tab_filter.start()
def set_lab_lockowner(self, text):
self.lab_status_dblock.setText(text)
def set_lab_filter(self,text):
self.lab_status_filter.setText(text)
def set_lab_writer(self,text):
self.lab_status_writer.setText(text)
def set_view_model(self):
""" establishes a database connection via the QtSqlite module and populates table_widget on writer tab
"""
db_lock.acquire()
# establish Qt database connection
if not hasattr(self, 'qt_db'):
self.qt_db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
self.qt_db.setDatabaseName(db_path)
self.qt_db.open()
self.qt_db_model = QtSql.QSqlTableModel(db=self.qt_db)
#set model view as read only
self.tableview.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers);
if self.select_list_category.currentText() == 'track':
table= 'view_temp_track'
else:
table= 'view_temp_album'
self.qt_db_model.setTable(table)
#sqlite driver only returns 257 items
self.qt_db_model.select()
#therefore this construction needs to be used to populate table
while self.qt_db_model.canFetchMore():
self.qt_db_model.fetchMore()
self.tableview.setModel(self.qt_db_model)
self.qt_db.commit()
# other threads are using the sqllite module to access database, close connection to avoid database access conflict
self.qt_db.close()
db_lock.release()
print 'filtered items passed to writer'
self.set_lab_writer('filtered items passed to writer')
def set_playlist_category(self):
""" is executed when playlist category is changed by user, changes a number of GUI elements according to the selection
"""
category = self.select_list_category.currentText()
self.select_tag_category.clear()
self.select_tag_category.addItem('artist')
self.select_tag_category.addItem(category)
self.select_plays_category.clear()
self.select_plays_category.addItem('artist')
self.select_plays_category.addItem(category)
self.select_date_category.clear()
self.select_date_category.addItem('artist')
self.select_date_category.addItem(category)
self.update_list_filt()
self.update_filtIDs_filtmanager()
def set_writer_selectionboxes(self):
""" sets selectionboxes of writer tab according to playlist category is executed after filtermanager passes items to writer
"""
category = self.select_list_category.currentText()
# fill wrtier tab selection boxes with appopriate options
self.select_list_rankby.clear()
self.select_list_sortby.clear()
if category == 'track':
for column in ('plays_%s_user' % category,'plays_%s_total' % category,'plays_artist_user', \
'date_%s' % category, 'date_artist', 'i_score_track', 'i_score_artist','trackName', 'artistName'):
self.select_list_sortby.addItem(column)
for column in ('plays_%s_user' % category,'plays_%s_total' % category,\
'date_%s' % category, 'i_score_track' ):
self.select_list_rankby.addItem(column)
if category == 'album':
for column in ('plays_%s_user' % category,'plays_%s_total' % category,'plays_artist_user', \
'date_%s' % category, 'date_artist', 'i_score_artist','albumName','artistName'):
self.select_list_sortby.addItem(column)
for column in ('plays_%s_user' % category,'plays_%s_total' % category,\
'date_%s' % category ):
self.select_list_rankby.addItem(column)
self.select_list_sortby.setCurrentIndex(0)
def write_list(self):
""" writes playlist according to user settings
"""
sort_by = str( self.select_list_sortby.currentText() )
rank_by = str( self.select_list_rankby.currentText() )
name = str( self.in_txt_list_name.text() )
name = ''.join( [c for c in name if c.isalnum()] )
if self.select_list_sortby_asc.currentText() == 'ASC':
asc=True
else:
asc=False
writer=self.get_writer()
writer.sort(sort_by = sort_by, con= con, asc=asc )
writer.write_playlist(name=name, path=path, con= con)
print r'playlist "%s" written to %s' % (name, path)
self.set_lab_writer(r'playlist "%s" written to %s' % (name, path))
if __name__ == '__main__':
# execute Gui
app = QtGui.QApplication([]) # starts GUI app
form = WindowApp() # instanciates Gui class
form.show()
sys.exit(app.exec_())
user = form.in_txt_user.text