def test_play_next_with_shuffle(self): music = Music( room=self.r, music_id='a', name='a', total_duration=200, duration=200, thumbnail='https://a.com/a.jpg', ) music.save() music2 = Music( room=self.r, music_id='b', name='b', total_duration=200, duration=200, thumbnail='https://a.com/a.jpg', ) music2.save() self.r.shuffle = True self.r.save() PlaylistTrack(track=music, room=self.r).save() self.r.play_next() self.r.current_music.should.eql(music) self.r.play_next() # No music in the playlist, but should select an other. self.r.current_music.should_not.be.none
def test_next(self): m = Music( music_id="a", name="a", thumbnail="https://a.com", total_duration=114, duration=114, url="https://www.a.com", source="youtube", room=self.r, ) m.save() self.r.current_music = m self.r.save() m2 = Music( music_id="b", name="b", thumbnail="https://a.com", total_duration=114, duration=114, url="https://www.a.com", source="youtube", room=self.r, ) m2.save() PlaylistTrack.objects.create(room=self.r, track=m2) response = self.client.post('/room/next', {'music_pk': m.pk}) response.status_code.should.eql(status.HTTP_200_OK) self.assertResponseEqualsMusic(response.data['current_music'], self.reload(m2))
def test_patch(self): m = Music( music_id="a", name="a", thumbnail="https://a.com", total_duration=114, duration=114, url="https://www.a.com", source="youtube", room=self.r, ) m.save() response = self.client.patch('/music/%s' % m.pk, { 'timer_start': 8, 'duration': 106 }) response.status_code.should.eql(status.HTTP_200_OK) response.data.should.have.key('timer_start').which.should.equal(8) response.data.should.have.key('duration').which.should.equal(106) m = self.reload(m) m.timer_start.should.eql(8) m.duration.should.eql(106)
def create_label(request): # get the address of the wav audio if request.method == 'POST': # wav_path = request.POST.get('path') file = request.FILES['file'] # print(wav_path) wavName = "./music/wav/" + file.name print(wavName) with open(wavName, 'wb') as wav: for c in file.chunks(): wav.write(c) music = Music() music.wav_path = wavName # load the web of ASR gen = load_model('music\MusicClass\music_cla_model.h5') # check the length of the audio and cut into a proper length x, sr = librosa.load(wavName) if len(x) < 88200: x = np.pad(x, (0, 88200 - x.shape[0]), 'constant') else: x = x[0:88200:1] # add some feature and reshape it mfcc = librosa.feature.mfcc(y=x, sr=sr, n_mfcc=40) norm_mfcc = sklearn.preprocessing.scale(mfcc, axis=1) mfcc = norm_mfcc.reshape(1, mfcc.shape[0], mfcc.shape[1], 1) # predict the result and get the best one and its label result = gen.predict(mfcc) probability = [] result = result.reshape(10, 1) for num in result: probability.append(float(num)) print(probability, sum(probability), max(probability)) music.probability = max(probability) music.label = probability.index(max(probability)) print("label:" + str(music.label)) music.save() return HttpResponse("succeed!!!") # def create_label(request): # # get the address of the wav audio # if request.method == 'POST': # # wav_path = request.POST.get('path') # file = request.FILES['file'] # print(type(file)) # print(file.name) # wavName = "./music/wav/" + file.name # print(wavName) # with open(wavName, 'wb') as wav: # for c in file.chunks(): # wav.write(c) # return HttpResponse("succeed!!!")
def test_post_below_or_above_action(self): m2 = Music( music_id="b", name="b", thumbnail="https://a.com", total_duration=114, duration=114, url="https://www.a.com", source="youtube", room=self.r, ) m2.save() pt2 = PlaylistTrack(track=m2, room=self.r) pt2.save() response = self.client.post('/playlist/%s/below/%s' % (self.pt.pk, pt2.pk)) response.status_code.should.eql(status.HTTP_200_OK) list(self.r.playlist.all()).should.eql([pt2, self.pt]) response = self.client.post('/playlist/%s/above/%s' % (pt2.pk, self.pt.pk)) response.status_code.should.eql(status.HTTP_200_OK) list(self.r.playlist.all()).should.eql([pt2, self.pt])
def test_music_serializer(self): m = Music( music_id='a', name='a', thumbnail='https://a.com', total_duration=114, duration=114, url='https://www.a.com', source='youtube', room=self.r, ) m.save() expected_serialization = { 'pk': m.pk, 'music_id': 'a', 'name': 'a', 'thumbnail': 'https://a.com', 'total_duration': 114, 'duration': 114, 'url': 'https://www.a.com', 'source': 'youtube', 'timer_start': 0, 'count': 0, 'last_play': None, 'one_shot': False } dict(MusicSerializer(m).data).should.eql(expected_serialization)
def test_initialization(self): settings.TESTING = False # Create fake app to test ready method init = Init.create('music') init.models = { 'playlisttrack': PlaylistTrack } music = Music( room=self.r, music_id="a", name="a", total_duration=211, duration=211, thumbnail="https://a.com/a.jpg", ) music.save() PlaylistTrack(track=music, room=self.r).save() init.ready() self.r.tracks.count().should.eql(0) settings.TESTING = True
def test_post_existing_music(self): m = Music( music_id="a", name="a", thumbnail="https://a.com", total_duration=114, duration=114, url="https://www.a.com", source="youtube", room=self.r, ) m.save() music_to_post = { "music_id": "a", "name": "a", "thumbnail": "https://a.com", "total_duration": 114, "duration": 100, "url": "https://www.a.com", "source": "youtube", } response = self.client.post('/music', music_to_post) response.status_code.should.eql(status.HTTP_201_CREATED) response.data.should.have.key('duration').which.should.eql(100) Music.objects.filter(music_id='a', room=self.r).first().duration.should.be.eql(100)
def get_new_music(self): music = Music(name='Test', album=self.album, order=1, file=self._get_mp3()) music.save() return music
def test_get(self): # Create a classic music that should be sent by /musics Music( music_id="a", name="a", thumbnail="https://a.com", total_duration=114, duration=114, url="https://www.a.com", source="youtube", room=self.r, ).save() # Create new room and a new music that should not be sent by /musics r2 = Room(name='b', password='******') r2.save() Music( music_id="a", name="a", thumbnail="https://a.com", total_duration=114, duration=114, url="https://www.a.com", source="youtube", room=r2, ).save() response = self.client.get('/musics') response.status_code.should.eql(status.HTTP_200_OK) response.data.should.have.key('count') response.data.should.have.key('next') response.data.should.have.key('previous') response.data.should.have.key('results') response.data['results'].should.be.a(list) response.data['results'].should.have.length_of(1) self.assertResponseEqualsMusic( response.data['results'][0], Music.objects.get(music_id='a', room=self.r))
def post(self, request): file = request.FILES.get("file", None) if not file: return JsonResponse({"code": 400, "error": "file can not empty"}) file_name = "{time}_{origin_name}".format( origin_name=file.name, time=datetime.now().strftime("%Y-%m-%d_%H:%M%S")) destination = open(os.path.join("static/uploads/", file_name), 'wb+') # 打开特定的文件进行二进制的写操作 for chunk in file.chunks(): # 分块写入文件 destination.write(chunk) destination.close() print(request.data) print(request.data['music_name'], request.data['music_auth']) music_info = { **request.data, **{ 'user': request.user.id, 'path': "static/uploads/{name}".format(name=file_name) } } music_info['music_name'] = music_info['music_name'][0] music_info['music_auth'] = music_info['music_auth'][0] # music_info['file'] = music_info['file'][0] serilizer = UploadMusicSerializer(data=music_info) if serilizer.is_valid(): serilizer.save() # return JsonResponse({"code": 200, "data": serilizer.data, 'error': ""}) else: return JsonResponse({ "code": 200, "data": "", 'error': serilizer.errors }) music = Music(music_name=request.data['music_name'], music_auth=request.data['music_auth'], music_url=serilizer.data.get('path')) print(serilizer.data.get('path')) music.save() _data = { "music_name": music.music_name, "music_auth": music.music_auth, "music_url": music.music_url, "id": music.id } print(_data) return JsonResponse({"code": 200, "data": _data, 'error': ""})
def test_get_musics_remaining(self): music = Music( room=self.r, music_id='a', name='a', total_duration=200, duration=200, thumbnail='https://a.com/a.jpg', ) music.save() PlaylistTrack(track=music, room=self.r).save() list(self.r.get_musics_remaining()).should.eql([music])
def test_get_remaining_time(self): # Still no music self.r.get_remaining_time().should.eql(0) music = Music(room=self.r, music_id='a', name='a', total_duration=200, duration=200, thumbnail='https://a.com/a.jpg', last_play=datetime.now()) music.save() PlaylistTrack(track=music, room=self.r).save() self.r.get_remaining_time().should.eql(200)
def test_stop(self): music = Music( room=self.r, music_id='a', name='a', total_duration=200, duration=200, thumbnail='https://a.com/a.jpg', ) music.save() self.r.current_music = music self.r.save() self.r.stop() self.r.current_music.should.be.none
def test_update(self): music = Music(room=self.r, music_id='a', name='a', total_duration=200, duration=200, thumbnail='https://a.com/a.jpg', source='youtube') music.save() self.r.update({'shuffle': True}) self.r.shuffle.should.be.true self.r.update({'can_adjust_volume': True}) self.r.can_adjust_volume.should.be.true
def setUp(self): super().setUp() self.m = Music( music_id="a", name="a", thumbnail="https://a.com", total_duration=114, duration=104, url="https://www.a.com", source="youtube", timer_start=10, room=self.r, ) self.m.save() self.pt = PlaylistTrack(track=self.m, room=self.r) self.pt.save()
def test_patch_bad_arguments(self): m = Music( music_id="a", name="a", thumbnail="https://a.com", total_duration=114, duration=114, url="https://www.a.com", source="youtube", room=self.r, ) m.save() response = self.client.patch('/music/%s' % m.pk, {'total_duration': 'wtf'}) response.status_code.should.eql(status.HTTP_400_BAD_REQUEST)
def test_add_music(self): music = Music(room=self.r, music_id='b', name='b', total_duration=200, duration=200, thumbnail='https://a.com/a.jpg', source='youtube') music.save() self.r.add_music(music) self.r.music_set.count().should.eql(1) self.r.current_music.music_id.should.eql('b') self.r.add_music(music) self.r.tracks.count().should.eql(1)
def test_next_no_current_music(self): m = Music( music_id="a", name="a", thumbnail="https://a.com", total_duration=114, duration=114, url="https://www.a.com", source="youtube", room=self.r, ) m.save() response = self.client.post('/room/next', {'music_pk': m.pk}) response.status_code.should.eql(status.HTTP_400_BAD_REQUEST) response.data.should.eql( "Can't next while no music is currently played")
def create(self, validated_data): """ Override the default Serializer.save() method ============================================= create(..) is called if we don't pass an existing music to the Serializer update(..) method NEED to be implemented too ! :param self: Instance param :param validated_data: A dict of validated data from the Serializer :type self: MusicSerializer :type validated_data: dict :return: The Music object CREATED with the valid data from the Serializer :rtype: Music """ music = Music(**validated_data) music.save() return music
def test_get_current_time_past_percent(self): self.r.get_current_time_past_percent().should.eql(0) music = Music( room=self.r, music_id='a', name='a', total_duration=240, duration=240, thumbnail='https://a.com/a.jpg', last_play=datetime.now() - timedelta(minutes=2) # Music started 2 minutes ago ) music.save() self.r.current_music = music self.r.save() self.r.get_current_time_past_percent().should.eql(float(50))
def test_play(self): music = Music( room=self.r, music_id='a', name='a', total_duration=200, duration=200, thumbnail='https://a.com/a.jpg', ) music.save() self.r.play(music) self.r.current_music.should.eql(music) music.count.should.eql(1) music.last_play.should_not.be.none Events.get(self.r).should_not.be.none
def test_delete(self): m = Music( music_id="a", name="a", thumbnail="https://a.com", total_duration=114, duration=114, url="https://www.a.com", source="youtube", room=self.r, ) m.save() response = self.client.delete('/music/%s' % m.pk) response.status_code.should.eql(status.HTTP_204_NO_CONTENT) Music.objects.filter(music_id="a", room=self.r).exists().should.be.false
def test_play_next_without_shuffle(self): music = Music( room=self.r, music_id='a', name='a', total_duration=200, duration=200, thumbnail='https://a.com/a.jpg', ) music.save() PlaylistTrack(track=music, room=self.r).save() self.r.play_next() self.r.current_music.should.eql(music) self.r.play_next() # No more music in the playlist. self.r.current_music.should.be.none
def test_initialization(self): settings.TESTING = False # Create fake app to test "ready" method init = Init.create('player') init.models = { 'room': Room } # Clean events Events.events = {} Events.get_all().should_not.have.key('a') # Sanity check of events have been cleared room = Room(password='******', name='b') room.save() music = Music( room=room, music_id="a", name="a", total_duration=211, duration=211, thumbnail="https://a.com/a.jpg", ) music.save() room.current_music = music room.shuffle = True room.save() init.ready() room = self.reload(room) room.current_music.should.be.none room.shuffle.should.be.false Events.get_all().should.have.key('b') Events.get_all().should.have.key('a') settings.TESTING = True
def test_set_shuffle(self): self.r.set_shuffle.when.called_with(True).should.throw( Room.UnableToUpdate, "Can't activate shuffle when there is no musics.") music = Music( room=self.r, music_id='a', name='a', total_duration=200, duration=200, thumbnail='https://a.com/a.jpg', ) music.save() self.r.set_shuffle(True) self.r.shuffle.should.be.true self.r.current_music.should.eql(music) self.r.set_shuffle(False) self.r.shuffle.should.be.false
def test_other_action(self): m2 = Music( music_id="b", name="b", thumbnail="https://a.com", total_duration=114, duration=114, url="https://www.a.com", source="youtube", room=self.r, ) m2.save() pt2 = PlaylistTrack(track=m2, room=self.r) pt2.save() # test only one action to test the endpoint. Actions themselves are already tested in OrderedModel lib response = self.client.post('/playlist/%s/top' % pt2.pk) response.status_code.should.eql(status.HTTP_200_OK) list(self.r.playlist.all()).should.eql([pt2, self.pt])
def test_patch_shuffle(self): m = Music( music_id="a", name="a", thumbnail="https://a.com", total_duration=114, duration=114, url="https://www.a.com", source="youtube", room=self.r, ) m.save() response = self.client.patch('/room', {'shuffle': True}) response.status_code.should.eql(status.HTTP_200_OK) response.data['shuffle'].should.be.true response.data['current_music']['music_id'].should.eql('a') response = self.client.patch('/room', {'shuffle': False}) response.status_code.should.eql(status.HTTP_200_OK) response.data['shuffle'].should.be.false
def add(request): if request.method == 'GET': singers = Singer.objects.all() types = Type.objects.all() singers_li = [] for singer in singers: singers_li.append({'id': singer.id, 'name': singer.name}) types_li = [] for type in types: types_li.append({'id': type.id, 'name': type.name}) data = {'singers': singers_li, 'types': types_li} return JsonResponse(data) else: name = request.POST['name'] singers_id = request.POST.getlist('singers_id') # print(singers_id, '-----------') music = Music.objects.filter(name=name).first() is_exit = True if music is not None: # print(music.singers.all()) if len(singers_id) == len(music.singers.all()): for singer in music.singers.all(): if str(singer.id) not in singers_id: is_exit = False break else: is_exit = False else: is_exit = False if is_exit is True: data = {'status': 'no', 'info': '添加歌曲失败,歌曲已存在'} return JsonResponse(data) else: type_id = request.POST['type_id'] img = request.FILES.get('img') file = request.FILES.get('file') if img is not None: # print(img.name, '==============') img_path = MUSIC_IMG_DIR if not os.path.exists(img_path): os.makedirs(img_path) with open(img_path + img.name, 'wb') as f: for chunk in img.chunks(): f.write(chunk) imgPath = MUSIC_IMG_URL + img.name else: imgPath = '' if file is not None: file_path = MUSIC_FILE_DIR if not os.path.exists(file_path): os.makedirs(file_path) # file_name=change_filename(file.name) with open(file_path + file.name, 'wb') as f: for chunk in file.chunks(): f.write(chunk) filePath = MUSIC_FILE_URL + file.name else: filePath = '' # print(type_id) typeObj = get_object_or_404(Type, id=type_id) music = Music(name=name, img=imgPath, file=filePath, type=typeObj) music.save() for id in singers_id: music.singers.add(int(id)) music.save() data = {'status': 'ok', 'info': '添加歌曲成功'} return JsonResponse(data)
from music.models import Music from urllib2 import urlopen import json from utils import * url = 'https://itunes.apple.com/lookup?id=284910350' response = urlopen(url) json_obj = json.load(response) print json_obj print '##########################' print 'debugging' for i in json_obj['results']: music = Music() if i['screenshotUrls']: app_url = [] for url in i['screenshotUrls']: app_url.append(strip_unicode(url)) music.app_url = app_url else: pass print i['trackName'] if i['trackName']: music.app_name = i['trackName'] else: pass if i['genres']: