示例#1
0
 def get_songs_contains_key_words(self, keywords):
     yeganeh = Artist("mohsen", "yeganeh", datetime.datetime(1985, 4, 4))
     khaje_amiri = Artist("ehsan", "kaje_amiri",
                          datetime.datetime(1987, 5, 6))
     songs_list = [
         Song("akarin_bar", yeganeh, 123, SongTypes.pop, ["love"], None),
         Song("avalin_bar", khaje_amiri, 456, SongTypes.pop, ["love"], None)
     ]
     return songs_list
示例#2
0
 def get_recommendation(self, playlist, recent_played, favorite_songs,
                        favorite_albums, favorite_artists):
     yeganeh = Artist("mohsen", "yeganeh", datetime.datetime(1985, 4, 4))
     khaje_amiri = Artist("ehsan", "kaje_amiri",
                          datetime.datetime(1987, 5, 6))
     songs_list = [
         Song("akarin_bar", yeganeh, 123, SongTypes.pop, ["love"], None),
         Song("avalin_bar", khaje_amiri, 456, SongTypes.pop, ["love"], None)
     ]
     return songs_list
示例#3
0
 def add_songs_from_dom(self, songs_dom):
     for song_dom_element in songs_dom:
         song_title = song_dom_element.contents[0]
         link_to_song_lyrics = song_dom_element['href']
         response_from_song_lyrics_page = requests.get(link_to_song_lyrics)
         song_lyrics_page = BeautifulSoup(
             response_from_song_lyrics_page.text, 'html.parser')
         title = song_lyrics_page.find_all('h1')[0].contents[0]
         year = song_lyrics_page.find_all('div',
                                          {'class': 'date'})[0].contents[0]
         lyrics = song_lyrics_page.find_all(
             'div', {'class': 'lyrics'})[0].find_all('p')
         song = Song(self, title, year, lyrics)
         song.record_lyrics()
示例#4
0
    def reco_from_csv(self, csv):
        vals = csv.split(",")
        s = Song()
        s.songid = vals[0]
        #Ignore 	vals[1]
        s.mood = vals[2]
        s.genre = vals[3]
        s.userid = vals[4]
        s.album = vals[5]
        s.artist = vals[6]
        s.title = vals[7]
        s.tempo = vals[8]

        return s
示例#5
0
 def pl_from_csv(self, csv):
     vals = csv.split(",")
     s = Song()
     s.songid = vals[0]
     s.userid = vals[1]  #For readability, mainly
     s.title = vals[2]
     s.artist = vals[3]
     s.mood = vals[4]
     s.genre = vals[5]
     s.tempo = vals[6]
     return s
示例#6
0
    def minik(self, url):
        # 解析参数
        result = parse.urlparse(url)
        params = parse.parse_qs(result.query)
        if "uid" in params and 'jobid' in params:
            uid = params['uid'][0]
            jobid = params['jobid'][0]
        else:
            fragment = str(result.fragment)
            if fragment.find("-&-") != -1:
                array = fragment.replace("/details/", "").split("-&-")
                uid = array[0]
                jobid = array[1]
            else:
                jobid = fragment.replace("/details/", "").replace("--ml--", "")
                params = parse.parse_qs(result.query)
                uid = params['uid'][0]

        req_url = "http://weixin.singworld.cn/api/record/record_detail/?&uid={0}&jobid={1}".format(
            uid, jobid)
        content = Converter.get_content(req_url)
        music_info = json.loads(content)['data']['record']
        song_url = "http://{0}/{1}".format(music_info['domain'],
                                           music_info['url'])
        song = Song(music_info['song_name'], song_url)
        return song
示例#7
0
        def matched(widget, model, iter):
            item = model[iter]
            data_a = item[4]
            data_b = item[5]

            self.aview.matched = [data_a, data_b]
            self.albumfilter.refilter()

            if data_b == 'blm.!ARTIST!':
                # Matched an artist: show albums
                return False
            elif exists(data_b):
                # Matched a song: queue to playlist
                sng = Song(filename=item[5])
                self.aview.queue(sng)

                # Go back to empty search
                self.aview.matched = False
                searchentry = widget.get_entry()
                searchentry.set_text('')
                return True
            #elif len(self.albumfilter) == 1:
            else:
                # Matched an album: load it in a panel
                album = Album(data_b, data_a, self.songs_tree)
                if hasattr(album, 'name'):
                    self.aview.on_album_matched(album)

                    # Go back to empty search
                    self.aview.matched = False
                    searchentry = widget.get_entry()
                    searchentry.set_text('')
                    return True
示例#8
0
    def __init__(self, artist_name, album_name, songs_tree):
        """Initialization of the Album() model class.

        Usage:
         alb = Album('Artist', 'Album name', songs_tree)
        """

        self.__is_loaded = False

        # Try to load an Album() object with the artist, name and the tree.
        try:
            alb = songs_tree[artist_name][album_name]
        except KeyError:
            return self.__is_loaded

        self.__is_loaded = True

        alb.sort(key=lambda item: item[6])

        self.name = album_name
        self.artist = artist_name
        self.tracks = []
        self.statistics = self.__get_statistics()

        for sng in alb:
            self.tracks.append(
                Song(title=sng[0],
                     artist=sng[1],
                     album=sng[2],
                     comment=sng[3],
                     genre=sng[4],
                     year=sng[5],
                     track=sng[6],
                     length=sng[7],
                     filename=sng[8]))
示例#9
0
    def shuffle_song_asked(self):
        if len(self.database) > 1:
            index = randrange(len(self.database))
            song_inf = self.database[index]

            song = Song(filename=song_inf[8])
            self.extensions.load_event('OnPlayNewSong', song)
示例#10
0
 def load_playlist(self, csv):
     vals = csv.split(",")
     s = Song()
     s.songid = vals[0]
     s.userid = vals[1]  #For readability, mainly
     s.title = vals[2]
     s.artist = vals[3]
     s.mood = vals[4]
     s.genre = vals[5]
     return s
	def reco_from_csv(self,csv):
		vals = csv.split(",")
		s = Song()
		s.songid = vals[0]
		#Ignore 	vals[1]
		s.mood = vals[2]
		s.genre = vals[3]
		s.userid = vals[4]
		s.album = vals[5]
		s.artist = vals[6]
		s.title = vals[7]
		s.tempo = vals[8]
		
		return s
示例#12
0
class Interpretation(BaseModel):
    def __init__(self, database):
        self.song = Song(database)
        self.database = database

    def create_interpretation(self, data):
        data['wave_file'] = 'storage/wave_files/' + md5(
            str(data['song_id']) + data['registry'] +
            list_to_csv(data['effects'])) + '.wav'

        rtttl = self.song.get_song_rtttl_by_id(data['song_id'])
        wav_generator = WavGenerator(data['song_id'], data['registry'], rtttl,
                                     data['effects'])
        wav_generator.save()

        data['effects'] = list_to_csv(data['effects'])

        self.database.query(
            'INSERT INTO interpretations(song_id, registry, effects, wave_file, votes) VALUES(?, ?, ?, ?, ?)',
            (data['song_id'], data['registry'], data['effects'],
             data['wave_file'], 0))

        data['id'] = self.database.cursor.lastrowid

        return data

    def get_all_interpretations(self):
        interpretations = self.database.fetch('SELECT * FROM interpretations')
        return interpretations

    def get_interpretation_by_id(self, id):
        interpretation = self.database.fetch(
            'SELECT * FROM interpretations WHERE id=?', (id, ))
        return interpretation[0]

    def get_interpretation_votes_by_id(self, id):
        interpretation = self.database.fetch(
            'SELECT votes FROM interpretations WHERE id=?', (id, ))
        return interpretation[0]['votes']

    def get_interpretations_by_song_id(self, song_id):
        interpretations = self.database.fetch(
            'SELECT * FROM interpretations WHERE song_id=?', (song_id, ))
        return interpretations

    def get_interpretations_wave_files_by_song_id(self, song_id):
        wave_files = self.database.fetch(
            'SELECT * FROM interpretations WHERE song_id=?', (song_id, ))
        return wave_files

    def upvote_interpretation_by_id(self, id):
        self.database.query(
            'UPDATE interpretations SET votes = votes + 1 WHERE id=?', (id, ))

    def downvote_interpretation_by_id(self, id):
        self.database.query(
            'UPDATE interpretations SET votes = votes - 1 WHERE id=?', (id, ))
示例#13
0
def addSong(file, title, artist=None, cover=None):
    song = Song(owner=current_user.no,
                title=title,
                artist=artist,
                cover=cover,
                file=file,
                p=randomStringDigits(32))
    db.session.add(song)
    db.session.commit()
示例#14
0
文件: song.py 项目: Graf-J/PianoApp
async def add_song(song: Song):
    try:
        song.added = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        repository.add_song(song)
        songId = repository.get_songId_by_name(song.name)
        return {'id': songId}

    except Exception as ex:
        raise HTTPException(status_code=400, detail='Unable to add Song')
示例#15
0
 def quanmin_ktv(self, url):
     api = "http://localhost:8050/render.html?url={0}&timeout=10&wait=0.5".format(
         url)
     content = subprocess.getoutput("curl %s" % api)
     bs = BeautifulSoup(content, 'html.parser')
     song_url = bs.find('video').attrs['src']
     song_name = bs.find("h3", {"id": "song_name"}).text
     song = Song(song_name, song_url)
     return song
	def pl_from_csv(self,csv):
		vals = csv.split(",")
		s = Song()
		s.songid = vals[0]
		s.userid = vals[1]	#For readability, mainly
		s.title = vals[2]
		s.artist = vals[3]
		s.mood = vals[4]
		s.genre = vals[5]
		s.tempo = vals[6]
		return s
示例#17
0
 def minik2(self, uid, jobid):
     # 解析参数
     req_url = "http://weixin.singworld.cn/api/record/record_detail/?&uid={0}&jobid={1}".format(
         uid, jobid)
     content = Converter.get_content(req_url)
     music_info = json.loads(content)['data']['record']
     song_url = "http://{0}/{1}".format(music_info['domain'],
                                        music_info['url'])
     song = Song(music_info['song_name'], song_url)
     return song
示例#18
0
def search_song_in_website(searched_song_string):
    """Return SearchResult Object"""
    searched_song_string = searched_song_string.strip()
    if searched_song_string == "":
        return

    search_url = construct_search_url(searched_song_string)
    response = requests.get(search_url)

    if response.status_code != requests.codes.ok:
        return

    html_text = response.text
    soup = BeautifulSoup(html_text, 'html.parser')

    result_list = soup.find_all("div", {"class": "lm-list"})

    # Result list must be only one
    if len(result_list) != 1:
        print("ERROR")
        return

    songs_rows = result_list[0].findChildren("div", recursive=False)

    if len(songs_rows) == 1:
        # Check if there are no more
        div = songs_rows[0]
        if len(div.find_all("div")) == 1:
            # No songs found
            result = SearchResult(searched_song_string, [])
            return result

    count = len(songs_rows)
    if count == 0:
        print("NO SONGS")
        return

    all_songs = []
    for i in range(0, count):
        song = songs_rows[i]
        singer = (song.select(".lm-link--secondary")[0])['title']
        song_name_link_tag = (song.select(".lm-link--primary")[0])

        link = song_name_link_tag['href']
        if link[0] == "/":
            link = link[1:]
        link = BASE_URL + link

        name = song_name_link_tag['title']

        song = Song(name, singer, link)
        all_songs.append(song)

    result = SearchResult(searched_song_string, all_songs)
    return result
示例#19
0
 def changba(self, url):
     content = Converter.get_content(url)
     # <div class="title">普通的disco【洛天依】</div>
     # (function(){var a="http://qiniuuwmp3.changba.com/939278470.mp3"
     name_matches = re.findall(r'<div class="title">(.*)</div>', content,
                               re.M)
     url_matches = re.findall(r'https?:.*\.mp3",', content, re.M)
     song_name = name_matches[0].replace("\",", "")
     song_url = url_matches[0].replace("\",", "")
     song = Song(song_name, song_url)
     return song
def set_max_track():
    data = Song.objects().order_by("-track_n")[0]
    print data.track_n
    
    songsMeta = SongsMeta.objects().all()
    if(len(songsMeta)>0):
        m = songsMeta[0]
    else:
        m = SongsMeta()
    m.n = data.track_n
    m.save()
def set_max_track():
    data = Song.objects().order_by("-track_n")[0]
    print data.track_n

    songsMeta = SongsMeta.objects().all()
    if (len(songsMeta) > 0):
        m = songsMeta[0]
    else:
        m = SongsMeta()
    m.n = data.track_n
    m.save()
示例#22
0
    def scan_file(self, file_path):
        """

        :param file_path:
        :return:
        """

        song = taglib.File(file_path)
        return Song(
                track=self.get_tag(song, 'TRACKNUMBER', 0), title=self.get_tag(song, 'TITLE', '- No title -'),
                album=self.get_tag(song, 'ALBUM', '- No album -'), rating=self.get_tag(song, 'RATING', 0)
            )
示例#23
0
文件: app.py 项目: ubien/play-this
    def vote(self):
        SongID = strip_tags(self.request.POST.get('SongID'));
        song = db.GqlQuery("SELECT * FROM Song where id = :1", int(SongID)).get()
        if song is not None:
            song.votes += 1
        else:
            Name = strip_tags(self.request.POST.get('Name'));
            Artist = strip_tags(self.request.POST.get('Artist'));
            song = Song(key_name=SongID,
                id=int(SongID),
                name=Name,
                artist=Artist,
                votes=1)

        song.put()
        songs = get_current_songs()
        session = get_current_session()
        time_left = get_time_left(session)
        resp = return_json_data('true',session[VOTES_KEY],time_left.vote,session[SEARCHES_KEY],time_left.search,jsonifySongs(songs))
        #resp = '{"Success":true,"Remain":'+str(MIN_BETWEEN_VOTES)+',"Result":'+ simplejson.dumps(jsonifySongs(songs)) +'}'
        self.response.out.write(resp)
	def load_playlist(self,csv):
		vals = csv.split(",")
		s = Song()
		s.songid = vals[0]
		s.userid = vals[1]	#For readability, mainly
		s.title = vals[2]
		s.artist = vals[3]
		s.mood = vals[4]
		s.genre = vals[5]
		return s
示例#25
0
    def populate(self, playlist_id):
        if playlist_id in (1, 2):
            # Automatic playlists based on listening stats
            if playlist_id == 1:
                tb = 'stats_songs'
                lm = 50
            elif playlist_id == 2:
                tb = 'stats_albums'
                lm = 10

            result = []
            txt = ('select * from %s order by tracks desc limit %u' % (tb, lm))

            sql = SQLite()
            cur = sql.execute(txt)
            for sg in cur:
                result.append(sg)
            sql.close()

            for item in result:
                if playlist_id == 1:
                    sng = Song(filename=item[0])
                    if hasattr(sng, 'title'):
                        self.on_new_song_queued(sng)
                elif playlist_id == 2:
                    album_name = item[0]
                    for it in self.songs_tree:
                        if album_name in self.songs_tree[it]:
                            self.on_new_album_queued(Album(it, album_name,
                                                           self.songs_tree))
                            break
        elif playlist_id > 3:
            # User-created playlists
            user_plist = self.user_playlists[playlist_id]
            plist = self.playlists_mgmnt.load_playlist(user_plist)

            for item in plist:
                sng = Song(filename=item)
                if hasattr(sng, 'title'):
                    self.on_new_song_queued(sng)
示例#26
0
def get_songs(song_id: str):
    songs = []
    if song_id:
        try:
            songs.append(Song.objects.get(id=song_id))

        except DoesNotExist:
            return make_response('', 404)

    else:
        songs = Song.objects()

    return make_response(jsonify(_resolve_songs(*songs)), 200)
示例#27
0
 def quan_min(self, url):
     content = Converter.get_content(url)
     bs = BeautifulSoup(content, 'html.parser')
     elements = bs.find_all('script', type='text/javascript')
     song = None
     for element in elements:
         if element is not None and str(
                 element.string).startswith("window.__DATA__"):
             info = str(element.string).replace("window.__DATA__ =",
                                                "").replace(";", "")
             music_info = json.loads(info)["detail"]
             song = Song(music_info["song_name"], music_info["playurl"])
             break
     return song
示例#28
0
 def wow(self, url):
     api = "http://localhost:8050/render.html?url={0}&timeout=10&wait=0.5".format(
         url)
     logger.info("wow url: %s" % api)
     # content = self.get_content(api)
     content = subprocess.getoutput("curl %s" % api)
     # class="name">盛夏的果实</p>
     # id="audio" src="http://wow-thunder.b0.upaiyun.com/record/201712/00E07E00A270_20171208185730_fmliMb.mp3" preload="metadata"></audio>
     name_matches = re.findall(r'class="name">(.*)</p>', content, re.M)
     url_matches = re.findall(r'http://wow-thunder.*\.mp3', content, re.M)
     song_name = name_matches[0]
     song_url = url_matches[0]
     song = Song(song_name, song_url)
     return song
示例#29
0
    def youchang(self, url):
        result = parse.urlparse(url)
        if url.find("shareDetail") != -1:
            fragment = result.fragment
            index = str(fragment).replace("/shareDetail/", "")
        elif url.find("?id="):
            index = str(result.query).replace("id=", "")

        api_url = "https://uc.ipktv.com/youCS/youC20170216/wxYouCApi20170330/index"
        headers = {
            'User-Agent':
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.691.400 QQBrowser/9.0.2524.400"
        }
        values = {
            "header": {
                "data_type": "proxy",
                "data_direction": "request",
                "server": "vod_http_server",
                "id": "vod_http_server"
            },
            "request": {
                "function":
                10207,
                "version":
                "1.0",
                "clientFunc":
                "dataQuery",
                "privateFunc":
                "immediateIndex",
                "fondDebug":
                "",
                "id":
                "{0}".format(index),
                "user_id":
                "113081042",
                "url":
                "https://uc.ipktv.com/youCS/youC20170216/youCShare/index#/shareDetail/"
                + index
            },
            "comment": ""
        }
        req = request.Request(api_url, headers=headers, method="POST")
        response = request.urlopen(req, json.dumps(values).encode())
        json_obj = json.loads(response.read().decode())
        print(json_obj)
        music_info = json_obj['response']['data']['row']

        song = Song(music_info['_title'],
                    music_info['_merge_songs_file_url_mp3'])
        return song
def insert_init_data():

    Album.drop_collection()
    Song.drop_collection()

    data = json.loads(open("mapped_songs.json", "r").read())
    count = 0
    for movie_name in data:
        movie = data[movie_name]
        a = Album()
        a.name = movie_name
        a.directors = movie.get("directors", None)
        a.music_directors = movie.get("music_directors", None)
        a.image_url = movie.get("img", None)
        a.actors = movie.get("actors", None)
        a.save()

        print "saved :: ", a.name
        for song_title_path in movie.get("song_entries", []):
            if (not song_title_path): continue
            song_title, path = song_title_path
            s = Song()
            s.title = song_title
            #             s.lyricists = song.get("lyricists",None)
            #             s.singers = song.get("singers",None)
            s.path = path
            s.album = a
            s.track_n = count
            count += 1
            s.save()
            print "    ", "saved song : ", s.title, s.album

    poll = Poll.create_next_poll("telugu")
    print poll.to_json()
    print Poll.get_current_poll("telugu").to_json()

    set_max_track()
def insert_init_data():
    
    Album.drop_collection()
    Song.drop_collection()
    
    
    data = json.loads(open("mapped_songs.json","r").read())
    count = 0
    for movie_name in data:
        movie = data[movie_name]
        a = Album()
        a.name = movie_name
        a.directors = movie.get("directors",None)
        a.music_directors = movie.get("music_directors",None)
        a.image_url = movie.get("img",None)
        a.actors = movie.get("actors",None)
        a.save()
        
        
        print "saved :: ", a.name
        for song_title_path  in  movie.get("song_entries",[]):
            if(not song_title_path): continue
            song_title , path  = song_title_path
            s = Song()
            s.title = song_title
#             s.lyricists = song.get("lyricists",None)
#             s.singers = song.get("singers",None)
            s.path = path
            s.album = a
            s.track_n = count
            count +=1
            s.save()
            print "    ", "saved song : " , s.title , s.album 
            
    
    poll = Poll.create_next_poll("telugu")
    print poll.to_json()
    print Poll.get_current_poll("telugu").to_json()        
    
    
    set_max_track()
示例#32
0
def add_song():
    r = request.get_json()

    song_data = base64.b64decode(r.get('song').encode('utf-8'))

    # Read song metadata
    metadata = MP3(BytesIO(song_data))
    title = str(metadata.get('TIT2'))
    album = str(metadata.get('TALB'))
    artist = str(metadata.get('TPE1'))
    runtime = int(metadata.info.length)
    bitrate = int(metadata.info.bitrate)

    new_song = Song(
        title=title,
        artist=artist,
        album=album,
        runtime=runtime,
        bitrate=bitrate,
    )
    new_song.song.put(BytesIO(song_data), content_type='audio/mpeg')
    new_song.save()

    return make_response(jsonify(_resolve_songs(new_song)), 200)
示例#33
0
 def get_highest_poll_song(cls, stream_id):
     poll = cls.get_current_poll(stream_id)
     mx = -1
     mx_song = None
     for poll_item in poll.poll_items:
         poll_item.song = Song.objects(id=poll_item.song.id).get()
         print poll_item.song.title , poll_item.poll_count
         
         if(poll_item.poll_count>=mx):
             if(poll_item.poll_count==mx):
                 if(random.randint(0,1)==1):
                     continue
             mx = poll_item.poll_count
             mx_song = poll_item.song
     
     return mx_song
示例#34
0
 def process_song(self, song):
     source.track('processing_song')
     if (SeenRecording.objects(mbid=song.mbid)):
         source.track('seen_song')
         return
     SeenRecording(mbid=song.mbid).save()
     if Song.objects(mbid=song.mbid):
         source.track('already_present')
         # We already have the song
         return
     lyric = scraper.get_lyrics(artist=song.artist, title=song.title)
     source.track('searching_for_lyric')
     if lyric:
         source.track('found_lyric')
         song.add_lyric(lyric['string'], lyric['source'])
         song.save()
class Interpretation(BaseModel):
    def __init__(self, database):
        self.song     = Song(database)
        self.database = database

    def create_interpretation(self, data):
        data['wave_file'] = 'storage/wave_files/' + md5(str(data['song_id']) + data['registry'] + list_to_csv(data['effects'])) + '.wav'

        rtttl = self.song.get_song_rtttl_by_id(data['song_id'])
        wav_generator = WavGenerator(data['song_id'], data['registry'], rtttl, data['effects'])
        wav_generator.save()

        data['effects'] = list_to_csv(data['effects'])

        self.database.query('INSERT INTO interpretations(song_id, registry, effects, wave_file, votes) VALUES(?, ?, ?, ?, ?)', (data['song_id'], data['registry'], data['effects'], data['wave_file'], 0))

        data['id'] = self.database.cursor.lastrowid

        return data

    def get_all_interpretations(self):
        interpretations = self.database.fetch('SELECT * FROM interpretations')
        return interpretations

    def get_interpretation_by_id(self, id):
        interpretation = self.database.fetch('SELECT * FROM interpretations WHERE id=?', (id,))
        return interpretation[0]

    def get_interpretation_votes_by_id(self, id):
        interpretation = self.database.fetch('SELECT votes FROM interpretations WHERE id=?', (id,))
        return interpretation[0]['votes']

    def get_interpretations_by_song_id(self, song_id):
        interpretations = self.database.fetch('SELECT * FROM interpretations WHERE song_id=?', (song_id,))
        return interpretations

    def get_interpretations_wave_files_by_song_id(self, song_id):
        wave_files = self.database.fetch('SELECT * FROM interpretations WHERE song_id=?', (song_id,))
        return wave_files

    def upvote_interpretation_by_id(self, id):
        self.database.query('UPDATE interpretations SET votes = votes + 1 WHERE id=?', (id,))

    def downvote_interpretation_by_id(self, id):
        self.database.query('UPDATE interpretations SET votes = votes - 1 WHERE id=?', (id,))
示例#36
0
def get_init_data(stream_id, user=None):
    from requests import stream_events_handler
    song = Song.objects().order_by("-last_played")[0]

    poll = Poll.get_current_poll(stream_id)

    init_data = InitData()
    if (user):
        init_data.user = user
        poll_item = user.get_poll_item(poll)
        if (poll_item):
            init_data.user_poll_item_id = str(poll_item.id)  #string

    init_data.poll = poll
    init_data.n_user = len(stream_events_handler.event_listeners[stream_id])
    init_data.current_song = song

    return init_data
示例#37
0
def get_init_data(stream_id, user=None):
    from requests import stream_events_handler
    song = Song.objects().order_by("-last_played")[0]
    
    poll = Poll.get_current_poll(stream_id)
    
    init_data = InitData()
    if(user):
        init_data.user = user
        poll_item = user.get_poll_item(poll)
        if(poll_item):
            init_data.user_poll_item_id = str(poll_item.id)#string
        
    init_data.poll = poll
    init_data.n_user = len( stream_events_handler.event_listeners[stream_id])
    init_data.current_song  = song
    
    return init_data
示例#38
0
 def create_next_poll(cls, stream_id , save_in_db = True):
     #pick , 7 songs, 
     # create poll items , 
     # create poll item with the stream Id
     #return 
     total_songs = SongsMeta.objects().get().n
         
     poll = Poll()
     poll.stream_id = stream_id
     if(save_in_db):
         poll.save()
     poll_items = []
     try:
         temp_track_hash = {}
         while(len(poll_items)<7):
             try:
                 random_track_n = random.randint(0,total_songs)
                 if(temp_track_hash.get(random_track_n, None)): continue# dont repeat tracks
                 
                 song = Song.objects(track_n=random_track_n).get()
                 poll_item =  PollItem(song = song , poll_count =0 , poll= poll)
                 poll_items.append(poll_item)
                 temp_track_hash[random_track_n] = True
                 
             except (MultipleObjectsReturned, DoesNotExist) as ex:
                 pass
             
                 
         for poll_item in poll_items:
             if(save_in_db): 
                 poll_item.save()
         
         poll.poll_items = poll_items
         if(save_in_db):
             poll.save()#again with updates pollItems
     except Exception as ex:
         print ex
         poll.delete()
         poll = None
         for poll_item in poll_items:
             if(save_in_db):
                 poll_item.delete()
         
     return poll
示例#39
0
    def search(self, query, limit=10):
        """Full text search on mongodb.
        Also submit any search queries to be crawled.
        Returns a list of models.Song objects
        """
        #TODO: Hopefully mongoengine supports this soon.
        resultset = db.command(
            'text',  # text search
            'song',  # must be consistant with mongoengien
            search=query,
            project={
                'lyric': 0,  # conserve bandwidth?
            },
            limit=limit)['results']

        #sort resultset by mongo full text search's score
        resultset = sorted(resultset, key=lambda x: x['score'], reverse=True)
        result = [Song(id=x['obj']['_id'], **x['obj']) for x in resultset]
        # Also report search query
        self.enqueue_query(query)
        return result
示例#40
0
def song(song_id):
    if not current_app.config['GENERATE_ENABLED']:
        return redirect(url_for('web.landing'))

    song = Song.get(song_id)

    if not song:
        return redirect(url_for('web.landing'))

    pre_chorus = Line.get(song.pre_chorus_id)
    chorus = Line.get(song.chorus_id)
    verse = Line.get(song.verse_id)
    bridge = Line.get(song.bridge_id)

    return render_template(
        'generate.html',
        pre_chorus=pre_chorus,
        chorus=chorus,
        verse=verse,
        bridge=bridge,
    )
class ApiController(object):
    def __init__(self, database):
        self.song           = Song(database)
        self.interpretation = Interpretation(database)

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def index(self):
        return self.respond_failure('The API root has no resources.')

    @cherrypy.tools.json_out()
    @cherrypy.expose
    def create_song(self, rtttl):
        try:
            if len(rtttl) == 0:
                raise Exception('Empty RTTTL string.')

            data = {
                'rtttl': str(rtttl)
            }

            data = self.song.create_song(data)

            return self.respond_success(data = data)
        except Exception as e:
            return self.respond_failure(str(e))

    @cherrypy.tools.json_out()
    @cherrypy.expose
    def create_interpretation(self, song_id, registry, effects):
        try:
            if len(song_id) == 0:
                raise Exception('Empty song ID.')

            if len(registry) == 0:
                raise Exception('Empty registry.')

            if len(effects) == 0:
                effects = []
            else:
                effects = effects.split(',')

            data = {
                'song_id':  int(song_id),
                'registry': str(registry),
                'effects':  list(effects)
            }

            data = self.interpretation.create_interpretation(data)

            return self.respond_success(data = data)
        except Exception as e:
            return self.respond_failure(str(e))

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def list_songs(self):
        try:
            songs = self.song.get_all_songs()

            data = {
                'songs': list(songs)
            }

            return self.respond_success(data = data)
        except Exception as e:
            return self.respond_failure(str(e))

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def list_song_files(self, id):
        try:
            wave_form_file = self.song.get_song_wave_form_file_by_id(id)
            wave_files = self.interpretation.get_interpretations_wave_files_by_song_id(id)

            data = {
                'wave_form_file': str(wave_form_file),
                'wave_files': list(wave_files)
            }

            return self.respond_success(data = data)
        except Exception as e:
            return self.respond_failure(str(e))

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def get_notes(self, id):
        try:
            notes = self.song.get_song_rtttl_by_id(id)

            data = {
                'notes': str(notes)
            }

            return self.respond_success(data = data)
        except Exception as e:
            return self.respond_failure(str(e))

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def get_wave_file(self, id):
        try:
            interpretation = self.interpretation.get_interpretation_by_id(id)

            data = {
                'wave_file': str(interpretation['wave_file'])
            }

            return self.respond_success(data = data)
        except Exception as e:
            return self.respond_failure(str(e))

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def get_wave_form(self, id):
        try:
            wave_form_file = self.song.get_song_wave_form_file_by_id(id)

            data = {
                'wave_form_file': str(wave_form_file)
            }

            return self.respond_success(data = data)
        except Exception as e:
            return self.respond_failure(str(e))

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def submit_vote(self, id, vote):
        try:
            if int(vote) > 0:
                self.interpretation.upvote_interpretation_by_id(id)
            else:
                self.interpretation.downvote_interpretation_by_id(id)
            return self.respond_success()
        except Exception as e:
            return self.respond_failure(str(e))

    @cherrypy.tools.json_out()
    def respond(self, success = True, message = '', data = []):
        output = {
            'success': success,
            'message': message,
            'data': data
        }

        return output

    @cherrypy.tools.json_out()
    def respond_success(self, message = 'Your request was successful.', data = []):
        return self.respond(True, message, data)

    @cherrypy.tools.json_out()
    def respond_failure(self, message = 'Your request was a failure.', data = []):
        return self.respond(False, message, data)
示例#42
0
def load():
    album = Album()
    album.name = "100 Kotlu"
    album.actors = [
            "Krishna", 
            "Baladitya", 
            "Syerabhanu", 
            "Brahmanandam"
        ]
    album.music_directors = ["Vandemataram Srinivas"]
    album.directors = ["maruthi"]
    album.imageUrl = "http://rgamedia.blob.core.windows.net/raagaimg/r_img/catalog/cd/a/a0001232.jpg"
    album.save()
    
    print album.to_json()
    
    song = Song()
    
    song.album = album
    song.title = "Chirunayyu"
    song.genre  = None
    
    song.lyricists = [
                    "Surisetty Ramarao"
                ]
    
    song.singers =  [
                    "Malathi"
                ]
    song.rating = 10
    song.save()
    
    print song.to_json()
 def __init__(self, database):
     self.song           = Song(database)
     self.interpretation = Interpretation(database)
示例#44
0
from pymongo import MongoClient
from models.song import Song
from mongoengine import connect

connect('test')

client = MongoClient()
db = client.test

print('hello')
for n_song in db.target.find():
    mbid = n_song.get('mbid', None)
    if not mbid:
        continue
    song = Song.objects(mbid=mbid)
    if not song:
        song = Song(
                mbid=mbid,
                title=n_song['title'],
                artist=n_song['artist']
                )

    song.add_lyric(n_song.get('lyric', None), 'target')
    song.save()
示例#45
0
def test2():
    song = Song.objects().get()
    data = SON()
    data["song"] = song.to_son()
    print json_util.dumps(data)
 def __init__(self, database):
     self.song     = Song(database)
     self.database = database
    def _run(self):
        print "loading audio stream :: ", self.stream_id
        while(True):
            song_url_path = None
            current_poll = Poll.get_current_poll(self.stream_id)
            if(current_poll):
                if(not IS_TEST_BUILD):
                    song = current_poll.get_highest_poll_song(self.stream_id)
                else:
                    song = Song.objects(track_n=158).get()
                    
                if(song):
                    song_url_path = song.path

                    
            retry_poll_creation = 3
            while(retry_poll_creation>0):
                poll = Poll.create_next_poll(self.stream_id , not IS_TEST_BUILD)
                if(poll!=None):
                    break
                retry_poll_creation-=1
                
            if(poll==None):
                continue
            
            if(not song_url_path):
                song_url_path = "http://storage.googleapis.com/telugubeats_files/music/Telugu/devisri%20prasad/arya/amalapuram.mp3"
                
            if(song_url_path.startswith("/Users/abhinav/Desktop/Telugu//")):                    
                song_url_path="http://storage.googleapis.com/telugubeats_files/music/Telugu/"+urllib.quote(song_url_path[31:])
                
            print "playing::", song_url_path
            self.fd = RemoteUrlFileObject(song_url_path)
            
            #spawn greenlet, keep reading into buffer
            #block calls to seek and read if buffer is not sufficient enough
            
            
            reset_data = InitData()
            
            reset_data.poll = poll
            reset_data.n_user = 1000+len( stream_events_handler.event_listeners[self.stream_id])
            reset_data.current_song  = song
            song.last_played = datetime.utcnow()
            if(not IS_TEST_BUILD):
                song.save()
            event_data = json_util.dumps(reset_data.to_son())
            
            stream_events_handler.publish_event(self.stream_id, Event.RESET_POLLS_AND_SONG, event_data, from_user = None)

            # if there is valid ID3 data, read it out of the file first,
            # so we can skip sending it to the client
            try:
                self.id3 = id3reader.Reader(self.fd)
                if isinstance(self.id3.header.size, int): # read out the id3 data
                    self.fd.seek(self.id3.header.size)
                
                while(True):
                    try:
                        cur_time = time.time()
                        if(cur_time- self.last_time_stamp > self.sleep_time):
                            self.last_time_stamp = cur_time
                            self.buffer.queue_chunk(self.fd.read(self.buffer.chunk_byte_size))
                            gevent.sleep(self.sleep_time- time.time()+self.last_time_stamp)
                    except EOFError:
                        self.fd.close()
                        break        
            except Exception as e:
                    print e