| import gradio as gr |
| import subprocess |
| import re |
|
|
| def list_formats(video_url): |
| try: |
| cmd = [ |
| "yt-dlp", "-F", video_url |
| ] |
| result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=60) |
| output = result.stdout + result.stderr |
|
|
| formats = [] |
| started = False |
| for line in output.splitlines(): |
| if re.match(r'format code', line, re.I): |
| started = True |
| continue |
| if not started or line.strip() == "": |
| continue |
| m = re.match(r"^(\d+)\s+(\w+)\s+([0-9x]+|\w+)\s+(.*)", line) |
| if m: |
| format_id, ext, res, note = m.groups() |
| if "video only" in note or re.match(r"\d+x\d+", res): |
| formats.append((format_id, ext, res, note.strip())) |
| if not formats: |
| return gr.update(choices=[], value=None, label="选择画质(无可用项,请检查链接)") |
| choices = [f"{fid} | {ext} | {res} | {note}" for fid, ext, res, note in formats] |
| return gr.update(choices=choices, value=choices[0] if choices else None) |
| except Exception as e: |
| return gr.update(choices=[], value=None, label=f"解析格式失败:{e}") |
|
|
| def get_download_url(video_url, format_choice): |
| try: |
| if not format_choice: |
| return "请选择一个画质格式。" |
| format_id = format_choice.split("|")[0].strip() |
| cmd2 = [ |
| "yt-dlp", "-f", format_id, "--get-url", video_url |
| ] |
| result2 = subprocess.run(cmd2, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=60) |
| url = result2.stdout.strip().split('\n')[0] |
| if not url.startswith("http"): |
| return "未能成功解析出视频下载链接。" |
| return f"选定画质直链(可右键另存为,或复制到下载工具):\n\n{url}\n\n如果遇到问题可尝试其它画质。" |
| except Exception as e: |
| return f"解析失败:{str(e)}" |
|
|
| with gr.Blocks() as demo: |
| gr.Markdown( |
| "# 🎬 在线视频直链解析(yt-dlp powered)\n" |
| "支持B站、抖音、YouTube等多平台。输入视频链接后,选择画质,自动返回可下载的视频直链。" |
| ) |
| url_input = gr.Textbox(label="输入视频链接", placeholder="如:https://b23.tv/Yp80ZTi") |
| with gr.Row(): |
| format_dropdown = gr.Dropdown(label="选择画质", choices=[], interactive=True) |
| fetch_btn = gr.Button("获取画质列表") |
| output = gr.Textbox(label="结果") |
| btn = gr.Button("解析并获取直链") |
| |
| fetch_btn.click(list_formats, inputs=url_input, outputs=format_dropdown) |
| btn.click(get_download_url, inputs=[url_input, format_dropdown], outputs=output) |
|
|
| if __name__ == "__main__": |
| demo.launch() |