py 多线程 m3u8 转mp4 过滤广告,结合ffmpeg使用

2024-09-01 08:44

本文主要是介绍py 多线程 m3u8 转mp4 过滤广告,结合ffmpeg使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

python代码:

import csv
import os
import subprocess
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urljoin
import sys
import requestsdef resource_path(relative_path):"""获取资源文件的绝对路径,兼容PyInstaller打包后的环境"""try:base_path = sys._MEIPASSexcept AttributeError:base_path = os.path.abspath(".")return os.path.join(base_path, relative_path)def process_csv(csv_file, output_dir, begin_num, max_workers=8):csv_file = resource_path(csv_file)with open(csv_file, 'r', encoding='utf-8') as file:reader = csv.reader(file)next(reader)  # 跳过表头with ThreadPoolExecutor(max_workers=max_workers) as executor:futures = []try:for index, row in enumerate(reader, start=1):if index < begin_num:continueprint(f"Processing row {index}...")title, _, m3u8_url = rowbase_name = f"{index}.m3u8"cleaned_m3u8_file_name = f"{index}_cleaned.m3u8"# 提交任务到线程池future = executor.submit(download_and_process_m3u8, m3u8_url, output_dir, base_name,cleaned_m3u8_file_name, title, index)futures.append(future)# 等待所有线程完成for future in as_completed(futures):try:future.result()except Exception as e:print(f"Task generated an exception: {e}")except KeyboardInterrupt:print("用户中断,正在取消所有任务...")for future in futures:future.cancel()executor.shutdown(wait=False)sys.exit(1)def download_and_process_m3u8(m3u8_url, output_dir, m3u8_file_name, cleaned_m3u8_file_name, title, index):m3u8_content = requests.get(m3u8_url).textprint(f"Downloaded m3u8 file from {m3u8_url}, content: {m3u8_content}")m3u8_file_path = os.path.join(output_dir, m3u8_file_name)with open(m3u8_file_path, 'w') as m3u8_file:m3u8_file.write(m3u8_content)print(f"m3u8 file downloaded and saved as {m3u8_file_path}")tsM3u8 = os.path.join(output_dir, f"{index}_ts.m3u8")download_ts_files(m3u8_file_path, m3u8_url, tsM3u8)cleaned_m3u8_file_path = os.path.join(output_dir, cleaned_m3u8_file_name)cleaned_m3u8_path = filter_advertisement(m3u8_url, tsM3u8, cleaned_m3u8_file_path)convert_to_mp4(cleaned_m3u8_path, "video_output", title, index)def download_ts_files(m3u8_file_path, m3u8_url, ts_filename):with open(m3u8_file_path, 'r') as m3u8_file:lines = m3u8_file.readlines()for line in lines:if line.startswith('#'):continuets_url = urljoin(m3u8_url, line.strip())with requests.get(ts_url, stream=True) as r:if r.status_code == 200:with open(ts_filename, 'wb') as ts_file:for chunk in r.iter_content(chunk_size=8192):ts_file.write(chunk)print(f"Downloaded {ts_filename}")else:print(f"Failed to download {ts_url}, status code: {r.status_code}")print("All .ts files have been downloaded.")def filter_advertisement(base_url, m3u8_file_path, cleaned_m3u8_file_path):with open(m3u8_file_path, 'r') as m3u8_file:lines = m3u8_file.readlines()cleaned_lines = []skip = Falsead_removed = Falsefor i, line in enumerate(lines):if line.startswith("#EXT-X-KEY") and not ad_removed:skip = Truead_removed = Trueprint(f"Removing key and associated segments starting with: {line.strip()}")continueif skip and line.startswith("#EXTINF"):continueif skip and (line.startswith("http") or line.startswith("/")):continueif line.strip().startswith("https"):last_element = cleaned_lines[-1]if last_element.startswith("#EXTINF"):cleaned_lines.pop()continueif skip and line.startswith("#EXT-X-DISCONTINUITY"):skip = Falseif not skip:cleaned_lines.append(line)new_lines = []for line in cleaned_lines:if line.startswith('#EXT-X-KEY'):uri_part = line.split('URI="')[1].split('"')[0]if not uri_part.startswith('http'):full_uri = urljoin(base_url, uri_part)line = line.replace(uri_part, full_uri)new_lines.append(line)elif line.startswith('/') and not line.startswith('http'):line = urljoin(base_url, line.strip())new_lines.append(line + "\n")else:new_lines.append(line)with open(cleaned_m3u8_file_path, 'w') as cleaned_m3u8_file:cleaned_m3u8_file.writelines(new_lines)print(f"Filtered m3u8 file saved as {cleaned_m3u8_file_path}")return cleaned_m3u8_file_pathdef convert_to_mp4(m3u8_file_path, output_dir, title, index):output_mp4 = os.path.join(output_dir, f"{index}_{title}.mp4")ffmpeg_command = ["ffmpeg","-protocol_whitelist", "file,http,https,tcp,tls,crypto","-i", m3u8_file_path,"-c", "copy","-bsf:a", "aac_adtstoasc",f"{output_mp4}"]print(f"命令行:{' '.join(ffmpeg_command)}")try:subprocess.run(ffmpeg_command, check=True)print(f"Successfully created {output_mp4}")except subprocess.CalledProcessError as e:print(f"Failed to create MP4: {e}")if __name__ == "__main__":csv_file = "ai_video.csv"output_dir = "ts_files"video_outputh = "video_output"max_workers = 4if not os.path.exists(video_outputh):os.makedirs(video_outputh)if not os.path.exists(output_dir):os.makedirs(output_dir)files = [f for f in os.listdir(video_outputh) ifos.path.isfile(os.path.join(video_outputh, f)) and not f.startswith('.')]files_sorted = sorted(files, key=lambda x: int(x.split('_')[0]))print("files:", files_sorted)begin_num = 1if files_sorted:last_file = files_sorted[-1]num = int(last_file.split('_')[0])if num > 0 and num - max_workers > 0:begin_num = num - max_workers + 1print("最后一个文件名是:", last_file, begin_num)else:print("目录中没有符合条件的文件。")try:process_csv(csv_file, output_dir, begin_num, max_workers=max_workers)except KeyboardInterrupt:print("程序被用户中断。")

写入 pip freeze > requirements.txt

打包使用github action
mkdir -p .github/workflows

name: Build Windows Executableon: [push]jobs:build:runs-on: windows-lateststeps:- name: Checkout codeuses: actions/checkout@v2- name: Set up Pythonuses: actions/setup-python@v2with:python-version: '3.12.4'  # 使用适合你的 Python 版本- name: Install dependenciesrun: |python -m pip install --upgrade pippip install pyinstaller requests  # 安装 pyinstaller 和 requestspip install -r requirements.txt  # 如果你有 requirements.txt 文件- name: Build executablerun: pyinstaller --onefile --add-data "ai_video.csv;." test_ts.py- name: Upload artifactuses: actions/upload-artifact@v2with:name: Windows Executablepath: dist/test_ts.exe

ffmpeg 常用命令


ffmpeg -i demo.mp4 -ss 1 -f image2 -vframes 1 out.jpg  // 原视频截图
ffmpeg -hide_banner -i demo.mp4 -i logo.png -filter_complex "overlay=x=xxx:y=xxx" with_watermark.mp4 -y // 原视频添加水印
ffmpeg -i with_watermark.mp4 -ss 1 -f image2 -vframes 1 with_watermark.jpg  // 对添加水印视频截图
ffmpeg -i with_watermark.mp4 -vf "delogo=x=xxx:y=xxx:w=xxx:h=xxx:show=0" -c:a copy no_watermark.mp4 // 给添加水印的视频,去除水印
ffmpeg -protocol_whitelist "file,http,https,tcp,tls,crypto" -i ./ts_files/cleaned_index.m3u8 -c copy -bsf:a aac_adtstoasc output.mp4 转成视频
ffmpeg -i "https://xxx.com/20240814/Zf8gOK3i/index.m3u8" -c copy output.ts 转视频ps网页榜:https://www.nuanque.com/ps/ffmpeg -i demo.mp4 -ss 16 -f image2 -vframes 1 out.jpg  // 原视频截图
ffmpeg -i demo.mp4 -vf "delogo=x=892:y=589:w=385:h=113:show=0" -c:a copy no_watermark.mp4 // 给添加水印的视频,去除水印
ffmpeg -i demo.mp4 -vf "delogo=x=892:y=589:w=385:h=113:show=0, delogo=x=100:y=100:w=150:h=50:show=0" -c:a copy no_watermark.mp4

这篇关于py 多线程 m3u8 转mp4 过滤广告,结合ffmpeg使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1126465

相关文章

Java使用SLF4J记录不同级别日志的示例详解

《Java使用SLF4J记录不同级别日志的示例详解》SLF4J是一个简单的日志门面,它允许在运行时选择不同的日志实现,这篇文章主要为大家详细介绍了如何使用SLF4J记录不同级别日志,感兴趣的可以了解下... 目录一、SLF4J简介二、添加依赖三、配置Logback四、记录不同级别的日志五、总结一、SLF4J

使用Python实现一个优雅的异步定时器

《使用Python实现一个优雅的异步定时器》在Python中实现定时器功能是一个常见需求,尤其是在需要周期性执行任务的场景下,本文给大家介绍了基于asyncio和threading模块,可扩展的异步定... 目录需求背景代码1. 单例事件循环的实现2. 事件循环的运行与关闭3. 定时器核心逻辑4. 启动与停

如何使用Nginx配置将80端口重定向到443端口

《如何使用Nginx配置将80端口重定向到443端口》这篇文章主要为大家详细介绍了如何将Nginx配置为将HTTP(80端口)请求重定向到HTTPS(443端口),文中的示例代码讲解详细,有需要的小伙... 目录1. 创建或编辑Nginx配置文件2. 配置HTTP重定向到HTTPS3. 配置HTTPS服务器

Python结合PyWebView库打造跨平台桌面应用

《Python结合PyWebView库打造跨平台桌面应用》随着Web技术的发展,将HTML/CSS/JavaScript与Python结合构建桌面应用成为可能,本文将系统讲解如何使用PyWebView... 目录一、技术原理与优势分析1.1 架构原理1.2 核心优势二、开发环境搭建2.1 安装依赖2.2 验

Java使用ANTLR4对Lua脚本语法校验详解

《Java使用ANTLR4对Lua脚本语法校验详解》ANTLR是一个强大的解析器生成器,用于读取、处理、执行或翻译结构化文本或二进制文件,下面就跟随小编一起看看Java如何使用ANTLR4对Lua脚本... 目录什么是ANTLR?第一个例子ANTLR4 的工作流程Lua脚本语法校验准备一个Lua Gramm

Java Optional的使用技巧与最佳实践

《JavaOptional的使用技巧与最佳实践》在Java中,Optional是用于优雅处理null的容器类,其核心目标是显式提醒开发者处理空值场景,避免NullPointerExce... 目录一、Optional 的核心用途二、使用技巧与最佳实践三、常见误区与反模式四、替代方案与扩展五、总结在 Java

使用Java将DOCX文档解析为Markdown文档的代码实现

《使用Java将DOCX文档解析为Markdown文档的代码实现》在现代文档处理中,Markdown(MD)因其简洁的语法和良好的可读性,逐渐成为开发者、技术写作者和内容创作者的首选格式,然而,许多文... 目录引言1. 工具和库介绍2. 安装依赖库3. 使用Apache POI解析DOCX文档4. 将解析

Qt中QUndoView控件的具体使用

《Qt中QUndoView控件的具体使用》QUndoView是Qt框架中用于可视化显示QUndoStack内容的控件,本文主要介绍了Qt中QUndoView控件的具体使用,具有一定的参考价值,感兴趣的... 目录引言一、QUndoView 的用途二、工作原理三、 如何与 QUnDOStack 配合使用四、自

C++使用printf语句实现进制转换的示例代码

《C++使用printf语句实现进制转换的示例代码》在C语言中,printf函数可以直接实现部分进制转换功能,通过格式说明符(formatspecifier)快速输出不同进制的数值,下面给大家分享C+... 目录一、printf 原生支持的进制转换1. 十进制、八进制、十六进制转换2. 显示进制前缀3. 指

使用Python构建一个Hexo博客发布工具

《使用Python构建一个Hexo博客发布工具》虽然Hexo的命令行工具非常强大,但对于日常的博客撰写和发布过程,我总觉得缺少一个直观的图形界面来简化操作,下面我们就来看看如何使用Python构建一个... 目录引言Hexo博客系统简介设计需求技术选择代码实现主框架界面设计核心功能实现1. 发布文章2. 加