├── .gitignore ├── LICENSE ├── README.md ├── api2d.py ├── app.py ├── bgm └── 红色高跟鞋.mp3 ├── char2voice.py ├── chatgpt.py ├── check_path.py ├── config.yaml ├── cover_drawing.py ├── extract_role.py ├── install.bat ├── load_config.py ├── main.py ├── mass_production.py ├── participle.py ├── prompt.py ├── prompt.txt ├── requirements.txt ├── roles ├── 女5.png ├── 女6.png ├── 男3.png ├── 男5.png └── 男6.png ├── sd.py ├── simhei.ttf ├── stable_diffusion.json ├── test.py ├── translate.py ├── utils ├── __init__.py ├── english_segment.py └── video_filter.py ├── video_composition.py ├── voice_caption.py └── webui.bat /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | participle 162 | video 163 | images 164 | 165 | local_config.yaml 166 | local_stable_diffusion.json 167 | *.txt 168 | !prompt.txt 169 | 170 | bgm 171 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ComicTweets 2 | 自动化构建漫画推文,使用stable diffusion来生成图片 3 | 4 | # Video Effects 5 | [![Watch the video](https://img.youtube.com/vi/ZcZbA1lVa34/0.jpg)](https://youtu.be/ZcZbA1lVa34 "Watch the video") 6 | 7 | 8 | # 教程 9 | B站:https://www.bilibili.com/video/BV1pt42177v9/ 10 | 11 | # Installation and Running 12 | 13 | ## Windows 10/11 or Linux or macos 14 | 15 | 1. Install Python 3.8 or later from https://www.python.org/downloads/ or Install Conda https://www.anaconda.com/download 16 | 2. Install the required Python packages 17 | - - Run `pip install -r requirements.txt` 18 | 3. Run `python main.py` 19 | 20 | Please make sure to install `ImageMagick` and `FFmpeg` if you encounter any issues. 21 | 22 | ## ImageMagick Install 23 | 24 | 1. Download and install ImageMagick from https://www.imagemagick.org/script/download.php 25 | 2. Add ImageMagick to your PATH environment variable 26 | 3. Put magick.exe absolute path under the video.imagemagick_path of config.yaml under the project (macos or linux negligible) 27 | 28 | ## FFmpeg Install 29 | 30 | 1. Download and install FFmpeg from https://www.ffmpeg.org/ 31 | 2. Add FFmpeg to your PATH environment variable 32 | 33 | 34 | # Introduction to use 35 | Place the .txt file in the project root directory 36 | Then copy the name of txt into the book name of config.yaml 37 | running python main.py 38 | 39 | # GPT 40 | Supports API2D only 41 | Type the key into the ForwardKey of chatgpt in config 42 | 43 | 44 | # 下一步开发打算 45 | 1. ~~并发异步执行,现在都是同步执行,后面会让生产语音和生成图片的协程并行~~ 46 | 2. 人物形象图,现在人物都是让GPT理解上下文的人物,形象可能会有一点变化,后面考虑使用 Reference 或者 ip-adapter 生成人物形象图参考。 47 | 3. ~~moviepy 代码迁移到ffmpeg的原生命令,moviepy的最新版居然是2020年!!! 已经没人更新了~~ 48 | 4. 代码结构优化,现在代码写的很乱,需要优化 49 | 5. 新增ChatGPT 官方 API,因为没有key 只能使用国内的代理商,但是贵了1.5倍!!! 50 | 51 | # 联系我 52 | - Email: anningforchina@gmail.com 53 | - QQ群:100419879 54 | - QQ\V:864399407 55 | - 欢迎合作👏🏻 56 | -------------------------------------------------------------------------------- /api2d.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -*- 3 | # @author:anning 4 | # @email:anningforchina@gmail.com 5 | # @time:2023/08/01 18:08 6 | # @file:app.py 7 | import asyncio 8 | 9 | import aiohttp 10 | import requests 11 | from aiohttp import ClientTimeout, ClientConnectionError 12 | from requests import ConnectionError 13 | from requests import Timeout 14 | 15 | from load_config import get_yaml_config 16 | 17 | config = get_yaml_config() 18 | ForwardKey = config["chatgpt"]["ForwardKey"] 19 | 20 | class Main: 21 | url = "https://oa.api2d.net/v1/chat/completions" 22 | 23 | def __str__(self): 24 | return "API2D请求失败,请检查配置!" 25 | 26 | async def prompt_generation_chatgpt(self, param, messages): 27 | # 发送HTTP POST请求 28 | headers = { 29 | "Content-Type": "application/json", 30 | "Authorization": f"Bearer {ForwardKey}", 31 | } 32 | 33 | msg = messages + [ 34 | { 35 | "role": "user", 36 | "content": param, 37 | } 38 | ] 39 | data = { 40 | "model": "gpt-3.5-turbo", 41 | "messages": msg, 42 | } 43 | print("-----------开始请求API2D-----------") 44 | try: 45 | response = requests.post(self.url, headers=headers, json=data, timeout=15) 46 | except Timeout: 47 | raise TimeoutError("API2D连接超时,15秒未响应!") 48 | # return False, "API2D连接超时,15秒未响应!" 49 | except ConnectionError: 50 | raise ConnectionError(f"API2D连接错误,{self.url} 建立连接失败,请检查网络!") 51 | # return False, f"连接错误,{self.url} 建立连接失败,请检查网络。" 52 | except Exception as e: 53 | raise Exception(str(e)) 54 | # return False, str(e) 55 | if response.status_code != 200: 56 | raise Exception( 57 | response.json().get( 58 | "message", "API2D返回状态码错误,请检查配置!" 59 | ) 60 | ) 61 | # return False, response.json().get( 62 | # "message", "API2D返回状态码错误,请检查配置!" 63 | # ) 64 | 65 | # 发送HTTP POST请求 66 | result_json = response.json() 67 | # 输出结果 68 | # 计算token 69 | total_tokens = result_json["usage"]["total_tokens"] 70 | return msg, result_json["choices"][0]["message"], total_tokens 71 | 72 | 73 | if __name__ == "__main__": 74 | 75 | with open("1txt.txt", "r", encoding="utf8") as file: 76 | # 初始化行数计数器 77 | line_number = 0 78 | lines = file.readlines() 79 | messages = [] 80 | # 循环输出每一行内容 81 | for line in lines: 82 | line_number += 1 83 | 84 | text = f"第{line_number}段:" + line.strip() 85 | if line_number == 1: 86 | with open("prompt.txt", "r", encoding="utf8") as f: 87 | messages = [ 88 | { 89 | "role": "system", 90 | "content": f.read(), 91 | } 92 | ] 93 | result, message = Main().prompt_generation_chatgpt(text, messages) 94 | 95 | messages = result + [message] 96 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | from io import StringIO 2 | import os 3 | import subprocess 4 | import streamlit as st 5 | from load_config import edit_yaml_config, get_yaml_config 6 | from mass_production import main 7 | from contextlib import redirect_stdout 8 | from PIL import Image 9 | 10 | config = get_yaml_config() 11 | source_path = config["batch"]["source_path"] 12 | output_path = config["batch"]["output_path"] 13 | ending_splice_path = config["batch"]["ending_splice_path"] 14 | ForwardKey = config["chatgpt"]["ForwardKey"] 15 | chat_url = config["chatgpt"]["url"] 16 | model = config["chatgpt"]["model"] 17 | access_key_id = config["potential"]["access_key_id"] 18 | access_key_secret = config["potential"]["access_key_secret"] 19 | ROLES_DIR = "roles" 20 | 21 | 22 | def processing(): 23 | st.title("批量处理") 24 | st.header("欢迎使用我们的视频处理工具") 25 | 26 | st.write("选择操作类型:") 27 | options = { 28 | "一键完成": "1", 29 | "生成分词+图片": "2", 30 | "生成语音": "3", 31 | "已经检测过图片,直接合成视频": "4", 32 | "先固定角色": "5" 33 | } 34 | 35 | # 使用 selectbox 进行类型选择 36 | classify = st.selectbox("请选择操作类型:", list(options.keys()), index=0) 37 | classify_value = options[classify] 38 | 39 | st.write(f"你选择的操作类型是:{classify}") 40 | 41 | st.write("输出路径:", output_path) 42 | 43 | 44 | # 创建一个占位符用于显示终端输出信息 45 | output_placeholder = st.empty() 46 | output_buffer = StringIO() 47 | 48 | 49 | # 批量处理按钮 50 | if st.button("开始批量处理"): 51 | entries = os.listdir(source_path) 52 | subdirectories = [ 53 | entry for entry in entries 54 | if os.path.isdir(os.path.join(source_path, entry)) and not entry.startswith('.') and not entry.startswith('_') 55 | ] 56 | 57 | # 显示处理进度 58 | with st.spinner("正在处理..."): 59 | total_tasks = len(subdirectories) + 1 # 包括 source_path 的处理 60 | progress_bar = st.progress(0) 61 | for i, directory in enumerate(subdirectories): 62 | with redirect_stdout(output_buffer): 63 | print(f"Processing directory: {directory}") 64 | main(os.path.join(source_path, directory), directory) 65 | output_placeholder.text(output_buffer.getvalue()) 66 | progress_bar.progress((i + 1) / total_tasks) 67 | with redirect_stdout(output_buffer): 68 | main(source_path, classify_value, None, output_path) 69 | output_placeholder.text(output_buffer.getvalue()) 70 | progress_bar.progress(1.0) 71 | st.toast('处理完成!', icon='😍') 72 | subprocess.Popen(f'explorer "{output_path}"') 73 | 74 | # 加载roles目录下的所有图片和昵称 75 | def load_role_images(): 76 | images = [] 77 | if os.path.exists(ROLES_DIR): 78 | for filename in os.listdir(ROLES_DIR): 79 | if filename.lower().endswith(('.png', '.jpg', '.jpeg')): 80 | image_path = os.path.join(ROLES_DIR, filename) 81 | # 假设昵称和文件名(不带扩展名)相同 82 | nickname = os.path.splitext(filename)[0] 83 | images.append((nickname, image_path)) 84 | return images 85 | 86 | def cycle_values(values): 87 | """ 88 | Generate values from the given list in a circular fashion. 89 | 90 | Args: 91 | values (list): List of values to cycle through. 92 | 93 | Returns: 94 | Generator: Yields the next value in the cycle. 95 | """ 96 | index = 0 97 | while True: 98 | yield values[index] 99 | index = (index + 1) % len(values) # Increment index and wrap around if necessary 100 | 101 | 102 | def roles(): 103 | st.title("角色管理") 104 | 105 | # 上传新图片 106 | uploaded_file = st.file_uploader("上传新图片到roles目录", type=["png", "jpg", "jpeg"]) 107 | if uploaded_file is not None: 108 | # 保存图片到roles目录 109 | filename = uploaded_file.name 110 | new_filename = os.path.join(ROLES_DIR, filename) 111 | with open(new_filename, 'wb') as f: 112 | f.write(uploaded_file.getbuffer()) 113 | # 假设昵称和文件名(不带扩展名)相同 114 | nickname = os.path.splitext(filename)[0] 115 | 116 | # 显示所有图片和昵称 117 | cycle = cycle_values(st.columns(3)) 118 | for nickname, image_path in load_role_images(): 119 | instance = next(cycle) 120 | instance.write(f"昵称: {nickname}") 121 | # 对于每个角色,显示修改昵称和删除图片的按钮 122 | instance.image(Image.open(image_path)) 123 | 124 | 125 | def configuration_information(): 126 | st.title("配置信息") 127 | 128 | def save_config(): 129 | config["batch"]["source_path"] = source_path_ 130 | config["batch"]["output_path"] = output_path_ 131 | config["batch"]["ending_splice_path"] = ending_splice_path_ 132 | config["chatgpt"]["ForwardKey"] = ForwardKey_ 133 | config["chatgpt"]["url"] = url_ 134 | config["chatgpt"]["model"] = model_ 135 | config["potential"]["access_key_id"] = access_key_id_ 136 | config["potential"]["access_key_secret"] = access_key_secret_ 137 | edit_yaml_config(config) 138 | st.toast('配置已更新', icon='😍') 139 | st.experimental_rerun() # 重新加载 Streamlit 应用 140 | 141 | source_path_ = st.text_input("小说目录", source_path, help="请复制小说目录绝对路径或相对路径") 142 | output_path_ = st.text_input("输出目录", output_path, help="生产后视频的保存路径") 143 | ending_splice_path_ = st.text_input("视频尾部拼接", ending_splice_path, help="统一拼接尾部视频") 144 | ForwardKey_ = st.text_input("openai key, 支持国内代理,以及本地LLM大模型", ForwardKey, help="openai key, 支持国内代理,以及本地LLM大模型") 145 | url_ = st.text_input("openai url 代理或者本地需要填", chat_url, help="openai url,代理或者本地需要填") 146 | model_ = st.text_input("openai model 代理或者本地需要填", model, help="openai model,代理或者本地需要填") 147 | access_key_id_ = st.text_input("阿里云翻译access_key_id", access_key_id, help="阿里云access_key_id") 148 | access_key_secret_ = st.text_input("阿里云翻译access_key_secret", access_key_secret, help="阿里云access_key_secret") 149 | 150 | st.button("保存配置", on_click=save_config, use_container_width=True) 151 | 152 | 153 | if __name__ == "__main__": 154 | st.sidebar.title("Apps") 155 | 156 | st.sidebar.write("Select an app:") 157 | if st.sidebar.button("配置信息", use_container_width=True): 158 | st.session_state.page = '配置' 159 | if st.sidebar.button("批量处理", use_container_width=True): 160 | st.session_state.page = '批量处理' 161 | if st.sidebar.button("角色管理", use_container_width=True): 162 | st.session_state.page = '角色管理' 163 | 164 | # 页面显示逻辑 165 | if 'page' in st.session_state: 166 | if st.session_state.page == '配置': 167 | configuration_information() 168 | elif st.session_state.page == '批量处理': 169 | processing() 170 | elif st.session_state.page == '角色管理': 171 | roles() 172 | else: 173 | st.session_state.page = '配置' 174 | configuration_information() -------------------------------------------------------------------------------- /bgm/红色高跟鞋.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anning01/ComicTweets/2b3350cbaf46efc3484d2e716acb293bc5fb5ae7/bgm/红色高跟鞋.mp3 -------------------------------------------------------------------------------- /char2voice.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import os.path 3 | import re 4 | import aiofiles 5 | import edge_tts 6 | 7 | from load_config import get_yaml_config 8 | 9 | config = get_yaml_config() 10 | limit = config["audio"]["limit"] 11 | role = config["audio"]["role"] 12 | rate = config["audio"]["rate"] 13 | volume = config["audio"]["volume"] 14 | 15 | 16 | async def spilt_str2(s, t, k=limit): 17 | """ 18 | :param s: 切片文本 19 | :param t: 切分前时间 20 | :param k: 切分最大字数 21 | :return: 新的切片信息 22 | 23 | @ samples 24 | s = "并且觉醒天赋 得到力量 对抗凶兽 觉醒天赋 便是人人在十八岁时能以血脉沟通沟通 觉醒天赋" 25 | t = "00:00:35,184 --> 00:00:42,384" 26 | k = 15 27 | """ 28 | 29 | async def time2second(ti): 30 | """ 31 | :param ti: 输入时间, 格式示例:00:02:56,512 32 | :return: float 33 | """ 34 | a, b, _c = ti.split(":") 35 | c, d = _c.split(",") 36 | 37 | a, b, c, d = int(a), int(b), int(c), int(d) 38 | 39 | second = a * 3600 + b * 60 + c + d / 1000 40 | 41 | return second 42 | 43 | async def second2time(si): 44 | hours = int(si // 3600) 45 | minutes = int((si % 3600) // 60) 46 | seconds = int(si % 60) 47 | milliseconds = round((si % 1) * 1000) 48 | 49 | v = "00" 50 | u = "000" 51 | a = v[: 2 - len(str(hours))] + str(hours) 52 | b = v[: 2 - len(str(minutes))] + str(minutes) 53 | c = v[: 2 - len(str(seconds))] + str(seconds) 54 | d = u[: 3 - len(str(milliseconds))] + str(milliseconds) 55 | 56 | return f"{a}:{b}:{c},{d}" 57 | 58 | ss = s.split(" ") 59 | ss_valid = [] 60 | 61 | # todo 将所有片段设置成不超过15 62 | for _ss in ss: 63 | if len(_ss) > k: 64 | 65 | # 暴力截断几段 66 | e = len(_ss) // k + 1 67 | n_e = len(_ss) // e + 1 68 | 69 | for _i in range(e): 70 | if _i == e - 1: 71 | ss_valid.append(_ss[n_e * _i :]) 72 | else: 73 | ss_valid.append(_ss[n_e * _i : n_e * (_i + 1)]) 74 | else: 75 | ss_valid.append(_ss) 76 | 77 | # todo 片段合并 78 | tmp = "" 79 | new_ss = [] 80 | for i in range(len(ss_valid)): 81 | tmp += ss_valid[i] 82 | 83 | if i < len(ss_valid) - 1: 84 | if len(tmp + ss_valid[i + 1]) > k: 85 | new_ss.append(tmp) 86 | tmp = "" 87 | else: 88 | continue 89 | else: 90 | new_ss.append(tmp) 91 | tmp = "" 92 | 93 | # 分配时间戳 94 | t1, t2 = t.split("-->") 95 | ft1 = await time2second(t1) 96 | ft2 = await time2second(t2) 97 | ftd = ft2 - ft1 98 | 99 | # 转换成秒数 100 | all_str = " ".join(new_ss) 101 | 102 | tt_s = 0 103 | line_srt = [] 104 | for z in new_ss: 105 | tt_e = len(z) + tt_s 106 | 107 | # 文章最后一句异常处理 108 | if len(all_str) * ftd == 0: 109 | continue 110 | 111 | t_start = tt_s / len(all_str) * ftd 112 | t_end = tt_e / len(all_str) * ftd 113 | t_start = round(t_start, 3) 114 | t_end = round(t_end, 3) 115 | 116 | rec_s = await second2time(ft1 + t_start) 117 | rec_e = await second2time(ft1 + t_end) 118 | 119 | cc = (f"{rec_s} --> {rec_e}", z) 120 | line_srt.append(cc) 121 | 122 | tt_s = tt_e + 1 123 | 124 | return line_srt 125 | 126 | 127 | async def load_srt_new(filename, flag=True): 128 | time_format = r"(\d{2}:\d{2}:\d{2}),\d{3} --> (\d{2}:\d{2}:\d{2}),\d{3}" 129 | 130 | n = 0 # srt 文件总行数 131 | index = 0 # strs 文字串移动下标 132 | line_tmp = "" # 每个时间区间后的字数累计 133 | count_tmp = 0 # 每个时间区间后的字数行计数 134 | new_srt = [] 135 | 136 | async with aiofiles.open(filename, mode="r", encoding="utf-8") as f3: 137 | f_lines = await f3.readlines() 138 | for line in f_lines: 139 | line = line.strip("\n") 140 | 141 | n += 1 142 | 143 | # 写入新的数据 144 | # 1)当出现在文本末写入一次 145 | if n == len(f_lines): 146 | new_srt_line = await spilt_str2(line_tmp, t_line_cur) 147 | new_srt.append(new_srt_line) 148 | 149 | # 2)当新的一行是数字时,srt语句段写入 150 | # case1: 判断新的一行是不是数字 151 | if line.isdigit(): 152 | if flag: 153 | print(line) 154 | if n > 1: 155 | new_srt_line = await spilt_str2(line_tmp, t_line_cur) 156 | new_srt.append(new_srt_line) 157 | continue 158 | 159 | # case2: 判断新的一行是不是时间段 160 | if re.match(time_format, line): 161 | t_line_cur = line 162 | 163 | # reset line_tmp 164 | line_tmp = "" 165 | count_tmp = 0 166 | continue 167 | 168 | # case3: 判断新的一行是空格时 169 | if len(line) == 0: 170 | continue 171 | 172 | # case4: 新的一行不属于上面其中之一 173 | line_std = line.replace(" ", "") 174 | if flag: 175 | print(f"{line}\n{line_std}") 176 | 177 | if count_tmp: 178 | line_tmp += " " + line_std 179 | else: 180 | line_tmp += line_std 181 | count_tmp += 1 182 | 183 | srt = [] 184 | for _line in new_srt: 185 | for _l in _line: 186 | srt.append(_l) 187 | 188 | return srt 189 | 190 | 191 | async def save_srt(filename, srt_list): 192 | async with aiofiles.open(filename, mode="w", encoding="utf-8") as f: 193 | for _li, _l in enumerate(srt_list): 194 | if _li == len(srt_list) - 1: 195 | info = "{}\n{}\n{}".format(_li + 1, _l[0], _l[1]) 196 | else: 197 | info = "{}\n{}\n{}\n\n".format(_li + 1, _l[0], _l[1]) 198 | await f.write(info) 199 | 200 | 201 | async def srt_regen_new(f_srt, f_save, flag): 202 | srt_list = await load_srt_new(f_srt, flag) 203 | await save_srt(f_save, srt_list) 204 | 205 | 206 | class CustomSubMaker(edge_tts.SubMaker): 207 | """重写此方法更好的支持中文""" 208 | 209 | async def generate_cn_subs(self, text): 210 | 211 | PUNCTUATION = [",", "。", "!", "?", ";", ":", "”", ",", "!"] 212 | 213 | def clause(self): 214 | start = 0 215 | i = 0 216 | text_list = [] 217 | while i < len(text): 218 | if text[i] in PUNCTUATION: 219 | try: 220 | while text[i] in PUNCTUATION: 221 | i += 1 222 | except IndexError: 223 | pass 224 | text_list.append(text[start:i]) 225 | start = i 226 | i += 1 227 | return text_list 228 | 229 | self.text_list = clause(self) 230 | if len(self.subs) != len(self.offset): 231 | raise ValueError("subs and offset are not of the same length") 232 | data = "WEBVTT\r\n\r\n" 233 | j = 0 234 | for text in self.text_list: 235 | text = await self.remove_non_chinese_chars(text) 236 | try: 237 | start_time = self.offset[j][0] 238 | except IndexError: 239 | return data 240 | try: 241 | while self.subs[j + 1] in text: 242 | j += 1 243 | except IndexError: 244 | pass 245 | data += edge_tts.submaker.formatter(start_time, self.offset[j][1], text) 246 | j += 1 247 | return data 248 | 249 | async def remove_non_chinese_chars(self, text): 250 | # 使用正则表达式匹配非中文字符和非数字 251 | pattern = re.compile(r"[^\u4e00-\u9fff0-9]+") 252 | # 使用空字符串替换匹配到的非中文字符和非数字 253 | cleaned_text = re.sub(pattern, "", text) 254 | return cleaned_text 255 | 256 | 257 | async def edge_gen_srt2(f_txt, f_mp3, f_vtt, f_srt, p_voice, p_rate, p_volume) -> None: 258 | content = f_txt 259 | communicate = edge_tts.Communicate( 260 | text=content, voice=p_voice, rate=p_rate, volume=p_volume 261 | ) 262 | sub_maker = CustomSubMaker() 263 | async with aiofiles.open(f_mp3, "wb") as file: 264 | async for chunk in communicate.stream(): 265 | if chunk["type"] == "audio": 266 | await file.write(chunk["data"]) 267 | elif chunk["type"] == "WordBoundary": 268 | sub_maker.create_sub( 269 | (chunk["offset"], chunk["duration"]), chunk["text"] 270 | ) 271 | 272 | async with aiofiles.open(f_vtt, "w", encoding="utf-8") as file: 273 | content_to_write = await sub_maker.generate_cn_subs(content) 274 | await file.write(content_to_write) 275 | 276 | # vtt -》 srt 277 | idx = 1 # 字幕序号 278 | with open(f_srt, "w", encoding="utf-8") as f_out: 279 | for line in open(f_vtt, encoding="utf-8"): 280 | if "-->" in line: 281 | f_out.write("%d\n" % idx) 282 | idx += 1 283 | line = line.replace(".", ",") # 这行不是必须的,srt也能识别'.' 284 | if idx > 1: # 跳过header部分 285 | f_out.write(line) 286 | 287 | 288 | async def create_voice_srt_new2( 289 | index, file_txt, save_dir, p_voice=role, p_rate=rate, p_volume=volume 290 | ): 291 | mp3_name = f"{index}.mp3" 292 | vtt_name = f"{index}.vtt" 293 | srt_name = f"{index}.tmp.srt" 294 | srt_name_final = f"{index}.srt" 295 | 296 | file_mp3 = os.path.join(save_dir, mp3_name) 297 | file_vtt = os.path.join(save_dir, vtt_name) 298 | file_srt = os.path.join(save_dir, srt_name) 299 | file_srt_final = os.path.join(save_dir, srt_name_final) 300 | 301 | await edge_gen_srt2(file_txt, file_mp3, file_vtt, file_srt, p_voice, p_rate, p_volume) 302 | 303 | await srt_regen_new(file_srt, file_srt_final, False) 304 | 305 | # 删除其他生成文件 306 | os.remove(file_vtt) 307 | os.remove(file_srt) 308 | 309 | return file_mp3, file_srt_final 310 | -------------------------------------------------------------------------------- /chatgpt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -*- 3 | # @author:anning 4 | # @email:anningforchina@gmail.com 5 | # @time:2024/05/01 23:40 6 | # @file:chatgpt.py 7 | 8 | from openai import OpenAI 9 | 10 | from load_config import get_yaml_config 11 | 12 | config = get_yaml_config() 13 | ForwardKey = config["chatgpt"]["ForwardKey"] 14 | base_url = config["chatgpt"]["url"] 15 | model = config["chatgpt"]["model"] 16 | 17 | 18 | class Main: 19 | 20 | client = OpenAI( 21 | api_key=ForwardKey, 22 | base_url=base_url, 23 | ) 24 | 25 | def chat(self, query, history): 26 | 27 | history += [{ 28 | "role": "user", 29 | "content": query 30 | }] 31 | 32 | completion = self.client.chat.completions.create( 33 | model=model, 34 | messages=history, 35 | ) 36 | 37 | result = completion.choices[0].message.content 38 | 39 | history += [{ 40 | "role": "assistant", 41 | "content": result 42 | }] 43 | 44 | return history, result, completion.usage.total_tokens 45 | -------------------------------------------------------------------------------- /check_path.py: -------------------------------------------------------------------------------- 1 | import os 2 | import subprocess 3 | import sys 4 | import urllib.request 5 | import zipfile 6 | 7 | import nltk 8 | import requests 9 | from load_config import get_yaml_config 10 | config = get_yaml_config() 11 | server_ip = config["stable_diffusion"]["server_ip"] 12 | 13 | 14 | def check_command_installed(command): 15 | """检查命令是否安装在系统中""" 16 | try: 17 | subprocess.run([command, '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True) 18 | print(f"{command} 已安装。") 19 | except (subprocess.CalledProcessError, FileNotFoundError): 20 | print(f"警告:未检测到 {command}。") 21 | 22 | 23 | def check_python_version(min_version=(3, 8)): 24 | """检查Python版本是否符合要求""" 25 | if sys.version_info >= min_version: 26 | print(f"Python 版本符合要求:{sys.version.split()[0]}。") 27 | else: 28 | print(f"警告:Python 版本不符合要求,当前版本:{sys.version.split()[0]},需要 >= {'.'.join(map(str, min_version))}。") 29 | 30 | 31 | def download_and_install_nltk_data(package_name): 32 | try: 33 | # 检查包是否已经下载 34 | nltk.data.find(f'tokenizers/{package_name}') 35 | print(f"{package_name} 数据包已经安装。") 36 | except LookupError: 37 | # 如果没有安装,则下载并安装数据包 38 | print(f"{package_name} 数据包未安装,正在下载...") 39 | 40 | # 定义下载 URL 和目标路径 41 | url = f'https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/packages/tokenizers/{package_name}.zip' 42 | download_path = f'{package_name}.zip' 43 | 44 | # 下载文件 45 | urllib.request.urlretrieve(url, download_path) 46 | print(f"{package_name} 数据包下载完成。") 47 | 48 | # 找到NLTK数据目录 49 | nltk_data_dir = nltk.data.path[0] if nltk.data.path else os.path.join(os.path.expanduser('~'), 'nltk_data') 50 | extract_path = os.path.join(nltk_data_dir, 'tokenizers') 51 | 52 | # 如果tokenizers目录不存在,则创建它 53 | if not os.path.exists(extract_path): 54 | os.makedirs(extract_path) 55 | 56 | # 解压文件到目标路径 57 | with zipfile.ZipFile(download_path, 'r') as zip_ref: 58 | zip_ref.extractall(extract_path) 59 | 60 | # 删除下载的 zip 文件 61 | os.remove(download_path) 62 | 63 | print(f"{package_name} 数据包已安装到 {extract_path}") 64 | 65 | 66 | def check_api_response(url): 67 | """检查API接口是否可调用""" 68 | try: 69 | response = requests.get(url) 70 | if response.status_code == 200: 71 | print(f"API 接口调用成功:{url}。") 72 | else: 73 | print(f"警告:API 接口调用失败,状态码:{response.status_code},接口:{url}。") 74 | except requests.RequestException as e: 75 | print(f"警告:无法连接到 API 接口:{url},错误:{e}。") 76 | 77 | 78 | if __name__ == "__main__": 79 | # 检查 ImageMagick 和 ffmpeg 是否安装 80 | check_command_installed('magick') # ImageMagick 的命令通常是 `magick` 81 | check_command_installed('ffmpeg') 82 | 83 | # 检查 Python 版本 84 | check_python_version() 85 | 86 | # 检测SD 87 | check_api_response(server_ip) 88 | 89 | # punkt 为英语包 其他包替换 90 | download_and_install_nltk_data('punkt') -------------------------------------------------------------------------------- /config.yaml: -------------------------------------------------------------------------------- 1 | # 书配置 记得要加一个空格!!!!!!!! 2 | book: 3 | # 小说书名 要和文件同目录 不要带.txt 4 | name: 5 | # 是否开启记忆,意外退出重新启动从上次意外退出的地方开始执行 6 | memory: true 7 | # 小说使用的语言 默认 zh | en 为英语 具体请查看阿里云翻译的文档 8 | language: zh 9 | # 批量文件处理 使用mass_production.py 文件 10 | batch: 11 | # 资源文件目录 12 | source_path: 13 | # 输出文件目录 14 | output_path: 15 | # 尾部视频拼接路径 16 | ending_splice_path: 17 | # 音频 18 | audio: 19 | # 每行的字数限制 20 | limit: 18 21 | # 角色 终端输入 edge-tts --list-voices 可以查看所有声音 22 | # 推荐 zh-CN-YunxiNeural 男 zh-CN-XiaoyiNeural 一般 女 zh-CN-XiaoxiaoNeural 最好 女 23 | role: zh-CN-YunxiNeural 24 | # 语速 25 | rate: +30% 26 | # 音量 27 | volume: +100% 28 | # 是否开启bgm 开启bgm 项目下要有一个bgm的目录 29 | bgm: true 30 | # 主音频分贝db 31 | main_db: 15 32 | # 背景音频分贝db 33 | bgm_db: -15 34 | 35 | # 分词 36 | potential: 37 | # 角色名字最小长度 38 | min_length: 2 39 | # 角色名字最大长度 40 | max_length: 4 41 | # 角色数量 42 | top_n: 2 43 | # 每张图片的最小文字数量 44 | min_words: 30 45 | # 每张图片的最大文字数量 46 | max_words: 40 47 | # 是否使用阿里云翻译 不使用GPT 48 | translate: true 49 | # 阿里云翻译key 50 | access_key_id: 51 | # 阿里云翻译access_key_secret 52 | access_key_secret: 53 | 54 | # 这里只放常规参数,更多参数请修改stable diffusion.json 55 | stable_diffusion: 56 | # 服务器ip 57 | server_ip: http://127.0.0.1:7860 58 | # 图片高 59 | height: 960 60 | # 图片宽 61 | width: 540 62 | # lora 多个用英文,隔开 63 | lora: 64 | # 角色固定 使用 Reference 65 | role: false 66 | 67 | # 合成视频配置 68 | video: 69 | # ImageMagick 路径 # C:\Program Files\ImageMagick-7.1.1-Q16-HDRI\magick.exe 70 | imagemagick_path: 71 | # 字幕字体大小 72 | fontsize: 12 73 | # 字体颜色 74 | fontcolor: FFFFFF 75 | # 字体文件 要求在项目目录下 76 | fontfile: simhei.ttf 77 | # 描边颜色 内描边 78 | stroke_color: yellow 79 | # 描边宽 80 | stroke_width: 1.2 81 | # 文字间距 82 | kerning: 1 83 | # 字幕位置 越小越靠山 越大越靠下 0 - 1 开启ffmpeg后 6=上 10中 2下 84 | position: 10 85 | # 使用moviepy或者ffmpeg合成视频 86 | use_moviepy: false 87 | # 一次性合成 不用分段合成 视频效果更好 需要安装ffmpeg环境 88 | once: true 89 | # 是否开启动画,只有once开启时候才会有动画 90 | animation: true 91 | # 动画幅度比例 最佳1.2 92 | animation_speed: 1.2 93 | # 是否开启字幕 94 | subtitles: true 95 | 96 | chatgpt: 97 | # ForwardKey 98 | ForwardKey: ollama 99 | # url 100 | url: https://oa.api2d.net/v1 101 | # 最大token数量 102 | max_token: 16385 103 | # 模型 104 | model: gpt-3.5-turbo -------------------------------------------------------------------------------- /cover_drawing.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -*- 3 | # @author:anning 4 | # @email:anningforchina@gmail.com 5 | # @time:2024/04/11 15:02 6 | # @file:cover_drawing.py 7 | from PIL import Image, ImageDraw, ImageFont 8 | 9 | 10 | def add_watermark(image_path, output_path, text, font_path="simhei.ttf", font_color=(255, 165, 0), 11 | margin_percentage=0.1): 12 | # 打开图片 13 | image = Image.open(image_path).convert("RGBA") 14 | image_width, image_height = image.size 15 | 16 | # 创建ImageDraw对象 17 | draw = ImageDraw.Draw(image) 18 | 19 | # 通过图片宽度和预定的边距百分比动态计算最大允许的文字宽度 20 | max_text_width = image_width * (1 - 2 * margin_percentage) 21 | 22 | # 初始化字体大小 23 | font_size = 1 24 | font = ImageFont.truetype(font_path, font_size) 25 | text_width, text_height = draw.textsize(text, font=font) 26 | 27 | # 动态调整字体大小,直到文字宽度接近最大允许宽度 28 | while text_width < max_text_width and text_height < image_height: 29 | font_size += 1 30 | font = ImageFont.truetype(font_path, font_size) 31 | text_width, text_height = draw.textsize(text, font=font) 32 | 33 | # 为了避免超出最大宽度,最后减小一点字体大小 34 | font_size -= 1 35 | font = ImageFont.truetype(font_path, font_size) 36 | 37 | # 计算文字位置以居中显示 38 | position = ((image_width - text_width) / 2, (image_height - text_height) / 2) 39 | 40 | # 绘制文字阴影或边线 41 | shadow_offset = 2 42 | for x_offset in range(-shadow_offset, shadow_offset + 1): 43 | for y_offset in range(-shadow_offset, shadow_offset + 1): 44 | draw.text((position[0] + x_offset, position[1] + y_offset), text, fill=(0, 0, 0), font=font) 45 | 46 | # 在阴影或边线之上绘制原始颜色的文字 47 | draw.text(position, text, fill=font_color, font=font) 48 | 49 | # 如果输出格式为JPG,需要将图像转换为RGB模式 50 | if output_path.endswith(".jpg") or output_path.endswith(".jpeg"): 51 | image = image.convert("RGB") 52 | 53 | # 保存图片 54 | image.save(output_path) 55 | 56 | 57 | if __name__ == "__main__": 58 | # 使用示例 59 | add_watermark( 60 | image_path="image1.png", # 图片路径 61 | output_path="output_image.png", # 输出图片路径 62 | text="《回到古代从种田开始1》", # 水印文字 63 | font_path="simhei.ttf", # 字体路径,确保这个路径在你的系统上是有效的 64 | font_color=(255, 165, 0) # 橙色字体 65 | ) 66 | -------------------------------------------------------------------------------- /extract_role.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | import jieba 4 | 5 | from load_config import get_yaml_config 6 | 7 | config = get_yaml_config() 8 | min_length = config["potential"]["min_length"] 9 | max_length = config["potential"]["max_length"] 10 | top_n = config["potential"]["top_n"] 11 | 12 | 13 | async def extract_potential_names(text): 14 | 15 | # 使用 jieba 进行中文分词 16 | words = jieba.lcut(text) 17 | 18 | # 过滤出符合要求的词汇 19 | filtered_words = [word for word in words if min_length <= len(word) <= max_length] 20 | 21 | # 统计词频 22 | word_counts = Counter(filtered_words) 23 | 24 | # 选取频率最高的词汇 25 | top_names = [word for word, count in word_counts.most_common(top_n)] 26 | 27 | return top_names 28 | 29 | 30 | if __name__ == "__main__": 31 | # 假设这是你的中文小说文本 32 | with open("./表白.txt", "r", encoding="utf8") as f: 33 | novel_text = f.read().replace("\n", "").replace("\r", "").replace("\r\n", "") 34 | 35 | # 提取文本中的潜在人名 36 | names = extract_potential_names(novel_text) 37 | 38 | print(names) 39 | -------------------------------------------------------------------------------- /install.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | chcp 65001 3 | 4 | echo 创建虚拟环境... 5 | python -m venv .venv 6 | 7 | echo 激活虚拟环境... 8 | call .venv\Scripts\activate 9 | 10 | echo 安装依赖... 11 | pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt 12 | 13 | echo 启动程序... 14 | python main.py 15 | 16 | echo 运行完成,按任意键退出。 17 | pause > nul 18 | -------------------------------------------------------------------------------- /load_config.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -*- 3 | # @author:anning 4 | # @email:anningforchina@gmail.com 5 | # @time:2024/04/06 11:33 6 | # @file:load_config.py 7 | import json 8 | import os 9 | import yaml 10 | from aiofiles import os as aio_os 11 | import aiofiles 12 | # 自用配置文件路径 13 | local_config_path = "local_config.yaml" 14 | # 公共配置文件路径 15 | public_config_path = "config.yaml" 16 | 17 | # 尝试打开自用配置文件 18 | if os.path.exists(local_config_path): 19 | config_path = local_config_path 20 | else: 21 | # 如果自用配置文件不存在,使用公共配置文件 22 | config_path = public_config_path 23 | 24 | 25 | def get_yaml_config(config_path=config_path): 26 | """读取yaml配置文件""" 27 | with open(config_path, 'r', encoding='utf-8') as f: 28 | config = yaml.safe_load(f) 29 | return config 30 | 31 | 32 | def edit_yaml_config(data, config_path=config_path): 33 | """读取yaml配置文件""" 34 | with open(config_path, 'w', encoding='utf-8') as file: 35 | yaml.dump(data, file) 36 | 37 | # 自用配置文件路径 38 | local_stable_diffusion_path = "stable_diffusion.json" 39 | # 公共配置文件路径 40 | public_stable_diffusion_path = "local_stable_diffusion.json" 41 | 42 | 43 | # 尝试打开自用配置文件 44 | if os.path.exists(public_stable_diffusion_path): 45 | stable_diffusion_path = public_stable_diffusion_path 46 | else: 47 | # 如果自用配置文件不存在,使用公共配置文件 48 | stable_diffusion_path = local_stable_diffusion_path 49 | 50 | 51 | def get_sd_config(config_path=stable_diffusion_path): 52 | """读取stable diffusion配置文件""" 53 | with open(config_path, 'r', encoding='utf-8') as f: 54 | config = json.load(f) 55 | return config 56 | 57 | 58 | async def print_tip(tip, blank_line=0): 59 | """打印提示文字和空行""" 60 | blank = '\n' * blank_line if blank_line else '' 61 | print('-' * 20, tip, '-' * 20, blank) 62 | 63 | 64 | async def check_file_exists(file_path): 65 | exists = await aio_os.path.exists(file_path) 66 | return exists 67 | 68 | 69 | async def get_file(file_path): 70 | async with aiofiles.open(file_path, "r", encoding="utf-8") as f: 71 | content = await f.read() 72 | return content 73 | 74 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -*- 3 | # @author:anning 4 | # @email:anningforchina@gmail.com 5 | # @time:2024/04/06 17:20 6 | # @file:async_main.py 7 | import asyncio 8 | import json 9 | import os 10 | import random 11 | from concurrent.futures import ProcessPoolExecutor 12 | 13 | import aiofiles 14 | 15 | from check_path import check_command_installed, check_python_version 16 | from extract_role import extract_potential_names 17 | from load_config import get_yaml_config, print_tip 18 | from participle import main as participle 19 | from prompt import generate_prompt 20 | from sd import new_draw_picture 21 | from video_composition import Main as vc 22 | from voice_caption import voice_srt 23 | 24 | config = get_yaml_config() 25 | 26 | memory = config["book"]["memory"] 27 | once = config["video"]["once"] 28 | is_translate = config["potential"]["translate"] 29 | name = config["book"]["name"] 30 | language = config["book"]["language"] 31 | role_enabled = config["stable_diffusion"]["role"] 32 | 33 | # if not name: 34 | # raise Exception("请输入书名") 35 | 36 | 37 | async def role(path, book_name): 38 | await print_tip("开始提取角色") 39 | role_path = os.path.join(path, f"{book_name}.txt") 40 | async with aiofiles.open(role_path, "r", encoding="utf-8") as f: 41 | content = await f.read() 42 | novel_text = content.replace("\n", "").replace("\r", "").replace("\r\n", "") 43 | 44 | # 提取文本中的潜在人名 45 | names = await extract_potential_names(novel_text) 46 | await print_tip(f"查询出角色:{', '.join(names)}") 47 | if role_enabled: 48 | role_file = os.path.join(path, "role.json") 49 | if not os.path.exists(role_file): 50 | all_files = os.listdir("roles") 51 | images = [file for file in all_files if file.endswith('.png')] 52 | # 固定任务 抽卡 53 | data = [] 54 | for i, n in enumerate(names): 55 | data.append({"name": n, "role": random.sample(images, len(names))[i]}) 56 | 57 | async with aiofiles.open(role_file, "w", encoding="utf-8") as f: 58 | await f.write(json.dumps(data, ensure_ascii=False)) 59 | 60 | if not is_translate: 61 | async with aiofiles.open("prompt.txt", "r", encoding="utf-8") as f: 62 | prompt_text = await f.read() 63 | text_ = "" 64 | for n in names: 65 | text_ += f"- {n}\n" 66 | async with aiofiles.open(f"{book_name}prompt.txt", "w", encoding="utf-8") as f: 67 | await f.write(prompt_text + text_) 68 | 69 | 70 | # 包装函数,用于在新进程中执行 voice_srt 71 | def run_voice_srt_in_new_process(participle_path, path, name): 72 | # 在新进程中创建新的事件循环并运行 voice_srt 73 | loop = asyncio.new_event_loop() 74 | asyncio.set_event_loop(loop) 75 | loop.run_until_complete(voice_srt(participle_path, path, f'{name}.txt', name)) 76 | loop.close() 77 | 78 | 79 | async def main(): 80 | if not os.path.exists(f"{name}.txt"): 81 | raise Exception("请将小说文件放入根目录") 82 | path = os.path.join(name, "participle") 83 | participle_path = os.path.join(path, f"{name}.txt") 84 | 85 | await participle(f"{name}.txt", path, participle_path) 86 | 87 | await role(path, name) 88 | 89 | # 创建 ProcessPoolExecutor 来运行新的进程 90 | executor = ProcessPoolExecutor() 91 | 92 | # 在新的进程中异步执行 voice_srt 93 | # 注意:这里不需要使用 run_coroutine_threadsafe 94 | loop = asyncio.get_running_loop() 95 | future = loop.run_in_executor(executor, run_voice_srt_in_new_process, participle_path, path, name) 96 | 97 | # await asyncio.gather(voice_srt(participle_path, path), generate_prompt(path, path, name), draw_picture(path)) 98 | # await asyncio.gather(generate_prompt(path, path, name), draw_picture(path), future) 99 | await generate_prompt(path, path, name) 100 | save_path = os.path.join(name, "pictures") 101 | await asyncio.gather(new_draw_picture(path, name, save_path), future) 102 | # await asyncio.gather(new_draw_picture(path), voice_srt(participle_path, path)) 103 | 104 | await print_tip("开始合成视频") 105 | picture_path_path = os.path.abspath(f"./{name}/pictures") 106 | audio_path_path = os.path.abspath(f"./{name}/participle") 107 | save_path = os.path.abspath(f"./{name}/video") 108 | vc().merge_video(picture_path_path, audio_path_path, name, save_path) 109 | 110 | 111 | if __name__ == "__main__": 112 | # 检查 ImageMagick 和 ffmpeg 是否安装 113 | check_command_installed('magick') # ImageMagick 的命令通常是 `magick` 114 | check_command_installed('ffmpeg') 115 | # 检查 Python 版本 116 | check_python_version() 117 | asyncio.run(main()) 118 | -------------------------------------------------------------------------------- /mass_production.py: -------------------------------------------------------------------------------- 1 | # 编写此脚本的目的是为了批量生产 会将source_path下的文件生成到dest_path下 2 | import asyncio 3 | import os.path 4 | import re 5 | import subprocess 6 | 7 | from load_config import get_yaml_config 8 | from main import role 9 | from translate import Sample as translate 10 | from cover_drawing import add_watermark 11 | from participle import main as participle 12 | from prompt import generate_prompt 13 | from sd import new_draw_picture 14 | from voice_caption import voice_srt 15 | from video_composition import Main as vc 16 | from sd import Main as sd 17 | 18 | config = get_yaml_config() 19 | 20 | width = config["stable_diffusion"]["width"] 21 | height = config["stable_diffusion"]["height"] 22 | source_path = config["batch"]["source_path"] 23 | dest_path = config["batch"]["output_path"] 24 | ending_splice_video_path = config["batch"]["ending_splice_path"] 25 | 26 | 27 | def create_cover(save_path, filename, directory_nickname=None): 28 | obj = { 29 | "prompt": "Cover image, shocking, eye-catching,", 30 | "negative_prompt": "nsfw,(low quality,normal quality,worst quality,jpeg artifacts),cropped,monochrome,lowres,low saturation,((watermark)),(white letters)" 31 | } 32 | cover = True 33 | if directory_nickname: 34 | dirname_path_ = os.path.dirname(save_path) 35 | dirname_path = os.path.dirname(dirname_path_) 36 | 37 | if os.path.exists(os.path.join(dirname_path, "cover.png")): 38 | cover = False 39 | if cover: 40 | obj["prompt"] += translate.main(filename) 41 | if directory_nickname: 42 | asyncio.run(sd().draw_picture(obj, "cover", dirname_path)) 43 | else: 44 | asyncio.run(sd().draw_picture(obj, "cover", save_path)) 45 | if directory_nickname: 46 | cover_path = os.path.join(dirname_path, "cover.png") 47 | out_path = os.path.join(save_path, "cover.png") 48 | else: 49 | cover_path = os.path.join(save_path, "cover.png") 50 | out_path = os.path.join(save_path, "out_cover.png") 51 | add_watermark(cover_path, out_path, f"《{filename}》") 52 | if not directory_nickname: 53 | os.replace(out_path, cover_path) 54 | return out_path if directory_nickname else cover_path 55 | 56 | 57 | def merge_cover(save_path, filename, video_path, directory_nickname=None): 58 | cover_video = os.path.join(save_path, "temp_cover_video.mp4") 59 | cover_image = create_cover(save_path, filename, directory_nickname) 60 | # 将 PNG 图片转换为短视频片段 61 | subprocess.run([ 62 | 'ffmpeg', '-y', '-loop', '1', '-framerate', '25', '-i', cover_image, 63 | '-c:v', 'libx264', '-t', '0.04', '-pix_fmt', 'yuv420p', 64 | '-vf', f'scale={width}:{height}', cover_video 65 | ], check=True) 66 | 67 | output_video = os.path.join(save_path, "output.mp4") 68 | ffmpeg_command = [ 69 | "ffmpeg", 70 | "-y", 71 | "-i", cover_video, # 第一个视频文件路径 72 | "-i", video_path, # 第二个视频文件路径 73 | "-filter_complex", 74 | "[0:v][1:v]concat=n=2:v=1:a=0[outv]", # 使用concat滤镜进行拼接 75 | "-map", "[outv]", # 映射视频输出 76 | "-map", "1:a?", # 映射音频输出 77 | output_video # 输出文件路径 78 | ] 79 | subprocess.run(ffmpeg_command, check=True) 80 | # 删除临时的封面视频文件 81 | os.remove(cover_video) 82 | os.replace(output_video, video_path) 83 | 84 | 85 | def merge_videos(secondary_video_path, output_video_path, name): 86 | main_video_path = os.path.join(output_video_path, f"{name}.mp4") 87 | final_path = os.path.join(output_video_path, f"{name}_final.mp4") 88 | ffmpeg_command = [ 89 | "ffmpeg", 90 | "-y", 91 | "-i", main_video_path, # 第一个视频文件路径 92 | "-i", secondary_video_path, # 第二个视频文件路径 93 | "-filter_complex", 94 | "[0:v][0:a][1:v][1:a]concat=n=2:v=1:a=1[outv][outa]", # 使用concat滤镜进行拼接 95 | "-map", "[outv]", # 映射视频输出 96 | "-map", "[outa]", # 映射音频输出 97 | final_path # 输出文件路径 98 | ] 99 | subprocess.run(ffmpeg_command, check=True) 100 | 101 | # 清理临时文件 102 | os.replace(final_path, main_video_path) 103 | 104 | 105 | class Colors: 106 | HEADER = '\033[95m' 107 | OKBLUE = '\033[36m' 108 | BRIGHT_BLUE = '\033[94m' 109 | OKCYAN = '\033[96m' 110 | OKGREEN = '\033[92m' 111 | WARNING = '\033[93m' 112 | FAIL = '\033[91m' 113 | ENDC = '\033[0m' 114 | BOLD = '\033[1m' 115 | UNDERLINE = '\033[4m' 116 | 117 | 118 | # 使用正则表达式从文件名中提取数字 119 | def extract_number(filename): 120 | match = re.search(r'\d+', filename) 121 | if match: 122 | return int(match.group()) 123 | return float('inf') 124 | 125 | 126 | def main(source_path, classify, directory_nickname=None, dest_path=dest_path): 127 | txt_files = [f for f in os.listdir(source_path) if f.endswith('.txt')] 128 | sorted_files = sorted(txt_files, key=extract_number) 129 | for filename in sorted_files: 130 | file_path = os.path.join(source_path, filename) 131 | if os.path.isfile(file_path): 132 | name = filename.split(".")[0] 133 | store_path = os.path.join(dest_path, name) 134 | if directory_nickname: 135 | store_path = os.path.join(dest_path, directory_nickname, name) 136 | path = os.path.join(store_path, "participle") 137 | participle_path = os.path.join(path, f"{name}.txt") 138 | picture_save_path = os.path.join(store_path, "pictures") 139 | save_path = os.path.join(store_path, "video") 140 | asyncio.run(participle(file_path, path, participle_path)) 141 | asyncio.run(role(path, name)) 142 | if classify in ["1", "2"]: 143 | asyncio.run(generate_prompt(path, path, name)) 144 | asyncio.run(new_draw_picture(path, name, picture_save_path)) 145 | if classify in ["1", "3"]: 146 | asyncio.run(voice_srt(participle_path, path, file_path, name)) 147 | if classify in ["1", "4"]: 148 | is_exists = vc().merge_video(picture_save_path, path, name, save_path) 149 | if bool(ending_splice_video_path) and not is_exists: 150 | merge_videos(ending_splice_video_path, save_path, name) 151 | if not is_exists: 152 | merge_cover(save_path, name, os.path.join(save_path, f"{name}.mp4"), directory_nickname) 153 | # 将原文移到新目录 并且名字加上已完成 154 | os.rename(file_path, os.path.join(store_path, f"{name}_已完成.txt")) 155 | 156 | 157 | if __name__ == "__main__": 158 | # 使用定义好的颜色和样式来打印选项 159 | print(f"{Colors.HEADER}欢迎使用我们的视频处理工具{Colors.ENDC}") 160 | print(f"{Colors.OKGREEN}1: {Colors.BOLD}一键完成{Colors.ENDC}") 161 | print(f"{Colors.BRIGHT_BLUE}2: {Colors.BOLD}生成分词+图片{Colors.ENDC}") 162 | print(f"{Colors.OKGREEN}3: {Colors.BOLD}生成语音{Colors.ENDC}") 163 | print(f"{Colors.WARNING}4: {Colors.BOLD}已经检测过图片,直接合成视频{Colors.ENDC}") 164 | print(f"{Colors.WARNING}5: {Colors.BOLD}先固定角色{Colors.ENDC}") 165 | print(f"{Colors.HEADER}输入后回车,默认为1{Colors.ENDC}") 166 | classify = input(f"{Colors.OKCYAN}请输入要操作的类型:{Colors.ENDC}") or "1" 167 | entries = os.listdir(source_path) 168 | subdirectories = [ 169 | entry for entry in entries 170 | if 171 | os.path.isdir(os.path.join(source_path, entry)) and not entry.startswith('.') and not entry.startswith('_') 172 | ] 173 | # 这里是所有source_path目录下的子目录,首先先 174 | for directory in subdirectories: 175 | main(os.path.join(source_path, directory), classify, directory) 176 | main(source_path, classify, None) 177 | -------------------------------------------------------------------------------- /participle.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import os 3 | 4 | from load_config import get_yaml_config, print_tip, check_file_exists 5 | 6 | import aiofiles 7 | from aiofiles import os as aio_os 8 | 9 | from utils.english_segment import split_text_into_paragraphs, split_paragraphs_into_sentences, \ 10 | split_spain_paragraphs_into_sentences 11 | 12 | config = get_yaml_config() 13 | min_words = config["potential"]["min_words"] 14 | max_words = config["potential"]["max_words"] 15 | memory = config["book"]["memory"] 16 | language = config["book"]["language"] 17 | 18 | 19 | # 根据小说文本进行分词 20 | async def combine_strings(strings): 21 | combined = [] 22 | current_srt = "" 23 | for s in strings: 24 | if min_words <= len(current_srt + s) <= max_words: 25 | combined.append(current_srt + s + "\n") 26 | current_srt = "" 27 | elif len(current_srt) > max_words: 28 | combined.append(current_srt + "\n") 29 | current_srt = s 30 | else: 31 | current_srt += s 32 | if current_srt: 33 | combined.append(current_srt + "\n") 34 | return combined 35 | 36 | 37 | async def participle(text): 38 | PUNCTUATION = [",", "。", "!", "?", ";", ":", "”", ",", "!", "…"] 39 | 40 | # async def clause(): 41 | # start = 0 42 | # i = 0 43 | # text_list = [] 44 | # while i < len(text): 45 | # if text[i] in PUNCTUATION: 46 | # try: 47 | # while text[i] in PUNCTUATION: 48 | # i += 1 49 | # except IndexError: 50 | # pass 51 | # text_list.append(text[start:i].strip()) 52 | # start = i 53 | # i += 1 54 | # return text_list 55 | # 56 | # text_list = await clause() 57 | # result = await combine_strings(text_list) 58 | # return result 59 | async def clause(): 60 | start = 0 61 | i = 0 62 | text_list = [] 63 | while i < len(text): 64 | if text[i] in PUNCTUATION: 65 | try: 66 | while text[i] in PUNCTUATION: 67 | i += 1 68 | except IndexError: 69 | pass 70 | text_list.append(text[start:i].strip()) 71 | start = i 72 | i += 1 73 | return text_list 74 | 75 | if language == "zh": 76 | text_list = await clause() 77 | result = await combine_strings(text_list) 78 | return result 79 | elif language == "en": 80 | paragraphs = split_text_into_paragraphs(text) 81 | return [sentence + '\n' for sentence in split_paragraphs_into_sentences(paragraphs)] 82 | 83 | elif language == "es": 84 | paragraphs = split_text_into_paragraphs(text) 85 | return [sentence + '\n' for sentence in split_spain_paragraphs_into_sentences(paragraphs)] 86 | else: 87 | raise Exception("Unsupported language") 88 | 89 | 90 | 91 | async def main(name_path, path, participle_path): 92 | await print_tip("正在分词") 93 | 94 | async with aiofiles.open(name_path, "r", encoding="utf-8") as f: 95 | content = await f.read() 96 | novel = content.replace("\n", "").replace("\r", "").replace("\r\n", "").replace("\u2003", "") 97 | await aio_os.makedirs(path, exist_ok=True) 98 | is_exists = await check_file_exists(participle_path) 99 | if memory and is_exists: 100 | await print_tip("读取缓存分词") 101 | else: 102 | async with aiofiles.open(participle_path, "w", encoding="utf-8") as f: 103 | participles = await participle(novel) 104 | await f.writelines(participles) 105 | await print_tip("分词完成") 106 | 107 | 108 | if __name__ == "__main__": 109 | with open("./斗破苍穹.txt", "r", encoding="utf-8") as f: 110 | novel = f.read().replace("\n", "").replace("\r", "").replace("\r\n", "").replace("\u2003", "") 111 | with open("./斗破苍穹txt.txt", "w", encoding="utf-8") as f: 112 | content = asyncio.run(participle(novel)) 113 | f.writelines(content) 114 | -------------------------------------------------------------------------------- /prompt.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | 4 | import aiofiles 5 | 6 | from api2d import Main 7 | from chatgpt import Main as GPT 8 | from load_config import get_yaml_config, check_file_exists, print_tip 9 | from translate import Sample as translate 10 | 11 | config = get_yaml_config() 12 | memory = config["book"]["memory"] 13 | is_translate = config["potential"]["translate"] 14 | role_enabled = config["stable_diffusion"]["role"] 15 | max_token = config["chatgpt"]["max_token"] 16 | 17 | 18 | def write_to_json(data, filename): 19 | try: 20 | with open(filename, "rb+") as file: 21 | file.seek(0, 2) # 移到文件末尾 22 | if file.tell(): # 如果文件非空 23 | file.seek(-1, 2) # 定位到文件的最后一个字符(即结尾的 ']' 前) 24 | file.truncate() # 删除最后一个字符(']') 25 | if file.tell() > 1: 26 | file.write(b",\n") # 如果不是文件开头,写入逗号和换行符 27 | else: 28 | file.write(b"\n") # 否则只写入换行符 29 | file.write(json.dumps(data).encode()) # 写入新的 JSON 对象 30 | file.write(b"\n]") # 重新添加结尾的 ']' 31 | else: # 如果文件为空 32 | file.write( 33 | json.dumps([data], indent=4).encode() 34 | ) # 创建新文件并写入数组 35 | except FileNotFoundError: 36 | with open(filename, "wb") as file: # 如果文件不存在,创建并写入 37 | file.write(json.dumps([data], indent=4).encode()) 38 | 39 | 40 | def extract_str(text): 41 | xxx = text.split("**Negative Prompt:**", 1) 42 | 43 | prompt = ( 44 | xxx[0] 45 | .replace("**Negative Prompt:**", "") 46 | .replace("**Prompt:**", "") 47 | .replace("Prompt:", "") 48 | .replace("\n", "") 49 | ) 50 | negative_prompt = ( 51 | xxx[1] 52 | .replace("**Negative Prompt:**", "") 53 | .replace("Negative", "") 54 | .replace("Prompt:", "") 55 | .replace("**Prompt:**", "") 56 | .replace("\n", "") 57 | ) 58 | 59 | return prompt, negative_prompt 60 | 61 | 62 | async def process_line2(line, line_number, prompt_json_save_path, messages_save_path, name, path): 63 | await print_tip(f"正在处理第{line_number}段") 64 | is_exists = await check_file_exists(prompt_json_save_path) 65 | is_message_exists = await check_file_exists(messages_save_path) 66 | if memory and is_exists: 67 | with open(prompt_json_save_path, "r", encoding="utf-8") as file: 68 | prompt_data = json.load(file) 69 | if line_number <= len(prompt_data): 70 | await print_tip(f"使用缓存:跳过第{line_number}段") 71 | return 72 | else: 73 | if is_message_exists: 74 | async with aiofiles.open( 75 | messages_save_path, "r", encoding="utf-8" 76 | ) as f: 77 | content = await f.read() 78 | messages = json.loads(content) 79 | text = f"第{line_number}段:" + line.strip() 80 | if not is_message_exists: 81 | with open(f"{name}prompt.txt", "r", encoding="utf-8") as f: 82 | messages = [ 83 | { 84 | "role": "system", 85 | "content": f.read(), 86 | } 87 | ] 88 | 89 | result, message, total_tokens = GPT().chat(text, messages) 90 | await print_tip(f"当前total_tokens:{total_tokens}") 91 | if total_tokens >= max_token: 92 | # token 已经达到上限 重新请求GPT 清空之前的记录 93 | os.remove(messages_save_path) 94 | return await process_line2(line, line_number, prompt_json_save_path, messages_save_path, name, path) 95 | else: 96 | prompt, negative_prompt = extract_str(message) 97 | obj = {"prompt": prompt, "negative_prompt": negative_prompt} 98 | if role_enabled: 99 | # 固定人物 100 | if os.path.join(path, "role.json"): 101 | with open(os.path.join(path, "role.json"), "r", encoding="utf-8") as file: 102 | role_data = json.load(file) 103 | roles = [] 104 | for role in role_data: 105 | if role["name"] in text: 106 | roles.append(role["name"]) 107 | obj["role"] = roles 108 | write_to_json(obj, prompt_json_save_path) 109 | messages = result 110 | with open(messages_save_path, "w") as f: 111 | f.write(json.dumps(messages)) 112 | return 113 | 114 | 115 | async def translates(text, line_number, prompt_json_save_path, path): 116 | is_exists = await check_file_exists(prompt_json_save_path) 117 | if memory and is_exists: 118 | with open(prompt_json_save_path, "r", encoding="utf-8") as file: 119 | prompt_data = json.load(file) 120 | if line_number <= len(prompt_data): 121 | return 122 | prompt = translate.main(text) 123 | obj = {"prompt": prompt, "negative_prompt": "nsfw,(low quality,normal quality,worst quality,jpeg artifacts),cropped,monochrome,lowres,low saturation,((watermark)),(white letters)"} 124 | if role_enabled: 125 | # 固定人物 126 | if os.path.join(path, "role.json"): 127 | with open(os.path.join(path, "role.json"), "r", encoding="utf-8") as file: 128 | role_data = json.load(file) 129 | roles = [] 130 | for role in role_data: 131 | if role["name"] in text: 132 | roles.append(role["name"]) 133 | obj["role"] = roles 134 | write_to_json(obj, prompt_json_save_path) 135 | 136 | 137 | async def generate_prompt(path, save_path, name): 138 | await print_tip("开始生成提示词") 139 | async with aiofiles.open(f"{path}/{name}.txt", "r", encoding="utf8") as file: 140 | # 初始化行数计数器 141 | lines = await file.readlines() 142 | # 循环输出每一行内容 143 | prompt_json_save_path = os.path.join(save_path, f"{name}.json") 144 | messages_save_path = os.path.join(save_path, f"{name}messages.json") 145 | for line_number, line in enumerate(lines, start=1): 146 | if line: 147 | if is_translate: 148 | await translates(line, line_number, prompt_json_save_path, path) 149 | else: 150 | await process_line2(line, line_number, prompt_json_save_path, messages_save_path, name, path) 151 | 152 | if __name__ == "__main__": 153 | generate_prompt() 154 | -------------------------------------------------------------------------------- /prompt.txt: -------------------------------------------------------------------------------- 1 | # Stable Diffusion prompt 助理 2 | 3 | 你来充当一位有艺术气息的Stable Diffusion prompt 助理。 4 | 5 | ## 任务 6 | 7 | 我用自然语言告诉你要生成的prompt的主题,你的任务是根据这个主题想象一幅完整的画面,然后转化成一份详细的、高质量的prompt,让Stable Diffusion可以生成高质量的图像,对内容有不明白的可以参考上下文。 8 | 9 | ## 背景介绍 10 | 11 | Stable Diffusion是一款利用深度学习的文生图模型,支持通过使用 prompt 来产生新的图像,描述要包含或省略的元素。 12 | 13 | ## prompt 概念 14 | 15 | - 完整的prompt包含“**Prompt:**”和"**Negative Prompt:**"两部分。 16 | - prompt 用来描述图像,由普通常见的单词构成,使用英文半角","做为分隔符。 17 | - negative prompt用来描述你不想在生成的图像中出现的内容。 18 | - 以","分隔的每个单词或词组称为 tag。所以prompt和negative prompt是由系列由","分隔的tag组成的。 19 | 20 | ## () 和 [] 语法 21 | 22 | 调整关键字强度的等效方法是使用 () 和 []。 (keyword) 将tag的强度增加 1.1 倍,与 (keyword:1.1) 相同,最多可加三层。 [keyword] 将强度降低 0.9 倍,与 (keyword:0.9) 相同。 23 | 24 | ## Prompt 格式要求 25 | 26 | 下面我将说明 prompt 的生成步骤,这里的 prompt 可用于描述人物、风景、物体或抽象数字艺术图画。你可以根据需要添加合理的、但不少于5处的画面细节。 27 | 28 | ### 1. prompt 要求 29 | 30 | - 你输出的 Stable Diffusion prompt 以“**Prompt:**”开头。 31 | - prompt 内容包含画面主体、材质、附加细节、图像质量、艺术风格、色彩色调、灯光等部分,但你输出的 prompt 不能分段,例如类似"medium:"这样的分段描述是不需要的,也不能包含":"和"."。 32 | - 画面主体:不简短的英文描述画面主体, 如 A girl in a garden,主体细节概括(主体可以是人、事、物、景)画面核心内容。这部分根据我每次给你的主题来生成。你可以添加更多主题相关的合理的细节。 33 | - 对于人物主题,你必须描述人物的眼睛、鼻子、嘴唇,例如'beautiful detailed eyes,beautiful detailed lips,extremely detailed eyes and face,longeyelashes',以免Stable Diffusion随机生成变形的面部五官,这点非常重要。你还可以描述人物的外表、情绪、衣服、姿势、视角、动作、背景等。人物属性中,1girl表示一个女孩,2girls表示两个女孩。 34 | - 材质:用来制作艺术品的材料。 例如:插图、油画、3D 渲染和摄影。 Medium 有很强的效果,因为一个关键字就可以极大地改变风格。 35 | - 附加细节:画面场景细节,或人物细节,描述画面细节内容,让图像看起来更充实和合理。这部分是可选的,要注意画面的整体和谐,不能与主题冲突。 36 | - 图像质量:这部分内容开头永远要加上“(best quality,4k,8k,highres,masterpiece:1.2),ultra-detailed,(realistic,photorealistic,photo-realistic:1.37)”, 这是高质量的标志。其它常用的提高质量的tag还有,你可以根据主题的需求添加:HDR,UHD,studio lighting,ultra-fine painting,sharp focus,physically-based rendering,extreme detail description,professional,vivid colors,bokeh。 37 | - 艺术风格:这部分描述图像的风格。加入恰当的艺术风格,能提升生成的图像效果。常用的艺术风格例如:portraits,landscape,horror,anime,sci-fi,photography,concept artists等。 38 | - 色彩色调:颜色,通过添加颜色来控制画面的整体颜色。 39 | - 灯光:整体画面的光线效果。 40 | - 人物:遇到匹配的人物,关于人物的形象描述相差不能太大 41 | 42 | ### 2. negative prompt 要求 43 | - negative prompt部分以"**Negative Prompt:**"开头,Negative Prompt 的内容是你想要避免出现在图像中的内容都可以。 44 | - 任何情况下,negative prompt都要包含这段内容:"nsfw,(low quality,normal quality,worst quality,jpeg artifacts),cropped,monochrome,lowres,low saturation,((watermark)),(white letters)" 45 | - 如果是人物相关的主题,你的输出需要另加一段人物相关的 negative prompt,内容为:“skin spots,acnes,skin blemishes,age spot,mutated hands,mutated fingers,deformed,bad anatomy,disfigured,poorly drawn face,extra limb,ugly,poorly drawn hands,missing limb,floating limbs,disconnected limbs,out of focus,long neck,long body,extra fingers,fewer fingers,,(multi nipples),bad hands,signature,username,bad feet,blurry,bad body”。 46 | 47 | ### 3. 限制: 48 | - tag 内容用英语单词或短语来描述,并不局限于我给你的单词。注意只能包含关键词或词组。 49 | - 注意不要输出句子,不要有任何解释。 50 | - tag数量限制40个以内,单词数量限制在60个以内。 51 | - tag不要带引号("")。 52 | - 使用英文半角","做分隔符。 53 | - tag 按重要性从高到低的顺序排列。 54 | - 我给你的主题可能是用中文描述,你给出的prompt和negative prompt只用英文。 55 | 56 | ### 4. 人物 57 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests 2 | edge_tts 3 | jieba 4 | pillow 5 | tqdm 6 | moviepy 7 | pyyaml 8 | aiofiles 9 | alibabacloud-alimt20181012 10 | openai 11 | nltk 12 | streamlit 13 | pillow==9.5 -------------------------------------------------------------------------------- /roles/女5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anning01/ComicTweets/2b3350cbaf46efc3484d2e716acb293bc5fb5ae7/roles/女5.png -------------------------------------------------------------------------------- /roles/女6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anning01/ComicTweets/2b3350cbaf46efc3484d2e716acb293bc5fb5ae7/roles/女6.png -------------------------------------------------------------------------------- /roles/男3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anning01/ComicTweets/2b3350cbaf46efc3484d2e716acb293bc5fb5ae7/roles/男3.png -------------------------------------------------------------------------------- /roles/男5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anning01/ComicTweets/2b3350cbaf46efc3484d2e716acb293bc5fb5ae7/roles/男5.png -------------------------------------------------------------------------------- /roles/男6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anning01/ComicTweets/2b3350cbaf46efc3484d2e716acb293bc5fb5ae7/roles/男6.png -------------------------------------------------------------------------------- /sd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -*- 3 | # @author:anning 4 | # @email:anningforchina@gmail.com 5 | # @time:2023/08/01 14:30 6 | # @file:app.py 7 | import asyncio 8 | import base64 9 | import json 10 | import os 11 | import io 12 | import aiofiles 13 | 14 | import aiohttp 15 | from PIL import Image 16 | from tqdm import tqdm 17 | 18 | from load_config import get_sd_config, get_yaml_config, check_file_exists, print_tip 19 | 20 | config = get_yaml_config() 21 | server_ip = config["stable_diffusion"]["server_ip"] 22 | firstphase_width = config["stable_diffusion"]["width"] 23 | firstphase_height = config["stable_diffusion"]["height"] 24 | lora = config["stable_diffusion"]["lora"] 25 | memory = config["book"]["memory"] 26 | role_enabled = config["stable_diffusion"]["role"] 27 | 28 | sd_url = server_ip + "/sdapi/v1/txt2img" 29 | 30 | 31 | class Main: 32 | 33 | async def find_role_by_name(self, data, name): 34 | for item in data: 35 | if item['name'] == name: 36 | return item['role'] 37 | return None # 如果没有找到匹配的名称,返回 None 38 | 39 | async def draw_picture(self, obj, index, save_path): 40 | data = get_sd_config() 41 | if not os.path.isdir(save_path): 42 | os.makedirs(save_path) 43 | is_exists = await check_file_exists(os.path.join(save_path, f"{index}.png")) 44 | if memory and is_exists: 45 | return 46 | await print_tip(f"开始生成第{index}张图片") 47 | prompt = obj["prompt"] 48 | if lora: 49 | prompt = f"{lora}, {prompt}" 50 | novel_dict = { 51 | "width": firstphase_width, 52 | "height": firstphase_height, 53 | "negative_prompt": obj["negative_prompt"], 54 | "prompt": prompt, 55 | **data, 56 | } 57 | if role_enabled and obj.get("role"): 58 | controlnet = [] 59 | 60 | with open(os.path.join(os.path.dirname(save_path), "participle", "role.json"), "r", encoding="utf-8") as file: 61 | role_data = json.load(file) 62 | for i in obj["role"]: 63 | role_image = await self.find_role_by_name(role_data, i) 64 | with open(os.path.join("roles", role_image), "rb") as f: 65 | img_data = f.read() 66 | 67 | base64_data = base64.b64encode(img_data) 68 | base64_str = base64_data.decode("utf-8") 69 | controlnet.append({ 70 | # "model": "ip-adapter_sd15 [6a3f6166]", 71 | "module": "reference_only", 72 | "weight": 1, 73 | "input_image": base64_str, 74 | "enabled": True, 75 | "resize_mode": "Crop and Resize", 76 | "guidance_end": 1, 77 | "guidance_start": 0, 78 | "save_detected_map": False, 79 | }) 80 | 81 | novel_dict["alwayson_scripts"] = {"controlnet": {"args": controlnet}} 82 | try: 83 | # 替换成异步协程 84 | async with aiohttp.ClientSession() as session: 85 | async with session.post(sd_url, json=novel_dict) as response: 86 | html = await response.read() 87 | except Exception as e: 88 | print(e) 89 | raise ConnectionError( 90 | "Stable Diffusion 连接失败,请查看ip+端口是否匹配,是否开启。" 91 | ) 92 | try: 93 | img_response = json.loads(html) 94 | except Exception as e: 95 | if str(e) == "Expecting value: line 2 column 1 (char 1)": 96 | raise Exception( 97 | f"{sd_url} 返回数据异常,请查看是否开启,或者是否连接成功。" 98 | ) 99 | raise Exception(str(html)) 100 | images = img_response.get("images", None) 101 | if not images: 102 | error = img_response.get( 103 | "error", 104 | "Stable Diffusion 返回数据异常,请查看ip+端口是否匹配,是否开启。", 105 | ) 106 | raise Exception(error) 107 | image_bytes = base64.b64decode(images[0]) 108 | image = Image.open(io.BytesIO(image_bytes)) 109 | # 图片存放 110 | picture_name = str(index) + ".png" 111 | 112 | picture_path = os.path.join(save_path, picture_name) 113 | image.save(picture_path) 114 | 115 | 116 | async def new_draw_picture(path, name, save_path): 117 | obj_path = os.path.join(path, f"{name}.json") 118 | is_exists = await check_file_exists(obj_path) 119 | if not is_exists: 120 | raise Exception(f"{name}.json文件不存在") 121 | await print_tip(f"开始生成《{name}》图片") 122 | with open(obj_path, "r", encoding="utf-8") as f: 123 | obj_list = json.load(f) 124 | for index, obj in enumerate(obj_list, start=1): 125 | await Main().draw_picture(obj, index, save_path) 126 | 127 | 128 | if __name__ == "__main__": 129 | book_name = "千金" 130 | # main = Main() 131 | # with open("participle/千金/千金.json", "r", encoding="utf-8") as f: 132 | # obj_list = json.load(f) 133 | # asyncio.run(main.draw_picture(obj_list, "千金")) 134 | file_path = os.path.join(book_name, "pictures") 135 | print(file_path) 136 | -------------------------------------------------------------------------------- /simhei.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anning01/ComicTweets/2b3350cbaf46efc3484d2e716acb293bc5fb5ae7/simhei.ttf -------------------------------------------------------------------------------- /stable_diffusion.json: -------------------------------------------------------------------------------- 1 | { 2 | "seed": -1, 3 | "batch_size": 1, 4 | "steps": 30, 5 | "cfg_scale": 7 6 | } 7 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anning01/ComicTweets/2b3350cbaf46efc3484d2e716acb293bc5fb5ae7/test.py -------------------------------------------------------------------------------- /translate.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # This file is auto-generated, don't edit it. Thanks. 3 | 4 | from alibabacloud_alimt20181012.client import Client as alimt20181012Client 5 | from alibabacloud_tea_openapi import models as open_api_models 6 | from alibabacloud_alimt20181012 import models as alimt_20181012_models 7 | 8 | from load_config import get_yaml_config 9 | 10 | config = get_yaml_config() 11 | access_key = config["potential"]["access_key_id"] 12 | secret = config["potential"]["access_key_secret"] 13 | language = config["book"]["language"] 14 | 15 | 16 | class Sample: 17 | def __init__(self): 18 | pass 19 | 20 | @staticmethod 21 | def create_client( 22 | access_key_id: str, 23 | access_key_secret: str, 24 | region_id: str, 25 | ) -> alimt20181012Client: 26 | config = open_api_models.Config() 27 | config.access_key_id = access_key_id 28 | config.access_key_secret = access_key_secret 29 | config.region_id = region_id 30 | config.connect_timeout = 5000 31 | config.read_timeout = 10000 32 | return alimt20181012Client(config) 33 | 34 | @staticmethod 35 | async def create_client_async( 36 | access_key_id: str, 37 | access_key_secret: str, 38 | region_id: str, 39 | ) -> alimt20181012Client: 40 | config = open_api_models.Config() 41 | config.access_key_id = access_key_id 42 | config.access_key_secret = access_key_secret 43 | config.region_id = region_id 44 | return alimt20181012Client(config) 45 | 46 | @staticmethod 47 | def main( 48 | text, 49 | region="cn-hangzhou", 50 | format_type="text", 51 | source_language=language, 52 | target_language="en", 53 | ) -> None: 54 | if language == "en": 55 | return text 56 | client = Sample.create_client( 57 | access_key, secret, region 58 | ) 59 | request = alimt_20181012_models.TranslateGeneralRequest( 60 | format_type=format_type, 61 | source_language=source_language, 62 | target_language=target_language, 63 | source_text=text, 64 | ) 65 | response = client.translate_general(request) 66 | return response.body.data.translated 67 | 68 | @staticmethod 69 | async def main_async( 70 | text, 71 | region="cn-hangzhou", 72 | format_type="text", 73 | source_language="zh", 74 | target_language="en", 75 | ) -> None: 76 | client = await Sample.create_client_async( 77 | access_key, secret, region 78 | ) 79 | request = alimt_20181012_models.TranslateGeneralRequest( 80 | format_type=format_type, 81 | source_language=source_language, 82 | target_language=target_language, 83 | source_text=text, 84 | ) 85 | response = await client.translate_general_async(request) 86 | return response.body.data.translated 87 | 88 | 89 | if __name__ == "__main__": 90 | print(Sample.main("你好")) 91 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -*- 3 | # @author:anning 4 | # @email:anningforchina@gmail.com 5 | # @time:2024/06/13 20:54 6 | # @file:__init__.py.py 7 | -------------------------------------------------------------------------------- /utils/english_segment.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -*- 3 | # @author:anning 4 | # @email:anningforchina@gmail.com 5 | # @time:2024/06/13 20:55 6 | # @file:english_segment.py 7 | import nltk 8 | 9 | 10 | def split_text_into_paragraphs(text): 11 | # 将文本分割成段落 12 | paragraphs = text.split('\n\n') 13 | return paragraphs 14 | 15 | 16 | def split_paragraphs_into_sentences(paragraphs): 17 | 18 | sentences = [] 19 | for paragraph in paragraphs: 20 | # 将段落分割成句子 21 | sentences.extend(nltk.sent_tokenize(paragraph)) 22 | return sentences 23 | 24 | 25 | def split_spain_paragraphs_into_sentences(paragraphs): 26 | 27 | sentences = [] 28 | for paragraph in paragraphs: 29 | # 使用西班牙语的punkt分词器 30 | sentences.extend(nltk.sent_tokenize(paragraph, language='spanish')) 31 | return sentences 32 | 33 | 34 | def main(file_path): 35 | with open(file_path, 'r') as file: 36 | text = file.read() 37 | 38 | paragraphs = split_text_into_paragraphs(text) 39 | sentences = split_paragraphs_into_sentences(paragraphs) 40 | 41 | # 输出分段后的内容 42 | for i, sentence in enumerate(sentences): 43 | print(f'Sentence {i + 1}: {sentence}') 44 | # 逐行写入文件 45 | with open('output.txt', 'a', encoding='utf-8') as file: 46 | file.write(sentence + '\n') 47 | 48 | 49 | if __name__ == '__main__': 50 | main('./小说目录/e.txt') -------------------------------------------------------------------------------- /utils/video_filter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -*- 3 | # @author:anning 4 | # @email:anningforchina@gmail.com 5 | # @time:2024/06/15 23:39 6 | # @file:video_filter.py 7 | 8 | 9 | import os 10 | import subprocess 11 | 12 | 13 | def blend_videos(normal_video, particle_video, output_video, alpha=0.5): 14 | # 获取正常视频的时长 15 | result = subprocess.run( 16 | ['ffprobe', '-v', 'error', '-show_entries', 'format=duration', 17 | '-of', 'default=noprint_wrappers=1:nokey=1', normal_video], 18 | stdout=subprocess.PIPE, stderr=subprocess.STDOUT 19 | ) 20 | normal_duration = float(result.stdout) 21 | 22 | # 创建一个临时调整后的粒子视频文件 23 | temp_particle_video = 'temp_particle.mp4' 24 | 25 | try: 26 | # 调整粒子视频长度 27 | ffmpeg_command_adjust = [ 28 | 'ffmpeg', 29 | '-i', particle_video, 30 | '-filter_complex', 31 | f'[0:v]loop=loop=-1:size=20000:start=0,setpts=N/FRAME_RATE/TB,trim=duration={normal_duration}[looped]', 32 | '-map', '[looped]', 33 | '-y', # overwrite output file if it exists 34 | temp_particle_video 35 | ] 36 | subprocess.run(ffmpeg_command_adjust, check=True) 37 | 38 | # 合并正常视频和调整后的粒子视频 39 | ffmpeg_command_blend = [ 40 | 'ffmpeg', 41 | '-i', normal_video, 42 | '-i', temp_particle_video, 43 | '-filter_complex', 44 | f'[1:v]format=rgba,colorchannelmixer=aa={alpha}[particle];[0:v][particle]overlay', 45 | '-c:a', 'copy', 46 | '-y', # overwrite output file if it exists 47 | output_video 48 | ] 49 | subprocess.run(ffmpeg_command_blend, check=True) 50 | 51 | finally: 52 | # 删除临时文件 53 | if os.path.exists(temp_particle_video): 54 | os.remove(temp_particle_video) 55 | 56 | 57 | if __name__ == '__main__': 58 | 59 | # 示例使用 60 | normal_video = '成品/e/video/e_final.mp4' 61 | particle_video = '粒子特效/665_1718178291.mp4' 62 | output_video = 'output.mp4' 63 | alpha = 0.5 # 调整粒子视频透明度 64 | 65 | blend_videos(normal_video, particle_video, output_video, alpha) 66 | -------------------------------------------------------------------------------- /video_composition.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -*- 3 | # @author:anning 4 | # @email:anningforchina@gmail.com 5 | # @time:2023/08/01 14:45 6 | # @file:app.py 7 | import ast 8 | import os 9 | import random 10 | import re 11 | import subprocess 12 | 13 | from load_config import get_yaml_config 14 | 15 | config = get_yaml_config() 16 | imagemagick_path = config["video"]["imagemagick_path"] 17 | fontsize = config["video"]["fontsize"] 18 | fontcolor = config["video"]["fontcolor"] 19 | fontfile = config["video"]["fontfile"] 20 | stroke_color = config["video"]["stroke_color"] 21 | stroke_width = config["video"]["stroke_width"] 22 | kerning = config["video"]["kerning"] 23 | position = config["video"]["position"] 24 | use_moviepy = config["video"]["use_moviepy"] 25 | once = config["video"]["once"] 26 | animation = config["video"]["animation"] 27 | width = config["stable_diffusion"]["width"] 28 | height = config["stable_diffusion"]["height"] 29 | animation_speed = config["video"]["animation_speed"] 30 | is_subtitles = config["video"]["subtitles"] 31 | 32 | if imagemagick_path: 33 | os.environ["IMAGEMAGICK_BINARY"] = rf"{imagemagick_path}" 34 | 35 | from moviepy.editor import ( 36 | AudioFileClip, 37 | concatenate_videoclips, 38 | TextClip, 39 | CompositeVideoClip, 40 | ImageClip, 41 | ) 42 | 43 | 44 | class Main: 45 | 46 | def merge_video( 47 | self, picture_path_path: str, audio_path_path: str, name: str, file_path: str 48 | ): 49 | """ 50 | :param picture_path_list: 图片路径列表 51 | :param audio_path_list: 音频路径列表 52 | :return: 53 | """ 54 | clips = [] 55 | 56 | def extract_number(filename): 57 | match = re.search(r"(\d+)", filename) 58 | if match: 59 | return int(match.group(0)) 60 | return 0 # 如果文件名中没有数字,则默认为 0 61 | 62 | picture_path_list = sorted( 63 | [ 64 | os.path.join(picture_path_path, name) 65 | for name in os.listdir(picture_path_path) 66 | if name.endswith(".png") 67 | ], 68 | key=lambda x: extract_number(os.path.basename(x)), 69 | ) 70 | if once: 71 | audio_path = os.path.join(audio_path_path, f"{name}.mp3") 72 | srt_path = os.path.join(audio_path_path, f"{name}.srt") 73 | time_file = os.path.join(audio_path_path, f"{name}time.txt") 74 | data = self.disposable_synthesis( 75 | picture_path_list, audio_path, srt_path, time_file, file_path, name 76 | ) 77 | return data 78 | else: 79 | audio_path_list = sorted( 80 | [ 81 | os.path.join(audio_path_path, name) 82 | for name in os.listdir(audio_path_path) 83 | if name.endswith(".mp3") 84 | ], 85 | key=lambda x: extract_number(os.path.basename(x)), 86 | ) 87 | srt_path_list = sorted( 88 | [ 89 | os.path.join(audio_path_path, name) 90 | for name in os.listdir(audio_path_path) 91 | if name.endswith(".srt") 92 | ], 93 | key=lambda x: extract_number(os.path.basename(x)), 94 | ) 95 | if os.path.isfile(f"{file_path}/{name}.txt"): 96 | os.remove(f"{file_path}/{name}.txt") 97 | if os.path.exists(file_path): 98 | filelist = os.listdir(file_path) 99 | if len(filelist) != 0: # 开始删除所有文件 100 | for file in filelist: 101 | os.remove(os.path.join(file_path, file)) 102 | os.rmdir(file_path) 103 | 104 | for index, value in enumerate(picture_path_list, start=1): 105 | audio_clip = AudioFileClip(audio_path_list[index - 1]) 106 | img_clip = ImageClip(value).set_duration(audio_clip.duration) 107 | 108 | img_clip = img_clip.set_position(("center", "center")).set_duration( 109 | audio_clip.duration 110 | ) 111 | if use_moviepy: 112 | # 解析对应的SRT文件 113 | subtitles = self.parse_srt(srt_path_list[index - 1]) 114 | # 为当前视频片段添加字幕 115 | subs = [ 116 | self.create_text_clip( 117 | img_clip, 118 | sub["text"], 119 | start=sub["start"], 120 | duration=sub["end"] - sub["start"], 121 | ) 122 | for sub in subtitles 123 | ] 124 | clip_with_subs = CompositeVideoClip([img_clip] + subs) 125 | clip = clip_with_subs.set_audio(audio_clip) 126 | else: 127 | clip = img_clip.set_audio(audio_clip) 128 | 129 | clips.append(clip) 130 | os.makedirs(file_path, exist_ok=True) 131 | video_path = os.path.join(file_path, f"{index}.mp4") 132 | clip.write_videofile(video_path, fps=24, audio_codec="aac") 133 | if not use_moviepy: 134 | self.create_srt( 135 | video_path, srt_path_list[index - 1], file_path, name 136 | ) 137 | with open(f"{file_path}/{name}.txt", "a", encoding="utf-8") as f: 138 | f.write(f"file '{video_path}'\n") 139 | print(f"-----------生成第{index}段视频-----------") 140 | print(f"-----------开始合成视频-----------") 141 | if use_moviepy: 142 | final_clip = concatenate_videoclips(clips) 143 | video_path = os.path.join(file_path, f"{name}.mp4") 144 | final_clip.write_videofile(video_path, fps=24, audio_codec="aac") 145 | else: 146 | self.mm_merge_video(file_path, name) 147 | 148 | def convert_time_string(self, time_str): 149 | try: 150 | # Split the string by colon 151 | time_parts = time_str.split(":") 152 | 153 | # If milliseconds are included, split them by the comma 154 | if ',' in time_parts[-1]: 155 | seconds, milliseconds = time_parts[-1].split(",") 156 | else: 157 | seconds = time_parts[-1] 158 | milliseconds = '0' # No milliseconds present, default to 0 159 | 160 | # Convert each part to an integer 161 | hours = int(time_parts[0]) 162 | minutes = int(time_parts[1]) 163 | seconds = int(seconds) 164 | milliseconds = int(milliseconds) 165 | 166 | # Calculate total seconds 167 | total_seconds = hours * 3600 + minutes * 60 + seconds + milliseconds / 1000 168 | except ValueError as e: 169 | # Return an error message if the input format is incorrect 170 | return f"Error: {str(e)}" 171 | 172 | # Return the total seconds 173 | return total_seconds 174 | 175 | def disposable_synthesis( 176 | self, picture_path_list, audio_path, srt_path, time_file, save_path, name 177 | ): 178 | # 一次性合成图片视频字幕 179 | """ 180 | ffmpeg -f concat -safe 0 -i filelist.txt -i audio.mp3 -vf "subtitles=subtitle_file.srt" -vsync vfr -pix_fmt yuv420p output.mp4 181 | """ 182 | 183 | with open(time_file, "r", encoding="utf-8") as f: 184 | content = f.read() 185 | time_list = ast.literal_eval(content) 186 | # 首先创建图片文件 187 | os.makedirs(save_path, exist_ok=True) 188 | out_path = os.path.join(save_path, f"{name}.mp4") 189 | 190 | if os.path.exists(out_path): 191 | return True 192 | 193 | if animation: 194 | self.disposable_synthesis_animation( 195 | picture_path_list, time_list, audio_path, save_path, out_path 196 | ) 197 | else: 198 | file_path = os.path.join(save_path, "filelist.txt") 199 | with open(file_path, "w", encoding="utf-8") as f: 200 | for index, picture_path in enumerate(picture_path_list): 201 | f.write(f"file '{picture_path}'\n") 202 | if index + 1 < len(time_list): 203 | f.write( 204 | f"duration {self.convert_time_string(time_list[index])}\n" 205 | ) 206 | cmd = [ 207 | "ffmpeg", 208 | "-f", 209 | "concat", 210 | "-safe", 211 | "0", 212 | "-i", 213 | file_path, 214 | "-i", 215 | audio_path, 216 | "-vsync", 217 | "cfr", 218 | "-pix_fmt", 219 | "yuv420p", 220 | out_path, 221 | ] 222 | subprocess.run(cmd, check=True) 223 | 224 | if is_subtitles: 225 | self.create_srt(out_path, srt_path, save_path, name) 226 | 227 | def create_animated_segment( 228 | self, image_path, duration, output_path, index, multiple, action 229 | ): 230 | initial_zoom = 1.0 231 | duration = self.convert_time_string(duration) 232 | zoom_steps = (multiple - initial_zoom) / (25 * duration) 233 | l_r_move = (width * multiple - width - 25) / (25 * duration) 234 | u_d_move = (height * multiple - height - 25 - 25) / (25 * duration) 235 | if action == "shrink": 236 | scale = ( 237 | f"scale=-2:ih*10,zoompan=z='if(lte(zoom,{initial_zoom}),{multiple},max(zoom-{zoom_steps},1))':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=25*" 238 | + str(duration) 239 | + f":s={width}x{height}" 240 | ) 241 | elif action == "left_move": 242 | scale = ( 243 | f"scale=-2:ih*10,zoompan='{multiple}':x='if(lte(on,-1),(iw-iw/zoom)/2,x+{l_r_move * 10})':y='if(lte(on,1),(ih-ih/zoom)/2,y)':d=25*" 244 | + str(duration) 245 | + f":s={width}x{height}" 246 | ) 247 | elif action == "right_move": 248 | scale = ( 249 | f"scale=-2:ih*10,zoompan='{multiple}':x='if(lte(on,1),(iw/zoom)/2,x-{l_r_move * 10})':y='if(lte(on,1),(ih-ih/zoom)/2,y)':d=25*" 250 | + str(duration) 251 | + f":s={width}x{height}" 252 | ) 253 | elif action == "up_move": 254 | """ffmpeg -y -i 1.jpg -vf "zoompan='1.5':x='if(lte(on,1),(iw-iw/zoom)/2,x)':y='if(lte(on,-1),(ih-ih/zoom)/2,y+2)':d=150" 1.mp4""" 255 | scale = ( 256 | f"scale=-2:ih*10,zoompan='{multiple}':x='if(lte(on,1),(iw-iw/zoom)/2,x)':y='if(lte(on,-1),(ih-ih/zoom)/2,y+{u_d_move * 10})':d=25*" 257 | + str(duration) 258 | + f":s={width}x{height}" 259 | ) 260 | elif action == "down_move": 261 | """ffmpeg -y -i 1.jpg -vf "zoompan='1.5':x='if(lte(on,1),(iw-iw/zoom)/2,x)':y='if(lte(on,1),(ih/zoom)/2,y-2)':d=150" 1.mp4""" 262 | scale = ( 263 | f"scale=-2:ih*10,zoompan='{multiple}':x='if(lte(on,1),(iw-iw/zoom)/2,x)':y='if(lte(on,1),(ih/zoom)/2,y-{u_d_move * 10})':d=25*" 264 | + str(duration) 265 | + f":s={width}x{height}" 266 | ) 267 | else: 268 | # scale = f"scale=-2:ih*10,zoompan=z='zoom+{zoom_steps}':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=25*{duration}:s={width}x{height}:fps=25" 269 | scale = f"scale=-2:ih*10,zoompan=z='min(zoom+{zoom_steps},{multiple})*if(gte(zoom,1),1,0)+if(lt(zoom,1),1,0)':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=25*{duration}:s={width}x{height}" 270 | 271 | cmd = [ 272 | "ffmpeg", 273 | "-y", # 覆盖输出文件 274 | "-r", 275 | "25", # 帧率 276 | "-loop", 277 | "1", # 循环输入图像 278 | "-t", 279 | str(duration), # 输出视频片段的持续时间 280 | "-i", 281 | image_path, # 输入图像 282 | "-filter_complex", 283 | scale, 284 | "-vframes", 285 | str(int(25 * duration)), 286 | "-c:v", 287 | "libx264", # 视频编解码器 288 | "-pix_fmt", 289 | "yuv420p", # 像素格式 290 | f"{output_path}/animated_segment_{index}.mp4", # 输出路径 291 | ] 292 | subprocess.run(cmd, check=True) 293 | 294 | def concat_videos(self, video_list, audio_path, output_video): 295 | with open("temp_list.txt", "w", encoding="utf-8") as f: 296 | for video in video_list: 297 | f.write(f"file '{video}'\n") 298 | 299 | cmd = [ 300 | "ffmpeg", 301 | "-y", # Overwrite output files without asking 302 | "-f", 303 | "concat", 304 | "-safe", 305 | "0", 306 | "-i", 307 | "temp_list.txt", 308 | "-i", 309 | audio_path, 310 | "-vsync", 311 | "cfr", 312 | "-pix_fmt", 313 | "yuv420p", 314 | output_video, 315 | ] 316 | subprocess.run(cmd, check=True) 317 | 318 | def disposable_synthesis_animation( 319 | self, picture_path_list, durations, audio_path, save_path, out_path 320 | ): 321 | if os.path.exists(out_path): 322 | return 323 | video_list = [] 324 | animations = ["shrink", "magnify", "left_move", "right_move", "up_move", "down_move"] 325 | for index, (image_path, duration) in enumerate( 326 | zip(picture_path_list, durations) 327 | ): 328 | output_path = os.path.join(save_path, f"animated_segment_{index}.mp4") 329 | if os.path.exists(output_path): 330 | if os.path.exists(os.path.join(save_path, f"animated_segment_{index+1}.mp4")): 331 | video_list.append(output_path) 332 | continue 333 | else: 334 | os.remove(output_path) 335 | selected_animation = random.choice(animations) 336 | self.create_animated_segment( 337 | image_path, 338 | duration, 339 | save_path, 340 | index, 341 | animation_speed, 342 | selected_animation, 343 | ) 344 | video_list.append(output_path) 345 | 346 | self.concat_videos(video_list, audio_path, out_path) 347 | 348 | # Optionally, remove temporary files 349 | for video in video_list: 350 | os.remove(video) 351 | os.remove("temp_list.txt") 352 | 353 | def create_srt(self, video_path, srt_path, file_path, name): 354 | """ 355 | 创建SRT字幕文件 356 | :param video_path: 视频文件路径 357 | :return: 358 | """ 359 | out_path = os.path.join(file_path, f"out{name}.mp4") 360 | 361 | # 构建字体样式字符串,只包含颜色和大小 362 | style = f"FontName={fontfile.split('.')[0]},Fontsize={fontsize},PrimaryColour=&H{fontcolor},Alignment={position}" 363 | 364 | # 构建 FFmpeg 命令,不再设置字体文件路径 365 | if os.name == "nt": 366 | # 由于绝对路径下win会报错 所以转换成相对路径 367 | proj_path = os.path.abspath("./") 368 | out_path = os.path.relpath(out_path, proj_path).replace("\\", "/") 369 | video_path = os.path.relpath(video_path, proj_path).replace("\\", "/") 370 | srt_path = os.path.relpath(srt_path, proj_path).replace("\\", "/") 371 | cmd = [ 372 | "ffmpeg", 373 | "-i", 374 | video_path, 375 | "-vf", 376 | f"subtitles='{srt_path}':force_style='{style}'", 377 | "-c:a", 378 | "copy", 379 | out_path, 380 | ] 381 | 382 | # 执行命令 383 | subprocess.run(cmd, check=True) 384 | os.replace(out_path, video_path) # 用输出文件替换原始文件 385 | 386 | def parse_srt(self, srt_path): 387 | """ 388 | 解析SRT字幕文件 389 | :param srt_path: SRT文件路径 390 | :return: 字幕数据列表,每个字幕包含开始时间、结束时间和文本 391 | """ 392 | subtitles = [] 393 | with open(srt_path, "r", encoding="utf-8") as file: 394 | lines = file.readlines() 395 | for i in range(0, len(lines), 4): 396 | start_end = lines[i + 1].split(" --> ") 397 | start = self.srt_time_to_seconds(start_end[0].strip()) 398 | end = self.srt_time_to_seconds(start_end[1].strip()) 399 | text = lines[i + 2].strip() 400 | subtitles.append({"start": start, "end": end, "text": text}) 401 | return subtitles 402 | 403 | def mm_merge_video(self, video_path, name): 404 | out_path = os.path.join(video_path, f"{name}.mp4") 405 | inputs_path = os.path.join(video_path, f"{name}.txt") 406 | subprocess.run( 407 | [ 408 | "ffmpeg", 409 | "-f", 410 | "concat", 411 | "-safe", 412 | "0", 413 | "-i", 414 | f"{inputs_path}", 415 | "-c", 416 | "copy", 417 | f"{out_path}", 418 | ] 419 | ) 420 | 421 | def srt_time_to_seconds(self, time_str): 422 | """ 423 | 将SRT时间格式转换为秒 424 | :param time_str: SRT时间字符串 425 | :return: 对应的秒数 426 | """ 427 | hours, minutes, seconds = map(float, time_str.replace(",", ".").split(":")) 428 | return hours * 3600 + minutes * 60 + seconds 429 | 430 | def create_text_clip(self, img_clip, text, start, duration): 431 | """ 432 | 创建包含文字的TextClip 433 | :param text: 字幕文本 434 | :param start: 字幕开始时间 435 | :param duration: 字幕持续时间 436 | :return: TextClip对象 437 | """ 438 | video_clip_height = img_clip.h # 获取视频的高度 439 | 440 | txt_clip = TextClip( 441 | text, 442 | fontsize=fontsize, 443 | color=fontcolor, 444 | font=fontfile, 445 | stroke_color=stroke_color, 446 | stroke_width=stroke_width, 447 | kerning=kerning, 448 | method="label", 449 | ) 450 | txt_clip = txt_clip.set_start(start).set_duration(duration) 451 | txt_clip = txt_clip.set_position( 452 | lambda t: ( 453 | "center", 454 | max( 455 | position * video_clip_height - t * 10, position * video_clip_height 456 | ), 457 | ) 458 | ) 459 | 460 | return txt_clip 461 | 462 | 463 | if __name__ == "__main__": 464 | m = Main() 465 | picture_path_path = os.path.abspath(f"./images/斗破苍穹") 466 | audio_path_path = os.path.abspath(f"./participle/斗破苍穹") 467 | name = "斗破苍穹" 468 | save_path = os.path.abspath(f"./") 469 | m.merge_video(picture_path_path, audio_path_path, name, save_path) 470 | -------------------------------------------------------------------------------- /voice_caption.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -*- 3 | # @author:anning 4 | # @email:anningforchina@gmail.com 5 | # @time:2024/04/09 14:44 6 | # @file:voice_caption.py 7 | # 将图片和文字,字幕 一次性合成 8 | import asyncio 9 | import json 10 | import os.path 11 | import random 12 | import re 13 | import subprocess 14 | from datetime import datetime 15 | from typing import List 16 | from xml.sax.saxutils import unescape 17 | 18 | import aiofiles 19 | import edge_tts 20 | from edge_tts.submaker import formatter 21 | 22 | from char2voice import create_voice_srt_new2 23 | from load_config import get_yaml_config, check_file_exists, print_tip 24 | 25 | config = get_yaml_config() 26 | limit = config["audio"]["limit"] 27 | role = config["audio"]["role"] 28 | rate = config["audio"]["rate"] 29 | volume = config["audio"]["volume"] 30 | bgm = config["audio"]["bgm"] 31 | main_db = config["audio"]["main_db"] 32 | bgm_db = config["audio"]["bgm_db"] 33 | once = config["video"]["once"] 34 | memory = config["book"]["memory"] 35 | language = config["book"]["language"] 36 | 37 | 38 | async def spilt_str2(s, t, k=limit): 39 | """ 40 | :param s: 切片文本 41 | :param t: 切分前时间 42 | :param k: 切分最大字数 43 | :return: 新的切片信息 44 | 45 | @ samples 46 | s = "并且觉醒天赋 得到力量 对抗凶兽 觉醒天赋 便是人人在十八岁时能以血脉沟通沟通 觉醒天赋" 47 | t = "00:00:35,184 --> 00:00:42,384" 48 | k = 15 49 | """ 50 | 51 | async def time2second(ti): 52 | """ 53 | :param ti: 输入时间, 格式示例:00:02:56,512 54 | :return: float 55 | """ 56 | a, b, _c = ti.split(":") 57 | c, d = _c.split(",") 58 | 59 | a, b, c, d = int(a), int(b), int(c), int(d) 60 | 61 | second = a * 3600 + b * 60 + c + d / 1000 62 | 63 | return second 64 | 65 | async def second2time(si): 66 | hours = int(si // 3600) 67 | minutes = int((si % 3600) // 60) 68 | seconds = int(si % 60) 69 | milliseconds = round((si % 1) * 1000) 70 | 71 | v = "00" 72 | u = "000" 73 | a = v[: 2 - len(str(hours))] + str(hours) 74 | b = v[: 2 - len(str(minutes))] + str(minutes) 75 | c = v[: 2 - len(str(seconds))] + str(seconds) 76 | d = u[: 3 - len(str(milliseconds))] + str(milliseconds) 77 | 78 | return f"{a}:{b}:{c},{d}" 79 | 80 | ss = s.split(" ") 81 | ss_valid = [] 82 | 83 | # todo 将所有片段设置成不超过15 84 | for _ss in ss: 85 | if len(_ss) > k: 86 | 87 | # 暴力截断几段 88 | e = len(_ss) // k + 1 89 | n_e = len(_ss) // e + 1 90 | 91 | for _i in range(e): 92 | if _i == e - 1: 93 | ss_valid.append(_ss[n_e * _i :]) 94 | else: 95 | ss_valid.append(_ss[n_e * _i : n_e * (_i + 1)]) 96 | else: 97 | ss_valid.append(_ss) 98 | 99 | # todo 片段合并 100 | tmp = "" 101 | new_ss = [] 102 | for i in range(len(ss_valid)): 103 | tmp += ss_valid[i] 104 | 105 | if i < len(ss_valid) - 1: 106 | if len(tmp + ss_valid[i + 1]) > k: 107 | new_ss.append(tmp) 108 | tmp = "" 109 | else: 110 | continue 111 | else: 112 | new_ss.append(tmp) 113 | tmp = "" 114 | 115 | # 分配时间戳 116 | t1, t2 = t.split("-->") 117 | ft1 = await time2second(t1) 118 | ft2 = await time2second(t2) 119 | ftd = ft2 - ft1 120 | 121 | # 转换成秒数 122 | all_str = " ".join(new_ss) 123 | 124 | tt_s = 0 125 | line_srt = [] 126 | for z in new_ss: 127 | tt_e = len(z) + tt_s 128 | 129 | # 文章最后一句异常处理 130 | if len(all_str) * ftd == 0: 131 | continue 132 | 133 | t_start = tt_s / len(all_str) * ftd 134 | t_end = tt_e / len(all_str) * ftd 135 | t_start = round(t_start, 3) 136 | t_end = round(t_end, 3) 137 | 138 | rec_s = await second2time(ft1 + t_start) 139 | rec_e = await second2time(ft1 + t_end) 140 | 141 | cc = (f"{rec_s} --> {rec_e}", z) 142 | line_srt.append(cc) 143 | 144 | tt_s = tt_e + 1 145 | 146 | return line_srt 147 | 148 | 149 | async def time_difference(time1, time2, time_format=r"%H:%M:%S,%f"): 150 | time1 = datetime.strptime(time1, time_format) 151 | time2 = datetime.strptime(time2, time_format) 152 | 153 | # 计算时间差 154 | delta = time2 - time1 155 | time_diff = str(delta).replace(".", ",")[:11] 156 | return time_diff 157 | 158 | 159 | async def load_srt_new(filename, flag=True): 160 | time_format = r"(\d{2}:\d{2}:\d{2}),\d{3} --> (\d{2}:\d{2}:\d{2}),\d{3}" 161 | 162 | n = 0 # srt 文件总行数 163 | index = 0 # strs 文字串移动下标 164 | line_tmp = "" # 每个时间区间后的字数累计 165 | count_tmp = 0 # 每个时间区间后的字数行计数 166 | new_srt = [] 167 | 168 | async with aiofiles.open(filename, mode="r", encoding="utf-8") as f3: 169 | f_lines = await f3.readlines() 170 | for line in f_lines: 171 | line = line.strip("\n") 172 | n += 1 173 | 174 | # 写入新的数据 175 | # 1)当出现在文本末写入一次 176 | if n == len(f_lines): 177 | new_srt_line = await spilt_str2(line_tmp, t_line_cur) 178 | new_srt.append(new_srt_line) 179 | 180 | # 2)当新的一行是数字时,srt语句段写入 181 | # case1: 判断新的一行是不是数字 182 | if line.isdigit(): 183 | if flag: 184 | print(line) 185 | if n > 1: 186 | new_srt_line = await spilt_str2(line_tmp, t_line_cur) 187 | new_srt.append(new_srt_line) 188 | continue 189 | 190 | # case2: 判断新的一行是不是时间段 191 | if re.match(time_format, line): 192 | t_line_cur = line 193 | # reset line_tmp 194 | line_tmp = "" 195 | count_tmp = 0 196 | continue 197 | 198 | # case3: 判断新的一行是空格时 199 | if len(line) == 0: 200 | continue 201 | 202 | # case4: 新的一行不属于上面其中之一 203 | line_std = line.replace(" ", "") 204 | if flag: 205 | print(f"{line}\n{line_std}") 206 | 207 | if count_tmp: 208 | line_tmp += " " + line_std 209 | else: 210 | line_tmp += line_std 211 | count_tmp += 1 212 | 213 | srt = [] 214 | for _line in new_srt: 215 | for _l in _line: 216 | srt.append(_l) 217 | return srt 218 | 219 | 220 | async def save_srt(filename, srt_list): 221 | async with aiofiles.open(filename, mode="w", encoding="utf-8") as f: 222 | for _li, _l in enumerate(srt_list): 223 | if _li == len(srt_list) - 1: 224 | info = "{}\n{}\n{}".format(_li + 1, _l[0], _l[1]) 225 | else: 226 | info = "{}\n{}\n{}\n\n".format(_li + 1, _l[0], _l[1]) 227 | await f.write(info) 228 | 229 | 230 | async def srt_regen_new(f_srt, f_save, flag): 231 | srt_list = await load_srt_new(f_srt, flag) 232 | await save_srt(f_save, srt_list) 233 | 234 | 235 | class CustomSubMaker(edge_tts.SubMaker): 236 | """重写此方法更好的支持中文""" 237 | 238 | async def generate_cn_subs(self, text): 239 | 240 | PUNCTUATION = [",", "。", "!", "?", ";", ":", "”", ",", "!", "…", "+", "-"] 241 | 242 | def clause(self): 243 | start = 0 244 | i = 0 245 | text_list = [] 246 | while i < len(text): 247 | if text[i] in PUNCTUATION: 248 | try: 249 | while text[i] in PUNCTUATION: 250 | i += 1 251 | except IndexError: 252 | pass 253 | text_list.append(text[start:i]) 254 | start = i 255 | i += 1 256 | return text_list 257 | 258 | self.text_list = clause(self) 259 | if len(self.subs) != len(self.offset): 260 | raise ValueError("subs and offset are not of the same length") 261 | data = "WEBVTT\r\n\r\n" 262 | j = 0 263 | for text in self.text_list: 264 | text = await self.remove_non_chinese_chars(text) 265 | try: 266 | start_time = self.offset[j][0] 267 | except IndexError: 268 | return data 269 | try: 270 | while self.subs[j + 1] in text: 271 | j += 1 272 | except IndexError: 273 | pass 274 | data += edge_tts.submaker.formatter(start_time, self.offset[j][1], text) 275 | j += 1 276 | return data 277 | 278 | async def generate_subs_based_on_punc(self, text) -> str: 279 | PUNCTUATION = [',', '。', '!', '?', ';', 280 | ':', '\n', '“', '”', ',', '!', '\\. '] 281 | 282 | def clause(self) -> list[str]: 283 | pattern = '(' + '|'.join(punc for punc in PUNCTUATION) + ')' 284 | text_list = re.split(pattern, text) 285 | 286 | index = 0 287 | pattern = '^[' + ''.join(p for p in PUNCTUATION) + ']+$' 288 | while (index < len(text_list) - 1): 289 | if not text_list[index + 1]: 290 | text_list.pop(index + 1) 291 | continue 292 | if re.match(pattern, text_list[index + 1]): 293 | if (text_list[index + 1] == '\n'): 294 | text_list.pop(index + 1) 295 | continue 296 | text_list[index] += text_list.pop(index + 1) 297 | else: 298 | index += 1 299 | 300 | return text_list 301 | 302 | self.text_list = clause(self) 303 | if len(self.subs) != len(self.offset): 304 | raise ValueError("subs and offset are not of the same length") 305 | data = "WEBVTT\r\n\r\n" 306 | j = 0 307 | for text in self.text_list: 308 | try: 309 | start_time = self.offset[j][0] 310 | except IndexError: 311 | return data 312 | try: 313 | while (self.subs[j + 1] in text): 314 | j += 1 315 | except IndexError: 316 | pass 317 | data += edge_tts.submaker.formatter(start_time, self.offset[j][1], text) 318 | j += 1 319 | return data 320 | 321 | async def remove_non_chinese_chars(self, text): 322 | # 使用正则表达式匹配非中文字符和非数字 323 | # pattern = re.compile(r"[^\u4e00-\u9fff0-9]+") 324 | pattern = re.compile(r"[^\u4e00-\u9fffA-Za-z0-9]+") 325 | # 使用空字符串替换匹配到的非中文字符和非数字 326 | cleaned_text = re.sub(pattern, "", text) 327 | return cleaned_text 328 | 329 | def generate_subs_pro(self, content_list) -> str: 330 | 331 | if len(self.subs) != len(self.offset): 332 | raise ValueError("subs and offset are not of the same length") 333 | 334 | data = "" 335 | sub_state_count = 0 336 | sub_state_start = -1.0 337 | sub_state_subs = "" 338 | index = 0 339 | content = content_list[index] 340 | 341 | for idx, (offset, subs) in enumerate(zip(self.offset, self.subs)): 342 | start_time, end_time = offset 343 | subs = unescape(subs) 344 | 345 | if len(sub_state_subs) > 0: 346 | sub_state_subs += " " 347 | sub_state_subs += subs 348 | 349 | if sub_state_start == -1.0: 350 | sub_state_start = start_time 351 | sub_state_count += 1 352 | if idx == len(self.offset) - 1 or self.subs[idx + 1] not in content: 353 | subs = sub_state_subs 354 | 355 | split_subs: List[str] = [ 356 | subs[i: i + 100] for i in range(0, len(subs), 100) 357 | ] 358 | for i in range(len(split_subs) - 1): 359 | sub = split_subs[i] 360 | split_at_word = True 361 | if sub[-1] == " ": 362 | split_subs[i] = sub[:-1] 363 | split_at_word = False 364 | 365 | if sub[0] == " ": 366 | split_subs[i] = sub[1:] 367 | split_at_word = False 368 | 369 | if split_at_word: 370 | split_subs[i] += "-" 371 | 372 | data += formatter( 373 | start_time=sub_state_start, 374 | end_time=end_time, 375 | subdata="\r\n".join(split_subs), 376 | ) 377 | sub_state_count = 0 378 | sub_state_start = -1 379 | sub_state_subs = "" 380 | if index < len(content_list) - 1: 381 | index += 1 382 | content = content_list[index] 383 | else: 384 | content = re.sub(subs, '', content, count=1) 385 | return data 386 | 387 | 388 | async def edge_gen_srt2(f_txt, f_mp3, f_vtt, f_srt, p_voice, p_rate, p_volume, participle_path) -> None: 389 | content = f_txt 390 | communicate = edge_tts.Communicate( 391 | text=content, voice=p_voice, rate=p_rate, volume=p_volume 392 | ) 393 | sub_maker = CustomSubMaker() 394 | async with aiofiles.open(f_mp3, "wb") as file: 395 | async for chunk in communicate.stream(): 396 | if chunk["type"] == "audio": 397 | await file.write(chunk["data"]) 398 | elif chunk["type"] == "WordBoundary": 399 | sub_maker.create_sub( 400 | (chunk["offset"], chunk["duration"]), chunk["text"] 401 | ) 402 | 403 | if language == "zh": 404 | async with aiofiles.open(f_vtt, "w", encoding="utf-8") as file: 405 | content_to_write = await sub_maker.generate_subs_based_on_punc(content) 406 | # content_to_write = sub_maker.generate_subs() 407 | await file.write(content_to_write) 408 | 409 | # vtt -》 srt 410 | idx = 1 # 字幕序号 411 | with open(f_srt, "w", encoding="utf-8") as f_out: 412 | for line in open(f_vtt, encoding="utf-8"): 413 | if "-->" in line: 414 | f_out.write("%d\n" % idx) 415 | idx += 1 416 | line = line.replace(".", ",") # 这行不是必须的,srt也能识别'.' 417 | if idx > 1: # 跳过header部分 418 | f_out.write(line) 419 | else: 420 | # 定义一个空列表来存储文件的每一行 421 | lines = [] 422 | 423 | # 打开文件并读取每一行 424 | with open(participle_path, 'r', encoding='utf-8') as file: 425 | for line in file: 426 | # 去除每行末尾的换行符,并添加到列表中 427 | lines.append(line.strip()) 428 | 429 | # 使用列表推导式去除空行 430 | lines = [line for line in lines if line and not line.isdigit()] 431 | 432 | with open(f_srt, "w", encoding="utf-8") as f_out: 433 | f_out.write(sub_maker.generate_subs_pro(lines)) 434 | 435 | 436 | # 合并文件夹下所有MP3文件为一个音频文件 437 | async def merge_bgm(bgm_folder): 438 | mp3_files = [ 439 | os.path.join(bgm_folder, mp3_file) 440 | for mp3_file in os.listdir(bgm_folder) 441 | if mp3_file.endswith(".mp3") 442 | ] 443 | random.shuffle(mp3_files) # 随机化列表中元素的顺序 444 | 445 | with open("bgm_list.txt", "w", encoding="utf-8") as filelist: 446 | for mp3_file in mp3_files: 447 | filelist.write(f"file '{mp3_file}'\n") 448 | 449 | subprocess.run( 450 | [ 451 | "ffmpeg", 452 | "-y", 453 | "-f", 454 | "concat", 455 | "-safe", 456 | "0", 457 | "-i", 458 | "bgm_list.txt", 459 | "-c", 460 | "copy", 461 | "merged_bgm.mp3", 462 | ], 463 | check=True, 464 | ) 465 | os.remove("bgm_list.txt") 466 | 467 | 468 | # 获取媒体文件长度 469 | async def get_media_length(file_path): 470 | result = subprocess.run( 471 | [ 472 | "ffprobe", 473 | "-v", 474 | "error", 475 | "-show_entries", 476 | "format=duration", 477 | "-of", 478 | "default=noprint_wrappers=1:nokey=1", 479 | file_path, 480 | ], 481 | stdout=subprocess.PIPE, 482 | text=True, 483 | ) 484 | return float(result.stdout) 485 | 486 | 487 | # 获取音频文件的详细信息(比特率、采样率、声道数) 488 | async def get_audio_details(file_path): 489 | cmd = [ 490 | "ffprobe", 491 | "-v", 492 | "error", 493 | "-select_streams", 494 | "a:0", 495 | "-show_entries", 496 | "stream=bit_rate,sample_rate,channels", 497 | "-of", 498 | "json", 499 | file_path, 500 | ] 501 | result = subprocess.run(cmd, capture_output=True, text=True) 502 | metadata = json.loads(result.stdout) 503 | details = { 504 | "bit_rate": int(metadata["streams"][0]["bit_rate"]), 505 | "sample_rate": int(metadata["streams"][0]["sample_rate"]), 506 | "channels": int(metadata["streams"][0]["channels"]), 507 | } 508 | return details 509 | 510 | 511 | # 循环BGM以匹配主音轨长度,然后与主音轨混合 512 | async def mix_main_and_bgm(main_audio, bgm_file, save_dir): 513 | await merge_bgm("bgm") 514 | main_length = await get_media_length(main_audio) 515 | bgm_length = await get_media_length(bgm_file) 516 | main_volume = f"{main_db}dB" 517 | bgm_volume = f"{bgm_db}dB" 518 | # 计算BGM需要循环的次数 519 | loop_count = int(main_length // bgm_length) + 1 if bgm_length < main_length else 1 520 | 521 | # 如果需要,循环BGM 522 | if loop_count > 1: 523 | with open("looped_bgm_list.txt", "w", encoding="utf-8") as loop_file: 524 | for _ in range(loop_count): 525 | loop_file.write(f"file '{bgm_file}'\n") 526 | subprocess.run( 527 | [ 528 | "ffmpeg", 529 | "-y", 530 | "-f", 531 | "concat", 532 | "-safe", 533 | "0", 534 | "-i", 535 | "looped_bgm_list.txt", 536 | "-c", 537 | "copy", 538 | "looped_bgm.mp3", 539 | ], 540 | check=True, 541 | ) 542 | looped_bgm = "looped_bgm.mp3" 543 | os.remove("looped_bgm_list.txt") 544 | else: 545 | looped_bgm = bgm_file 546 | 547 | audio_details = await get_audio_details(main_audio) 548 | 549 | # 采样率、声道和比特率 550 | sample_rate = str(audio_details["sample_rate"]) 551 | channels = str(audio_details["channels"]) 552 | bitrate = str(audio_details["bit_rate"]) 553 | # 转换循环后的BGM为单声道,采样率调整为24kHz 554 | converted_bgm = os.path.join(save_dir, "bgm_converted.mp3") 555 | 556 | subprocess.run( 557 | ["ffmpeg", "-y", "-i", looped_bgm, "-ac", str(channels), "-ar", str(sample_rate), converted_bgm], 558 | check=True 559 | ) 560 | 561 | output_file = os.path.join(save_dir, "out.mp3") 562 | # 混合主音轨和已转换的BGM 563 | # subprocess.run([ 564 | # 'ffmpeg', '-i', main_audio, '-i', 'bgm_converted.mp3', 565 | # '-filter_complex', 566 | # f"[0:a]aformat=sample_rates=24000:channel_layouts=mono,volume={main_volume}[a0];[1:a]aformat=sample_rates=24000:channel_layouts=mono,volume={bgm_volume}[a1];[a0][a1]amix=inputs=2:duration=first[aout]", 567 | # '-map', '[aout]', '-ac', '1', '-ar', '24000', '-y', output_file 568 | # ], check=True) 569 | subprocess.run( 570 | [ 571 | "ffmpeg", 572 | "-y", 573 | "-i", 574 | main_audio, 575 | "-i", 576 | converted_bgm, 577 | "-filter_complex", 578 | f"[0:a]aformat=sample_rates={sample_rate}:channel_layouts=stereo,volume={main_volume}[a0];[1:a]aformat=sample_rates={sample_rate}:channel_layouts=stereo,volume={bgm_volume}[a1];[a0][a1]amix=inputs=2:duration=first[aout]", 579 | "-map", 580 | "[aout]", 581 | "-ac", 582 | channels, 583 | "-ar", 584 | sample_rate, 585 | "-b:a", 586 | bitrate, 587 | output_file, 588 | ], 589 | check=True, 590 | ) 591 | # 清理临时文件 592 | os.remove("merged_bgm.mp3") 593 | os.remove(converted_bgm) 594 | if loop_count > 1: 595 | os.remove("looped_bgm.mp3") 596 | os.replace(output_file, main_audio) 597 | 598 | 599 | async def srt_to_list(filename): 600 | subtitles = [] # 存储最终结果的列表 601 | text = [] # 临时存储当前字幕块的文本行 602 | timecode = None # 初始化时间码变量 603 | 604 | with open(filename, "r", encoding="utf-8") as file: 605 | for line in file: 606 | line = line.strip() # 移除行首尾的空白字符 607 | 608 | if line.isdigit(): # 跳过字幕编号行 609 | continue 610 | 611 | if "-->" in line: # 检测时间码行 612 | if text: # 如果前一个字幕块的文本已经读取,存储前一个字幕块 613 | subtitles.append((timecode, " ".join(text))) 614 | text = [] # 重置文本列表为下一个字幕块做准备 615 | timecode = line # 更新时间码 616 | 617 | elif line: # 非空行即为字幕文本行 618 | text.append(line) 619 | 620 | # 添加文件末尾的最后一个字幕块(如果有) 621 | if text: 622 | subtitles.append((timecode, " ".join(text))) 623 | return subtitles 624 | 625 | 626 | async def picture_processing_time(filename, section_path, save_dir, name): 627 | 628 | subtitles = await srt_to_list(filename) 629 | if language == "zh": 630 | with open(section_path, "r", encoding="utf-8") as f: 631 | section_list = f.readlines() 632 | section_time_list = [] 633 | index_ = 0 634 | time_ = "00:00:00,000" 635 | for si, section in enumerate(section_list): 636 | if len(section_list) == si + 1: 637 | # 最后这段不处理 默认使用剩余所有time 638 | next_start_time = subtitles[-1][0].split(" --> ")[1] 639 | diff = await time_difference(time_, next_start_time) 640 | section_time_list.append(diff) 641 | break 642 | content_ = await CustomSubMaker().remove_non_chinese_chars(section) 643 | for i, v in enumerate(subtitles): 644 | if i <= index_: 645 | continue 646 | v_text = await CustomSubMaker().remove_non_chinese_chars(v[1]) 647 | if v_text not in content_: 648 | next_start_time = v[0].split(" --> ")[0] 649 | diff = await time_difference(time_, next_start_time) 650 | section_time_list.append(diff) 651 | index_ = i 652 | time_ = next_start_time 653 | break 654 | with open(os.path.join(save_dir, f"{name}time.txt"), "w", encoding="utf-8") as f3: 655 | f3.write(str(section_time_list)) 656 | else: 657 | time_list = [] 658 | init_time = "00:00:00.000" 659 | for subtitle in subtitles: 660 | duration = await time_difference(init_time, subtitle[0].split(" --> ")[1], time_format=r"%H:%M:%S.%f") 661 | time_list.append(duration) 662 | init_time = subtitle[0].split(" --> ")[1] 663 | with open(os.path.join(save_dir, f"{name}time.txt"), "w", encoding="utf-8") as f3: 664 | f3.write(str(time_list)) 665 | 666 | 667 | async def create_voice_srt_new3( 668 | name, file_txt, save_dir, participle_path=None, p_voice=role, p_rate=rate, p_volume=volume 669 | ): 670 | mp3_name = f"{name}.mp3" 671 | vtt_name = f"{name}.vtt" 672 | srt_name = f"{name}.tmp.srt" 673 | srt_name_final = f"{name}.srt" 674 | 675 | file_mp3 = os.path.join(save_dir, mp3_name) 676 | file_vtt = os.path.join(save_dir, vtt_name) 677 | file_srt = os.path.join(save_dir, srt_name) 678 | file_srt_final = os.path.join(save_dir, srt_name_final) 679 | mp3_exists = await check_file_exists(file_mp3) 680 | srt_exists = await check_file_exists(file_srt_final) 681 | time_exists = await check_file_exists(os.path.join(save_dir, f"{name}time.txt")) 682 | if mp3_exists and srt_exists and time_exists: 683 | return 684 | await edge_gen_srt2( 685 | file_txt, file_mp3, file_vtt, file_srt, p_voice, p_rate, p_volume, participle_path 686 | ) 687 | 688 | if language == 'zh': 689 | await srt_regen_new(file_srt, file_srt_final, False) 690 | # 删除其他生成文件 691 | os.remove(file_vtt) 692 | os.remove(file_srt) 693 | else: 694 | os.replace(file_srt, file_srt_final) 695 | await picture_processing_time( 696 | file_srt_final, os.path.join(save_dir, f"{name}.txt"), save_dir, name 697 | ) 698 | 699 | if bgm: 700 | # 如果使用bgm 701 | await mix_main_and_bgm(file_mp3, "merged_bgm.mp3", save_dir) 702 | 703 | return file_mp3, file_srt_final 704 | 705 | 706 | async def voice_srt(participle_path, path, name_path, name): 707 | await print_tip("开始生成语音字幕") 708 | if once: 709 | with open(name_path, "r", encoding="utf-8") as f: 710 | content = f.read() 711 | max_attempts = 10 # 设置最大尝试次数 712 | attempts = 0 # 初始化尝试次数计数器 713 | while attempts < max_attempts: 714 | try: 715 | # 尝试执行可能出错的操作 716 | await create_voice_srt_new3(name, content, path, participle_path) 717 | break # 如果成功,则跳出循环 718 | except Exception as e: 719 | # 捕获到异常,打印错误信息,并决定是否重试 720 | print(f"尝试生成语音字幕时出错: {e}") 721 | attempts += 1 # 增加尝试次数 722 | await asyncio.sleep(10) # 等待一段时间后重试,避免立即重试 723 | 724 | if attempts == max_attempts: 725 | raise Exception("尝试生成语音字幕失败次数过多,停止重试。") 726 | else: 727 | async with aiofiles.open(participle_path, "r", encoding="utf8") as file: 728 | lines = await file.readlines() 729 | # 循环输出每一行内容 730 | index = 1 731 | for line in lines: 732 | if line: 733 | mp3_exists = await check_file_exists( 734 | os.path.join(path, f"{index}.mp3") 735 | ) 736 | srt_exists = await check_file_exists( 737 | os.path.join(path, f"{index}.srt") 738 | ) 739 | if memory and mp3_exists and srt_exists: 740 | await print_tip(f"使用缓存,读取第{index}段语音字幕") 741 | else: 742 | await create_voice_srt_new2(index, line, path) 743 | index += 1 744 | 745 | 746 | if __name__ == "__main__": 747 | save_dir = './' 748 | asyncio.run(mix_main_and_bgm("./20075.mp3", "merged_bgm.mp3", save_dir)) 749 | 750 | -------------------------------------------------------------------------------- /webui.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | set CURRENT_DIR=%CD% 3 | echo ***** Current directory: %CURRENT_DIR% ***** 4 | set PYTHONPATH=%CURRENT_DIR% 5 | 6 | call .venv\Scripts\activate 7 | rem set HF_ENDPOINT=https://hf-mirror.com 8 | streamlit run .\app.py --browser.gatherUsageStats=False --server.enableCORS=True --------------------------------------------------------------------------------