mirror of
https://github.com/JefferyHcool/BiliNote.git
synced 2026-09-07 00:27:37 +08:00
- 新增关于页面组件,介绍项目背景、功能和使用方法 - 重构笔记生成逻辑,支持多版本笔记 - 新增笔记版本选择、复制和导出功能 -优化笔记界面布局和交互 - 调整部分组件样式,提升用户体验
95 lines
3.1 KiB
Python
95 lines
3.1 KiB
Python
import os
|
|
from abc import ABC
|
|
from typing import Union, Optional
|
|
|
|
import yt_dlp
|
|
|
|
from app.downloaders.base import Downloader, DownloadQuality
|
|
from app.models.notes_model import AudioDownloadResult
|
|
from app.utils.path_helper import get_data_dir
|
|
from app.utils.url_parser import extract_video_id
|
|
|
|
|
|
class YoutubeDownloader(Downloader, ABC):
|
|
def __init__(self):
|
|
|
|
super().__init__()
|
|
|
|
def download(
|
|
self,
|
|
video_url: str,
|
|
output_dir: Union[str, None] = None,
|
|
quality: DownloadQuality = "fast",
|
|
need_video:Optional[bool]=False
|
|
) -> AudioDownloadResult:
|
|
if output_dir is None:
|
|
output_dir = get_data_dir()
|
|
if not output_dir:
|
|
output_dir=self.cache_data
|
|
os.makedirs(output_dir, exist_ok=True)
|
|
|
|
output_path = os.path.join(output_dir, "%(id)s.%(ext)s")
|
|
|
|
ydl_opts = {
|
|
'format': 'bestaudio[ext=m4a]/bestaudio/best',
|
|
'outtmpl': output_path,
|
|
'noplaylist': True,
|
|
'quiet': False,
|
|
}
|
|
|
|
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
|
info = ydl.extract_info(video_url, download=True)
|
|
video_id = info.get("id")
|
|
title = info.get("title")
|
|
duration = info.get("duration", 0)
|
|
cover_url = info.get("thumbnail")
|
|
ext = info.get("ext", "m4a") # 兜底用 m4a
|
|
audio_path = os.path.join(output_dir, f"{video_id}.{ext}")
|
|
print('os.path.join(output_dir, f"{video_id}.{ext}")',os.path.join(output_dir, f"{video_id}.{ext}"))
|
|
|
|
return AudioDownloadResult(
|
|
file_path=audio_path,
|
|
title=title,
|
|
duration=duration,
|
|
cover_url=cover_url,
|
|
platform="youtube",
|
|
video_id=video_id,
|
|
raw_info={'tags':info.get('tags')}, #全部返回会报错
|
|
video_path=None # ❗音频下载不包含视频路径
|
|
)
|
|
|
|
def download_video(
|
|
self,
|
|
video_url: str,
|
|
output_dir: Union[str, None] = None,
|
|
) -> str:
|
|
"""
|
|
下载视频,返回视频文件路径
|
|
"""
|
|
if output_dir is None:
|
|
output_dir = get_data_dir()
|
|
video_id = extract_video_id(video_url, "youtube")
|
|
video_path = os.path.join(output_dir, f"{video_id}.mp4")
|
|
if os.path.exists(video_path):
|
|
return video_path
|
|
os.makedirs(output_dir, exist_ok=True)
|
|
output_path = os.path.join(output_dir, "%(id)s.%(ext)s")
|
|
|
|
ydl_opts = {
|
|
'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]',
|
|
'outtmpl': output_path,
|
|
'noplaylist': True,
|
|
'quiet': False,
|
|
'merge_output_format': 'mp4', # 确保合并成 mp4
|
|
}
|
|
|
|
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
|
info = ydl.extract_info(video_url, download=True)
|
|
video_id = info.get("id")
|
|
video_path = os.path.join(output_dir, f"{video_id}.mp4")
|
|
|
|
if not os.path.exists(video_path):
|
|
raise FileNotFoundError(f"视频文件未找到: {video_path}")
|
|
|
|
return video_path
|