Spaces:
Running
Running
import os | |
import re | |
import json | |
import shutil | |
import requests | |
import gradio as gr | |
def get_first_integer(input_string): | |
match = re.search(r"\d+", input_string) | |
if match: | |
return str(int(match.group())) | |
else: | |
return "" | |
def clean_dir(dirpath="./flagged"): | |
if os.path.exists(dirpath): | |
shutil.rmtree(dirpath) | |
if not os.path.exists(dirpath): | |
os.makedirs(dirpath) | |
def download_mp3(url: str, local_filename: str): | |
try: | |
response = requests.get(url) | |
if response.status_code == 200: | |
with open(local_filename, "wb") as f: | |
f.write(response.content) | |
print(f"Successfully downloaded: {local_filename}") | |
return True | |
else: | |
print(f"Error: {response.status_code}, {response.text}") | |
return False | |
except Exception as e: | |
print(f"Error: {e}") | |
return False | |
def song_info(id: str): | |
detail_api = "https://music.163.com/api/v3/song/detail" | |
parm_dict = {"id": id, "c": str([{"id": id}]), "csrf_token": ""} | |
free = False | |
song_name = "Failed to get song" | |
response = requests.get(detail_api, params=parm_dict) | |
# 检查请求是否成功 | |
if response.status_code == 200: | |
# 处理成功响应 | |
data = json.loads(response.text) | |
if data and "songs" in data and data["songs"]: | |
fee = int(data["songs"][0]["fee"]) | |
free = fee == 0 or fee == 8 | |
song_name = str(data["songs"][0]["name"]) | |
else: | |
song_name = "The song doesn't exist." | |
else: | |
# 处理错误 | |
print(f"Error: {response.status_code}, {response.text}") | |
return song_name, free | |
def inference(song: str): | |
api = "https://music.163.com/song/media/outer/url?id=" | |
fail_voice = "./examples/fail.mp3" | |
vip_voice = "./examples/vip.mp3" | |
if not song: | |
return fail_voice, "Please enter the song ID or link", "" | |
song_id = song | |
if "music.163.com" in song_id and not ".mp3" in song_id: | |
song_id = get_first_integer(song_id.split("?id=")[1]) | |
if not song_id.isdigit(): | |
return fail_voice, "Invalid song ID or link", "" | |
song_name, free = song_info(song_id) | |
if song_name == "The song doesn't exist.": | |
return fail_voice, song_name, "" | |
clean_dir() | |
if free: | |
dld_url = f"{api}{song_id}.mp3" | |
outpath = f"./flagged/{song_id}.mp3" | |
if download_mp3(dld_url, outpath): | |
return outpath, song_name, dld_url | |
else: | |
return vip_voice, song_name, "" | |
if __name__ == "__main__": | |
iface = gr.Interface( | |
fn=inference, # 使用 text_to_speech 函数 | |
inputs=gr.Textbox( | |
label="Enter the song ID or play page url" | |
), # 输入框用于输入文本 | |
outputs=[ | |
gr.Audio(label="Download mp3", type="filepath"), | |
gr.Textbox(label="Song title", show_copy_button=True), | |
gr.Textbox(label="MP3 Direct URL", show_copy_button=True), | |
], | |
flagging_mode="never", | |
) | |
iface.launch() | |