vid2uploadDB / app.py
mzltest's picture
Update app.py
56ccd9c
import gradio as gr
import os,secrets,requests
from basic_pitch.inference import predict_and_save
from urllib.parse import quote
import traceback
from deta import Deta # Import Deta
# Initialize
deta = Deta()
# This how to connect to or create a database.
last= deta.Base("last")
records=deta.Base("records")
files=deta.Drive('music')
os.system('chmod +x ./pget')
def addrecord(video_id,orig,pitmp3,mid,gname,ghint):
if not gname or not ghint:
return 'E/缺少name或hint.'
names=list(set(gname.split('\n')))
lastkey=last.get('last')
if not lastkey:
thiskey=0
else:
thiskey=lastkey['next']
if records.fetch({'vid':video_id}).count>0:
return 'Already In'
#upload file src
print(files.put(name=orig,path=orig))
print(files.put(name=pitmp3,path=pitmp3))
print(files.put(name=mid,path=mid))
print(records.put({"vid":video_id,"name":names,"hint":ghint,"orig":orig,"pitmp3":pitmp3,"mid":mid},str(thiskey)))
print(last.put({'next':thiskey+1},'last'))
return 'OK'
def downloadaud(video_id,gname,ghint):
try:
filename=secrets.token_hex()
# Step 1: Search for videos with the given query
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')
o,m,i= predict(f'/tmp/{filename}.mp3')
res=addrecord(video_id,o,m,i,gname,ghint)
return o,m,i,res
except Exception as e:
print(traceback.print_exc(e))
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="视频ID,最长三分半(YouTube视频地址栏的?v=xxxx&...的xxxx)")
g_name=gr.TextArea(label="游戏名称(谜底),回车分名称,一行一个")
g_hint=gr.TextArea(label="开发厂商、发售日期(提示)")
oar=gr.Audio(label="下载的音频")
oa=gr.Audio(label="预览midi")
pf=gr.File(label="下载midi")
res=gr.Textbox(label="结果")
demo = gr.Interface(fn=downloadaud, inputs=[aud,g_name,g_hint], outputs=[oar,oa,pf,res])
demo.launch()