楚汉传奇---Python脚本

news2026/5/8 0:34:18
脚本如下#!/usr/bin/env python3 # -*- coding: utf-8 -*- YouTube 下载工具 (基于 yt-dlp) 支持单个视频、播放列表、仅音频、画质选择、进度显示、错误重试等 import yt_dlp import os import sys import argparse import subprocess import re from pathlib import Path # 控制台颜色可选用于美化输出 class Colors: GREEN \033[92m YELLOW \033[93m RED \033[91m BLUE \033[94m RESET \033[0m def print_info(msg): print(f{Colors.BLUE}[INFO]{Colors.RESET} {msg}) def print_success(msg): print(f{Colors.GREEN}[SUCCESS]{Colors.RESET} {msg}) def print_error(msg): print(f{Colors.RED}[ERROR]{Colors.RESET} {msg}) def print_warning(msg): print(f{Colors.YELLOW}[WARNING]{Colors.RESET} {msg}) def progress_hook(d): 下载进度回调函数 if d[status] downloading: # 获取下载进度 if d.get(total_bytes): total d[total_bytes] downloaded d.get(downloaded_bytes, 0) percent (downloaded / total) * 100 speed d.get(speed, 0) if speed: speed_mb speed / 1024 / 1024 print(f\r 下载进度: {percent:.1f}% | 速度: {speed_mb:.2f} MB/s, end) else: print(f\r 下载进度: {percent:.1f}%, end) elif d.get(total_bytes_estimate): total d[total_bytes_estimate] downloaded d.get(downloaded_bytes, 0) percent (downloaded / total) * 100 print(f\r 下载进度: {percent:.1f}% (估算), end) elif d[status] finished: print(\n ✅ 下载完成正在进行后续处理合并/转换...) elif d[status] error: print_error(下载过程中出现错误) def merge_video_audio_with_ffmpeg(video_file, audio_file, output_file): 使用 FFmpeg 合并视频和音频文件 参数: video_file: 视频文件路径 audio_file: 音频文件路径 output_file: 输出文件路径 返回: bool: 合并成功返回 True否则返回 False try: print_info(f开始合并视频和音频...) print_info(f 视频: {os.path.basename(video_file)}) print_info(f 音频: {os.path.basename(audio_file)}) # FFmpeg 合并命令 cmd [ ffmpeg, -i, video_file, -i, audio_file, -c:v, copy, # 视频流直接复制不重新编码 -c:a, aac, # 音频编码为 AAC -map, 0:v:0, # 使用第一个输入文件的第一个视频流 -map, 1:a:0, # 使用第二个输入文件的第一个音频流 -shortest, # 以较短的流为准 -y, # 覆盖输出文件如果存在 output_file ] # 执行命令 result subprocess.run(cmd, capture_outputTrue, textTrue) if result.returncode 0: print_success(f合并成功输出文件: {output_file}) # 可选删除原始的分开文件 try: os.remove(video_file) os.remove(audio_file) print_info(已删除原始的分开文件) except: pass return True else: print_error(f合并失败: {result.stderr}) return False except Exception as e: print_error(f合并过程中出现错误: {str(e)}) return False def find_video_audio_files(directory, video_patternNone, audio_patternNone): 在目录中查找视频和音频文件 参数: directory: 目录路径 video_pattern: 视频文件匹配模式正则表达式 audio_pattern: 音频文件匹配模式正则表达式 返回: tuple: (video_file, audio_file) 或 (None, None) files os.listdir(directory) # 如果没有指定模式尝试常见的格式 if video_pattern is None: # 查找 .mp4 视频文件通常包含 f数字 格式 video_files [f for f in files if .mp4 in f and not .f251 in f and not audio in f.lower()] # 优先选择包含 f399 或 f400 等高质量的文件 video_files.sort(reverseTrue) video_file video_files[0] if video_files else None else: video_matches [f for f in files if re.search(video_pattern, f)] video_file video_matches[0] if video_matches else None if audio_pattern is None: # 查找 .webm 或 .m4a 音频文件 audio_files [f for f in files if (.webm in f or .m4a in f) and (f251 in f or audio in f.lower())] audio_file audio_files[0] if audio_files else None else: audio_matches [f for f in files if re.search(audio_pattern, f)] audio_file audio_matches[0] if audio_matches else None return (os.path.join(directory, video_file) if video_file else None, os.path.join(directory, audio_file) if audio_file else None) def download_media(url, output_dirDownloads, format_specbest, audio_onlyFalse, audio_formatmp3, audio_quality192, playlistFalse, embed_subsFalse, subs_langen, max_heightNone, proxyNone, retries10, merge_manuallyFalse): 通用下载函数 参数: url: YouTube 视频或播放列表 URL output_dir: 输出目录 format_spec: 画质/格式规格 (例如: best, bestvideobestaudio, worst) audio_only: 是否仅下载音频 audio_format: 音频格式 (mp3, m4a, opus, etc.) audio_quality: 音频比特率 (如 128, 192, 320) playlist: 是否强制按播放列表下载 (即使URL不是播放列表形式) embed_subs: 是否嵌入字幕 subs_lang: 字幕语言代码 (如 en, zh-Hans, zh-Hant) max_height: 限制视频最大高度 (如 1080, 720) proxy: 代理地址 (如 http://127.0.0.1:10809) retries: 重试次数 merge_manually: 是否手动合并下载分开的视频和音频后手动合并 # 确保输出目录存在 Path(output_dir).mkdir(parentsTrue, exist_okTrue) # 基础配置 ydl_opts { outtmpl: os.path.join(output_dir, %(title)s.%(ext)s), ignoreerrors: True, # 忽略单个视频的错误继续下载列表中的其他视频 nooverwrites: True, # 跳过已下载的文件 retries: retries, # 全局重试次数 fragment_retries: retries, # 分片重试次数 socket_timeout: 30, # 网络超时 progress_hooks: [progress_hook], # 进度回调 } # 代理配置 if proxy: ydl_opts[proxy] proxy # 播放列表处理 if playlist: ydl_opts[noplaylist] False # 下载整个播放列表 else: ydl_opts[noplaylist] True # 只下载单个视频 # 字幕配置 if embed_subs: ydl_opts[writesubtitles] True ydl_opts[writeautomaticsub] True # 也下载自动生成的字幕 ydl_opts[subtitleslangs] [subs_lang] ydl_opts[embedsubs] True ydl_opts[embedmetadata] True # 嵌入元数据标题、封面等 # 画质限制 if max_height: # 例如bestvideo[height1080]bestaudio/best[height1080] format_spec fbestvideo[height{max_height}]bestaudio/best[height{max_height}] # 音频/视频模式 if audio_only: print_info(音频模式已启用将下载最佳音质并转换为 {} 格式 ({}kbps).format(audio_format, audio_quality)) ydl_opts[format] bestaudio/best ydl_opts[postprocessors] [{ key: FFmpegExtractAudio, preferredcodec: audio_format, preferredquality: audio_quality, }] # 对于音频修改输出模板为 .audio 前缀可选 ydl_opts[outtmpl] os.path.join(output_dir, %(title)s.%(ext)s) else: if merge_manually: # 手动合并模式分别下载视频和音频不自动合并 print_info(手动合并模式将分别下载视频和音频流) ydl_opts[format] bestvideobestaudio # 不设置 merge_output_format 和 postprocessors else: print_info(f视频模式画质规格: {format_spec}) ydl_opts[format] format_spec ydl_opts[merge_output_format] mp4 # 最终合并为 MP4 # 确保视频格式为 MP4后处理 ydl_opts[postprocessors] [{ key: FFmpegVideoConvertor, preferedformat: mp4, }] # 开始下载 try: with yt_dlp.YoutubeDL(ydl_opts) as ydl: print_info(f正在解析 URL: {url}) # 先获取视频信息可选用于显示标题 info ydl.extract_info(url, downloadFalse) video_title None if entries in info: # 播放列表 count len(info[entries]) if info[entries] else 0 print_info(f检测到播放列表: {info.get(title, Unknown)} (共 {count} 个视频)) if count 0: print_warning(播放列表为空退出。) return # 如果是播放列表获取第一个视频的标题作为参考 if info[entries] and info[entries][0]: video_title info[entries][0].get(title, Unknown) else: # 单个视频 video_title info.get(title, Unknown) print_info(f视频标题: {video_title}) # 实际下载 ydl.download([url]) print_success(下载完成) # 如果是手动合并模式尝试合并分开的视频和音频 if merge_manually and not audio_only: print_info(尝试查找并合并分开的视频和音频文件...) # 等待文件写入完成 import time time.sleep(2) # 查找视频和音频文件 video_file, audio_file find_video_audio_files(output_dir) if video_file and audio_file: # 生成输出文件名 if video_title: # 清理标题中的非法字符 safe_title re.sub(r[\\/*?:|], , video_title) output_file os.path.join(output_dir, f{safe_title}_merged.mp4) else: output_file os.path.join(output_dir, merged_output.mp4) # 执行合并 merge_video_audio_with_ffmpeg(video_file, audio_file, output_file) else: print_warning(未找到需要合并的视频和音频文件) print_info(f请手动合并: {output_dir} 目录下的视频和音频文件) print_success(所有任务执行完毕) except Exception as e: print_error(f下载失败: {str(e)}) sys.exit(1) def main(): parser argparse.ArgumentParser( descriptionYouTube 下载工具 - 支持视频/音频、播放列表、画质选择, formatter_classargparse.RawDescriptionHelpFormatter, epilog 示例: %(prog)s https://youtu.be/xxxxx # 下载单个视频最佳画质 %(prog)s https://youtu.be/xxxxx -a # 仅下载音频为 MP3 %(prog)s 播放列表URL -p # 下载整个播放列表 %(prog)s 视频URL -q 720 # 限制最大高度720p %(prog)s 视频URL -o ./my_videos -f best[height480] # 自定义输出和格式 %(prog)s 视频URL --proxy http://127.0.0.1:10809 # 使用代理 %(prog)s 视频URL --merge-manual # 手动合并模式下载分开的视频和音频 ) parser.add_argument(url, helpYouTube 视频或播放列表的 URL) parser.add_argument(-o, --output, defaultDownloads, help输出目录 (默认: Downloads)) parser.add_argument(-f, --format, defaultbestvideobestaudio/best, helpyt-dlp 格式规格 (默认: bestvideobestaudio/best)) parser.add_argument(-a, --audio, actionstore_true, help仅下载音频模式) parser.add_argument(--audio-format, defaultmp3, choices[mp3, m4a, opus, aac, flac, wav], help音频格式 (默认: mp3)) parser.add_argument(--audio-quality, default192, help音频比特率 kbps (默认: 192)) parser.add_argument(-p, --playlist, actionstore_true, help强制下载整个播放列表 (即使 URL 是单个视频)) parser.add_argument(-s, --subs, actionstore_true, help嵌入字幕 (英文字幕)) parser.add_argument(--subs-lang, defaulten, help字幕语言代码 (默认: en中文可用 zh-Hans 或 zh-Hant)) parser.add_argument(-q, --max-height, typeint, metavarHEIGHT, help限制视频最大高度 (如 1080, 720, 480)) parser.add_argument(--proxy, helpHTTP/HTTPS 代理如 http://127.0.0.1:10809) parser.add_argument(--retries, typeint, default10, help下载重试次数 (默认: 10)) parser.add_argument(--merge-manual, actionstore_true, help手动合并模式下载分开的视频和音频文件然后使用 FFmpeg 合并) args parser.parse_args() # 如果只下载音频自动将 playlist 设为 False 更合理但是用户仍可手动加 -p 来下载播放列表的音频 if args.audio and args.playlist: print_info(下载播放列表的音频版本...) download_media( urlargs.url, output_dirargs.output, format_specargs.format, audio_onlyargs.audio, audio_formatargs.audio_format, audio_qualityargs.audio_quality, playlistargs.playlist, embed_subsargs.subs, subs_langargs.subs_lang, max_heightargs.max_height, proxyargs.proxy, retriesargs.retries, merge_manuallyargs.merge_manual, ) if __name__ __main__: # 检查是否安装了 yt-dlp try: import yt_dlp except ImportError: print_error(未安装 yt-dlp请先运行: pip install yt-dlp) sys.exit(1) # 简单提醒 FFmpeg不强制但如果没有某些功能会受限 print_info(确保已安装 FFmpeg (视频合并/音频转换需要) 可从 https://ffmpeg.org/ 下载并添加到 PATH) main()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2528600.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

SpringBoot-17-MyBatis动态SQL标签之常用标签

文章目录 1 代码1.1 实体User.java1.2 接口UserMapper.java1.3 映射UserMapper.xml1.3.1 标签if1.3.2 标签if和where1.3.3 标签choose和when和otherwise1.4 UserController.java2 常用动态SQL标签2.1 标签set2.1.1 UserMapper.java2.1.2 UserMapper.xml2.1.3 UserController.ja…

wordpress后台更新后 前端没变化的解决方法

使用siteground主机的wordpress网站,会出现更新了网站内容和修改了php模板文件、js文件、css文件、图片文件后,网站没有变化的情况。 不熟悉siteground主机的新手,遇到这个问题,就很抓狂,明明是哪都没操作错误&#x…

网络编程(Modbus进阶)

思维导图 Modbus RTU(先学一点理论) 概念 Modbus RTU 是工业自动化领域 最广泛应用的串行通信协议,由 Modicon 公司(现施耐德电气)于 1979 年推出。它以 高效率、强健性、易实现的特点成为工业控制系统的通信标准。 包…

UE5 学习系列(二)用户操作界面及介绍

这篇博客是 UE5 学习系列博客的第二篇,在第一篇的基础上展开这篇内容。博客参考的 B 站视频资料和第一篇的链接如下: 【Note】:如果你已经完成安装等操作,可以只执行第一篇博客中 2. 新建一个空白游戏项目 章节操作,重…

IDEA运行Tomcat出现乱码问题解决汇总

最近正值期末周,有很多同学在写期末Java web作业时,运行tomcat出现乱码问题,经过多次解决与研究,我做了如下整理: 原因: IDEA本身编码与tomcat的编码与Windows编码不同导致,Windows 系统控制台…

利用最小二乘法找圆心和半径

#include <iostream> #include <vector> #include <cmath> #include <Eigen/Dense> // 需安装Eigen库用于矩阵运算 // 定义点结构 struct Point { double x, y; Point(double x_, double y_) : x(x_), y(y_) {} }; // 最小二乘法求圆心和半径 …

使用docker在3台服务器上搭建基于redis 6.x的一主两从三台均是哨兵模式

一、环境及版本说明 如果服务器已经安装了docker,则忽略此步骤,如果没有安装,则可以按照一下方式安装: 1. 在线安装(有互联网环境): 请看我这篇文章 传送阵>> 点我查看 2. 离线安装(内网环境):请看我这篇文章 传送阵>> 点我查看 说明&#xff1a;假设每台服务器已…

XML Group端口详解

在XML数据映射过程中&#xff0c;经常需要对数据进行分组聚合操作。例如&#xff0c;当处理包含多个物料明细的XML文件时&#xff0c;可能需要将相同物料号的明细归为一组&#xff0c;或对相同物料号的数量进行求和计算。传统实现方式通常需要编写脚本代码&#xff0c;增加了开…

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器的上位机配置操作说明

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器专为工业环境精心打造&#xff0c;完美适配AGV和无人叉车。同时&#xff0c;集成以太网与语音合成技术&#xff0c;为各类高级系统&#xff08;如MES、调度系统、库位管理、立库等&#xff09;提供高效便捷的语音交互体验。 L…

(LeetCode 每日一题) 3442. 奇偶频次间的最大差值 I (哈希、字符串)

题目&#xff1a;3442. 奇偶频次间的最大差值 I 思路 &#xff1a;哈希&#xff0c;时间复杂度0(n)。 用哈希表来记录每个字符串中字符的分布情况&#xff0c;哈希表这里用数组即可实现。 C版本&#xff1a; class Solution { public:int maxDifference(string s) {int a[26]…

【大模型RAG】拍照搜题技术架构速览:三层管道、两级检索、兜底大模型

摘要 拍照搜题系统采用“三层管道&#xff08;多模态 OCR → 语义检索 → 答案渲染&#xff09;、两级检索&#xff08;倒排 BM25 向量 HNSW&#xff09;并以大语言模型兜底”的整体框架&#xff1a; 多模态 OCR 层 将题目图片经过超分、去噪、倾斜校正后&#xff0c;分别用…

【Axure高保真原型】引导弹窗

今天和大家中分享引导弹窗的原型模板&#xff0c;载入页面后&#xff0c;会显示引导弹窗&#xff0c;适用于引导用户使用页面&#xff0c;点击完成后&#xff0c;会显示下一个引导弹窗&#xff0c;直至最后一个引导弹窗完成后进入首页。具体效果可以点击下方视频观看或打开下方…

接口测试中缓存处理策略

在接口测试中&#xff0c;缓存处理策略是一个关键环节&#xff0c;直接影响测试结果的准确性和可靠性。合理的缓存处理策略能够确保测试环境的一致性&#xff0c;避免因缓存数据导致的测试偏差。以下是接口测试中常见的缓存处理策略及其详细说明&#xff1a; 一、缓存处理的核…

龙虎榜——20250610

上证指数放量收阴线&#xff0c;个股多数下跌&#xff0c;盘中受消息影响大幅波动。 深证指数放量收阴线形成顶分型&#xff0c;指数短线有调整的需求&#xff0c;大概需要一两天。 2025年6月10日龙虎榜行业方向分析 1. 金融科技 代表标的&#xff1a;御银股份、雄帝科技 驱动…

观成科技:隐蔽隧道工具Ligolo-ng加密流量分析

1.工具介绍 Ligolo-ng是一款由go编写的高效隧道工具&#xff0c;该工具基于TUN接口实现其功能&#xff0c;利用反向TCP/TLS连接建立一条隐蔽的通信信道&#xff0c;支持使用Let’s Encrypt自动生成证书。Ligolo-ng的通信隐蔽性体现在其支持多种连接方式&#xff0c;适应复杂网…

铭豹扩展坞 USB转网口 突然无法识别解决方法

当 USB 转网口扩展坞在一台笔记本上无法识别,但在其他电脑上正常工作时,问题通常出在笔记本自身或其与扩展坞的兼容性上。以下是系统化的定位思路和排查步骤,帮助你快速找到故障原因: 背景: 一个M-pard(铭豹)扩展坞的网卡突然无法识别了,扩展出来的三个USB接口正常。…

未来机器人的大脑:如何用神经网络模拟器实现更智能的决策?

编辑&#xff1a;陈萍萍的公主一点人工一点智能 未来机器人的大脑&#xff1a;如何用神经网络模拟器实现更智能的决策&#xff1f;RWM通过双自回归机制有效解决了复合误差、部分可观测性和随机动力学等关键挑战&#xff0c;在不依赖领域特定归纳偏见的条件下实现了卓越的预测准…

Linux应用开发之网络套接字编程(实例篇)

服务端与客户端单连接 服务端代码 #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <pthread.h> …

华为云AI开发平台ModelArts

华为云ModelArts&#xff1a;重塑AI开发流程的“智能引擎”与“创新加速器”&#xff01; 在人工智能浪潮席卷全球的2025年&#xff0c;企业拥抱AI的意愿空前高涨&#xff0c;但技术门槛高、流程复杂、资源投入巨大的现实&#xff0c;却让许多创新构想止步于实验室。数据科学家…

深度学习在微纳光子学中的应用

深度学习在微纳光子学中的主要应用方向 深度学习与微纳光子学的结合主要集中在以下几个方向&#xff1a; 逆向设计 通过神经网络快速预测微纳结构的光学响应&#xff0c;替代传统耗时的数值模拟方法。例如设计超表面、光子晶体等结构。 特征提取与优化 从复杂的光学数据中自…