├── background.png ├── backgroundMusic.mp3 ├── conf.py ├── requirements.txt ├── generation.py ├── preprocess.py ├── banfoTextSpider.py ├── README.md ├── train.py ├── edit.py ├── utils.py ├── mainWindow.py ├── main.py └── LICENSE /background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WithHades/banfoStyle/HEAD/background.png -------------------------------------------------------------------------------- /backgroundMusic.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WithHades/banfoStyle/HEAD/backgroundMusic.mp3 -------------------------------------------------------------------------------- /conf.py: -------------------------------------------------------------------------------- 1 | BackgroundMusic = 'backgroundMusic.mp3' 2 | DoutulaButton = 0 3 | BaiduButton = 1 4 | MODELNAME = 'gpt-cpm-small-cn-distill' 5 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | moviepy==1.0.3 2 | requests~=2.24.0 3 | numpy==1.21.2 4 | beautifulsoup4==4.10.0 5 | PyQt5==5.15.4 6 | system_hotkey==1.0.3 7 | Flask~=2.0.2 8 | bs4~=0.0.1 9 | Pillow~=8.3.2 10 | piexif~=1.1.3 11 | googletrans~=3.0.0 12 | paddlepaddle-gpu==2.1.3.post110 13 | paddlenlp~=2.1.0 -------------------------------------------------------------------------------- /generation.py: -------------------------------------------------------------------------------- 1 | import paddle 2 | import paddlenlp 3 | 4 | from conf import MODELNAME 5 | 6 | paddle.set_device('gpu') 7 | gptModel = paddlenlp.transformers.GPTModel.from_pretrained('models') 8 | gptModel = paddlenlp.transformers.GPTForPretraining(gptModel) 9 | gptModel.eval() 10 | tokenizer = paddlenlp.transformers.GPTChineseTokenizer.from_pretrained(MODELNAME) 11 | 12 | 13 | def getPredictText(text: str, length: int = 200) -> str: 14 | """ 15 | 生成半佛风格文本 16 | :param text: 前面部分的文本 17 | :param length: 生成文本长度 18 | :return: 生成的文本 19 | """ 20 | encodedText = tokenizer(text=text, return_token_type_ids=False) 21 | inputIds = paddle.to_tensor(encodedText['input_ids'], dtype='int64').unsqueeze(0) 22 | ids, _ = gptModel.generate(input_ids=inputIds, max_length=length, min_length=32, decode_strategy='sampling') 23 | ids = ids[0].numpy().tolist() 24 | # 使用tokenizer将生成的id转为文本 25 | generatedText = tokenizer.convert_ids_to_string(ids) 26 | return generatedText 27 | 28 | 29 | getPredictText('开始预测模型会先初始化一下, 抵消掉这个时间') 30 | 31 | -------------------------------------------------------------------------------- /preprocess.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pickle 3 | import paddlenlp 4 | 5 | # 加载tokeniezer 6 | from conf import MODELNAME 7 | 8 | tokenizer = paddlenlp.transformers.GPTChineseTokenizer.from_pretrained(MODELNAME) 9 | 10 | trainData = [] 11 | # 处理所有的公众号文章 12 | for index, path in enumerate(os.listdir('banfoText')): 13 | if not path.endswith('.txt'): 14 | continue 15 | print(index, path) 16 | with open(os.path.join('banfoText', path), 'r+', encoding='utf-8') as f: 17 | data = f.read() 18 | data = tokenizer(text=data, return_token_type_ids=False) 19 | data = data['input_ids'] 20 | start = -30 21 | lenght = 100 22 | step = 30 23 | if len(data) <= 2 * lenght: 24 | continue 25 | # 滑动窗口截断获取inputData和label 26 | while start + step + 1 < len(data) and start + step + lenght + 1 < len(data): 27 | start = start + step 28 | input_data = data[start: start + lenght] 29 | label = data[start + 1: start + lenght + 1] 30 | trainData.append([input_data, label]) 31 | trainData.append([data[-lenght-1: -1], data[-lenght:]]) 32 | 33 | if not os.path.exists('preprocessData'): 34 | os.mkdir('preprocessData') 35 | with open(os.path.join('preprocessData', 'trainData.pkl'), 'wb') as f: 36 | pickle.dump(trainData, f) 37 | 38 | print(len(trainData)) 39 | print('done!') 40 | -------------------------------------------------------------------------------- /banfoTextSpider.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os.path 3 | import re 4 | from collections.abc import Iterable 5 | 6 | import requests 7 | 8 | from config import BANFOMSGURL, BANFOMSGHEADERS 9 | 10 | 11 | def getAllMsgUrl(start: int = 0) -> [Iterable, None]: 12 | """ 13 | 获取半佛仙人公众号文章. 14 | :param start: 起始索引 15 | :return: None 16 | """ 17 | offset = start 18 | # 请将下面两个参数换成自己的!抓包公众号历史消息即可. 19 | while True: 20 | url = BANFOMSGURL.format(offset) 21 | headers = BANFOMSGHEADERS 22 | ret = requests.get(url, headers=headers) 23 | if ret.status_code != 200: 24 | return None 25 | data = json.loads(ret.text) 26 | if 'general_msg_list' not in data: 27 | return None 28 | can_msg_continue = data['can_msg_continue'] 29 | data = json.loads(data['general_msg_list']) 30 | data = data['list'] 31 | for msg in data: 32 | if 'app_msg_ext_info' not in msg: 33 | continue 34 | msgUrl = msg['app_msg_ext_info']['content_url'] 35 | if len(msgUrl) >= 1: 36 | yield msgUrl 37 | if can_msg_continue == 1: 38 | offset += 10 39 | else: 40 | return None 41 | 42 | 43 | def getText(msgUrl: str) -> str: 44 | """ 45 | 获取公众号单条文章的文本记录 46 | :param msgUrl: 47 | :return: 48 | """ 49 | data = requests.get(msgUrl) 50 | if data.status_code != 200: 51 | return '' 52 | pattern = '

([^(([^<]*?)|

([^<]*?)

' 53 | matchs = re.findall(pattern, data.text) 54 | ret = '' 55 | for match in matchs: 56 | ret += match[0].strip() + match[1].strip() + match[2].strip() 57 | return ret.replace('半佛仙人', '').replace('看一看入口已关闭', '') 58 | 59 | 60 | if __name__ == '__main__': 61 | for index, msgUrl in enumerate(getAllMsgUrl(start=0)): 62 | if index < 557: 63 | if index < 217 or index > 226: 64 | continue 65 | ret = getText(msgUrl) 66 | if ret == '': 67 | continue 68 | print(index, msgUrl) 69 | print(ret) 70 | with open(os.path.join('banfoText', '{}.txt'.format(index)), 'w+', encoding='utf-8') as f: 71 | f.write(ret) 72 | print('done!') 73 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 半佛视频风格生成器 2 | 3 | 视频地址: [看我如何克隆半佛仙人,批量产出视频!](https://www.bilibili.com/video/BV12v411u7kw) 4 | ## 项目背景 5 | 半佛在2020年凭借众多沙雕表情包视频 + 魔性的文案迅速出圈。正如上一句所说,一个优秀的视频需要两部分组成,优秀的文案以及优秀的视频。那么半佛的成功是否可以复制呢?我认为在一定程度上是可以复制的。那么具体应该如何复制呢?我们尝试分析一下: 6 | 7 | ### 优秀的文案 8 | 半佛仙人的文案普遍比较nice,直接分析视频的文案似乎有点儿难度。好在半佛仙人还有微信公众号,直接学习微信公众号的写作风格是一个不错的选择,但是需要我们付出比较多的时间成本,并且学习效果不够直观。有没有什么更省事更直观效果更nice的方法呢?有。得益于GPT2模型强大的文本生成能力,我们也可以借助该模型训练一个半佛仙人风格文章生成器。 9 | ### 优秀的视频 10 | 直观上来说视频的生成似乎要简单一些,事实上确实如此。半佛仙人的视频大部分是由相关性不是很强的表情包堆砌起来,我们不可能有大量精力来寻找下载一个个导入视频制作软件并设置字幕。有没有什么自动化的方法?有。搞一个图片搜索接口,不妨我们自定义一个视频制作软件。 11 | 12 | **理论存在,实践开始。** 13 | 14 | ## 思路: 15 | 我们再来详细复习一下思路,理清一下我们要做的每一件事情。 16 | ### 文案生成 17 | 直接生成大篇幅文案似乎不太现实,因为就目前来看,GPT2模型逻辑性不够强,上下文能力也有待提高,雪上加霜的是我们的电脑性能也不太行,只能采用GPT2蒸馏过后的模型,效果进一步下降,因此我们可以做一个文案提示器。当我们撰写文案的时候,轻松一按,即可生成相应的下文提示,这个思路是没有任何问题的。 18 | 1. 爬取半佛仙人微信公众号历史文章 19 | 2. 此处我们思考了一下框架的选择。不是很想在本地训练,目前体验以及部署最快的方案应该属于百度的AI Studio了。正好百度paddlenlp提供了中文GPT2预训练模型,因此我们就利用AI studio对GPT2Chinese预训练模型进行微调。 20 | 3. 数据集预处理。既然要微调自然需要预处理,由于只爬取到800+文章,为了扩大数据量,我们将滑动窗口设置的小一些。 21 | 4. 直接开整训练,数据不是很多的情况下,并不需要训练太久。百度每天8个小时免费GPU,训练几天也就ok了。 22 | 5. 写一个小小的窗口。 23 | 24 | ### 视频生成 25 | 1. 输入断句后的文案 26 | 2. 将文案根据短句分割,每句作为一条字幕 27 | 3. 根据字幕搜索表情包并选择设置 28 | 4. 利用语音合成手段合成配音 29 | 5. 重复3、4步骤,直到所有的字幕均完成表情包设定、字幕设定、配音设定 30 | 6. 合成视频并加入背景音乐 31 | 7. 导出成品 32 | 33 | ## 安装 34 | 1. 安装python3.8.3 35 | 2. 安装requirements.txt依赖 36 | 3. 运行`python main.py` 37 | 4. 运行`edit.py`请先按照百度paddlepaddle安装教程安装相应的库 38 | 39 | ## 使用 40 | 41 | ### 文案生成 42 | 1. 输入文件名或拖入文件 43 | 2. 输入文案 44 | 3. 按F1或者点击提示获取提示 45 | 4. 导出文案 46 | 5. 需要注意的是,导出文案需手动逐句分割 47 | 48 | ### 视频生成 49 | 1. 确定文件名,点击设置按钮可以新建工程。 50 | 2. 可以拖入txt格式的文案或者直接拖入软件内,或者直接增加文案。 51 | 3. 点击上一句以及下一句文案,预览区可预览字幕,搜索区可搜索相关图片/表情包。 52 | 4. 预览字幕时,若需要将一句话分为两页,则应用\n分开。 53 | 5. 所有字幕均设置完毕可进行生成视频。 54 | 6. 软件每5秒保存一次工程文件。崩溃时可重新拖放加载工程文件。工程文件位置:`material/{ProgectName}/*.bfs` 55 | 7. 工程所用到的素材默认会存放至`material/{ProgectName}/audio/`以及`material/{ProgectName}/img/` 56 | 8. 可将工程文件拖放入软件加载上一次的工程内容。需要注意的是加载工程要求素材文件夹必须存在! 57 | 9. 可将txt格式的文案拖入软件! 58 | 10. 可将表情包图片/gif文件拖入软件,用于设置当前字幕的表情包! 59 | 60 | ## TODO 61 | - [x] 优化gif显示 62 | - [x] 表情包尺寸的统一问题 63 | - [x] 编辑保存防止异常退出工作丢失 64 | - [x] 支持修改文案 65 | - [x] 文件名自定义 66 | - [x] 使用的图片与未使用的图片缓存分开,依据文件名归档 67 | - [x] 使用过的配音缓存分类归档 68 | - [x] 支持字幕不设置表情包 69 | - [x] 修复只修改字幕最后成品无效果的bug 70 | - [x] 修改单词拼写错误的小问题 71 | - [x] 支持单条字幕分割成多页, 需要分割请在单条字幕分割的地方加上\n 72 | - [ ] 自定义背景音乐 73 | - [x] 跳转到n条文案 74 | - [x] 生成视频的过程中主页面卡死问题 75 | - [x] 生成视频显示进度条 76 | - [ ] 下拉到底继续加载图片 77 | - [x] 文案生成 78 | 79 | ## Reference 80 | [一键生成半佛仙人视频,表情包之王你也可以!](https://www.bilibili.com/video/BV1oz411e7Jk) 81 | 82 | [MoviePy](https://zulko.github.io/moviepy/) 83 | 84 | [斗图啦](https://www.doutula.com/article/list/) 85 | 86 | [百度图片](https://image.baidu.com/) 87 | 88 | [百度在线语音合成](https://cloud.baidu.com/product/speech/tts_online) 89 | 90 | [百度飞桨AI studio](https://aistudio.baidu.com/aistudio/index) 91 | 92 | [百度飞桨NLP](https://paddlenlp.readthedocs.io/zh/latest/) 93 | 94 | [deepai](https://deepai.org/) 95 | 96 | ## License 97 | [GNU General Public License v3.0](LICENSE) -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pickle 3 | 4 | import paddle 5 | import paddlenlp 6 | from paddle.io import Dataset, DataLoader 7 | import paddle.nn as nn 8 | 9 | from conf import MODELNAME 10 | 11 | 12 | class BanfoDataset(Dataset): 13 | def __init__(self, data, tokenizer): 14 | super().__init__() 15 | self.data = data 16 | self.tokenizer = tokenizer 17 | 18 | def __getitem__(self, idx): 19 | return paddle.to_tensor(self.data[idx][0], dtype='int64'), paddle.to_tensor(self.data[idx][1], dtype='int64') 20 | 21 | def __len__(self): 22 | return len(self.data) 23 | 24 | 25 | if not os.path.exists('models'): 26 | os.mkdir('models') 27 | 28 | paddle.set_device('gpu') 29 | 30 | gptModel = paddlenlp.transformers.GPTModel.from_pretrained(MODELNAME) 31 | gptModel = paddlenlp.transformers.GPTForPretraining(gptModel) 32 | tokenizer = paddlenlp.transformers.GPTChineseTokenizer.from_pretrained(MODELNAME) 33 | 34 | # 有本地模型存在,则加载本地模型 35 | checkpoint = os.path.join('models', 'model_state.pdparams') 36 | if os.path.exists(checkpoint): 37 | model_state = paddle.load(checkpoint) 38 | gptModel.set_state_dict(model_state) 39 | 40 | # 设置为评估模型 41 | gptModel.eval() 42 | 43 | # 测试效果 44 | encodedText = tokenizer(text='前段时间我跟一个老大哥一起吃火锅。大哥的孩子,都上学了', return_token_type_ids=False) 45 | ids, _ = gptModel.generate(input_ids=paddle.to_tensor(encodedText['input_ids'], dtype='int64').unsqueeze(0), 46 | max_length=16, min_length=1, decode_strategy='sampling') 47 | ids = ids[0].numpy().tolist() 48 | # 使用tokenizer将生成的id转为文本 49 | text = tokenizer.convert_ids_to_string(ids) 50 | print('generation text is {}'.format(text)) 51 | 52 | # 加载训练数据 53 | with open(os.path.join('preprocessData', 'trainData.pkl'), 'rb') as f: 54 | data = pickle.load(f) 55 | 56 | trainDataLoader = DataLoader(dataset=BanfoDataset(data, tokenizer), batch_size=64, shuffle=True, return_list=True) 57 | 58 | numEpochs = 100 59 | learningRate = 2e-5 60 | warmupProportion = 0.1 61 | weightDecay = 0.1 62 | 63 | maxSteps = (len(trainDataLoader) * numEpochs) 64 | lr_scheduler = paddle.optimizer.lr.LambdaDecay(learningRate, 65 | lambda currentStep, numWarmupSteps=maxSteps * warmupProportion, numTrainingSteps=maxSteps: float(currentStep) / float(max(1, numWarmupSteps)) if currentStep < numWarmupSteps else max(0.0, float(numTrainingSteps - currentStep) / float(max(1, numTrainingSteps - numWarmupSteps)))) 66 | 67 | optimizer = paddle.optimizer.AdamW(learning_rate=lr_scheduler, 68 | parameters=gptModel.parameters(), 69 | weight_decay=weightDecay, 70 | grad_clip=nn.ClipGradByGlobalNorm(1.0), 71 | apply_decay_param_fun=lambda x: x in [ 72 | p.name for n, p in gptModel.named_parameters() 73 | if not any(nd in n for nd in ["bias", "norm"]) 74 | ]) 75 | 76 | globalStep = 1 77 | save_steps = 100 78 | criterion = paddle.nn.loss.CrossEntropyLoss() 79 | gptModel.train() 80 | for epoch in range(numEpochs): 81 | for step, batch in enumerate(trainDataLoader, start=1): 82 | ids, label = batch 83 | logits, _ = gptModel.forward(ids, use_cache=True) 84 | loss = criterion(logits, label) 85 | loss.backward() 86 | optimizer.step() 87 | lr_scheduler.step() 88 | optimizer.clear_gradients() 89 | if globalStep % save_steps == 0: 90 | print(globalStep, loss.numpy()) 91 | gptModel.save_pretrained('models') 92 | globalStep += 1 93 | -------------------------------------------------------------------------------- /edit.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Form implementation generated from reading ui file 'edit.ui' 4 | # 5 | # Created by: PyQt5 UI code generator 5.15.4 6 | # 7 | # WARNING: Any manual changes made to this file will be lost when pyuic5 is 8 | # run again. Do not edit this file unless you know what you are doing. 9 | import os 10 | import sys 11 | import time 12 | 13 | from PyQt5 import QtCore, QtWidgets 14 | from PyQt5.QtCore import QThread, pyqtSignal, QObject 15 | from system_hotkey import SystemHotkey 16 | 17 | from generation import getPredictText 18 | from utils import getTips 19 | 20 | 21 | class getTipsThread(QThread): 22 | """ 23 | 获取提示线程类 24 | """ 25 | signal = pyqtSignal(str) 26 | 27 | def __init__(self, mText: str) -> None: 28 | """ 29 | 初始化获取提示线程类 30 | :param mText: 关键词句 31 | """ 32 | super().__init__() 33 | self.text = mText 34 | 35 | def __del__(self): 36 | self.wait() 37 | 38 | def run(self): 39 | """ 40 | 文本生成 41 | :return: None 42 | """ 43 | 44 | ''' 45 | # 使用deepai的文本生成服务 46 | text = getTips(self.text) 47 | self.signal.emit(text) 48 | ''' 49 | 50 | text = getPredictText(self.text.replace('\n', ''), length=500) 51 | self.signal.emit(text) 52 | 53 | 54 | 55 | class Ui_MainWindow(QObject): 56 | 57 | hotkeySign = pyqtSignal() 58 | 59 | def __init__(self): 60 | super().__init__() 61 | self.subThread = None 62 | self.fileName = None 63 | 64 | def setupUi(self, MainWindow): 65 | MainWindow.resize(862, 579) 66 | self.mainWindow = MainWindow 67 | self.centralwidget = QtWidgets.QWidget(MainWindow) 68 | 69 | # 文案输入&编辑框 70 | self.writingEdit = QtWidgets.QPlainTextEdit(self.centralwidget) 71 | self.writingEdit.setGeometry(QtCore.QRect(10, 10, 431, 501)) 72 | 73 | # 给文案提示加个框框 74 | self.groupBox = QtWidgets.QGroupBox(self.centralwidget) 75 | self.groupBox.setGeometry(QtCore.QRect(450, 10, 401, 501)) 76 | self.groupBox.setCheckable(False) 77 | self.groupBox.setTitle('提示') 78 | 79 | # 文案提示框框 80 | self.tipsEdit = QtWidgets.QPlainTextEdit(self.groupBox) 81 | self.tipsEdit.setGeometry(QtCore.QRect(10, 20, 381, 471)) 82 | 83 | # 文件名 84 | self.FileNameLabel = QtWidgets.QLabel(self.centralwidget) 85 | self.FileNameLabel.setGeometry(QtCore.QRect(10, 520, 101, 31)) 86 | self.FileNameLabel.setText('文件路径:') 87 | self.fileNameEdit = QtWidgets.QLineEdit(self.centralwidget) 88 | self.fileNameEdit.setGeometry(QtCore.QRect(90, 520, 351, 31)) 89 | 90 | # 三个按钮水平分布 91 | self.horizontalLayoutWidget = QtWidgets.QWidget(self.centralwidget) 92 | self.horizontalLayoutWidget.setGeometry(QtCore.QRect(450, 514, 401, 41)) 93 | self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget) 94 | self.horizontalLayout.setContentsMargins(0, 0, 0, 0) 95 | self.horizontalLayout.setObjectName('horizontalLayout') 96 | 97 | # 打开 98 | self.openButton = QtWidgets.QPushButton(self.horizontalLayoutWidget) 99 | self.openButton.setText('打开') 100 | self.openButton.clicked.connect(self.openFile) 101 | self.horizontalLayout.addWidget(self.openButton) 102 | 103 | # 保存 104 | self.saveButton = QtWidgets.QPushButton(self.horizontalLayoutWidget) 105 | self.saveButton.setText('保存') 106 | self.saveButton.clicked.connect(self.saveFile) 107 | self.horizontalLayout.addWidget(self.saveButton) 108 | 109 | # 提示 110 | self.tipsButton = QtWidgets.QPushButton(self.horizontalLayoutWidget) 111 | self.tipsButton.setText('提示') 112 | self.tipsButton.clicked.connect(self.tips) 113 | self.horizontalLayout.addWidget(self.tipsButton) 114 | 115 | # 热键 116 | self.hotkeySign.connect(self.tips) 117 | self.F1Hotkey = SystemHotkey() 118 | self.F1Hotkey.register(['f1'], callback=lambda x: self.hotkeyEvent()) 119 | 120 | MainWindow.setCentralWidget(self.centralwidget) 121 | QtCore.QMetaObject.connectSlotsByName(MainWindow) 122 | 123 | def hotkeyEvent(self): 124 | self.hotkeySign.emit() 125 | 126 | def msgBox(self, msg: str, hasQuery: bool = False) -> bool: 127 | """ 128 | :param msg: 消息 129 | :param hasQuery: 是否带询问 130 | :return: 如果hasQuery为True,返回值为用户是否点击了确定 131 | """ 132 | if not hasQuery: 133 | QtWidgets.QMessageBox.information(self.mainWindow, '提示', msg, QtWidgets.QMessageBox.Ok, 134 | QtWidgets.QMessageBox.Ok) 135 | return True 136 | reply = QtWidgets.QMessageBox.question(self.mainWindow, '提示', msg, 137 | QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel, 138 | QtWidgets.QMessageBox.Cancel) 139 | return reply == QtWidgets.QMessageBox.Yes 140 | 141 | def openFile(self) -> None: 142 | """ 143 | 打开一个文件 144 | :return: None 145 | """ 146 | fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self.mainWindow, '选择文案', os.path.join(os.getcwd(), 'writing'), 'Text Files (*.txt)') 147 | if not os.path.exists(fileName): 148 | self.msgBox('未选择文件!') 149 | return 150 | with open(fileName, 'r+', encoding='UTF-8') as f: 151 | data = f.read() 152 | self.writingEdit.appendPlainText(data) 153 | self.fileName = fileName 154 | self.fileNameEdit.setText(fileName) 155 | 156 | def saveFile(self) -> None: 157 | """ 158 | 保存文件 159 | :return: None 160 | """ 161 | fileName = self.fileNameEdit.text() 162 | if os.path.sep not in fileName: 163 | if fileName == '': 164 | self.msgBox('请先设置文件名!') 165 | return 166 | if len(fileName) <= 4: 167 | self.msgBox('文件名非法!') 168 | return 169 | fileName = os.path.join('writing', fileName) 170 | if not os.path.exists('writing'): 171 | os.mkdir('writing') 172 | self.fileName = fileName 173 | with open(fileName, 'w+', encoding='UTF-8') as f: 174 | f.write(self.writingEdit.toPlainText()) 175 | self.msgBox('文件已保存在{}'.format(fileName)) 176 | 177 | def tips(self) -> None: 178 | text = self.writingEdit.toPlainText() 179 | if text == '': 180 | return 181 | self.tipsEdit.setPlainText('') 182 | if self.subThread is not None: 183 | self.subThread.terminate() 184 | while self.subThread.isRunning() and not self.subThread.isFinished(): 185 | time.sleep(0.1) 186 | self.subThread = getTipsThread(self.writingEdit.toPlainText()) 187 | self.subThread.signal.connect(self.setTips) 188 | self.subThread.start() 189 | 190 | def setTips(self, text: str) -> None: 191 | """ 192 | 设置提示 193 | :param text: 提示文本 194 | :return: None 195 | """ 196 | self.tipsEdit.setPlainText(text) 197 | 198 | 199 | if __name__ == "__main__": 200 | app = QtWidgets.QApplication(sys.argv) 201 | MainWindow = QtWidgets.QMainWindow() 202 | ui = Ui_MainWindow() 203 | ui.setupUi(MainWindow) 204 | MainWindow.show() 205 | sys.exit(app.exec_()) 206 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import hashlib 3 | import json 4 | import os 5 | import random 6 | from collections.abc import Iterable 7 | from urllib.parse import quote 8 | 9 | import piexif 10 | import requests 11 | from PIL import Image 12 | from bs4 import BeautifulSoup 13 | 14 | from config import APIKEY, BAIDUAPPID, BAIDUAPPKEY 15 | 16 | proxies = None 17 | verify = True 18 | 19 | 20 | def getUuid() -> str: 21 | """ 22 | 生成一个uuid 23 | :return: uuid 24 | """ 25 | return str(random.randint(1, 999999)).zfill(6) 26 | 27 | 28 | def getBaiDuAudio(text: str, filePath: str) -> [str, None]: 29 | """ 30 | 利用百度语音合成将文字合成语音 31 | :param text: 合成语音的文字 32 | :param filePath: 文件保存路径 33 | :return: 文件路径或者None 34 | """ 35 | # 生成文件名 36 | md5 = hashlib.md5() 37 | md5.update(text.encode('utf-8')) 38 | fileName = md5.hexdigest() + '.mp3' 39 | fileName = os.path.join(filePath, fileName) 40 | # 文件已经存在的话直接返回 41 | if os.path.exists(fileName): 42 | return fileName 43 | 44 | url = 'https://cloud.baidu.com/aidemo' 45 | data = 'type=tns&per=4105&spd=8&pit=7&vol=5&aue=6&tex=' + quote(text) 46 | headers = { 47 | 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36', 48 | 'Content-Type': 'application/x-www-form-urlencoded', 49 | 'Accept': '*/*', 50 | 'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7' 51 | } 52 | res = requests.post(url, data=data, headers=headers, verify=False) 53 | if res.status_code != 200: 54 | return None 55 | res = json.loads(res.text) 56 | if res['msg'] != 'success': 57 | return None 58 | data = res['data'].replace('data:audio/x-mpeg;base64,', '') 59 | if ',' in data: 60 | data = data[:data.find(',')] 61 | data = base64.b64decode(data) 62 | with open(fileName, 'wb') as f: 63 | f.write(data) 64 | return fileName 65 | 66 | 67 | def decodeBaiduImg(objUrl: str) -> str: 68 | """ 69 | 百度图片地址解码函数 70 | :param objUrl: 编码的url 71 | :return: 解码的url 72 | """ 73 | res = '' 74 | c = ['_z2C$q', '_z&e3B', 'AzdH3F'] 75 | d = {'w': 'a', 76 | 'k': 'b', 77 | 'v': 'c', 78 | '1': 'd', 79 | 'j': 'e', 80 | 'u': 'f', 81 | '2': 'g', 82 | 'i': 'h', 83 | 't': 'i', 84 | '3': 'j', 85 | 'h': 'k', 86 | 's': 'l', 87 | '4': 'm', 88 | 'g': 'n', 89 | '5': 'o', 90 | 'r': 'p', 91 | 'q': 'q', 92 | '6': 'r', 93 | 'f': 's', 94 | 'p': 't', 95 | '7': 'u', 96 | 'e': 'v', 97 | 'o': 'w', 98 | '8': '1', 99 | 'd': '2', 100 | 'n': '3', 101 | '9': '4', 102 | 'c': '5', 103 | 'm': '6', 104 | '0': '7', 105 | 'b': '8', 106 | 'l': '9', 107 | 'a': '0', 108 | '_z2C$q': ':', 109 | '_z&e3B': '.', 110 | 'AzdH3F': '/'} 111 | for m in c: 112 | objUrl = objUrl.replace(m, d[m]) 113 | for char in objUrl: 114 | char = d[char] if char in d else char 115 | res = res + char 116 | return res 117 | 118 | 119 | def getBaiduImgPath(text: str) -> [Iterable, None]: 120 | """ 121 | 从百度图片接口拉取图片 122 | :param text: 搜索关键字 123 | :return: 图片路径迭代器或者None 124 | """ 125 | url = 'https://image.baidu.com/search/acjson?tn=resultjson_com&logid=8763701186511659178&ipn=rj&ct=201326592&is=' \ 126 | '&fp=result&queryWord={0}&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=0&hd=&latest=©right=&word={0}' \ 127 | '&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&nojc=&acjsonfr=click&pn=0&rn=30&itg=1' \ 128 | '&gsm=3c&1634043752626=' 129 | url = url.format(text) 130 | headers = { 131 | 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36', 132 | 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 133 | 'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'} 134 | res = requests.get(url, headers=headers, verify=False) 135 | if res.status_code != 200: 136 | return None 137 | try: 138 | jsonData = json.loads(res.text) 139 | except: 140 | return None 141 | if 'data' not in jsonData: 142 | return None 143 | data = jsonData['data'] 144 | for img in data: 145 | imgUrl = '' 146 | if 'objURL' in img: 147 | imgUrl = decodeBaiduImg(img['objURL']) 148 | elif 'middleURL' in img: 149 | imgUrl = img['middleURL'] 150 | elif 'thumbURL' in img: 151 | imgUrl = img['thumbURL'] 152 | elif imgUrl == '': 153 | return None 154 | if 'is_gif' in img and img['is_gif'] == 1: 155 | is_gif = 1 156 | else: 157 | is_gif = 0 158 | res = requests.get(imgUrl) 159 | if res.status_code != 200: 160 | continue 161 | md5 = hashlib.md5() 162 | md5.update(res.content) 163 | fileName = md5.hexdigest() + '.gif' if is_gif else md5.hexdigest() + '.png' 164 | path = os.path.join('tmp', fileName) 165 | with open(path, 'wb') as f: 166 | f.write(res.content) 167 | yield path 168 | 169 | 170 | def getDoutulaImgPath(text: str) -> [Iterable, None]: 171 | """ 172 | 从斗图啦表情包接口拉取图片 173 | :param text: 搜索关键字 174 | :return: 图片路径迭代器或者None 175 | """ 176 | url = 'https://www.doutula.com/search?keyword=' + text 177 | headers = { 178 | 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36', 179 | 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 180 | 'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'} 181 | res = requests.get(url, headers=headers) 182 | if res.status_code != 200: 183 | return None 184 | soup = BeautifulSoup(res.text, 'html.parser') 185 | randomPics = soup.find_all('a', attrs={'class': 'col-xs-6 col-md-2'}) 186 | for pic in randomPics: 187 | imgUrl = pic.find('img', attrs={'referrerpolicy': 'no-referrer'})['data-original'] 188 | try: 189 | res = requests.get(imgUrl) 190 | except: 191 | return None 192 | if res.status_code != 200: 193 | continue 194 | path = os.path.join('tmp', imgUrl[imgUrl.rfind('/') + 1:]) 195 | with open(path, 'wb') as f: 196 | f.write(res.content) 197 | yield path 198 | 199 | 200 | def resizeImg(width: int, height: int) -> (int, int): 201 | """ 202 | 重新设置图片大小 203 | :param width: 图片宽度 204 | :param height: 图片高度 205 | :return: (width, height) 206 | """ 207 | default_width, default_height = 440, 360 208 | if (width < default_width and height < default_height) or (width > default_width and height > default_height): 209 | # 如果比例大于1.5,就不强制拉伸,按照宽度进行缩放 210 | if width / height >= 1.5: 211 | width, height = default_width, height * default_width / width 212 | elif height / width > 1.5: 213 | height, width = default_height, width * default_height / height 214 | else: 215 | # 小于1.5的强制拉伸 216 | width, height = default_width, default_height 217 | elif width > default_width and height <= default_height: 218 | width, height = default_width, height * default_width / width 219 | if height > default_height and width <= default_width: 220 | height, width = default_height, width * default_height / height 221 | return width, height 222 | 223 | 224 | def convertToRGB(path: str) -> None: 225 | """ 226 | 如果图片不是RGB模式,则转换成RGB模式,否则生成视频会出错 227 | :param path: 图片路径 228 | :return: None 229 | """ 230 | # convert to RGB 231 | im = Image.open(path) 232 | if im.mode != 'RGB': 233 | im = im.convert('RGB') 234 | 235 | # 获取exif是否正常,不正常则添加 236 | try: 237 | im.getexif() 238 | im.save(path) 239 | except: 240 | exif_dict = {} 241 | exif_dat = piexif.dump(exif_dict) 242 | im.save(path, exif=exif_dat) 243 | 244 | 245 | def baiduTranslate(text: str, zhcn2en: bool = True) -> str: 246 | """ 247 | 将中文翻译成英文 248 | :param text: 中文/英文 249 | :param zhcn2en : 是否为中文转英文, 默认为是 250 | :return: 英文/中文 251 | """ 252 | url = 'https://fanyi-api.baidu.com/api/trans/vip/translate' 253 | headers = {'Content-Type': 'application/x-www-form-urlencoded'} 254 | data = BAIDUAPPID + text + url + BAIDUAPPKEY 255 | md5 = hashlib.md5() 256 | md5.update(data.encode('utf-8')) 257 | if zhcn2en: 258 | data = {'appid': BAIDUAPPID, 'q': text, 'from': 'zh', 'to': 'en', 'salt': url, 'sign': md5.hexdigest()} 259 | else: 260 | data = {'appid': BAIDUAPPID, 'q': text, 'from': 'en', 'to': 'zh', 'salt': url, 'sign': md5.hexdigest()} 261 | res = requests.post(url, data=data, headers=headers) 262 | if res.status_code != 200: 263 | return '' 264 | res = json.loads(res.text) 265 | if 'trans_result' not in res: 266 | return '' 267 | result = '' 268 | for trans in res['trans_result']: 269 | result += trans['dst'] + '。' 270 | return result 271 | 272 | 273 | # TODO 274 | # 有点儿问题, 翻译的结果为多行的时候解决比较麻烦 275 | def googleTranslate(text: str, zhcn2en: bool = True) -> str: 276 | """ 277 | 将中文翻译成英文 278 | :param text: 中文/英文 279 | :param zhcn2en : 是否为中文转英文, 默认为是 280 | :return: 英文/中文 281 | """ 282 | global proxies 283 | global verify 284 | text = text.replace('\n', r'\\n').replace('"', r'\\\"') 285 | url = 'https://translate.google.cn/_/TranslateWebserverUi/data/batchexecute' 286 | if zhcn2en: 287 | data = '[[["MkEWBc","[[\\"{}\\",\\"zh-CN\\",\\"en\\",true],[null]]",null,"generic"]]]'.format(text) 288 | else: 289 | data = '[[["MkEWBc","[[\\"{}\\",\\"en\\",\\"zh-CN\\",true],[null]]",null,"generic"]]]'.format(text) 290 | data = quote(data) 291 | data = 'f.req=' + data + '&' 292 | headers = { 293 | 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36', 294 | 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 295 | 'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'} 296 | res = requests.post(url=url, data=data, headers=headers, verify=verify, proxies=proxies) 297 | if res.status_code != 200: 298 | return '' 299 | lIndex = res.text.find('l,[[\\"') 300 | rIndex = res.text.find('\\"', lIndex + len('l,[[\\"')) 301 | if lIndex != -1 and rIndex != -1: 302 | text = res.text[lIndex + len('l,[[\\"'):rIndex] 303 | text = text.replace(r'\\n', '\n').replace(r'\\\"', '"') 304 | return text 305 | return '' 306 | 307 | 308 | def getTips(text: str) -> str: 309 | """ 310 | 获取指定文本的生成文本信息 311 | :param text: 线索文本 312 | :return: 生成的文本 313 | """ 314 | global proxies 315 | global verify 316 | # 中文 -> 英文 317 | text = baiduTranslate(text) 318 | if text == '': 319 | return '' 320 | # 获取生成文本结果 321 | url = 'https://api.deepai.org/api/text-generator' 322 | data = {'text': text} 323 | headers = {'api-key': APIKEY} 324 | res = requests.post(url, files=data, headers=headers, verify=verify, proxies=proxies) 325 | if res.status_code != 200: 326 | return '' 327 | res = json.loads(res.text) 328 | if 'output' not in res: 329 | return '' 330 | text = res['output'] 331 | # 英文 -> 中文 332 | text = baiduTranslate(text, zhcn2en=False).replace('\n\n', '\n') 333 | return text 334 | 335 | 336 | def setProxies(switch: bool=False) -> None: 337 | """ 338 | 是否采用代理 339 | :param switch: 是 340 | :return: None 341 | """ 342 | global proxies 343 | global verify 344 | if switch: 345 | proxies = {'https': '127.0.0.1:8887', 346 | 'http': '127.0.0.1:8887'} 347 | verify = False 348 | else: 349 | proxies = None 350 | verify = True 351 | -------------------------------------------------------------------------------- /mainWindow.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Form implementation generated from reading ui file 'mainWindow.ui' 4 | # 5 | # Created by: PyQt5 UI code generator 5.15.4 6 | # 7 | # WARNING: Any manual changes made to this file will be lost when pyuic5 is 8 | # run again. Do not edit this file unless you know what you are doing. 9 | import math 10 | import os.path 11 | import shutil 12 | import time 13 | 14 | from PyQt5 import QtCore, QtGui, QtWidgets 15 | from PyQt5.QtGui import QMovie, QStandardItemModel, QStandardItem 16 | from moviepy.video.VideoClip import ImageClip 17 | from moviepy.video.io.VideoFileClip import VideoFileClip 18 | 19 | from conf import DoutulaButton, BaiduButton 20 | from utils import resizeImg 21 | 22 | 23 | class clickedButton(QtWidgets.QPushButton): 24 | """ 25 | 搜索表情包按钮事件,主要可以区分哪个按钮 26 | """ 27 | clicked = QtCore.pyqtSignal(int) 28 | 29 | def __init__(self, button, parent=None): 30 | super(clickedButton, self).__init__(parent) 31 | self.button = button 32 | 33 | def mouseReleaseEvent(self, QMouseEvent): 34 | self.clicked.emit(self.button) 35 | 36 | 37 | class clickedLabel(QtWidgets.QLabel): 38 | """ 39 | 标签类,主要增加了点击事件,用于图片缓存区,用户点击了图片后可知道点击了哪张图 40 | """ 41 | clicked = QtCore.pyqtSignal(int) 42 | 43 | def __init__(self, index: int, parent=None): 44 | """ 45 | :param index: 图片索引 46 | :param parent: 47 | """ 48 | super(clickedLabel, self).__init__(parent) 49 | self.index = index 50 | 51 | def mouseReleaseEvent(self, QMouseEvent): 52 | self.clicked.emit(self.index) 53 | 54 | 55 | class Ui_MainWindow(object): 56 | def __init__(self): 57 | # 所有缓存的图片 58 | self.img = [] 59 | # 当前视频预览区gif 60 | self.gif = None 61 | # 当前视频预览区图片 62 | self.videoImg = None 63 | 64 | def setupUi(self, MainWindow): 65 | # 初始设置窗口信息 66 | MainWindow.setObjectName('MainWindow') 67 | MainWindow.resize(1890, 702) 68 | MainWindow.setLayoutDirection(QtCore.Qt.LeftToRight) 69 | MainWindow.setWindowTitle('半佛风格视频生成') 70 | 71 | self.mainWindow = MainWindow 72 | self.centralwidget = QtWidgets.QWidget(MainWindow) 73 | 74 | # 输入文件名标签 75 | self.fileLabel = QtWidgets.QLabel(self.centralwidget) 76 | self.fileLabel.setGeometry(QtCore.QRect(10, 23, 121, 16)) 77 | self.fileLabel.setText('导出视频名称: ') 78 | 79 | # 文件名 80 | self.filenName = QtWidgets.QLineEdit(self.centralwidget) 81 | self.filenName.setGeometry(QtCore.QRect(140, 16, 361, 31)) 82 | self.filenName.setText('{}.mp4'.format(int(time.time()))) 83 | 84 | # 输入文件名确定按钮 85 | self.filenameButton = QtWidgets.QPushButton(self.centralwidget) 86 | self.filenameButton.setGeometry(QtCore.QRect(501, 16, 60, 31)) 87 | self.filenameButton.setText('设置') 88 | self.filenameButton.clicked.connect(MainWindow.setFilename) 89 | 90 | # 给输入框加个分组box 91 | self.groupBox = QtWidgets.QGroupBox(self.centralwidget) 92 | self.groupBox.setGeometry(QtCore.QRect(0, 53, 561, 618)) 93 | self.groupBox.setTitle('在此输入/编辑文案') 94 | 95 | # 文案以表格的形式展示 96 | self.model = QStandardItemModel(0, 0) 97 | self.model.itemChanged.connect(MainWindow.tableItemChange) 98 | # 设置水平方向四个头标签文本内容 99 | self.model.setHorizontalHeaderLabels(['文案&字幕']) 100 | self.row = 0 101 | self.tableView = QtWidgets.QTableView(self.groupBox) 102 | self.tableView.setGeometry(QtCore.QRect(10, 20, 541, 542)) 103 | self.tableView.setShowGrid(True) 104 | self.tableView.setModel(self.model) 105 | self.tableView.horizontalHeader().setStretchLastSection(True) 106 | self.tableView.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch) 107 | self.tableView.clicked.connect(MainWindow.jumpToIndex) 108 | 109 | # 打开文案/前增一句/后增一句/删除一句/修改一句/导出文案按钮布局 110 | self.tableButtonWidget = QtWidgets.QWidget(self.groupBox) 111 | self.tableButtonWidget.setGeometry(QtCore.QRect(10, 561, 541, 55)) 112 | # 水平分布 113 | self.hbox = QtWidgets.QHBoxLayout() 114 | self.hbox.setGeometry(QtCore.QRect()) 115 | self.hbox.setContentsMargins(0, 0, 0, 0) 116 | # 打开文案 117 | self.openText = QtWidgets.QPushButton() 118 | self.openText.setText('打开') 119 | self.openText.clicked.connect(MainWindow.loadText) 120 | self.hbox.addWidget(self.openText) 121 | # 在前面增加一句 122 | self.addFrontText = QtWidgets.QPushButton() 123 | self.addFrontText.setText('前增一句') 124 | self.addFrontText.clicked.connect(MainWindow.addFrontText) 125 | self.hbox.addWidget(self.addFrontText) 126 | # 在后面增加一句 127 | self.addBehindText = QtWidgets.QPushButton() 128 | self.addBehindText.setText('后增一句') 129 | self.addBehindText.clicked.connect(MainWindow.addBehindText) 130 | self.hbox.addWidget(self.addBehindText) 131 | # 删除该句 132 | self.delText = QtWidgets.QPushButton() 133 | self.delText.setText('删除该句') 134 | self.delText.clicked.connect(MainWindow.delText) 135 | self.hbox.addWidget(self.delText) 136 | # 导出文案 137 | self.exportText = QtWidgets.QPushButton() 138 | self.exportText.setText('导出文案') 139 | self.exportText.clicked.connect(MainWindow.exportText) 140 | self.hbox.addWidget(self.exportText) 141 | self.tableButtonWidget.setLayout(self.hbox) 142 | 143 | # 单句字幕 144 | self.singleText = QtWidgets.QLineEdit(self.centralwidget) 145 | self.singleText.setGeometry(QtCore.QRect(660, 620, 611, 50)) 146 | self.singleText.textChanged.connect(MainWindow.changeThePicText) 147 | 148 | # 搜索框文本 149 | self.searchText = QtWidgets.QLineEdit(self.centralwidget) 150 | self.searchText.setGeometry(QtCore.QRect(1360, 17, 421, 41)) 151 | 152 | # 斗图啦/百度搜索按钮 153 | self.searchDou = clickedButton(DoutulaButton, self.centralwidget) 154 | self.searchDou.setGeometry(QtCore.QRect(1785, 17, 45, 41)) 155 | self.searchDou.setText('斗图') 156 | self.searchDou.clicked.connect(MainWindow.search) 157 | 158 | self.searchBai = clickedButton(BaiduButton, self.centralwidget) 159 | self.searchBai.setGeometry(QtCore.QRect(1834, 17, 45, 41)) 160 | self.searchBai.setText('百度') 161 | self.searchBai.clicked.connect(MainWindow.search) 162 | 163 | # 视频背景图 164 | self.videoBackgroud = QtWidgets.QLabel(self.centralwidget) 165 | self.videoBackgroud.setGeometry(QtCore.QRect(560, 16, 800, 600)) 166 | self.videoBackgroud.setPixmap(QtGui.QPixmap('background.png')) 167 | self.videoBackgroud.setScaledContents(True) 168 | 169 | # 视频字幕 170 | self.addSubtitleLayout() 171 | 172 | # 上一句按钮 173 | self.last = QtWidgets.QPushButton(self.centralwidget) 174 | self.last.setGeometry(QtCore.QRect(560, 620, 101, 51)) 175 | self.last.setText('上一句') 176 | self.last.clicked.connect(MainWindow.last) 177 | 178 | # 下一句按钮 179 | self.next = QtWidgets.QPushButton(self.centralwidget) 180 | self.next.setGeometry(QtCore.QRect(1270, 620, 91, 51)) 181 | self.next.setText('下一句') 182 | self.next.clicked.connect(MainWindow.next) 183 | 184 | # 生成视频按钮 185 | self.genVideo = QtWidgets.QPushButton(self.centralwidget) 186 | self.genVideo.setGeometry(QtCore.QRect(1360, 620, 521, 51)) 187 | self.genVideo.setText('生成视频') 188 | self.genVideo.clicked.connect(MainWindow.genVideo) 189 | 190 | # 表情包图片位置布局 191 | self.widget = QtWidgets.QWidget(self.centralwidget) 192 | self.widget.setGeometry(QtCore.QRect(1349, 48, 540, 579)) 193 | self.topFiller = QtWidgets.QWidget() 194 | self.scroll = QtWidgets.QScrollArea() 195 | self.scroll.setWidget(self.topFiller) 196 | self.vbox = QtWidgets.QVBoxLayout() 197 | self.vbox.addWidget(self.scroll) 198 | self.widget.setLayout(self.vbox) 199 | 200 | QtCore.QMetaObject.connectSlotsByName(MainWindow) 201 | 202 | def addSubtitleLayout(self) -> None: 203 | """ 204 | 视频字幕设置布局 205 | :return: 206 | """ 207 | # 视频字幕 208 | self.videoText = QtWidgets.QLabel(self.centralwidget) 209 | self.videoText.setGeometry(QtCore.QRect(560, 526, 801, 51)) 210 | # 视频字幕字体颜色 211 | palette = QtGui.QPalette() 212 | brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) 213 | brush.setStyle(QtCore.Qt.SolidPattern) 214 | palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) 215 | brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) 216 | brush.setStyle(QtCore.Qt.SolidPattern) 217 | palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) 218 | brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) 219 | brush.setStyle(QtCore.Qt.SolidPattern) 220 | palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) 221 | self.videoText.setPalette(palette) 222 | # 视频字幕字体设置 223 | font = QtGui.QFont() 224 | font.setFamily('华文楷体') 225 | font.setPointSize(20) 226 | self.videoText.setFont(font) 227 | self.videoText.setTextFormat(QtCore.Qt.PlainText) 228 | self.videoText.setScaledContents(False) 229 | self.videoText.setAlignment(QtCore.Qt.AlignCenter) 230 | self.videoText.setWordWrap(False) 231 | 232 | def delVideoImg(self) -> None: 233 | """ 234 | 清空视频预览区图片 235 | :return: None 236 | """ 237 | if self.videoImg is not None: 238 | self.videoImg.deleteLater() 239 | self.videoImg = None 240 | if self.gif is not None: 241 | self.gif.deleteLater() 242 | self.gif = None 243 | 244 | def getResizedOfVideoImg(self, path) -> (int, int): 245 | """ 246 | 获取路径图片重新调整过的大小 247 | :param path: 图片路径 248 | :return: (width, height) 249 | """ 250 | try: 251 | clip = VideoFileClip(path) 252 | except: 253 | clip = ImageClip(path) 254 | width, height = clip.size 255 | return resizeImg(width, height) 256 | 257 | def changeVideoImg(self, path: str) -> None: 258 | """ 259 | 加载图片到视频预览区 260 | :param path: 图片路径 261 | :return: None 262 | """ 263 | # 如果图片不是在tmp目录保存,则转到tmp目录再加载,不然重命名工程会有问题 264 | if not path.startswith('tmp' + os.path.sep): 265 | newPath = os.path.join('tmp', os.path.basename(path)) 266 | if not os.path.exists(newPath): 267 | shutil.copyfile(path, newPath) 268 | path = newPath 269 | self.delVideoImg() 270 | self.videoImg = QtWidgets.QLabel(self.centralwidget) 271 | wight, height = self.getResizedOfVideoImg(path) 272 | self.videoImg.setGeometry(QtCore.QRect(int(960 - wight / 2), int(316 - height / 2), wight, height)) 273 | self.videoImg.setScaledContents(True) 274 | self.gif = QMovie(path) 275 | self.videoImg.setMovie(self.gif) 276 | self.videoImg.setAlignment(QtCore.Qt.AlignCenter) 277 | self.gif.start() 278 | self.videoImg.show() 279 | self.centralwidget.show() 280 | 281 | def addImg(self, path: str) -> None: 282 | """ 283 | 给图片缓存区加一张图片 284 | :param path: 图片路径 285 | :return: None 286 | """ 287 | # 计算图片框位置 288 | row = math.ceil((len(self.img) + 1) / 3) - 1 289 | col = len(self.img) % 3 290 | 291 | img_label = clickedLabel(len(self.img), self.topFiller) 292 | img_label.setGeometry(QtCore.QRect(1370, 60, 151, 151)) 293 | gif = QMovie(path) 294 | img_label.setMovie(gif) 295 | img_label.setScaledContents(True) 296 | gif.start() 297 | img_label.move(col * (151 + 10) + 10, row * (151 + 10) + 10) 298 | self.img.append((img_label, gif, path)) 299 | self.topFiller.setMinimumSize(490, (row + 1) * (151 + 10)) 300 | self.scroll.setWidget(self.topFiller) 301 | img_label.clicked.connect(self.mainWindow.imgClicked) 302 | img_label.show() 303 | self.topFiller.show() 304 | self.widget.show() 305 | 306 | def delImg(self) -> None: 307 | """ 308 | 清空从网络获取的所有的表情包 309 | :return: None 310 | """ 311 | for imgLabel, gif, _ in self.img: 312 | imgLabel.deleteLater() 313 | gif.deleteLater() 314 | self.img = [] 315 | self.widget.show() 316 | 317 | def getImgPathByIndex(self, index: int) -> str: 318 | """ 319 | 通过表情包缓存区的索引获取表情包的实际路径 320 | :param index: 表情包缓存区的索引 321 | :return: 表情包的实际位置 322 | """ 323 | return self.img[index][2] 324 | 325 | def addRow(self, text: str) -> None: 326 | """ 327 | 向表中添加一行新的数据 328 | :param text: 329 | :return: 330 | """ 331 | item = QStandardItem(text) 332 | self.model.setItem(self.row, 0, item) 333 | self.row += 1 334 | 335 | def delRow(self, row: int) -> None: 336 | """ 337 | 删除一行表中的数据 338 | :param row: 删除索引 339 | :return: 340 | """ 341 | self.model.removeRow(row) 342 | 343 | def delAllRow(self) -> None: 344 | """ 345 | 删除所有行 346 | :return: 347 | """ 348 | for index in range(self.model.rowCount())[::-1]: 349 | self.delRow(index) 350 | 351 | def msgBox(self, msg: str, hasQuery: bool = False) -> bool: 352 | """ 353 | :param msg: 消息 354 | :param hasQuery: 是否带询问 355 | :return: 如果hasQuery为True,返回值为用户是否点击了确定 356 | """ 357 | if not hasQuery: 358 | QtWidgets.QMessageBox.information(self.mainWindow, '提示', msg, QtWidgets.QMessageBox.Ok, 359 | QtWidgets.QMessageBox.Ok) 360 | return True 361 | reply = QtWidgets.QMessageBox.question(self.mainWindow, '提示', msg, 362 | QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel, 363 | QtWidgets.QMessageBox.Cancel) 364 | return reply == QtWidgets.QMessageBox.Yes 365 | 366 | def getCurrentSelected(self) -> int: 367 | """ 368 | 获取当前选中的表格单元索引 369 | :return: 前选中的表格单元索引 370 | """ 371 | selectedIndex = self.tableView.selectedIndexes() 372 | if len(selectedIndex) > 0: 373 | return selectedIndex[0].row() 374 | return -1 375 | 376 | def insertRow(self, index: int) -> None: 377 | """ 378 | 增加一行空白行 379 | :index: 增加的位置索引 380 | :return: None 381 | """ 382 | self.model.insertRow(index) 383 | 384 | def getSubtitle(self) -> str: 385 | """ 386 | 获取当前编辑的字幕信息 387 | :return: 前编辑的字幕 388 | """ 389 | return self.singleText.text() 390 | 391 | def getSearchText(self) -> str: 392 | """ 393 | 获取搜索框文本信息 394 | :return: 搜索框文本信息 395 | """ 396 | return self.searchText.text() 397 | 398 | def setVideoText(self, text: str) -> None: 399 | """ 400 | 设置视频预览区字幕信息 401 | :param text: 字幕信息 402 | :return: None 403 | """ 404 | self.videoText.setText(text) 405 | 406 | def setFileName(self, fileName: str) -> None: 407 | """ 408 | 设置文件名 409 | :param fileName: 文件名 410 | :return: None 411 | """ 412 | self.filenName.setText(fileName) 413 | 414 | def windowIsVisible(self) -> bool: 415 | """ 416 | 当前窗口是否可见,即是否被关闭 417 | :return: 返回当前窗口是否可见,即是否被关闭 418 | """ 419 | return self.centralwidget.isVisible() 420 | 421 | def setSubTileText(self, text: str) -> None: 422 | """ 423 | 设置字幕编辑框内容 424 | :param text: 字幕 425 | :return: None 426 | """ 427 | self.singleText.setText(text) 428 | self.singleText.home(False) 429 | 430 | def setSearchText(self, text: str) -> None: 431 | """ 432 | 设置搜索框内容 433 | :param text: 搜索文字 434 | :return: None 435 | """ 436 | self.searchText.setText(text) 437 | self.searchText.home(False) 438 | 439 | def getFileName(self) -> str: 440 | """ 441 | 获取文件名 442 | :return: 文件名 443 | """ 444 | return self.filenName.text() 445 | 446 | def setRowText(self, row: int, text: str) -> None: 447 | """ 448 | 设置某一行的文案信息 449 | :param row: 行索引 450 | :param text: 文本 451 | :return: 452 | """ 453 | item = self.model.item(row, 0) 454 | if item is not None: 455 | item.setText(text) 456 | 457 | def subtitleHasFocus(self) -> bool: 458 | """ 459 | 单句字幕编辑框是否有焦点 460 | :return: 单句字幕编辑框是否有焦点 461 | """ 462 | return self.singleText.hasFocus() 463 | 464 | def setGenVideoText(self, text: str) -> None: 465 | """ 466 | 设置生成视频按钮的文本 467 | :param text: 文本 468 | :return: None 469 | """ 470 | self.genVideo.setText(text) 471 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import math 3 | import os.path 4 | import pickle 5 | import random 6 | import shutil 7 | import threading 8 | import time 9 | 10 | from PyQt5 import QtWidgets 11 | from PyQt5.QtCore import QThread, pyqtSignal 12 | from PyQt5.QtGui import QDropEvent, QDragEnterEvent, QStandardItem 13 | 14 | import mainWindow 15 | from PyQt5.QtWidgets import QApplication, QDialog 16 | from moviepy.editor import * 17 | 18 | from conf import BackgroundMusic, BaiduButton, DoutulaButton 19 | 20 | from utils import getUuid, getBaiDuAudio, getBaiduImgPath, getDoutulaImgPath, resizeImg, convertToRGB 21 | 22 | 23 | class genVideoThread(QThread): 24 | """ 25 | 生成视频线程类 26 | """ 27 | signal = pyqtSignal(str) 28 | 29 | def __init__(self, sections: list, materialName: str, fileName: str) -> None: 30 | """ 31 | 初始化几个参数 32 | :param sections: 字幕以及图片信息 33 | :param materialName: 素材路径 34 | :param fileName: 保存视频名称 35 | """ 36 | super().__init__() 37 | self.sections = sections 38 | self.materialName = materialName 39 | self.fileName = fileName 40 | 41 | def __del__(self): 42 | self.wait() 43 | 44 | def run(self): 45 | screensize = (800, 600) 46 | videoClips = [] 47 | for i, section in enumerate(self.sections): 48 | 49 | imgPath, text = section[0], section[1] 50 | if len(text) >= 1: 51 | mark = text[-1] 52 | if mark == '$': 53 | text = text[:-1] 54 | text = text.split(r'\\') 55 | text = '\\'.join([x.replace(r'\n', '\n') for x in text]) 56 | text = text.strip().split('\n') 57 | if imgPath is None: 58 | imgPath = 'background.png' 59 | 60 | # gif用到,用于标记当前字幕对应的gif从哪儿开始 61 | index = 0 62 | print(text, imgPath) 63 | if imgPath.endswith('.gif'): 64 | # 首先计算一下当前所有语音时间长度 65 | clip = VideoFileClip(imgPath) 66 | clip = clip.loop() 67 | else: 68 | convertToRGB(imgPath) 69 | clip = ImageClip(imgPath) 70 | 71 | # 设置一下图片/gif大小 72 | if mark != '$': 73 | width, height = clip.size 74 | width, height = resizeImg(width, height) 75 | clip = clip.resize((width, height)) 76 | 77 | 78 | # 考虑到每张表情包可能对应多句字幕 79 | for txt in text: 80 | # 合成语音 81 | txtAudio = getBaiDuAudio(txt, os.path.join(self.materialName, 'audio')) 82 | if len(txt) < 12: 83 | fontsize = 50 84 | else: 85 | fontsize = 40 86 | txtClip = TextClip(txt, color='white', font='STKaiti', kerning=5, fontsize=fontsize, align='South') 87 | if txtAudio is None: 88 | logging.error('get the audio of {} failed!'.format(txt)) 89 | continue 90 | txtAudio = AudioFileClip(txtAudio) 91 | 92 | # 表情包视频与字幕融合 93 | cvc = CompositeVideoClip([clip.set_position(('center', 'center')).subclip(index, txtAudio.duration), 94 | txtClip.set_position(('center', 0.85), relative=True)], 95 | size=screensize) 96 | cvc = cvc.subclip(0, txtAudio.duration) 97 | index += txtAudio.duration 98 | # 添加配音 99 | cvc = cvc.set_audio(txtAudio) 100 | videoClips.append(cvc) 101 | self.signal.emit('进度: {}%'.format(math.ceil((i * 80) / len(self.sections)))) 102 | finalClip = concatenate_videoclips(videoClips) 103 | # 获取原视频声音 104 | audio = finalClip.audio 105 | 106 | # 整体背景音乐 107 | audioClip = AudioFileClip(BackgroundMusic) 108 | if audioClip.duration > finalClip.duration: 109 | audioClip = audioClip.subclip(0, audio.duration) 110 | elif audioClip.duration < finalClip.duration: 111 | audioClip = afx.audio_loop(audioClip, duration=audio.duration) 112 | audioClip = afx.volumex(audioClip, factor=0.35) 113 | self.signal.emit('进度: {}%'.format(math.ceil(i * 80 / len(self.sections)) + random.randint(5, 15))) 114 | # 声音结合起来 115 | audio = CompositeAudioClip([audio, audioClip]) 116 | finalClip = finalClip.set_audio(audio) 117 | fileName = os.path.join('out', self.fileName) 118 | self.signal.emit('进度: {}'.format('处理完成! 正在写出文件...')) 119 | finalClip.write_videofile(fileName, fps=25, codec='mpeg4') 120 | self.signal.emit(fileName) 121 | 122 | 123 | class addImgThread(QThread): 124 | """ 125 | 获取网络表情包线程类 126 | """ 127 | signal = pyqtSignal(str) 128 | 129 | def __init__(self, mText: str, mButton: int) -> None: 130 | """ 131 | 初始化获取网络表情包线程类 132 | :param mText: 搜索关键词 133 | :param mButton: 采用哪个搜索引擎 134 | """ 135 | super().__init__() 136 | self.text = mText 137 | self.button = mButton 138 | 139 | def __del__(self): 140 | self.wait() 141 | 142 | def run(self): 143 | if self.button == BaiduButton: 144 | for path in getBaiduImgPath(self.text): 145 | self.signal.emit(path) 146 | 147 | if self.button == DoutulaButton: 148 | for path in getDoutulaImgPath(self.text): 149 | self.signal.emit(path) 150 | 151 | 152 | class MainDialog(QDialog): 153 | def __init__(self, parent=None): 154 | super(QDialog, self).__init__(parent) 155 | 156 | # 当前指向的句子 157 | self.nowPos = None 158 | # 获取表情包线程句柄 159 | self.subThread = None 160 | # 已经设定好的句子以及表情包,三元组(图片路径, 文案, 时间戳),时间戳一旦生成不再修改,主要用于区分文案并生成对应的图片路径 161 | self.sections = [] 162 | # 接收拖放对象 163 | self.setAcceptDrops(True) 164 | self.fileName = None 165 | self.materialName = None 166 | 167 | # lock of save and read the bfs file 168 | self.lock = threading.Lock() 169 | 170 | self.ui = mainWindow.Ui_MainWindow() 171 | self.ui.setupUi(self) 172 | 173 | # start save thread 174 | self.saveThread = threading.Thread(target=self.save) 175 | self.saveThread.start() 176 | 177 | def save(self) -> None: 178 | """ 179 | 每隔5秒保存一次工程信息 180 | :return: None 181 | """ 182 | time.sleep(5) 183 | # 窗口存在则一直保存 184 | while self.ui.windowIsVisible(): 185 | self.lock.acquire() 186 | if len(self.sections) <= 0: 187 | self.lock.release() 188 | time.sleep(5) 189 | continue 190 | data = dict() 191 | data['nowPos'] = self.nowPos 192 | data['sections'] = self.sections 193 | data['fileName'] = self.fileName 194 | data['materialName'] = self.materialName 195 | fileName = os.path.join(self.materialName, self.fileName[:self.fileName.rfind('.')] + '.bfs') 196 | with open(fileName, 'wb') as f: 197 | pickle.dump(data, f) 198 | self.lock.release() 199 | time.sleep(5) 200 | 201 | def dragEnterEvent(self, event: QDragEnterEvent) -> None: 202 | """ 203 | 拖放事件 204 | :param event: QDragEnterEvent 205 | :return: None 206 | """ 207 | if event.mimeData().hasText(): 208 | event.accept() 209 | else: 210 | event.ignore() 211 | 212 | def dropEvent(self, event: QDropEvent) -> None: 213 | """ 214 | 拖放事件,主要处理.bfs工程文件, .txt文案文件, .gif/.png等图片文件 215 | :param event: 拖放对象事件 216 | :return: None 217 | """ 218 | filePathList = event.mimeData().text() 219 | filePath = filePathList.split('\n')[0].replace('file:///', '', 1) 220 | # 说明是加载的工程文件 221 | if filePath.endswith('.bfs'): 222 | self.loadBfs(filePath) 223 | return 224 | 225 | # 说明加载的是文案文件 226 | if filePath.endswith('.txt'): 227 | if self.fileName is None: 228 | self.ui.msgBox('请先设置工程目录!') 229 | return 230 | self.loadText(True, filePath) 231 | return 232 | 233 | # 其他情况应该是加载的图片文件,先判断是不是gif/图片 234 | if not filePath.endswith('.gif'): 235 | # 通过加载文件来判断是否为图片,不是则返回 236 | try: 237 | ImageClip(filePath) 238 | except: 239 | return 240 | self.loadPic(filePath) 241 | 242 | def loadBfs(self, filePath: str) -> None: 243 | """ 244 | 加载工程文件 245 | :param filePath: 工程文件路径 246 | :return: None 247 | """ 248 | if len(self.sections) > 0: 249 | if not self.ui.msgBox('导入工程文件将清空当前工作内容,可能导致部分内容丢失,是否继续?', True): 250 | return 251 | 252 | # 需要在material目录下有对应的文件夹,没有的禁止载入 253 | fileName = os.path.basename(filePath).replace('.bfs', '') 254 | if not os.path.exists(os.path.join('material', fileName)): 255 | self.ui.msgBox('未找到对应的素材文件夹!') 256 | return 257 | 258 | with open(filePath, 'rb') as f: 259 | data = pickle.load(f) 260 | 261 | self.lock.acquire() 262 | self.nowPos = data['nowPos'] 263 | self.sections = data['sections'] 264 | 265 | # 检查资源文件是否都存在 266 | for section in self.sections: 267 | if section[0] is not None and not os.path.exists(section[0]): 268 | self.nowPos = None 269 | self.sections = [] 270 | self.ui.msgBox('对应的素材缺失!') 271 | self.lock.release() 272 | return 273 | 274 | self.fileName = data['fileName'] 275 | self.ui.setFileName(self.fileName) 276 | self.materialName = data['materialName'] 277 | 278 | # 将sections的内容填充到表格 279 | self.ui.delAllRow() 280 | for section in self.sections: 281 | self.ui.addRow(section[1]) 282 | if self.nowPos is not None: 283 | self.ui.setSubTileText(self.sections[self.nowPos][1]) 284 | self.ui.setSearchText(self.sections[self.nowPos][1]) 285 | 286 | imgPath = self.sections[self.nowPos][0] 287 | if imgPath is None: 288 | self.ui.delVideoImg() 289 | else: 290 | self.ui.changeVideoImg(imgPath) 291 | else: 292 | self.ui.delVideoImg() 293 | self.lock.release() 294 | 295 | def loadPic(self, imgPath: str) -> None: 296 | """ 297 | 加载拖放进来的图片文件 298 | :param imgPath: 图片文件路径 299 | :return: None 300 | """ 301 | if self.nowPos is None: 302 | # 没有工程内容则忽略该次拖入文件 303 | self.ui.msgBox('请先设置字幕内容!') 304 | return 305 | 306 | self.ui.changeVideoImg(imgPath) 307 | 308 | imgBaseName = os.path.basename(imgPath) 309 | suffix = imgBaseName[imgBaseName.rfind('.') + 1:] 310 | uuid = self.sections[self.nowPos][2] 311 | newPath = '{}.{}'.format(uuid, suffix) 312 | newPath = os.path.join(os.path.join(self.materialName, 'img'), newPath) 313 | shutil.copyfile(imgPath, newPath) 314 | # 保存图片与字幕信息 315 | self.sections[self.nowPos] = [newPath, self.ui.getSubtitle(), uuid] 316 | self.ui.setRowText(self.nowPos, self.ui.getSubtitle()) 317 | 318 | def setFilename(self) -> None: 319 | """ 320 | 设置文件名 321 | :return: None 322 | """ 323 | # 加锁,禁止保存或者载入工程文件 324 | self.lock.acquire() 325 | fileName = self.ui.getFileName() 326 | materialName = os.path.join('material', fileName[:fileName.rfind('.')]) 327 | 328 | # 当前工作区没内容,说明是新建的工程,新建的工程的名字不能和之前重复 329 | if len(self.sections) <= 0 and os.path.exists(materialName): 330 | self.ui.msgBox('文件名已存在,请更换名字或加载之前缓存!') 331 | self.lock.release() 332 | return 333 | 334 | self.fileName = fileName 335 | 336 | # 文件名并未更改,可能是未修改或者只修改了后缀名,都可以忽略 337 | if self.materialName == materialName: 338 | self.ui.msgBox('设置工程文件夹成功!') 339 | self.lock.release() 340 | return 341 | # 当前工作区无内容,说明是新建的工程,需要新建文件夹 342 | if len(self.sections) <= 0: 343 | os.makedirs(os.path.join(materialName, 'audio')) 344 | os.makedirs(os.path.join(materialName, 'img')) 345 | self.ui.msgBox('新建工程文件夹成功!') 346 | else: 347 | # 当前工作区有内容,说明工程已经存在,需要对所有数据进行重命名 348 | self.changeFileName(self.materialName, materialName) 349 | self.ui.msgBox('重命名工程文件夹成功!') 350 | self.materialName = materialName 351 | self.lock.release() 352 | 353 | def changeFileName(self, oldMaterialName: str, materialName: str) -> None: 354 | """ 355 | 修改了文件名需要对文件夹等全部进行修改 356 | :param oldMaterialName: 旧的素材文件夹名 357 | :param materialName: 新的素材文件夹名 358 | :return: 359 | """ 360 | # 对sections里面包含的图片信息的地址进行修改 361 | for section in self.sections: 362 | if section[0] is None: 363 | continue 364 | imgBaseName = os.path.basename(section[0]) 365 | newPath = os.path.join(os.path.join(materialName, 'img'), imgBaseName) 366 | section[0] = newPath 367 | 368 | # 更改文件夹名字 369 | os.rename(oldMaterialName, materialName) 370 | 371 | def setSubtitleInfo(self) -> None: 372 | """ 373 | 设置上一句/下一句对应的字幕以及图片信息 374 | :return: None 375 | """ 376 | self.ui.setSubTileText(self.sections[self.nowPos][1]) 377 | self.ui.setSearchText(self.sections[self.nowPos][1]) 378 | # 如果已经设置好了表情包,显示出来;否则就清空 379 | imgPath = self.sections[self.nowPos][0] 380 | if imgPath is None: 381 | self.ui.delVideoImg() 382 | else: 383 | self.ui.changeVideoImg(imgPath) 384 | 385 | def last(self) -> None: 386 | """ 387 | 上一句,加载上一句字幕与图片 388 | :return: None 389 | """ 390 | if len(self.sections) <= 0: 391 | self.ui.msgBox('当前工作区暂无内容!') 392 | return 393 | 394 | # 计算当前应该到达的光标 395 | if self.nowPos is None: 396 | self.nowPos = 1 397 | else: 398 | # 保存下一句的字幕信息 399 | self.sections[self.nowPos][1] = self.ui.getSubtitle() 400 | self.ui.setRowText(self.nowPos, self.ui.getSubtitle()) 401 | 402 | self.nowPos = self.nowPos - 1 if self.nowPos > 0 else len(self.sections) - 1 403 | self.setSubtitleInfo() 404 | 405 | def next(self) -> None: 406 | """ 407 | 下一句,加载下一句字幕与图片 408 | :return: None 409 | """ 410 | if len(self.sections) <= 0: 411 | self.ui.msgBox('当前工作区暂无内容!') 412 | return 413 | 414 | if self.nowPos is None: 415 | self.nowPos = -1 416 | else: 417 | # 保存上一句的字幕信息 418 | self.sections[self.nowPos][1] = self.ui.getSubtitle() 419 | self.ui.setRowText(self.nowPos, self.ui.getSubtitle()) 420 | 421 | self.nowPos = self.nowPos + 1 if self.nowPos < len(self.sections) - 1 else 0 422 | self.setSubtitleInfo() 423 | 424 | def changeThePicText(self, text: str) -> None: 425 | """ 426 | 视频字幕实时更改 427 | :param text: 字幕信息 428 | :return: None 429 | """ 430 | if len(self.sections) <= 0: 431 | return 432 | self.ui.setVideoText(text) 433 | self.sections[self.nowPos][1] = text 434 | self.ui.setRowText(self.nowPos, text) 435 | 436 | def previewImg(self, path: str) -> None: 437 | """ 438 | 将网络表情包加载预览以供选择 439 | :param path: 网络表情包路径 440 | :return: None 441 | """ 442 | self.ui.addImg(path) 443 | 444 | def search(self, button: int) -> None: 445 | """ 446 | 搜索表情包,button代表了不同的搜索引擎 447 | :param button: 来自哪个按钮,代表了不同的搜索引擎 448 | :return: None 449 | """ 450 | if len(self.sections) <= 0 or self.ui.getSearchText() == '': 451 | self.ui.msgBox('工作区暂无内容或未输入搜索文字!') 452 | return 453 | if self.subThread is not None: 454 | self.subThread.terminate() 455 | while self.subThread.isRunning() and not self.subThread.isFinished(): 456 | time.sleep(0.1) 457 | # 清空当前的所有表情包图片 458 | self.ui.delImg() 459 | self.subThread = addImgThread(self.ui.getSearchText(), button) 460 | self.subThread.signal.connect(self.previewImg) 461 | self.subThread.start() 462 | 463 | def imgClicked(self, index: int) -> None: 464 | """ 465 | 表情包点击回调函数,将选好的表情包加载到视频预览区 466 | :param index: 选好的表情包索引 467 | :return: None 468 | """ 469 | if len(self.sections) <= 0: 470 | self.ui.msgBox('工作区无内容!') 471 | return 472 | if self.nowPos is None: 473 | self.ui.msgBox('暂未选择文案与字幕!') 474 | return 475 | imgPath = self.ui.getImgPathByIndex(index) 476 | self.ui.changeVideoImg(imgPath) 477 | # 将表情包复制到material目录 478 | imgBaseName = os.path.basename(imgPath) 479 | suffix = imgBaseName[imgBaseName.rfind('.') + 1:] 480 | uuid = self.sections[self.nowPos][2] 481 | newPath = '{}.{}'.format(uuid, suffix) 482 | newPath = os.path.join(os.path.join(self.materialName, 'img'), newPath) 483 | shutil.copyfile(imgPath, newPath) 484 | # 保存图片与字幕信息 485 | self.sections[self.nowPos] = [newPath, self.ui.getSubtitle(), uuid] 486 | self.ui.setRowText(self.nowPos, self.ui.getSubtitle()) 487 | 488 | def genVideo(self) -> None: 489 | """ 490 | 开始生成视频 491 | :return: None 492 | """ 493 | if len(self.sections) <= 0: 494 | self.ui.msgBox('工作区无内容!') 495 | return 496 | self.setDisabled(True) 497 | self.gvt = genVideoThread(self.sections, self.materialName, self.fileName) 498 | self.gvt.signal.connect(self.genVideoFinished) 499 | self.gvt.start() 500 | 501 | def genVideoFinished(self, msg: str) -> None: 502 | """ 503 | 视频生成完成回调函数 504 | :param msg: 生成视频传回的信息。主要有两种,第一是进度,第二是输出的视频的路径 505 | :return: None 506 | """ 507 | if ': ' in msg: 508 | self.ui.setGenVideoText(msg) 509 | return 510 | self.setDisabled(False) 511 | self.ui.setGenVideoText('生成视频') 512 | self.ui.msgBox('生成完毕!位置:{}'.format(msg)) 513 | 514 | def loadText(self, drag=False, fileName: str=None) -> None: 515 | """ 516 | 文件浏览器回调函数/同时支持拖放导入文案解析 517 | :param drag: 是否是拖放导入的 518 | :param fileName: 拖放进来的文件名 519 | :return: None 520 | """ 521 | if self.fileName is None: 522 | self.ui.msgBox('请先设置工程目录!') 523 | return 524 | if len(self.sections) > 0 and not self.ui.msgBox('当前导入会覆盖工作区内容,不可撤销!是否继续?', True): 525 | return 526 | self.ui.delAllRow() 527 | if not drag: 528 | fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self, '选择文案', os.getcwd(), 'Text Files (*.txt)') 529 | if not os.path.exists(fileName): 530 | self.ui.msgBox('未选择文件!') 531 | return 532 | with open(fileName, 'r', encoding='utf-8') as f: 533 | data = f.read() 534 | self.sections = list() 535 | for text in data.split('\n'): 536 | if text == '': 537 | continue 538 | text = text.strip() 539 | self.ui.addRow(text) 540 | self.sections.append([None, text, getUuid()]) 541 | self.ui.msgBox('导入完成!') 542 | 543 | def addFrontText(self) -> None: 544 | """ 545 | 在当前选中的表格单元前面增加一行空白行 546 | :return: None 547 | """ 548 | if len(self.sections) <= 0: 549 | if self.fileName is not None: 550 | index = 0 551 | else: 552 | self.ui.msgBox('请设置文件名后再添加!') 553 | return 554 | else: 555 | index = self.ui.getCurrentSelected() 556 | if index == -1: 557 | self.ui.msgBox('未选中表格!') 558 | return 559 | 560 | if self.nowPos is not None and self.nowPos >= index: 561 | self.nowPos += 1 562 | 563 | self.ui.insertRow(index) 564 | self.sections.insert(index, [None, '', getUuid()]) 565 | 566 | def addBehindText(self) -> None: 567 | """ 568 | 在当前选中的表格单元后面增加一行空白行 569 | :return: None 570 | """ 571 | if len(self.sections) <= 0: 572 | if self.fileName is not None: 573 | index = -1 574 | else: 575 | self.ui.msgBox('请设置文件名后再添加!') 576 | return 577 | else: 578 | index = self.ui.getCurrentSelected() 579 | if index == -1: 580 | self.ui.msgBox('未选中表格!') 581 | return 582 | 583 | if self.nowPos is not None and self.nowPos > index: 584 | self.nowPos += 1 585 | 586 | self.ui.insertRow(index + 1) 587 | self.sections.insert(index + 1, [None, '', getUuid()]) 588 | 589 | def delText(self) -> None: 590 | """ 591 | 删除该行 592 | :return: None 593 | """ 594 | if len(self.sections) <= 0: 595 | self.ui.msgBox('请先创建工程或输入文案!') 596 | return 597 | index = self.ui.getCurrentSelected() 598 | if index == -1: 599 | self.ui.msgBox('未选中表格!') 600 | return 601 | 602 | # 如果删除了当前预览位置的文案 603 | if self.nowPos is not None and self.nowPos == index: 604 | # 加载下一句文案 605 | self.next() 606 | 607 | # 如果在当前位置之前删除了一个文案,那么当前位置-1 608 | if self.nowPos is not None and self.nowPos >= index: 609 | self.nowPos -= 1 610 | 611 | self.ui.delRow(index) 612 | del self.sections[index] 613 | 614 | def exportText(self) -> None: 615 | """ 616 | 导出文案内容 617 | :return: None 618 | """ 619 | if len(self.sections) <= 0: 620 | self.ui.msgBox('当前工作区没有内容!') 621 | return 622 | texts = '' 623 | for section in self.sections: 624 | texts += section[1] + '\n' 625 | 626 | path = os.path.join(self.materialName, 'work.txt') 627 | with open(path, 'w+') as f: 628 | f.write(texts) 629 | self.ui.msgBox('导出文案成功!位置:{}'.format(path)) 630 | 631 | def tableItemChange(self, item: QStandardItem) -> None: 632 | """ 633 | 文案内容被修改时,同步到sections 634 | :param item: 被修改的表格item 635 | :return: 636 | """ 637 | if len(self.sections) > item.row(): 638 | self.sections[item.row()][1] = item.text() 639 | # 如果当前单句字幕正好是修改的单元格部分,则修改的内容同步修改到单句字幕编辑处. 需要排除由于单句字幕修改造成的表格修改的情况 640 | if self.nowPos is not None and self.nowPos == item.row() and self.ui.getSubtitle() != item.text(): 641 | self.ui.setSubTileText(item.text()) 642 | self.ui.setSearchText(item.text()) 643 | 644 | def jumpToIndex(self) -> None: 645 | """ 646 | 跳转到指定的文案 647 | :return: None 648 | """ 649 | if self.nowPos is not None and self.ui.getCurrentSelected() != -1: 650 | # 保存上一句的字幕信息 651 | self.sections[self.nowPos][1] = self.ui.getSubtitle() 652 | self.ui.setRowText(self.nowPos, self.ui.getSubtitle()) 653 | self.nowPos = self.ui.getCurrentSelected() 654 | self.setSubtitleInfo() 655 | 656 | 657 | if __name__ == '__main__': 658 | if os.path.exists('tmp'): 659 | shutil.rmtree('tmp') 660 | os.mkdir('tmp') 661 | if not os.path.exists('out'): 662 | os.mkdir('out') 663 | myapp = QApplication(sys.argv) 664 | myDlg = MainDialog() 665 | myDlg.show() 666 | sys.exit(myapp.exec_()) 667 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------