Concurrently calls get_lyrics to fetch the lyrics of a large list of songs.
423351
def run_mp(songs):
    
    stats = Stats()
    if CONFIG['debug']:
        good = open('found', 'w')
        bad = open('notfound', 'w')

    logger.debug('Launching a pool of %d processes\n', CONFIG['jobcount'])
    chunksize = math.ceil(len(songs) / os.cpu_count())
    try:
        with Pool(CONFIG['jobcount']) as pool:
            for result in pool.imap_unordered(get_lyrics, songs, chunksize):
                if result is None:
                    continue

                for source, runtime in result.runtimes.items():
                    stats.add_result(source, result.source == source, runtime)

                found = process_result(result)
                if CONFIG['debug']:
                    if found:
                        good.write(f'{id_source(source)}: {result.song}\n')
                        good.flush()
                    else:
                        bad.write(str(result.song) + '\n')
                        bad.flush()

    finally:
        if CONFIG['debug']:
            good.close()
            bad.close()

    return stats
414662
def get_playlists(self, search, start=0, max_items=100):
        
        return self.get_music_service_information('playlists', search, start,
                                                  max_items)
82948
def main():
    '''
    
    '''

    system('clear') # Must be system('cls') for windows

    setup()

    parser = argparse.ArgumentParser(
        description='Download songs with album art and metadata!')
    parser.add_argument('-c', '--config', action='store_true',
                        help='Set your API keys')
    parser.add_argument('-m', '--multiple', action='store', dest='multiple_file',
                        help='Download multiple songs from a text file list')
    parser.add_argument('-a', '--auto', action='store_true',
                        help='Automatically chooses top result')
    parser.add_argument('--album', action='store_true',
                        help='Downloads all songs from an album')
    args = parser.parse_args()
    arg_multiple = args.multiple_file or None
    arg_auto = args.auto or None
    arg_album = args.album or None
    arg_config = args.config


    if arg_config:
        add_config()

    elif arg_multiple and arg_album:
        log.log_error("Can't do both!")

    elif arg_album:
        album_name = input('Enter album name : ')
        try:
            tracks = get_tracks_from_album(album_name)
            for songs in tracks:
                print(songs)
            confirm = input(
                '\nAre these the songs you want to download? (Y/n)\n> ')

        except IndexError:
            log.log_error("Couldn't find album")
            exit()

        if confirm == '' or confirm.lower() == ('y'):
            for track_name in tracks:
                track_name = track_name + ' song'
                song_url, file_name = get_url(track_name, arg_auto)
                download_song(song_url, file_name)
                system('clear')
                repair.fix_music(file_name + '.mp3')

        elif confirm.lower() == 'n':
            log.log_error("Sorry, if appropriate results weren't found")
            exit()
        else:
            log.log_error('Invalid Input')
            exit()

    elif arg_multiple:
        with open(arg_multiple, "r") as f:
            file_names = []
            for line in f:
                file_names.append(line.rstrip('\n'))

        for files in file_names:
            files = files + ' song'
            song_url, file_name = get_url(files, arg_auto)
            download_song(song_url, file_name)
            system('clear')
            repair.fix_music(file_name + '.mp3')

    else:
        query = input('Enter Song Name : ')
        song_url, file_name = get_url(query, arg_auto)  # Gets YT url
        download_song(song_url, file_name)  # Saves as .mp3 file
        system('clear')
        repair.fix_music(file_name + '.mp3')
1004691
async def songs(self):
    '''
    '''
    items = []
    for i in await self.items:
      if i.type == 'Audio':
        items.append(i)
      elif hasattr(i, 'songs'):
        items.extend(await i.songs)
    return items
131899
def collection(self, user_id):
        
        # TODO further evaluation of the page param, I don't know where the
        # limit is.
        dct = {'userID': user_id, 'page': 0}
        r = 'userGetSongsInLibrary'
        result = self.connection.request(r, dct, self.connection.header(r))
        songs = result[1]['Songs']
        return [Song.from_response(song, self.connection) for song in songs]
1018327
def load(self):
        """"""
        page = requests.get(self._url)
        # Forces utf-8 to prevent character mangling
        page.encoding = 'utf-8'

        tree = html.fromstring(page.text)
        lyric_div = tree.get_element_by_id('lyrics-body-text')
        verses = [c.text_content() for c in lyric_div.find_class('verse')]
        self._lyrics = '\n\n'.join(verses)
        return self
1343514
def get_recent_matches(session, init_url, from_timestamp, limit):
    """"""
    if not from_timestamp:
        from_timestamp = datetime.datetime.now() - datetime.timedelta(days=1)
    matches = []
    page_id = 0
    done = False
    while not done and page_id < MAX_MATCH_PAGE_ID:
        url = '{}/{}'.format(init_url, page_id)
        parsed = make_scrape_request(session, url)
        for row in parsed.find('table').find_all('tr')[1:]:
            cols = row.find_all('td')
            played_at = dateparser.parse(cols[2].text)
            match_id = int(cols[5].find('a').text[1:])
            has_rec = cols[6].find('a').find('img')
            if played_at < from_timestamp or (limit and len(matches) == limit):
                done = True
                break
            if not has_rec:
                continue
            matches.append({
                'timestamp': played_at,
                'match_id': match_id
            })
        if not matches:
            break
        page_id += 1
    return matches
1013856
def songs(self, *, uploaded=True, purchased=True):
		

		if not uploaded and not purchased:
			raise ValueError("'uploaded' and 'purchased' cannot both be False.")

		if purchased and uploaded:
			song_list = []
			for chunk in self.songs_iter(export_type=1):
				song_list.extend(chunk)
		elif purchased:
			song_list = []
			for chunk in self.songs_iter(export_type=2):
				song_list.extend(chunk)
		elif uploaded:
			purchased_songs = []
			for chunk in self.songs_iter(export_type=2):
				purchased_songs.extend(chunk)

			song_list = [
				song
				for chunk in self.songs_iter(export_type=1)
				for song in chunk
				if song not in purchased_songs
			]

		return song_list
1264274
def fetchall(self):
        
        result = []
        iterate = True
        while iterate:
            try:
                result.append(self.next())
            except StopIteration:
                iterate = False
        return result
857531
def download_song_by_id(self, song_id, song_name, folder='.'):
        

        try:
            url = self.crawler.get_song_url(song_id)
            if self.lyric:
                # use old api
                lyric_info = self.crawler.get_song_lyric(song_id)
            else:
                lyric_info = None
            song_name = song_name.replace('/', '')
            song_name = song_name.replace('.', '')
            self.crawler.get_song_by_url(url, song_name, folder, lyric_info)
        except RequestException as exception:
            click.echo(exception)
925561
def _result_is_lyrics(self, song_title):
        

        default_terms = ['track\\s?list', 'album art(work)?', 'liner notes',
                         'booklet', 'credits', 'interview', 'skit',
                         'instrumental', 'setlist']
        if self.excluded_terms:
            if self.replace_default_terms:
                default_terms = self.excluded_terms
            else:
                default_terms.extend(self.excluded_terms)

        expression = r"".join(["({})|".format(term) for term in default_terms]).strip('|')
        regex = re.compile(expression, re.IGNORECASE)
        return not regex.search(self._clean_str(song_title))
111856
def songs(self):
        
        if self._songs is None:
            self._songs = [Song.from_response(song, self._connection) for song in
                           self._connection.request(
                               'artistGetArtistSongs',
                               {'artistID': self.id},
                               self._connection.header('artistGetArtistSongs'))[1]]
        return iter(self._songs)
1248166
def get_song_lyric(self, song_id):
        

        url = 'http://music.163.com/api/song/lyric?os=osx&id={}&lv=-1&kv=-1&tv=-1'.format(  # NOQA
            song_id)
        result = self.get_request(url)
        if 'lrc' in result and result['lrc']['lyric'] is not None:
            lyric_info = result['lrc']['lyric']
        else:
            lyric_info = 'Lyric not found.'
        return lyric_info
938293
def get_quoted_strings(quoted_string):
    '''
    
    '''
    try:
        # This regex grabs all quoted data from string.
        # Note that this gets everything in between the first and last double quote.
        # This is intentional, as printed (and quoted) strings from a target file may contain
        # double quotes, and this function should ignore those. However, it also means that any
        # data between two quoted strings (ex: '"quote 1" non-quoted data
        # "quote 2"') will also be included.
        return re.findall(r'\"(.*)\"', quoted_string)[0]
    except KeyboardInterrupt as e:
        raise e
    except Exception:
        return ''
202878
def load_matches(self):
        
        if not self.exists():
            return []

        matches = []
        with open(self.location(), 'r') as f:
            for line in f.readlines():
                match_obj = json.loads(line.strip("\n"))
                if match_obj['processed']:
                    continue

                matches.append(match_obj)

        return matches
1057625
def get_top_tracks(self, limit=None, cacheable=True):
        """"""

        params = {}
        if limit:
            params["limit"] = limit

        doc = _Request(self, "chart.getTopTracks", params).execute(cacheable)

        seq = []
        for node in doc.getElementsByTagName("track"):
            title = _extract(node, "name")
            artist = _extract(node, "name", 1)
            track = Track(artist, title, self)
            weight = _number(_extract(node, "playcount"))
            seq.append(TopItem(track, weight))

        return seq
737340
def fetch(args: List[str], env: Dict[str, str] = None,
          encoding: str = sys.getdefaultencoding()) -> str:
    
    stdout, _ = run(args, env=env, capture_stdout=True,
                    echo_stdout=False, encoding=encoding)
    log.debug(stdout)
    return stdout