import gradio as gr import os,secrets,requests from basic_pitch.inference import predict_and_save from urllib.parse import quote os.system('chmod +x ./pget') def downloadaud(query): filename=secrets.token_hex() # Step 1: Search for videos with the given query search_url = f"https://draw-8fj.begin.app/api/search/{quote(query)}" search_response = requests.get(search_url).json() print('1=>', search_response) # Step 2: Find the first video with duration less than 10 minutes and extract its ID video_id = None #search_response = sorted(search_response, key=lambda x: x["views"], reverse=True) for item in search_response: duration = item.get("duration_raw") if duration and len(duration.split(':'))< 3 and int(duration.split(':')[0])<10: video_id = item.get("id", {}).get("videoId") break print('1-r',video_id) # If no video with duration less than 10 minutes was found, return None if not video_id: return None # Step 3: Get the formats for the video and find the URL for the best audio-only format formats_url = f"https://draw-8fj.begin.app/api/info/{video_id}" formats = requests.get(formats_url) if formats.ok!=True: formats_url = f"https://draw-8fj-staging.begin.app/api/info/{video_id}" formats = requests.get(formats_url) formats_response=formats.json() print(formats_response["formats"]) best_audio_format = None for fmt in formats_response.get("formats", []): if fmt.get("hasVideo") is False and fmt.get("hasAudio") is True and fmt.get("container") == "mp4": if not best_audio_format or fmt.get("audioBitrate") > best_audio_format.get("audioBitrate"): best_audio_format = fmt print(best_audio_format) # If no suitable audio format was found, return None if not best_audio_format: return None aurl=best_audio_format["url"] print(aurl) command = f'./pget -o {filename}.mp4 -p 4 "{aurl}" ' os.system(command) os.system(f'ffmpeg -i {filename}.mp4 -q:a 0 -map a {filename}.mp3') os.system(f'mv {filename}.mp3 /tmp/{filename}.mp3') res= predict(f'/tmp/{filename}.mp3') return res def predict(ina): fn=ina predict_and_save( [ina], '/'.join(ina.split('/')[:-1]), True, True, False, False, ) ina='.'.join(ina.split('.')[:-1]) ina=ina+'_basic_pitch' os.system(f'ffmpeg -i "{ina}.wav" -f mp3 -acodec libmp3lame -y "{ina}.mp3"') return f'{fn}',f'{ina}.mp3',f'{ina}.mid' aud=gr.Textbox(label="yt query") oar=gr.Audio(label="下载的音频") oa=gr.Audio(label="预览midi") pf=gr.File(label="下载midi") demo = gr.Interface(fn=downloadaud, inputs=[aud], outputs=[oar,oa,pf]) demo.launch()