nddl / app.py
mzltest's picture
Update app.py
b81ee0f verified
raw
history blame
2.77 kB
import gradio as gr
# coding: utf-8
# Your code here!
import requests
from bs4 import BeautifulSoup
import html
import os
import json
def dlvid(vid):
s = requests.Session()
url = f"https://www.nicovideo.jp/watch/{vid}"
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0',
}
# 发送请求
response = s.get(url, headers=headers)
if response.status_code == 200:
# 解析 HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 获取 data-api-data 的值
data_api_data = soup.find('div', id='js-initial-watch-data').get('data-api-data')
# 对值进行 HTML 解码并转换为 JSON
json_data = json.loads(html.unescape(data_api_data))
# 在此处你可以将 JSON 数据加载并进行显示
# 解析 json_data 为字典
client_watchTrackId = json_data['client']['watchTrackId']
accessRightKey = json_data['media']['domand']['accessRightKey']
url = f"https://nvapi.nicovideo.jp/v1/watch/{vid}/access-rights/hls?actionTrackId={client_watchTrackId}"
payload = json.dumps({
"outputs": [
[
"video-h264-720p",
"audio-aac-192kbps"
]
]
})
headers = {
'origin': 'https://www.nicovideo.jp',
'referer': 'https://www.nicovideo.jp/',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0',
'x-access-right-key': accessRightKey,
'x-frontend-id': '6',
'x-frontend-version': '0',
'x-request-with': 'https://www.nicovideo.jp'
}
response = s.request("POST", url, headers=headers, data=payload)
hlsjson=response.json()
hlsuri=hlsjson['data']['contentUrl']
# 删除可能存在的旧的 test.mp4 文件
if os.path.exists("test.mp4"):
os.remove("test.mp4")
# 使用 ffmpeg 将 m3u8 转换为 mp4
cookie_dict = s.cookies.get_dict()
cookie_string = ''
for key, value in cookie_dict.items():
cookie_string += f'{key}={value}; path=/; domain=nicovideo.jp; \r\n'
ffmpeg_command = f'ffmpeg -protocol_whitelist "concat,file,http,https,tcp,tls,crypto" -cookies "{cookie_string}" -i "{hlsuri}" -c copy "test.mp4"'
print(ffmpeg_command)
os.system(ffmpeg_command)
return './test.mp4'
else:
print("请求失败:", response.status_code)
demo = gr.Interface(fn=dlvid, inputs="text", outputs="video")
demo.launch()