def __init__(screen): # Set up the base menu you can customize your menu with the colors above #set size of the screen size = width, height = 480, 320 screen = pygame.display.set_mode((size), pygame.FULLSCREEN ) pygame.init() pygame.mouse.set_visible(1) # define function for printing text in a specific place with a specific colour def make_label(text, xpo, ypo, fontsize, colour): font=pygame.font.Font(None,fontsize) label=font.render(str(text), 1, (colour)) screen.blit(label,(xpo,ypo)) def album_data(): try: cwd = os.getcwd() coverart = cwd + '/coverart' f=open(coverart) coverart = f.readline() file = cStringIO.StringIO(urllib.urlopen(coverart).read()) img = pygame.image.load(file) screen.blit(pygame.transform.scale(img, (200, 200)), (140, 112)) pygame.draw.rect(screen, black, [ 4, 4, 480, 100]) make_label(song(),4,2,32,music_data_color) make_label(artist(),4,28,32,music_data_color) make_label(album(),4,52,32,music_data_color) make_label(station(),4,76,32,music_data_color) pygame.display.update() except IOError: pass # always use a Clock to keep your framerate constant clock = pygame.time.Clock() album_data() album_var1 = song() album_var2 = song() while 1: clock.tick(10) if album_var1 != album_var2: album_data() album_var1 = album_var2 else: album_var2 = song() for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() main() if event.type == KEYDOWN: if event.key == K_ESCAPE: sys.exit()
def add_songs(Music): s1 = song.song('Welcome to the Jungle', 'Guns n\' Roses', 'Appetit for Destruction') s2 = song.song('Smells Like Teen Spirit', 'Nirvana', 'Nevermind') s3 = song.song('Jeremy', 'Pearl Jam', 'Ten') s4 = song.song('Times Like These', 'Foo Fighters', 'One by One') s5 = song.song('Sweet Child of Mine', 'Guns n\' Roses', 'Appetite for Destruction') Music.add_to_playlist(s1) Music.add_to_playlist(s2) Music.add_to_playlist(s3) Music.add_to_playlist(s4) Music.add_to_playlist(s5)
def conversation(): tts("ว่าไงคะ") text = stt() count = 0 if any([ 'ปิดไฟ' in text, 'ปิดปลั๊ก' in text, 'เปิดไฟ' in text, 'เปิดปลั๊ก' in text ]): count = open_close(text) if any(['เปิดเพลง' in text, 'เล่นเพลง' in text]): count = song(text) count = 1 if any([ 'เช็คเมล์' in text, 'เช็คอีเมล' in text, 'เช็ค inbox' in text, 'ตรวจอีเมล' in text, 'ตรวจเมล์' in text ]): checkemail() count = 1 if any([ 'บอกการแจ้งเตือนปฏิทิน' in text, 'ดูปฏิทิน' in text, 'แจ้งเตือนอะไร' in text, 'เช็คปฏิทิน' in text, 'เช็คแจ้งเตือน' in text, "ดูการแจ้งเตือน" in text, "มีการแจ้งเตือน" in text ]): count = checkcalendar(text) if (count == 0 and text != "ไม่เข้าใจค่ะกรุณาลองอีกครั้ง" and text != "ไม่เข้าใจที่พูดออกมาค่ะ"): tts("ไม่เข้าใจคำสั่งของคุณค่ะ")
def entry_playlist(purl): id = purl[-10:] purl = "http://music.163.com/api/playlist/detail?id={}&upd".format(id) headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36', 'Accept-Encoding': 'gzip, deflate', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'connection': 'keep-alive', 'cache-control': 'no-cache', 'Referer': 'http://music.163.com/' } s = BeautifulSoup( requests.get(purl, headers=headers).content, 'html.parser') pl = json.loads(s.text)['result'] pid = pl['id'] pname = pl['name'] pcreator = pl['creator']['nickname'] c = connection_mysql.connect() try: if c.wplaylist(playlist.playlist(pid, pname, pcreator)): print('歌单信息录入成功 ' + pname) for i in pl['tracks']: if c.wsong(song.song(i['id'], i['name'], "")): print('歌曲信息录入成功 ' + i['name']) else: print('此歌曲信息已存在 ' + i['name']) else: print('歌单信息已存在 ' + pname) except Exception: print('music_main出现异常') finally: c.connect_close()
def importPlaylist(file): songList = [] # Parse CSV file playList = readFile(file) for line in playList: songObj = song(line) songList.append(songObj) return songList
def search_song(title): title = re.sub(' ', '-', title) search_result = urllib2.urlopen( "http://api.rapgenius.com/search?q=" + str(title) ).read() data = json.loads(search_result) greatest = 0 sim_id = -1 for i in data["response"]["hits"]: sim = difflib.SequenceMatcher(a=title.lower(),b=i["result"]["title"].lower()).ratio() if(sim >= greatest): sim_id = i["result"]["id"] greatest = sim return song.song(sim_id)
def apply_command(): global queue global s global ready global idle if len(queue)>0: ready = False idle = False snum=random.randint(0,len(queue)-1); selected = queue.pop(snum) queue = [] command = selected["message"].lower() print command username = selected["username"] if (not robot): time.sleep(2) else: if(command=="forward" or command=="straight"): forward(1,1) elif(command=="backward" or command=="back"): backward(1,1) elif(command=="right"): turnRight(1,0.5) elif(command=="left"): turnLeft(1,0.5) elif(command=="spin"): turnRight(1,3) elif(command=="hasselhoff"): playsampledictionary.playHookedOnAFeeling() elif(command=="beep"): beep(1,440*5) elif(command=="birthday"): song.song() take_photo() socket.emit("selected", {'username': username, 'message': command}) #time.sleep(2) ready = True
def album_data(): try: cwd = os.getcwd() coverart = cwd + '/coverart' f=open(coverart) coverart = f.readline() file = cStringIO.StringIO(urllib.urlopen(coverart).read()) img = pygame.image.load(file) screen.blit(pygame.transform.scale(img, (200, 200)), (140, 112)) pygame.draw.rect(screen, black, [ 4, 4, 480, 100]) make_label(song(),4,2,32,music_data_color) make_label(artist(),4,28,32,music_data_color) make_label(album(),4,52,32,music_data_color) make_label(station(),4,76,32,music_data_color) pygame.display.update() except IOError: pass
def read_song( self,songname ): """ This function takes a song name as input and return the song object from the cache if the song given is not cached the function will raise error """ song_object = song.song() conn = self.connectDB() c = conn.cursor() foldername = os.path.dirname(songname) if( self.is_cached_folder( foldername) ) : try : c.execute("select * from {0} where filename = '{1}' " .format(foldername.replace('/','_') ,songname)) except sqlite3.OperationalError: raise IOError( " The folder name is cached but no folder table named %s is present in cache "%foldername) r = c.fetchone() if (r == None) : raise IOError( " Cannot read this file , The file named %s is not cached "%songname) else : song_object.create_from_row(r) return song_object else : raise IOError( " The folder named %s is not cached "%foldername)
def loadsongs(cfg, songlist, flg): opener = urllib.request.build_opener( urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()), urllib.request.HTTPRedirectHandler()) params = dict() params["owner_id"] = cfg.user_id params["need_user"] = 0 params["offset"] = 0 params["count"] = 6000 params["access_token"] = cfg.access_token par_list = [] for name in params: par_list.append(name + "=" + str(params[name])) params = "&".join(par_list) update_time = datetime.datetime.now() while True: if datetime.datetime.now() > cfg.expires_in: cfg.updateconfig() while datetime.datetime.now() < update_time: time.sleep(30) delta = datetime.timedelta(0,0,0,0,cfg.interval,0,0) update_time += delta print("Load tracklist") url = 'https://api.vk.com/method/audio.get?' + params response = opener.open(url) response = response.read() response = response.decode("UTF-8") response = response.replace('\/','/') response = response.replace('&','&') response = json.loads(response) songs = [] print("loaded") songlist.clear() flg.songlist = False for i in response: for song_info in response[i]: if isinstance(song_info,dict): some = song.song(song_info) songs.append(some) songlist.append(some) flg.songlist = True if not os.path.isdir(cfg.path): os.makedirs(cfg.path) skipped = 0 with open('skipped.dat', 'w') as f: f.write('') for sng in songs: sng.do_replacement(cfg.replacement) t_path = cfg.path + sng.artist + " - " + sng.title + '.mp3' if os.path.exists(t_path) and os.path.getsize(t_path) != 0: skipped += 1 with open('skipped.dat', 'ab') as f: f.write((t_path + ' skipped\n').encode("UTF-8")) else: print('Downloading ' + t_path) with open(t_path, 'wb') as f: response = opener.open(sng.url) response = response.read() f.write(response) print('ready') word = ' songs' if skipped == 1: word = ' song' print('Skipped ' + str(skipped) + word + '. More info in skipped.dat, you can open it as txt file.') print('Next update in ' + str(update_time))
def add(self, song_title, artist_name): new_song = song(song_title, artist_name, song_title + ".jpg") self.your_playlist.append(new_song)
def __init__(screen): # define function for printing text in a specific place with a specific width and height with a specific colour and border def make_button(text, xpo, ypo, height, width, colour): font=pygame.font.Font(None,28) label=font.render(str(text), 1, (colour)) screen.blit(label,(xpo,ypo)) pygame.draw.rect(screen, blue, (xpo-10,ypo-10,width,height),2) # define function for printing text in a specific place with a specific colour def make_label(text, xpo, ypo, fontsize, colour): font=pygame.font.Font(None,fontsize) label=font.render(str(text), 1, (colour)) screen.blit(label,(xpo,ypo)) # define function that checks for touch location def on_touch(): effect = pygame.mixer.Sound('beep2.ogg') effect.play() # get the position that was touched touch_pos = (pygame.mouse.get_pos() [0], pygame.mouse.get_pos() [1]) # x_min x_max y_min y_max # button 1 event if 30 <= touch_pos[0] <= 240 and 30 <= touch_pos[1] <=70: button(1) # button 2 event if 260 <= touch_pos[0] <= 470 and 30 <= touch_pos[1] <=70: button(2) # button 3 event if 30 <= touch_pos[0] <= 240 and 71 <= touch_pos[1] <=120: button(3) # button 4 event if 260 <= touch_pos[0] <= 470 and 71 <= touch_pos[1] <=120: button(4) # button 5 event if 30 <= touch_pos[0] <= 240 and 121 <= touch_pos[1] <=170: button(5) # button 6 event if 260 <= touch_pos[0] <= 470 and 121 <= touch_pos[1] <=170: button(6) # button 7 event if 30 <= touch_pos[0] <= 240 and 171 <= touch_pos[1] <=220: button(7) # button 8 event if 260 <= touch_pos[0] <= 470 and 171 <= touch_pos[1] <=220: button(8) # button 9 event if 30 <= touch_pos[0] <= 240 and 221 <= touch_pos[1] <=270: button(9) # button 10 event if 260 <= touch_pos[0] <= 470 and 221 <= touch_pos[1] <=270: button(10) # button 11 event if 30 <= touch_pos[0] <= 240 and 271 <= touch_pos[1] <=320: button(11) # button 12 event if 260 <= touch_pos[0] <= 470 and 271 <= touch_pos[1] <=320: button (12) # PianoBar Next Station def next_station(): command = "echo n >> ~/.config/pianobar/ctl" process = Popen(command.split(), stdout=PIPE) output = process.communicate()[0] return output # Wraper for shell comands def run_cmd(cmd): process = Popen(cmd.split(), stdout=PIPE) output = process.communicate()[0] return output # Define button selection def button(number): cwd = os.getcwd() if number == 1: # Music Data Screen music_data() if number == 2: # Music Data Screen music_data() if number == 3: # Pause Pianobar hotkey = cwd + "/hotkey.sh p" run_cmd(hotkey) if number == 4: # Next Track Pianobar hotkey = cwd + "/hotkey.sh n" run_cmd(hotkey) if number == 5: # Dislike Song hotkey = cwd + "/volumeDown.sh" run_cmd(hotkey) if number == 6: # Like Song hotkey = cwd + "/volumeUp.sh" run_cmd(hotkey) if number == 7: StationSelect = cwd + "/stationSelect.sh 10" run_cmd(StationSelect) if number == 8: StationSelect = cwd + "/stationSelect.sh 11" run_cmd(StationSelect) if number == 9: # Like Song hotkey = cwd + "/hotkey.sh -" run_cmd(hotkey) if number == 10: # Like Song hotkey = cwd + "/hotkey.sh +" run_cmd(hotkey) if number == 11: stations() if number == 12: music_data() # Set up the base menu you can customize your menu with the colors above #set size of the screen size = width, height = 480, 320 #screen = pygame.display.set_mode(size) screen = pygame.display.set_mode((size), pygame.FULLSCREEN ) # First Row #make_button(song(), 30, 30, 40, 215, black) #make_button(artist(), 260, 30, 40, 215, black) # Second Row make_button(" Pause ", 30, 80, 40, 215, menu_color) make_button(" Next ", 260, 80, 40, 215, menu_color) # Third Row make_button(" Volume Down", 30, 130, 40, 215, menu_color) make_button(" Volume Up", 260, 130, 40, 215, menu_color) # Fourth Row make_button(stationlist(10), 30, 180,40, 215, menu_color) make_button(stationlist(11), 260, 180, 40, 215, menu_color) # Fith Row make_button(" DisLike ", 30, 230,40, 215, menu_color) make_button(" Like! ", 260, 230, 40, 215, menu_color) # Sixth Row make_button(" Stations ", 30, 280,40, 215, menu_color) make_button(" Music Data ", 260, 280, 40, 215, menu_color) pygame.display.update() def menu_lable(): lable = song() + ' ... By ... ' + artist() pygame.draw.rect(screen, black, [ 30, 30, 469, 30]) make_button(lable , 30, 30, 40, 445, menu_color) pygame.display.update() clock = pygame.time.Clock() menu_lable() menu_var1 = song() menu_var2 = song() #While loop to manage touch screen inputs while 1: clock.tick(10) if menu_var1 != menu_var2: menu_lable() menu_var1 = menu_var2 else: menu_var2 = song() for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() on_touch() #ensure there is always a safe way to end the program if the touch screen fails if event.type == KEYDOWN: if event.key == K_ESCAPE: sys.exit()
def menu_lable(): lable = song() + ' ... By ... ' + artist() pygame.draw.rect(screen, black, [ 30, 30, 469, 30]) make_button(lable , 30, 30, 40, 445, menu_color) pygame.display.update()
def print_test_case(verses, chorus, test_description): print('\n' + f'test - {test_description}'.center(40, '_')) print('[start]', *song(verses, chorus), '[end]', sep='\n')
def songfromrow(self,row): song_object = song.song() song_object.create_from_row(row) return song_object
union = set(a).union(set(b)) union_size = len(union) return float(inter_size)/union_size # min_hash_file=sc.textFile("min_hashes.txt",partition_size).map(lambda x: x.split("~")) # file2 = sc.textFile("small1.txt",partition_size).map(lambda x: x.split(",")) # min_hash_file=sc.textFile(filename+"_hashes.txt",partition_size).map(lambda x: x.split("~")) # file2 = sc.textFile(filename+"_shingles.txt",partition_size).map(lambda x: x.split(",")) # f3=file2.map(lambda x:(x[0],x[1:])) # joiner=f3.join(min_hash_file) # songs = joiner.map(lambda (x,(y,z)): song(x,y,z)) # min_hash_file=sc.textFile("min_hashes.txt",partition_size).map(lambda x: x.split("~")) min_hash_file=sc.textFile(filename+"_hashes.txt",partition_size).map(lambda x: x.split("~")) songs = min_hash_file.map(lambda x: song(x[0],x[1])) def jaccard_cluster_updater(clusters): for cluster in clusters: for song in cluster.members: score=0 for other in cluster.members: if song.id!=other.id: score+=jaccard(song.signature,other.signature) print song.id,score song.similarity_score=score cluster.update_centroid() yield cluster def lsh_cluster_updater(clusters): for cluster in clusters: signature_length=len(cluster.centroid.signature)
def getSongScore3(s): ## Getter for a song's score 3 return s.score3 songlist = [] ## Declares a list for songs with open('data.csv', 'r', encoding='utf-8', errors='ignore') as csvfile: ## Opens CSV File reader = csv.reader(csvfile, delimiter=',') ## Creates a reader for the CSV File counter = 0 ## Counter to exclude the header for row in reader: ## Loop over all rows in CSV File if counter > 0: ## If not the first row, put needed column information into the song object and append to song list songlist.append( song(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[8], row[9], row[10], row[11], row[12], row[14], row[16], row[17], row[18])) counter += 1 ## Increment the row counter else: ## If the first row counter += 1 ## Increment the row counter scorelist = [] ## Declare a list for scores score1List = [] ## Declare a list for score 1s score2List = [] ## Declare a list for score 2s score3List = [] ## Declare a list for score 3s dictionary = { } ## Create a dictionary with songID, song object key-value pairs x = 0 size = len(songlist) for song in songlist: ## Loops over number of songs in songlist
def newRec(self, id=0, name='', year=0, duration=''): self.appendList(song(id, name, year, duration))
#con = cache.cache() #print con.is_cached_folder("/home/deepak/Downloads") #print con.is_cached_song("/home/deepak/Downloads/Arabic.mp3") ########################## #testing create_folder #con = cache.cache() #con.create_folder("/home/deepak/Downloads") #testing create_folder con = cache() song_obj = song.song() con.insert_folder("/media/New Volume_/Songs") gen = con.getAlbumItemList('Rock' ,None) #gen = con.getArtistList() #//print song_list.__len__() for son in gen : print son # /print "\n\n" #____ the test to is_cached_folder()________# #print con.is_cached_song("/home/deepak/Downloads/Arabic.mp3") #song_obj = song.song() #song_obj.create_from_file("/home/deepak/Downloads/am.mp3")