Example #1
0
def download_audio(artist, song, video_id=None):
    ydl_opts = {
        'format':
        'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
        'outtmpl':
        u'/home/louis_/Music/' + artist + ' - ' + song + '.%(ext)s'
    }

    try:
        open(save_path + artist + ' - ' + song + '.mp3', 'r')
    except:
        pass
    else:
        return True

    if not video_id:
        video_id = get_videos(artist, song)[0]
    try:
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            Logger.log("Downloading the audio for " + song +
                       " with video id " + video_id)
            ydl.download(['http://www.youtube.com/watch?v=' + video_id])
            return True
    except youtube_dl.DownloadError as e:
        Logger.log("Error downloading " + song + " - " + video_id)
        return False
Example #2
0
def deezer_load_artist(TRACK_ID):
    Logger.log("Getting the artist from song #%s from deezer")
    trck = deezer_load_track(TRACK_ID)

    if trck:

        art = trck.get_artist()

    return art
Example #3
0
 def get_playlist_songs(self, playlist_id):
     result_songs = []
     
     Logger.log("Getting playlist %s" % str(playlist_id))
     with connection.cursor() as cursor:
         
         sql = "call get_playlist_songs(%s)"
         cursor.execute(sql, (str(playlist_id),))
         
         result_songs = cursor.fetchall()
     
     return result_songs
Example #4
0
 def instantiate(self, num_available=-1):
     self.ready = True
     self.logger = Logger()
     self.num_available = num_available
     self.instantiated_attacks = [
         a.instantiate() for a in self.attacks.all()
     ]
     return self
Example #5
0
def get_videos(*textToSearch):
    Logger.log("Getting youtube links for " + textToSearch[1])

    good_query = format_query(*textToSearch) + "official+lyrics"
    url = _search_prefix + good_query
    response = urllib.request.urlopen(url)
    flhtml = response.read()
    soup = BeautifulSoup(flhtml, "lxml")

    vids = []

    parsed_html = soup.findAll(attrs={
        'class':
        'yt-lockup yt-lockup-tile yt-lockup-video vve-check clearfix'
    })

    for vid in parsed_html:
        vids.append(vid['data-context-item-id'])

    return vids
Example #6
0
def debug(name, show=False):
    '''这个函数以上下文管理器的方式,为一个代码块命名,如果代码块正常运行,记录代码块的执行时间,如果发生异常,报告异常类型,我们可以通过代码块名称找到问题来源'''
    global debug_layer
    global time_analysis

    print('begin', time_analysis, debug_layer)

    logger = Logger(logname='log.txt', loglevel=1, logger='mine').getlog()

    debug_layer += 1
    start = time()
    spacer = '    ' * debug_layer
    if show:
        print('\n%s------------\n%s%s 开始\n%s------------' %
              (spacer, spacer, name, spacer))
    try:
        yield
    except Exception as e:
        logger.info('%s: %s代码块以下被exception所结束: %s' % (name, spacer, e))
        debug_layer -= 1
    else:
        if show:
            print('%s------------\n%s%s 正常结束,耗时%f seconds\n%s------------' %
                  (spacer, spacer, name, time() - start, spacer))
        debug_layer -= 1
        if name not in time_analysis.keys():
            time_analysis[name] = time() - start
        else:
            time_analysis[name] += time() - start

        #当最外层debug层结束之后,输出时间占用报告
        if debug_layer == -1:
            time_line = "{0:<40}{1:<40}"
            logger.info('------------\n时间占用报告 \n------------')
            logger.info(time_line.format('内容', '耗时', chr(12288)))
            for name, time_consumed in time_analysis.items():
                logger.info(time_line.format(name, time_consumed, chr(12288)))
            time_analysis = {}
            return
Example #7
0
 def add_playlist(self, playlist):
     """ Register a playlist in the database, and its songs."""
     Logger.log("Adding the playlist %s to the database." % playlist.id)
     new_id = playlist.id
     new_name = playlist.name
     new_service = musicEntities.supported_services.index(playlist.service)
     new_link = playlist.link
     
     try:
         with connection.cursor() as cursor:
             sql = "insert into playlist (idplaylist, name, idservice, link) values(%s, %s, %s, %s)"
             
             cursor.execute(sql, (new_id, new_name, new_service, new_link))
     except Exception as e:
         print(e)
         connection.rollback()
     else:
         connection.commit()
     
     
     Logger.log("Adding it to the user_playlist table.")
     try:
         with connection.cursor() as cursor:
             sql = "insert into user_playlist (usrname, idplaylist) values(%s, %s)"
             
             cursor.execute(sql, (self.name, new_id))
             print("added to user_playlist")
     except Exception as e:
         print(e)
         
         connection.rollback()
     else:
         connection.commit()
     
         
     new_songs = playlist.tracks
     
     for song in new_songs:
         add_song(song, new_id)
Example #8
0
def add_song(the_song, playlist_id = None):
    """ Register the song in the database."""
    Logger.log("Adding song %s to the database." % str(the_song.id))
    artst = servicesConnection.deezer_load_artist(the_song.id)
    albm = servicesConnection.deezer_load_album(the_song.id)
    
    if not album_exists(albm.id):
        add_album(albm, artst)    
    
    with connection.cursor() as cursor:
        sql = "insert into song values(%s, %s, %s, %s, %s, %s)"
        now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        
        cursor.execute(sql, (the_song.id, the_song.title, the_song.length,
                             now, albm.id, artst.id))
    
    if playlist_id:
        with connection.cursor() as cursor:
            sql = "insert into playlist_song value(%s, %s)"
            Logger.log("Linking the song %s the playlist " + str(playlist_id))
            
            cursor.execute(sql, (str(playlist_id), str(the_song.id)))
    
    connection.commit()
Example #9
0
def deezer_load_list(LIST_ID):
    """Just Loads a List"""
    Logger.log("Getting the playlist #{} from deezer".format(LIST_ID))
    lis = None
    try:
        lis = cl.get_playlist(LIST_ID)
    except:
        Logger.log("[Error] Couldn't get the list.")
    else:
        Logger.log("Succesfully loaded the list.")
    return lis
Example #10
0
def spotify_load_list(LIST_ID):
    Logger.log("Getting the playlist {} from spotify".format(LIST_ID))
    lis = None
    try:
        pass
    except:
        Logger.log("[Error] Couldn't get the list.")
    else:
        Logger.log("Succesfully loaded the list.")

    return lis
Example #11
0
def deezer_load_track(TRACK_ID):
    Logger.log("Getting the track #%d from deezer" % TRACK_ID)

    trck = None
    try:
        trck = cl.get_track(TRACK_ID)
    except:
        Logger.log("[Error] Couldn't get the track.")
    else:
        Logger.log("Succesfully loaded the track.")

    return trck
Example #12
0
def set_tags(attributes):
    try:
        Logger.log("Setting tags for " + attributes.title)
        audio = EasyID3(attributes.file)
        valid = audio.valid_keys.keys()
        song_variables = attributes.__dict__
        for attr in song_variables.keys():
            if attr in valid:
                audio[attr] = song_variables[attr]
                audio.save()
        Logger.log("Tags set.")
    except Exception as e:
        print(e)
        Logger.log("[Error] Couldn't set file's tags.")
Example #13
0
def main_loop():
    global connected, prev_time, running
    notification.show("Starting Proccess!")
    Logger.log("Starting up program.")
    playlist_list = dataAccess.load_songs()
    while running:
        if not paused:
            if connected:
                for playlist in playlist_list:
                    main_process(playlist)
                    dataAccess.json_pickle(playlist_list)
                    #dataAccess.load_song(playlist_list)
                prev_time = time.time()

            if not dataAccess.internet_connection():
                if connected:
                    notification.show("No Internet Connection")
                    Logger.log("Disconnected from internet")
                    connected = False
            else:
                if not connected:
                    notification.show("Connected")
                    Logger.log("Connected to the internet")
                    connected = True

        loaded_config = dataAccess.load_config()
        current_globals = globals()
        for con_vars in loaded_config.keys():
            current_globals[con_vars] = loaded_config[con_vars]

        if restart:
            import commands
            commands.start()
            running = False

        # running = 0

        time.sleep(5)
Example #14
0
 def instantiate(self, turns_left=None):
     self.logger = Logger()
     self.turns_left = turns_left or self.max_turns
Example #15
0
 def instantiate(self, num_available=-1):
     self.ready = True
     self.logger = Logger()
     self.num_available = num_available
     self.instantiated_effects = list(self.effects.all())
     return self
class Heuristic:
    logger = Logger()

    def __init__(self):
        pass
Example #17
0
def exit_handler():
    Logger.log("Exiting the app")
    notification.show("Closing App")
Example #18
0
def main_process(local_playlist):
    global download, delete

    if not my_user:
        return None
    # notification.show("Starting downloads")

    song_list = local_playlist.tracks

    playlist = methods_to_load[local_playlist.service](local_playlist.id)

    tracks = []
    if not playlist:
        return None
    else:
        tracks = playlist.tracks[:]

    transformed_playlist = servicesConnection.convert_deezer_playlist(playlist)
    if not dbConnection.playlist_exists(transformed_playlist.id):
        my_user.add_playlist(transformed_playlist)

    del playlist

    Logger.log("Analizing  list for changes.")
    for x in tracks[:]:
        song_id = x.id
        if dataAccess.check_download(song_id, song_list):
            # notification.show(deezerConnection.make_str(x.title) + " has already been downloaded.\n")
            continue
        else:
            Logger.log(x.title + " isn't downloaded. Starting Download")
        artist = servicesConnection.make_str(x.artist.name)
        song = servicesConnection.make_str(x.title)

        notification.show("Downloading " + song.title() + "\nby " + artist +
                          "\n{0}/{1}".format(tracks.index(x) + 1, len(tracks)))

        if download:
            # vids = youtubeConnection.get_videos(artist, song)
            if youtubeConnection.download_audio(artist, song):
                Logger.log(
                    song +
                    " has been downloaded succesfully. Registering the file.")
                result_song = register_download(x)
                song_list.append(result_song)
                dbConnection.add_song(result_song, local_playlist.id)
                # notification.show(song.title() + " downloaded!")
                #dataAccess.json_pickle(song_list)
            else:
                Logger.log("[Error] Download of " + song +
                           " failed. Aborting.")

    max_iter = len(song_list)
    x = 0
    while x < max_iter:
        if not servicesConnection.contains(tracks, song_list[x]):
            Logger.log(song_list[x].title +
                       " isn't on the list anymore. Proceding to delete it")
            Logger.log("Deleting " + song_list[x].title)
            os.system('rm "' + song_list[x].file + '"')
            Logger.log("Deleted " + song_list[x].title)
            notification.show("Deleting " + song_list[x].title)

            dbConnection.delete_song(song_list[x].id)

            del song_list[x]
            max_iter -= 1
        x += 1
Example #19
0
class Simulator:
    logger = Logger()

    def __init__(self, pcs, enemies):
        """
        :param pcs: A list of creatures that represent the PCs
        :param enemies: A list of creatures that represent the enemies in the battle
        """
        self.pcs = deepcopy(pcs)
        self.enemies = deepcopy(enemies)
        self.legendary_action_users = [
            combatant for combatant in self.pcs + self.enemies
            if combatant.legendary_actions
        ]
        self.battle_order = None

        for pc in self.pcs:
            pc.enemies = self.enemies
            pc.allies = [x for x in self.pcs if x is not pc]
        for enemy in self.enemies:
            enemy.enemies = self.pcs
            enemy.allies = [x for x in self.enemies if x is not enemy]

    def log_deaths(self, dead, alignment):
        self.logger.log_death("{0} dead: {1}".format(alignment,
                                                     ", ".join(dead)))

    def log_enemy_deaths(self, dead):
        if len(dead) == 1:
            self.logger.log_death("Enemy dead: {0}".format(dead[0]))
        else:
            self.log_deaths(dead, "Enemies")

    def log_player_deaths(self, dead):
        if len(dead) == 1:
            self.logger.log_death("Player dead: {0}".format(dead[0]))
        else:
            self.log_deaths(dead, "Players")

    def calc_initiative(self):
        pc_initiative = [(pc, d20() + pc.saves['DEX']) for pc in self.pcs]
        enemies_initiative = [(enemy, d20() + enemy.saves['DEX'])
                              for enemy in self.enemies]
        self.battle_order = [
            (t[0], 0 if t[0] in self.pcs else 1)
            for t in sorted(pc_initiative + enemies_initiative,
                            key=lambda x: x[1],
                            reverse=True)
        ]

    def run_round(self, heuristic):
        for creature, team in self.battle_order:
            if creature.hp <= 0:
                continue
            allies = [
                x[0] for x in self.battle_order if x[1] == team and x[0].hp > 0
            ]
            enemies = [
                x[0] for x in self.battle_order if x[1] != team and x[0].hp > 0
            ]
            if not enemies:
                break
            creature.take_turn(allies, enemies, heuristic)
            for legendary_action_user in self.legendary_action_users:
                legendary_action_user.try_legendary_action(
                    legendary_action_user.enemies, heuristic)

        dead_enemies = [c.name for c in self.enemies if c.hp <= 0]
        dead_pcs = [c.name for c in self.pcs if c.hp <= 0]

        self.battle_order = [c for c in self.battle_order if c[0].hp > 0]
        self.enemies = [c for c in self.enemies if c.hp > 0]
        self.pcs = [c for c in self.pcs if c.hp > 0]

        return dead_enemies, dead_pcs

    def run_battle(self, heuristic):
        num_player_deaths = 0
        round_num = 0
        self.calc_initiative()
        while self.enemies and self.pcs:
            self.logger.log_info("---- Round {0} ----".format(round_num))
            enemies_dead, players_dead = self.run_round(heuristic)
            if players_dead:
                num_player_deaths += len(players_dead)

            if enemies_dead:
                self.log_enemy_deaths(enemies_dead)
            if players_dead:
                self.log_player_deaths(players_dead)

            round_num += 1
        winning_team = 0 if self.pcs else 1
        return round_num, num_player_deaths, winning_team