Spaces:
Runtime error
Runtime error
| import os.path | |
| import random | |
| from musicdl import musicdl | |
| from musicdl.modules import Downloader | |
| from pydub import AudioSegment | |
| def is_integer(string): | |
| if string.isdigit(): | |
| return int(string) | |
| else: | |
| return 0 | |
| def is_numeric(string): | |
| if string.isdigit(): | |
| return True | |
| if string.count('.') == 1: | |
| integer_part, decimal_part = string.split('.') | |
| if integer_part.isdigit() and decimal_part.isdigit(): | |
| return True | |
| return False | |
| def time_to_seconds(time_string): | |
| hours, minutes, seconds = map(lambda x: is_integer(x), time_string.split(':')) | |
| total_seconds = hours * 3600 + minutes * 60 + seconds | |
| return total_seconds | |
| def size_to_int(size_string): | |
| prefix_size_str = size_string[:-2] # 去除最后的单位部分,转换为浮点数 | |
| if not is_numeric(prefix_size_str): | |
| return 5.1 * 1024 * 1024 | |
| unit = size_string[-2:] # 获取单位部分 | |
| size = float(prefix_size_str) | |
| if unit == 'KB': | |
| size *= 1024 # 转换为字节 | |
| elif unit == 'MB': | |
| size *= 1024 * 1024 | |
| elif unit == 'GB': | |
| size *= 1024 * 1024 * 1024 | |
| elif unit == 'TB': | |
| size *= 1024 * 1024 * 1024 * 1024 | |
| return int(size) # 转换为整数 | |
| def get_albums(keywords, config): | |
| target_srcs = [ | |
| 'kugou', 'kuwo', 'qqmusic', 'qianqian', 'fivesing', | |
| 'netease', 'migu', 'joox', 'yiting', | |
| ] | |
| client = musicdl.musicdl(config=config) | |
| results = client.search(keywords, target_srcs) | |
| albums_set = set() | |
| valid_albums = [] | |
| for albums in results.values(): | |
| if len(albums) == 0: | |
| continue | |
| for album in albums: | |
| if album['songname'] in albums_set: | |
| continue | |
| if album['ext'] != 'mp3': | |
| continue | |
| if size_to_int(album['filesize']) > 5 * 1024 * 1024: | |
| continue | |
| if time_to_seconds(album['duration']) > 300: | |
| continue | |
| else: | |
| albums_set.add(album['songname']) | |
| valid_albums.append(album) | |
| return valid_albums | |
| def get_random_spit(songinfo): | |
| d = Downloader(songinfo) | |
| d.start() | |
| save_path = os.path.join(songinfo["savedir"], f"{songinfo['savename']}.{songinfo['ext']}") | |
| song = AudioSegment.from_mp3(save_path) | |
| # pydub does things in milliseconds | |
| length = len(song) | |
| left_idx = length / 2 - 15 * 1000 | |
| right_idx = length / 2 + 15 * 1000 | |
| if left_idx < 0: | |
| left_idx = 0 | |
| if right_idx > length: | |
| right_idx = length | |
| middle_30s = song[left_idx:right_idx] | |
| middle_30s.export(save_path, format="wav") | |
| return save_path | |
| if __name__ == '__main__': | |
| config = {'logfilepath': 'musicdl.log', 'downloaded': 'downloaded', 'search_size_per_source': 5, 'proxies': {}} | |
| get_albums('tayler', config) | |