Spaces:
Build error
Build error
github-actions[bot] commited on
Commit ·
b154daf
0
Parent(s):
Deploy from GitHub Actions - 2026-01-10 04:43:59
Browse filesFiles changed (14)
- .gitignoreAdded+7
- LICENSEAdded+201
- README.mdAdded+50
- app.pyAdded+407
- chapterbar/__init__.pyAdded+3
- chapterbar/chapter_extractor.pyAdded+198
- chapterbar/chapter_loader.pyAdded+141
- chapterbar/chapter_validator.pyAdded+234
- chapterbar/cli.pyAdded+181
- chapterbar/generator.pyAdded+469
- chapterbar/interactive_editor.pyAdded+260
- chapterbar/logger.pyAdded+28
- chapterbar/parser.pyAdded+78
- requirements.txtAdded+202
1234567__pycache__/*.py[cod].venv/*.mov*.mp4outputs/inputs/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950---title: Auto Chapter Baremoji: 🎬colorFrom: bluecolorTo: purplesdk: gradiopython_version: "3.13"sdk_version: "5.9.1"app_file: app.pypinned: falselicense: apache-2.0---
# 🎬 Auto Chapter Bar
Auto Chapter Bar(简称 `acb`)是一个开源的 Python 工具,可以快速将 SRT 字幕文件转换为带有 Alpha 透明通道的视频章节进度条。
## ✨ 核心特性
- **🎨 透明通道支持**:输出 RGBA 格式,可完美叠加在任意视频上- **🤖 AI 智能分段**:基于 Moonshot LLM 理解语义边界,自动识别章节- **🔒 隐私优先**:完全本地处理,视频文件不上传云端- **⚡ 高性能**:多进程并行处理,速度提升 2-4 倍- **🎛️ 三种模式**:AI 智能模式、自动分段模式、手动配置模式
## 🚀 使用方法
1. 上传 SRT 字幕文件2. 输入视频总时长(秒)3. 选择生成模式(AI 或 Auto)4. 点击生成按钮5. 下载生成的章节进度条视频
## 📦 在视频编辑软件中使用
生成的视频带有透明通道(Alpha Channel),可以直接叠加在原视频上:
- **Adobe Premiere Pro**:导入后放在最上层视频轨道- **剪映(CapCut)**:添加为画中画轨道- **DaVinci Resolve**:放在视频轨道最上层
## 🔗 项目链接
- **GitHub**: https://github.com/bbruceyuan/auto-chapter-bar- **文档**: 查看 GitHub 仓库获取完整文档- **许可证**: Apache License 2.0
---
⭐ 如果觉得这个项目有帮助,请在 GitHub 给个 Star!123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407import syssys.path.insert(0, "/app/src")"""Auto-Chapter-Bar Web Interface v2 with Interactive Editor支持 AI 生成后编辑章节"""
import osimport tempfile
import gradio as grimport pandas as pd
from chapterbar.chapter_extractor import ( BASE_COLOR, Chapter, extract_chapters_ai, extract_chapters_auto,)from chapterbar.chapter_validator import ChapterValidatorfrom chapterbar.generator import generate_videofrom chapterbar.parser import parse_srt
def format_time(seconds: float) -> str: """格式化时间为 mm:ss""" minutes = int(seconds // 60) secs = int(seconds % 60) return f"{minutes:02d}:{secs:02d}"
def parse_time(time_str: str) -> float: """解析时间字符串(mm:ss 或秒数)""" time_str = time_str.strip() if ":" in time_str: parts = time_str.split(":") if len(parts) == 2: return int(parts[0]) * 60 + int(parts[1]) return float(time_str)
def chapters_to_dataframe(chapters: list[Chapter]) -> pd.DataFrame: """将章节列表转换为 DataFrame""" data = [] for i, ch in enumerate(chapters, 1): data.append( { "序号": i, "开始时间": format_time(ch.start_time), "结束时间": format_time(ch.end_time), "标题": ch.title, } ) return pd.DataFrame(data)
def dataframe_to_chapters(df: pd.DataFrame, duration: float) -> tuple[list[Chapter], list[str]]: """将 DataFrame 转换为章节列表,并验证""" chapters = [] for _, row in df.iterrows(): try: start_time = parse_time(str(row["开始时间"])) end_time = parse_time(str(row["结束时间"])) title = str(row["标题"])
chapter = Chapter(title=title, start_time=start_time, end_time=end_time, color=BASE_COLOR) chapters.append(chapter) except Exception as e: return [], [f"解析第 {row['序号']} 行失败: {str(e)}"]
# 验证章节 validator = ChapterValidator(chapters, duration) is_valid, errors, warnings = validator.validate()
if errors: error_messages = [err.message for err in errors] return chapters, error_messages
return chapters, []
def extract_duration_from_srt(srt_file_path: str) -> float | None: """从 SRT 文件提取时长""" try: entries = parse_srt(srt_file_path) if not entries: return None return entries[-1].end_time except Exception as e: print(f"提取时长失败: {e}") return None
def generate_chapters(srt_file, mode: str, interval: int, api_key: str, model: str) -> tuple[pd.DataFrame, str, float]: """生成章节列表
返回: (章节DataFrame, 状态消息, 视频时长) """ try: if not srt_file: return pd.DataFrame(), "❌ 请先上传 SRT 文件", 0
# 解析 SRT file_path = srt_file.name if hasattr(srt_file, "name") else srt_file entries = parse_srt(file_path) if not entries: return pd.DataFrame(), "❌ SRT 文件解析失败", 0
# 获取时长 duration = extract_duration_from_srt(file_path) if not duration: return pd.DataFrame(), "❌ 无法获取视频时长", 0
# 提取章节 if mode == "ai": if not api_key or not api_key.strip(): return pd.DataFrame(), "❌ AI 模式需要提供 API Key", duration chapters = extract_chapters_ai(entries, duration, api_key, model) else: chapters = extract_chapters_auto(entries, interval, duration)
if not chapters: return pd.DataFrame(), "❌ 章节提取失败", duration
# 转换为 DataFrame df = chapters_to_dataframe(chapters) mode_name = "AI 智能分段" if mode == "ai" else "固定间隔" status = f"✅ 成功生成 {len(chapters)} 个章节({mode_name})\n📏 视频时长: {duration:.2f} 秒"
return df, status, duration
except Exception as e: return pd.DataFrame(), f"❌ 生成失败: {str(e)}", 0
def generate_video_from_chapters( chapters_df: pd.DataFrame, duration: float, width: int, height: int) -> tuple[str, str | None]: """从章节 DataFrame 生成视频
返回: (状态消息, 视频路径) """ try: if chapters_df.empty: return "❌ 章节列表为空,请先生成章节", None
if duration <= 0: return "❌ 视频时长无效", None
# 转换为章节列表并验证 chapters, errors = dataframe_to_chapters(chapters_df, duration)
if errors: error_msg = "❌ 验证失败:\n" + "\n".join(f" • {err}" for err in errors) return error_msg, None
# 生成视频 with tempfile.NamedTemporaryFile(suffix=".mov", delete=False) as tmp_file: output_path = tmp_file.name
generate_video( chapters=chapters, duration=duration, output_path=output_path, width=width, height=height, )
if not os.path.exists(output_path): return "❌ 视频生成失败", None
return ( f"✅ 视频生成成功!\n📊 共 {len(chapters)} 个章节\n📏 时长: {duration:.2f} 秒", output_path, )
except Exception as e: return f"❌ 生成失败: {str(e)}", None
def sort_and_renumber_chapters(chapters_df: pd.DataFrame) -> tuple[pd.DataFrame, str]: """整理章节:按开始时间排序并重新编号""" try: if chapters_df.empty: return chapters_df, "❌ 章节列表为空"
# 移除空行 chapters_df = chapters_df.dropna(subset=["标题"]).reset_index(drop=True)
if chapters_df.empty: return chapters_df, "❌ 没有有效的章节"
# 解析时间并排序 chapters_df["_start_seconds"] = chapters_df["开始时间"].apply(lambda x: parse_time(str(x))) chapters_df = chapters_df.sort_values("_start_seconds").reset_index(drop=True) chapters_df = chapters_df.drop("_start_seconds", axis=1)
# 重新编号 chapters_df["序号"] = range(1, len(chapters_df) + 1)
return chapters_df, f"✅ 已整理 {len(chapters_df)} 个章节" except Exception as e: return chapters_df, f"❌ 整理失败: {str(e)}"
def validate_chapters_only(chapters_df: pd.DataFrame, duration: float) -> str: """仅验证章节,不生成视频""" try: if chapters_df.empty: return "❌ 章节列表为空"
if duration <= 0: return "❌ 视频时长无效"
# 转换并验证 chapters, errors = dataframe_to_chapters(chapters_df, duration)
if errors: error_msg = "❌ 验证失败:\n" + "\n".join(f" • {err}" for err in errors) return error_msg
# 获取警告 validator = ChapterValidator(chapters, duration) is_valid, _, warnings = validator.validate()
if warnings: warning_msg = "\n⚠️ 警告:\n" + "\n".join(f" • {w.message}" for w in warnings) return f"✅ 验证通过!共 {len(chapters)} 个章节{warning_msg}"
return f"✅ 验证通过!共 {len(chapters)} 个章节,无警告"
except Exception as e: return f"❌ 验证失败: {str(e)}"
def create_interface(): """创建 Gradio 界面"""
with gr.Blocks(title="Auto-Chapter-Bar v2", theme=gr.themes.Soft()) as app: # 状态变量 duration_state = gr.State(0.0)
gr.Markdown( """ # 🎬 [Auto-Chapter-Bar](https://github.com/bbruceyuan/auto-chapter-bar) ### 将 SRT 字幕文件转换为可叠加的视频章节进度条动画
**使用说明**:上传 SRT 文件 → 设置参数 → 点击生成 → 下载透明视频
**特性**:
* AI 智能分段(需要 Moonshot API Key) * 固定间隔分段(免费) * 透明通道输出(直接叠加到原视频) * 支持中文字幕 """ )
with gr.Row(): # 左侧:输入和设置 with gr.Column(scale=1): gr.Markdown("### 1️⃣ 上传文件") srt_file = gr.File(label="SRT 字幕文件", file_types=[".srt"], file_count="single")
gr.Markdown("### 2️⃣ 生成章节") mode = gr.Radio( label="提取模式", choices=[("固定间隔", "auto"), ("AI 智能分段", "ai")], value="auto", )
with gr.Group() as auto_group: interval = gr.Slider(label="间隔(秒)", minimum=30, maximum=300, value=60, step=30)
with gr.Group(visible=False) as ai_group: api_key = gr.Textbox(label="API Key", type="password", placeholder="sk-...") model = gr.Dropdown( label="模型", choices=["moonshot-v1-8k", "moonshot-v1-32k"], value="moonshot-v1-8k", )
generate_chapters_btn = gr.Button("🎯 生成章节", variant="primary", size="lg")
status_gen = gr.Textbox(label="生成状态", lines=3, interactive=False)
# 右侧:章节编辑和生成 with gr.Column(scale=1): gr.Markdown("### 3️⃣ 编辑章节")
gr.Markdown( """ **编辑说明**: - 📝 **直接编辑**: 双击单元格修改内容 - ➕ **添加行**: 点击表格右上角的 ➕ 按��� - 🗑️ **删除行**: 选中行后点击表格右上角的 🗑️ 按钮 - 🔄 **重新排序**: 编辑后点击"整理章节"按钮 """ )
chapters_table = gr.Dataframe( headers=["序号", "开始时间", "结束时间", "标题"], datatype=["number", "str", "str", "str"], label="章节列表", interactive=True, wrap=True, row_count=(1, "dynamic"), # 允许动态添加行 col_count=(4, "fixed"), )
with gr.Row(): sort_btn = gr.Button("🔄 整理章节(按时间排序并重新编号)", size="sm") validate_btn = gr.Button("✅ 验证章节", size="sm", variant="secondary")
status_edit = gr.Textbox(label="编辑状态", lines=3, interactive=False)
gr.Markdown("### 4️⃣ 生成视频")
with gr.Row(): width = gr.Number(label="宽度", value=1920, minimum=640) height = gr.Number(label="高度", value=60, minimum=40)
generate_video_btn = gr.Button("🎬 生成视频", variant="primary", size="lg")
status_video = gr.Textbox(label="生成状态", lines=3, interactive=False)
output_video = gr.Video(label="预览") download_file = gr.File(label="下载")
gr.Markdown( """ --- ### 💡 使用提示 1. **时间格式**: 支持 `mm:ss` (如 `01:30`) 或秒数 (如 `90`) 2. **直接编辑**: 点击表格单元格可直接修改 3. **验证**: 生成视频时会自动检查时间重叠和间隙 4. **保存**: 编辑后的章节会在生成视频时使用
---
### 💡 其他
**固定间隔模式(推荐新手)**: - 免费使用,无需 API Key - 适合结构均匀的教程、课程类视频
**AI 智能分段模式(推荐高质量内容)**: - 需要 Moonshot API Key - 自动识别主题转换点,生成更自然的章节 - 成本约 ¥0.05/视频(5 分钟时长)
**后续步骤**: 1. 下载生成的 `.mov` 文件(透明通道) 2. 在 PR/剪映/达芬奇中导入原视频 3. 将章节条拖到最上层轨道 4. 导出最终视频
**GitHub 仓库**: [https://github.com/bbruceyuan/auto-chapter-bar](https://github.com/bbruceyuan/auto-chapter-bar)
--- Made with ❤️ by [Chaofa Yuan](https://yuanchaofa.com) """ )
# 事件处理 def toggle_mode(mode_value): if mode_value == "ai": return gr.Group(visible=False), gr.Group(visible=True) return gr.Group(visible=True), gr.Group(visible=False)
mode.change(fn=toggle_mode, inputs=[mode], outputs=[auto_group, ai_group])
generate_chapters_btn.click( fn=generate_chapters, inputs=[srt_file, mode, interval, api_key, model], outputs=[chapters_table, status_gen, duration_state], )
sort_btn.click( fn=sort_and_renumber_chapters, inputs=[chapters_table], outputs=[chapters_table, status_edit], )
validate_btn.click( fn=validate_chapters_only, inputs=[chapters_table, duration_state], outputs=[status_edit], )
def generate_and_display(df, dur, w, h): status, video_path = generate_video_from_chapters(df, dur, int(w), int(h)) return status, video_path, video_path
generate_video_btn.click( fn=generate_and_display, inputs=[chapters_table, duration_state, width, height], outputs=[status_video, output_video, download_file], )
return app
if __name__ == "__main__": app = create_interface() app.launch()123"""Auto-Chapter-Bar - 视频章节进度条生成器"""
__version__ = "0.1.0"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198"""章节提取器"""
import jsonimport osimport refrom dataclasses import dataclass
import openai
from chapterbar.logger import loggerfrom chapterbar.parser import SubtitleEntry
@dataclassclass Chapter: """章节信息"""
title: str start_time: float # 秒 end_time: float # 秒 color: tuple[int, int, int] # RGB
# 统一灰色方案(实际颜色在渲染时根据播放状态决定)# 未播放:浅灰色 (220, 220, 220)# 已播放:深灰色 (140, 140, 140)BASE_COLOR = (200, 200, 200) # 默认灰色
def extract_chapters_auto(entries: list[SubtitleEntry], interval: int, total_duration: float) -> list[Chapter]: """自动分段模式:按时间间隔分段
Args: entries: 字幕条目列表 interval: 分段间隔(秒) total_duration: 视频总时长(秒)
Returns: List[Chapter]: 章节列表 """ chapters = [] current_time = 0 chapter_index = 0
while current_time < total_duration: # 计算章节结束时间 end_time = min(current_time + interval, total_duration)
# 找到这个时间段内的字幕文本作为标题 title_parts = [] if entries: # 只有当有字幕时才尝试提取 for entry in entries: if current_time <= entry.start_time < end_time: title_parts.append(entry.text) if len(title_parts) >= 3: # 最多取3条字幕 break
# 生成标题 title = " ".join(title_parts)[:30] if title_parts else f"章节 {chapter_index + 1}"
# 使用统一的基础颜色 color = BASE_COLOR
chapters.append(Chapter(title=title, start_time=current_time, end_time=end_time, color=color))
current_time = end_time chapter_index += 1
return chapters
def format_time(seconds: float) -> str: """将秒数转换为 HH:MM:SS 格式""" hours = int(seconds // 3600) minutes = int((seconds % 3600) // 60) secs = int(seconds % 60) return f"{hours:02d}:{minutes:02d}:{secs:02d}"
def extract_chapters_ai( entries: list[SubtitleEntry], total_duration: float, api_key: str | None = None, model: str = "moonshot-v1-8k",) -> list[Chapter]: """AI 智能分段模式:使用 Moonshot AI 分析字幕内容
Args: entries: 字幕条目列表 total_duration: 视频总时长(秒) api_key: Moonshot API Key(可选,默认从环境变量读取) model: 使用的模型(默认 moonshot-v1-8k)
Returns: List[Chapter]: 章节列表 """ if not entries: # 如果没有字幕,回退到自动分段 return extract_chapters_auto(entries, interval=60, total_duration=total_duration)
# 获取 API Key if api_key is None: api_key = os.getenv("MOONSHOT_API_KEY")
if not api_key: raise ValueError("未提供 Moonshot API Key,请设置环境变量 MOONSHOT_API_KEY 或通过参数传入")
# 初始化客户端 client = openai.Client(base_url="https://api.moonshot.cn/v1", api_key=api_key)
# 构建字幕文本(带时间戳) subtitle_lines = [] for entry in entries: time_str = format_time(entry.start_time) subtitle_lines.append(f"[{time_str}] {entry.text}")
subtitle_text = "\n".join(subtitle_lines)
# 构建 prompt prompt = f"""请分析以下视频字幕内容,识别内容的主题转换点,并生成合理的章节划分。
要求:1. 识别 5-10 个主要章节(根据内容长度和复杂度调整)2. 每个章节给出开始时间(格式:HH:MM:SS)和简短标题(5-15 字)3. 章节标题要准确概括该段内容的核心主题4. 返回 JSON 格式数组,每个元素包含 time 和 title 字段5. 视频总时长为 {format_time(total_duration)}
示例输出格式:[ {{"time": "00:00:00", "title": "开场与自我介绍"}}, {{"time": "00:01:23", "title": "问题背景分析"}}, {{"time": "00:03:45", "title": "解决方案详解"}}]
字幕内容:{subtitle_text}
请直接返回 JSON 数组,不要包含其他说明文字。"""
# 调用 API try: response = client.chat.completions.create( model=model, messages=[ { "role": "system", "content": "你是一个专业的视频内容分析助手,擅长识别内容结构和主题转换点。", }, {"role": "user", "content": prompt}, ], temperature=0.3, # 较低的温度以获得更稳定的输出 max_tokens=2048, )
# 解析响应 content = response.choices[0].message.content.strip()
# 提取 JSON(可能被包裹在代码块中) json_match = re.search(r"```(?:json)?\s*(\[.*?\])\s*```", content, re.DOTALL) json_str = json_match.group(1) if json_match else content
# 解析 JSON chapter_data = json.loads(json_str)
# 转换为 Chapter 对象 chapters = [] for i, item in enumerate(chapter_data): # 解析时间 time_str = item["time"] time_parts = time_str.split(":") start_time = int(time_parts[0]) * 3600 + int(time_parts[1]) * 60 + int(time_parts[2])
# 计算结束时间 if i < len(chapter_data) - 1: next_time_str = chapter_data[i + 1]["time"] next_time_parts = next_time_str.split(":") end_time = int(next_time_parts[0]) * 3600 + int(next_time_parts[1]) * 60 + int(next_time_parts[2]) else: end_time = total_duration
# 使用统一的基础颜色 color = BASE_COLOR
chapters.append(Chapter(title=item["title"], start_time=start_time, end_time=end_time, color=color))
return chapters
except json.JSONDecodeError as e: logger.warning(f"AI 返回的内容无法解析为 JSON: {e}") logger.debug(f"原始内容: {content}") # 回退到自动分段 return extract_chapters_auto(entries, interval=60, total_duration=total_duration)
except Exception as e: logger.warning(f"AI 分段失败: {e}") # 回退到自动分段 return extract_chapters_auto(entries, interval=60, total_duration=total_duration)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141"""章节配置加载器"""
from pathlib import Pathfrom typing import Any
import yaml
from chapterbar.chapter_extractor import BASE_COLOR, Chapterfrom chapterbar.chapter_validator import ChapterValidator
class ChapterLoader: """章节配置加载器"""
@staticmethod def load_from_yaml(yaml_path: str) -> tuple[list[Chapter], float]: """ 从 YAML 文件加载章节配置
Args: yaml_path: YAML 文件路径
Returns: (chapters, duration)
Raises: FileNotFoundError: 文件不存在 ValueError: 配置格式错误或验证失败 """ # 检查文件是否存在 path = Path(yaml_path) if not path.exists(): raise FileNotFoundError(f"配置文件不存在: {yaml_path}")
# 读取 YAML try: with open(yaml_path, encoding="utf-8") as f: config = yaml.safe_load(f) except yaml.YAMLError as e: raise ValueError(f"YAML 格式错误: {e}") from e
# 验证配置结构 if not isinstance(config, dict): raise ValueError("配置文件必须是一个字典")
if "duration" not in config: raise ValueError("配置文件缺少 'duration' 字段")
if "chapters" not in config: raise ValueError("配置文件缺少 'chapters' 字段")
duration = float(config["duration"]) if duration <= 0: raise ValueError(f"视频时长必须大于 0,当前值: {duration}")
# 解析章节 chapters = ChapterLoader._parse_chapters(config["chapters"])
# 验证章节 validator = ChapterValidator(chapters, duration) is_valid, errors, warnings = validator.validate()
if not is_valid: error_messages = [f" - {err.message}" for err in errors] raise ValueError("章节配置验证失败:\n" + "\n".join(error_messages))
return chapters, duration, warnings
@staticmethod def _parse_chapters(chapters_data: list[dict[str, Any]]) -> list[Chapter]: """ 解析章节数据
Args: chapters_data: 章节数据列表
Returns: Chapter 对象列表 """ if not isinstance(chapters_data, list): raise ValueError("'chapters' 必须是一个列表")
chapters = [] for i, chapter_data in enumerate(chapters_data): if not isinstance(chapter_data, dict): raise ValueError(f"章节 {i + 1} 必须是一个字典")
# 必需字段 if "start" not in chapter_data: raise ValueError(f"章节 {i + 1} 缺少 'start' 字段") if "end" not in chapter_data: raise ValueError(f"章节 {i + 1} 缺少 'end' 字段") if "title" not in chapter_data: raise ValueError(f"章节 {i + 1} 缺少 'title' 字段")
# 解析字段 try: start_time = float(chapter_data["start"]) end_time = float(chapter_data["end"]) except (ValueError, TypeError) as e: raise ValueError(f"章节 {i + 1} 时间格式错误: {e}") from e
title = str(chapter_data["title"])
# 可选字段:颜色 if "color" in chapter_data: color_data = chapter_data["color"] if isinstance(color_data, list) and len(color_data) == 3: color = tuple(int(c) for c in color_data) else: raise ValueError(f"章节 {i + 1} 颜色格式错误,应为 [R, G, B]") else: color = BASE_COLOR
chapters.append(Chapter(title=title, start_time=start_time, end_time=end_time, color=color))
return chapters
@staticmethod def save_to_yaml(chapters: list[Chapter], duration: float, yaml_path: str) -> None: """ 保存章节配置到 YAML 文件
Args: chapters: 章节列表 duration: 视频总时长 yaml_path: 输出文件路径 """ config = {"duration": duration, "chapters": []}
for chapter in chapters: chapter_data = { "start": chapter.start_time, "end": chapter.end_time, "title": chapter.title, } config["chapters"].append(chapter_data)
# 写入文件 with open(yaml_path, "w", encoding="utf-8") as f: yaml.dump(config, f, allow_unicode=True, default_flow_style=False, sort_keys=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234"""章节验证器"""
from dataclasses import dataclass
from chapterbar.chapter_extractor import Chapter
@dataclassclass ValidationError: """验证错误"""
chapter_index: int error_type: str message: str is_warning: bool = False
class ChapterValidator: """章节验证器"""
def __init__(self, chapters: list[Chapter], total_duration: float): """ 初始化验证器
Args: chapters: 章节列表 total_duration: 视频总时长(秒) """ self.chapters = chapters self.total_duration = total_duration self.errors: list[ValidationError] = [] self.warnings: list[ValidationError] = []
def validate(self) -> tuple[bool, list[ValidationError], list[ValidationError]]: """ 验证章节列表
Returns: (is_valid, errors, warnings) """ self.errors = [] self.warnings = []
# 基础检查 self._check_empty() self._check_basic_fields()
# 时间检查 self._check_time_order() self._check_time_overlap() self._check_time_range() self._check_time_gaps()
# 内容检查 self._check_titles() self._check_duration()
is_valid = len(self.errors) == 0 return is_valid, self.errors, self.warnings
def _check_empty(self): """检查章节列表是否为空""" if not self.chapters: self.errors.append(ValidationError(chapter_index=-1, error_type="empty", message="章节列表为空"))
def _check_basic_fields(self): """检查基本字段""" for i, chapter in enumerate(self.chapters): if not hasattr(chapter, "start_time") or chapter.start_time is None: self.errors.append( ValidationError( chapter_index=i, error_type="missing_field", message=f"章节 {i + 1} 缺少开始时间", ) )
if not hasattr(chapter, "end_time") or chapter.end_time is None: self.errors.append( ValidationError( chapter_index=i, error_type="missing_field", message=f"章节 {i + 1} 缺少结束时间", ) )
if not hasattr(chapter, "title") or not chapter.title: self.errors.append( ValidationError( chapter_index=i, error_type="missing_field", message=f"章节 {i + 1} 缺少标题", ) )
def _check_time_order(self): """检查时间顺序""" for i, chapter in enumerate(self.chapters): if chapter.start_time >= chapter.end_time: self.errors.append( ValidationError( chapter_index=i, error_type="time_order", message=(f"章节 {i + 1} 开始时间 ({chapter.start_time}s) >= 结束时间 ({chapter.end_time}s)"), ) )
def _check_time_overlap(self): """检查时间重叠""" for i in range(len(self.chapters) - 1): current = self.chapters[i] next_chapter = self.chapters[i + 1]
if current.end_time > next_chapter.start_time: self.errors.append( ValidationError( chapter_index=i, error_type="time_overlap", message=( f"章节 {i + 1} 和章节 {i + 2} 时间重叠:章节 {i + 1} 结束于 " f"{current.end_time}s,但章节 {i + 2} 开始于 {next_chapter.start_time}s" ), ) )
def _check_time_range(self): """检查时间范围""" for i, chapter in enumerate(self.chapters): if chapter.start_time < 0: self.errors.append( ValidationError( chapter_index=i, error_type="time_range", message=f"章节 {i + 1} 开始时间 ({chapter.start_time}s) 不能为负数", ) )
if chapter.end_time > self.total_duration: self.errors.append( ValidationError( chapter_index=i, error_type="time_range", message=( f"章节 {i + 1} 结束时间 ({chapter.end_time}s) 超出视频总时长 ({self.total_duration}s)" ), ) )
def _check_time_gaps(self): """检查时间间隙(警告)""" # 检查第一个章节是否从 0 开始 if self.chapters and self.chapters[0].start_time > 0: self.warnings.append( ValidationError( chapter_index=0, error_type="time_gap", message=( f"第一个章节从 {self.chapters[0].start_time}s 开始,前面有 " f"{self.chapters[0].start_time}s 的间隙" ), is_warning=True, ) )
# 检查章节之间的间隙 for i in range(len(self.chapters) - 1): current = self.chapters[i] next_chapter = self.chapters[i + 1]
gap = next_chapter.start_time - current.end_time if gap > 0: self.warnings.append( ValidationError( chapter_index=i, error_type="time_gap", message=f"章节 {i + 1} 和章节 {i + 2} 之间有 {gap}s 的间隙", is_warning=True, ) )
# 检查最后一个章节是否到达视频结尾 if self.chapters and self.chapters[-1].end_time < self.total_duration: gap = self.total_duration - self.chapters[-1].end_time self.warnings.append( ValidationError( chapter_index=len(self.chapters) - 1, error_type="time_gap", message=(f"最后一个章节结束于 {self.chapters[-1].end_time}s,距离视频结尾还有 {gap}s"), is_warning=True, ) )
def _check_titles(self): """检查标题""" for i, chapter in enumerate(self.chapters): if chapter.title and len(chapter.title.strip()) == 0: self.errors.append( ValidationError(chapter_index=i, error_type="empty_title", message=f"章节 {i + 1} 标题为空") )
if chapter.title and len(chapter.title) > 100: self.warnings.append( ValidationError( chapter_index=i, error_type="long_title", message=(f"章节 {i + 1} 标题过长 ({len(chapter.title)} 字符),建议不超过 100 字符"), is_warning=True, ) )
def _check_duration(self): """检查章节时长(警告)""" for i, chapter in enumerate(self.chapters): duration = chapter.end_time - chapter.start_time
if duration < 5: self.warnings.append( ValidationError( chapter_index=i, error_type="short_duration", message=f"章节 {i + 1} 时长过短 ({duration}s),建议至少 5 秒", is_warning=True, ) )
if duration > 600: # 10 分钟 self.warnings.append( ValidationError( chapter_index=i, error_type="long_duration", message=f"章节 {i + 1} 时长过长 ({duration}s),建议不超过 10 分钟", is_warning=True, ) )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181"""命令行界面"""
from pathlib import Path
import typerfrom rich.console import Console
from chapterbar.chapter_extractor import extract_chapters_ai, extract_chapters_autofrom chapterbar.chapter_loader import ChapterLoaderfrom chapterbar.generator import generate_videofrom chapterbar.interactive_editor import display_chapters_tablefrom chapterbar.parser import parse_srt
app = typer.Typer(help="Auto-Chapter-Bar - 视频章节进度条生成器")console = Console()
@app.command()def main( srt_file: Path | None = typer.Argument(None, help="SRT 字幕文件路径(可选,使用 --chapters 时不需要)"), duration: float | None = typer.Argument(None, help="视频总时长(秒),不提供则从 SRT 文件自动获取"), output: Path = typer.Option("chapter_bar.mov", "--output", "-o", help="输出文件路径"), width: int = typer.Option(1920, "--width", "-w", help="视频宽度"), height: int = typer.Option(60, "--height", "-h", help="进度条高度"), mode: str = typer.Option( "ai", "--mode", "-m", help="章节提取模式:auto(固定间隔)、ai(智能分段,默认)或 manual(手动配置)", ), interval: int = typer.Option(60, "--interval", "-i", help="自动分段间隔(秒),仅在 auto 模式下使用"), api_key: str | None = typer.Option( None, "--api-key", help="Moonshot API Key(AI 模式需要,也可通过环境变量 MOONSHOT_API_KEY 设置)", ), model: str = typer.Option("moonshot-v1-8k", "--model", help="AI 模型名称(默认 moonshot-v1-8k)"), auto_confirm: bool = typer.Option(False, "--yes", "-y", help="自动确认所有提示(跳过时长确认和章节编辑)"), chapters_file: Path | None = typer.Option(None, "--chapters", help="手动章节配置文件(YAML 格式)"), save_chapters: Path | None = typer.Option(None, "--save-chapters", help="保存生成的章节配置到 YAML 文件"),): """生成视频章节进度条"""
try: # 1. 检查是否使用手动配置文件 if chapters_file: console.print(f"[cyan]📄 正在加载章节配置文件: {chapters_file}[/cyan]") try: chapters, duration, warnings = ChapterLoader.load_from_yaml(str(chapters_file)) console.print(f"[green]✓ 配置加载成功,共 {len(chapters)} 个章节[/green]") console.print(f"[cyan]📏 视频时长: {duration:.2f} 秒 ({duration / 60:.2f} 分钟)[/cyan]")
# 显示警告 if warnings: console.print(f"\n[yellow]⚠️ 发现 {len(warnings)} 个警告:[/yellow]") for warning in warnings: console.print(f"[yellow] - {warning.message}[/yellow]") console.print()
# 跳过 SRT 解析,直接到章节显示 entries = None
except (FileNotFoundError, ValueError) as e: console.print(f"[red]✗ 错误: {e}[/red]") raise typer.Exit(1) from e
# 2. 解析 SRT 文件(如果没有使用配置文件) elif srt_file: console.print(f"[cyan]正在解析 SRT 文件: {srt_file}[/cyan]") entries = parse_srt(str(srt_file)) console.print(f"[green]✓ 解析完成,共 {len(entries)} 条字幕[/green]")
if not entries: console.print("[red]✗ 错误: SRT 文件为空[/red]") raise typer.Exit(1) else: console.print("[red]✗ 错误: 必须提供 SRT 文件或章节配置文件(--chapters)[/red]") raise typer.Exit(1)
# 3. 处理视频时长(如果没有使用配置文件) if not chapters_file: srt_duration = entries[-1].end_time
if duration is None: # 用户未提供时长,自动从 SRT 获取 duration = srt_duration console.print( f"[cyan]📏 从 SRT 文件自动获取视频时长: {duration:.2f} 秒 ({duration / 60:.2f} 分钟)[/cyan]" ) else: # 用户提供了时长,检查是否与 SRT 一致 console.print(f"[cyan]📏 用户指定视频时长: {duration:.2f} 秒 ({duration / 60:.2f} 分钟)[/cyan]") console.print(f"[cyan]📏 SRT 文件实际时长: {srt_duration:.2f} 秒 ({srt_duration / 60:.2f} 分钟)[/cyan]")
# 如果差异超过 5 秒,显示警告 if abs(duration - srt_duration) > 5: console.print("\n[yellow]⚠️ 警告: 指定时长与 SRT 实际时长不一致![/yellow]") console.print(f"[yellow] 差异: {abs(duration - srt_duration):.2f} 秒[/yellow]\n")
if not auto_confirm: # 询问用户选择 console.print("请选择使用哪个时长:") console.print(f" [1] 使用 SRT 时长: {srt_duration:.2f} 秒 (推荐)") console.print(f" [2] 使用指定时长: {duration:.2f} 秒") console.print(" [3] 取消操作")
choice = typer.prompt("\n请输入选择 (1/2/3)", default="1")
if choice == "1": duration = srt_duration console.print(f"[green]✓ 使用 SRT 时长: {duration:.2f} 秒[/green]\n") elif choice == "2": console.print(f"[green]✓ 使用指定时长: {duration:.2f} 秒[/green]\n") else: console.print("[yellow]已取消操作[/yellow]") raise typer.Exit(0) else: # 自动确认模式,使用 SRT 时长 duration = srt_duration console.print(f"[green]✓ 自动使用 SRT 时长: {duration:.2f} 秒[/green]\n")
# 4. 提取章节(如果没有使用配置文件) if chapters_file: # 已经从配置文件加载了章节,跳过 pass elif mode == "ai": console.print(f"[cyan]🤖 正在使用 AI 智能分段(模型: {model})...[/cyan]") console.print("[yellow]这可能需要几秒钟,请稍候...[/yellow]") chapters = extract_chapters_ai(entries, duration, api_key, model) console.print(f"[green]✓ AI 分段完成,共 {len(chapters)} 个章节[/green]\n") else: console.print(f"[cyan]正在提取章节(间隔: {interval}秒)...[/cyan]") chapters = extract_chapters_auto(entries, interval, duration) console.print(f"[green]✓ 提取完成,共 {len(chapters)} 个章节[/green]\n")
# 5. 保存章节配置(如果指定了 --save-chapters) if save_chapters: console.print(f"\n[cyan]💾 正在保存章节配置到: {save_chapters}[/cyan]") try: ChapterLoader.save_to_yaml(chapters, duration, str(save_chapters)) console.print("[green]✓ 章节配置已保存[/green]") console.print(f"[cyan]💡 提示: 可以编辑 {save_chapters} 后使用 --chapters 参数重新生成[/cyan]\n") except Exception as e: console.print(f"[yellow]⚠️ 保存配置失败: {e}[/yellow]\n")
# 6. 显示章节列表 display_chapters_table(chapters) console.print()
# 7. 交互式确认(仅在 AI 或 Auto 模式下,且未使用配置文件时) # if not chapters_file and mode in ["ai", "auto"]: # chapters = confirm_chapters(chapters, skip_confirm=auto_confirm) # if chapters is None: # # 用户选择退出 # raise typer.Exit(0)
# 8. 生成视频 console.print(f"[cyan]正在生成视频: {output}[/cyan]") console.print("[yellow]这可能需要几分钟时间,请耐心等待...[/yellow]")
generate_video( chapters=chapters, output_path=str(output), width=width, height=height, duration=duration, )
console.print(f"[green]✓ 视频生成完成: {output}[/green]") console.print("\n[bold]使用说明:[/bold]") console.print("1. 在剪辑软件(PR/剪映/达芬奇)中打开原视频") console.print("2. 将生成的章节条视频拖入最上层轨道") console.print("3. 调整位置和大小,导出最终视频")
except Exception as e: console.print(f"[red]✗ 错误: {e}[/red]") raise typer.Exit(1) from e
if __name__ == "__main__": app()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469"""视频生成器 - 并行优化版本性能优化:1. 字体缓存 - 避免重复加载字体2. 预计算章节布局 - 避免每帧重复计算3. 多进程并行 - 利用多核 CPU 加速帧生成"""
from dataclasses import dataclassfrom functools import partialfrom multiprocessing import Pool, cpu_count
import numpy as np
# 使用 ImageSequenceClip 创建视频from moviepy.video.io.ImageSequenceClip import ImageSequenceClipfrom PIL import Image, ImageDraw, ImageFont
from chapterbar.chapter_extractor import Chapterfrom chapterbar.logger import logger
# ============================================================================# 全局字体缓存# ============================================================================
_font_cache: dict[int, ImageFont.FreeTypeFont | None] = {}_font_paths = [ "/System/Library/Fonts/STHeiti Light.ttc", # macOS 黑体 "/System/Library/Fonts/PingFang.ttc", # macOS 苹方 "/System/Library/Fonts/Hiragino Sans GB.ttc", # macOS "/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf", # Linux "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", # Linux "C:\\Windows\\Fonts\\msyh.ttc", # Windows 微软雅黑 "C:\\Windows\\Fonts\\simhei.ttf", # Windows 黑体]
def get_cached_font(size: int) -> ImageFont.FreeTypeFont | None: """获取缓存的字体
Args: size: 字体大小
Returns: 字体对象,如果加载失败则返回 None """ if size not in _font_cache: font = None for font_path in _font_paths: try: font = ImageFont.truetype(font_path, size) break except Exception: continue
# 如果所有字体都失败,尝试 Arial if font is None: try: font = ImageFont.truetype("Arial.ttf", size) except Exception: font = ImageFont.load_default()
_font_cache[size] = font
return _font_cache[size]
# ============================================================================# 预计算章节布局# ============================================================================
@dataclassclass ChapterLayout: """预计算的章节布局信息"""
x_offset: int width: int title: str original_title: str # 原始标题(未截断) font_size: int text_x: int text_y: int text_width: int text_height: int should_draw_text: bool # 是否应该绘制文字
def precompute_chapter_layouts( chapters: list[Chapter], width: int, height: int, duration: float) -> list[ChapterLayout]: """预计算所有章节的布局信息
Args: chapters: 章节列表 width: 视频宽度 height: 进度条高度 duration: 视频总时长
Returns: 章节布局列表 """ layouts = [] x_offset = 0
for chapter in chapters: # 计算章节宽度 chapter_duration = chapter.end_time - chapter.start_time chapter_width = int((chapter_duration / duration) * width)
# 如果章节太窄,跳过文字 if chapter_width < 50: layouts.append( ChapterLayout( x_offset=x_offset, width=chapter_width, title="", original_title=chapter.title, font_size=0, text_x=0, text_y=0, text_width=0, text_height=0, should_draw_text=False, ) ) x_offset += chapter_width continue
# 计算文字布局 text = chapter.title font_size = 20 font = get_cached_font(font_size)
# 创建临时 draw 对象用于测量 temp_img = Image.new("RGBA", (1, 1)) temp_draw = ImageDraw.Draw(temp_img)
bbox = temp_draw.textbbox((0, 0), text, font=font) text_width = bbox[2] - bbox[0] text_height = bbox[3] - bbox[1]
# 如果文字太长,逐步缩小字号 while text_width > chapter_width - 20 and font_size > 12: font_size -= 2 font = get_cached_font(font_size) bbox = temp_draw.textbbox((0, 0), text, font=font) text_width = bbox[2] - bbox[0] text_height = bbox[3] - bbox[1]
# 如果还是太长,截断文字 if text_width > chapter_width - 20: while text and text_width > chapter_width - 20: text = text[:-1] bbox = temp_draw.textbbox((0, 0), text + "...", font=font) text_width = bbox[2] - bbox[0] if text: text = text + "..."
# 计算文字位置(居中) text_x = x_offset + (chapter_width - text_width) // 2 text_y = (height - text_height) // 2
layouts.append( ChapterLayout( x_offset=x_offset, width=chapter_width, title=text, original_title=chapter.title, font_size=font_size, text_x=text_x, text_y=text_y, text_width=text_width, text_height=text_height, should_draw_text=bool(text), ) )
x_offset += chapter_width
return layouts
# ============================================================================# 优化的帧生成函数# ============================================================================
def create_chapter_bar_frame_optimized( t: float, chapters: list[Chapter], layouts: list[ChapterLayout], width: int, height: int, duration: float,) -> np.ndarray: """创建章节条的单帧图像(优化版本)
Args: t: 当前时间(秒) chapters: 章节列表 layouts: 预计算的章节布局 width: 视频宽度 height: 进度条高度 duration: 视频总时长
Returns: np.ndarray: RGBA 图像数组 """ # 定义颜色方案 COLOR_UNWATCHED = (220, 220, 220) # 未播放:浅灰色 COLOR_WATCHED = (140, 140, 140) # 已播放:深灰色 COLOR_SEPARATOR = (100, 100, 100) # 分隔线:更深灰色
# 创建透明背景 img = Image.new("RGBA", (width, height), (0, 0, 0, 0)) draw = ImageDraw.Draw(img)
# 绘制章节条 for i, (chapter, layout) in enumerate(zip(chapters, layouts, strict=True)): # 判断章节状态并绘制 if chapter.end_time <= t: # 完全播放完 → 深灰色 draw.rectangle( [layout.x_offset, 0, layout.x_offset + layout.width, height], fill=COLOR_WATCHED + (255,), ) elif chapter.start_time <= t < chapter.end_time: # 当前章节 → 分段绘制 chapter_duration = chapter.end_time - chapter.start_time played_duration = t - chapter.start_time played_width = int((played_duration / chapter_duration) * layout.width)
# 已播放部分:深灰色 if played_width > 0: draw.rectangle( [layout.x_offset, 0, layout.x_offset + played_width, height], fill=COLOR_WATCHED + (255,), )
# 未播放部分:浅灰色 if played_width < layout.width: draw.rectangle( [layout.x_offset + played_width, 0, layout.x_offset + layout.width, height], fill=COLOR_UNWATCHED + (255,), ) else: # 未播放 → 浅灰色 draw.rectangle( [layout.x_offset, 0, layout.x_offset + layout.width, height], fill=COLOR_UNWATCHED + (255,), )
# 绘制章节分隔线(除了第一个章节) if i > 0: draw.line( [(layout.x_offset, 0), (layout.x_offset, height)], fill=COLOR_SEPARATOR + (255,), width=2, )
# 绘制章节标题(使用预计算的布局) if layout.should_draw_text: font = get_cached_font(layout.font_size)
# 根据章节状态选择文字颜色 if chapter.end_time <= t: # 已播放章节:深灰色背景 → 白色文字 text_color = (255, 255, 255, 255) shadow_color = (0, 0, 0, 120) elif chapter.start_time <= t < chapter.end_time: # 当前章节:混合背景 → 白色文字 text_color = (255, 255, 255, 255) shadow_color = (0, 0, 0, 120) else: # 未播放章节:浅灰色背景 → 深灰色文字 text_color = (80, 80, 80, 255) shadow_color = (255, 255, 255, 120)
# 绘制文字阴影 draw.text((layout.text_x + 1, layout.text_y + 1), layout.title, fill=shadow_color, font=font) # 绘制文字 draw.text((layout.text_x, layout.text_y), layout.title, fill=text_color, font=font)
# 绘制进度指针(白色竖线,4px 宽) pointer_x = int((t / duration) * width) # 绘制指针阴影 draw.rectangle([pointer_x - 3, 0, pointer_x + 3, height], fill=(0, 0, 0, 100)) # 绘制指针主体 draw.rectangle([pointer_x - 2, 0, pointer_x + 2, height], fill=(255, 255, 255, 255))
# 转换为 numpy 数组 return np.array(img)
# ============================================================================# 并行帧生成# ============================================================================
def generate_frame_batch( frame_indices: list[int], chapters: list[Chapter], layouts: list[ChapterLayout], width: int, height: int, duration: float, fps: int,) -> list[tuple[int, np.ndarray]]: """生成一批帧(用于并行处理)
Args: frame_indices: 要生成的帧索引列表 chapters: 章节列表 layouts: 预计算的章节布局 width: 视频宽度 height: 进度条高度 duration: 视频总时长 fps: 帧率
Returns: (帧索引, 帧数据) 的列表 """ frames = [] for frame_num in frame_indices: t = frame_num / fps frame = create_chapter_bar_frame_optimized(t, chapters, layouts, width, height, duration) frames.append((frame_num, frame)) return frames
# ============================================================================# 优化的视频生成函数(支持并行)# ============================================================================
def generate_video( chapters: list[Chapter], output_path: str, width: int = 1920, height: int = 60, duration: float = None, fps: int = 30, use_parallel: bool = True, num_workers: int | None = None,) -> None: """生成章节进度条视频(支持并行优化)
Args: chapters: 章节列表 output_path: 输出文件路径 width: 视频宽度 height: 进度条高度 duration: 视频总时长(秒) fps: 帧率 use_parallel: 是否使用并行处理(默认 True) num_workers: 并行工作进程数(默认为 CPU 核心数) """ if duration is None: duration = chapters[-1].end_time if chapters else 10
# 预计算章节布局(只计算一次) logger.info("正在预计算章节布局...") layouts = precompute_chapter_layouts(chapters, width, height, duration) logger.info(f"布局计算完成,共 {len(layouts)} 个章节")
total_frames = int(duration * fps)
# 根据帧数决定是否使用并行 # 帧数太少时,并行开销可能大于收益 if total_frames < 300: use_parallel = False logger.info(f"帧数较少 ({total_frames} 帧),使用串行生成")
if use_parallel: # 并行生成帧 if num_workers is None: num_workers = cpu_count()
logger.info(f"正在并行生成 {total_frames} 帧(使用 {num_workers} 个进程)...")
# 分批:将帧索引分配给各个进程 batch_size = (total_frames + num_workers - 1) // num_workers frame_batches = [] for i in range(num_workers): start_idx = i * batch_size end_idx = min((i + 1) * batch_size, total_frames) if start_idx < total_frames: frame_batches.append(list(range(start_idx, end_idx)))
# 创建部分函数(固定参数) batch_func = partial( generate_frame_batch, chapters=chapters, layouts=layouts, width=width, height=height, duration=duration, fps=fps, )
# 并行生成 with Pool(num_workers) as pool: results = pool.map(batch_func, frame_batches)
# 合并结果并按帧索引排序 all_frames = [] for batch_result in results: all_frames.extend(batch_result)
# 按帧索引排序 all_frames.sort(key=lambda x: x[0]) frames = [frame for _, frame in all_frames]
logger.info("并行帧生成完成") else: # 串行生成帧(原有逻辑) logger.info(f"正在生成 {total_frames} 帧...") frames = []
last_progress = -1 for frame_num in range(total_frames): t = frame_num / fps frame = create_chapter_bar_frame_optimized(t, chapters, layouts, width, height, duration) frames.append(frame)
# 显示进度(每 5% 显示一次) progress = int((frame_num + 1) / total_frames * 100) if progress % 5 == 0 and progress != last_progress: logger.info(f"进度: {frame_num + 1}/{total_frames} ({progress}%)") last_progress = progress
logger.info("帧生成完成")
clip = ImageSequenceClip(frames, fps=fps)
# 输出视频 logger.info("正在编码视频...") try: clip.write_videofile( output_path, fps=fps, codec="qtrle", # QuickTime Animation codec with alpha audio=False, logger=None, ffmpeg_params=["-pix_fmt", "argb"], preset="ultrafast", # 加快编码速度 ) except Exception as e: # 如果 qtrle 失败,尝试使用 png logger.warning(f"qtrle 编码失败,使用 png 编码: {e}") clip.write_videofile(output_path, fps=fps, codec="png", audio=False, logger=None)
logger.info("视频生成完成")
# ============================================================================# 向后兼容:保留原函数名# ============================================================================
def create_chapter_bar_frame(t: float, chapters: list[Chapter], width: int, height: int, duration: float) -> np.ndarray: """创建章节条的单帧图像(向后兼容的包装函数)
注意:此函数为向后兼容保留,性能较差。 建议使用 create_chapter_bar_frame_optimized 配合预计算布局。 """ # 每次调用都重新计算布局(性能较差) layouts = precompute_chapter_layouts(chapters, width, height, duration) return create_chapter_bar_frame_optimized(t, chapters, layouts, width, height, duration)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260"""交互式章节编辑器"""
from rich.console import Consolefrom rich.table import Table
from chapterbar.chapter_extractor import BASE_COLOR, Chapterfrom chapterbar.chapter_validator import ChapterValidator
console = Console()
def format_time(seconds: float) -> str: """格式化时间为 mm:ss""" minutes = int(seconds // 60) secs = int(seconds % 60) return f"{minutes:02d}:{secs:02d}"
def parse_time_input(time_str: str) -> float | None: """解析时间输入(支持 mm:ss 或秒数)""" time_str = time_str.strip() if not time_str: return None
try: # 尝试解析为秒数 return float(time_str) except ValueError: pass
# 尝试解析为 mm:ss 格式 if ":" in time_str: try: parts = time_str.split(":") if len(parts) == 2: minutes = int(parts[0]) seconds = int(parts[1]) return minutes * 60 + seconds except ValueError: pass
return None
def display_chapters_table(chapters: list[Chapter], title: str = "章节列表"): """显示章节列表""" table = Table(title=title) table.add_column("序号", style="cyan") table.add_column("开始时间", style="magenta") table.add_column("结束时间", style="magenta") table.add_column("标题", style="green")
for i, chapter in enumerate(chapters, 1): table.add_row(str(i), format_time(chapter.start_time), format_time(chapter.end_time), chapter.title)
console.print(table)
def edit_chapter(chapters: list[Chapter], index: int, duration: float) -> bool: """编辑单个章节""" if index < 0 or index >= len(chapters): console.print("[red]✗ 无效的章节序号[/red]") return False
chapter = chapters[index] console.print(f"\n[cyan]编辑章节 {index + 1}:[/cyan]") console.print(f"当前: {format_time(chapter.start_time)} - {format_time(chapter.end_time)} | {chapter.title}") console.print()
# 编辑开始时间 start_input = input(f"开始时间 (mm:ss 或秒数,留空保持 {format_time(chapter.start_time)}): ").strip() if start_input: new_start = parse_time_input(start_input) if new_start is None: console.print("[red]✗ 无效的时间格式[/red]") return False chapter.start_time = new_start
# 编辑结束时间 end_input = input(f"结束时间 (mm:ss 或秒数,留空保持 {format_time(chapter.end_time)}): ").strip() if end_input: new_end = parse_time_input(end_input) if new_end is None: console.print("[red]✗ 无效的时间格式[/red]") return False chapter.end_time = new_end
# 编辑标题 title_input = input(f"标题 (留空保持 '{chapter.title}'): ").strip() if title_input: chapter.title = title_input
console.print(f"[green]✓ 章节 {index + 1} 已更新[/green]\n") return True
def add_chapter(chapters: list[Chapter], duration: float) -> bool: """添加新章节""" console.print("\n[cyan]添加新章节:[/cyan]")
# 输入开始时间 start_input = input("开始时间 (mm:ss 或秒数): ").strip() start_time = parse_time_input(start_input) if start_time is None: console.print("[red]✗ 无效的时间格式[/red]") return False
# 输入结束时间 end_input = input("结束时间 (mm:ss 或秒数): ").strip() end_time = parse_time_input(end_input) if end_time is None: console.print("[red]✗ 无效的时间格式[/red]") return False
# 输入标题 title = input("标题: ").strip() if not title: console.print("[red]✗ 标题不能为空[/red]") return False
# 创建新章节 new_chapter = Chapter(title=title, start_time=start_time, end_time=end_time, color=BASE_COLOR)
# 插入到合适的位置(按开始时间排序) insert_pos = len(chapters) for i, ch in enumerate(chapters): if new_chapter.start_time < ch.start_time: insert_pos = i break
chapters.insert(insert_pos, new_chapter) console.print(f"[green]✓ 章节已添加到位置 {insert_pos + 1}[/green]\n") return True
def delete_chapter(chapters: list[Chapter], index: int) -> bool: """删除章节""" if index < 0 or index >= len(chapters): console.print("[red]✗ 无效的章节序号[/red]") return False
removed = chapters.pop(index) console.print(f"[green]✓ 已删除章节 {index + 1}: {removed.title}[/green]\n") return True
def interactive_edit_chapters(chapters: list[Chapter], duration: float) -> list[Chapter] | None: """交互式编辑章节
返回: 编辑后的章节列表,如果用户取消则返回 None """ # 创建副本,避免修改原始数据 chapters = [Chapter(ch.title, ch.start_time, ch.end_time, ch.color) for ch in chapters]
console.print("\n[bold cyan]📝 编辑模式[/bold cyan]") console.print("\n可用命令:") console.print(" [数字] - 编辑章节 (如: 1)") console.print(" [d数字] - 删除章节 (如: d2)") console.print(" [a] - 添加章节") console.print(" [l] - 显示章节列表") console.print(" [done] - 完成编辑并继续") console.print(" [cancel] - 取消编辑\n")
while True: cmd = input("> ").strip().lower()
if cmd == "done": # 验证章节 console.print("\n[cyan]正在验证章节...[/cyan]") errors = ChapterValidator.validate_chapters(chapters, duration)
if errors: console.print("[red]✗ 验证失败:[/red]") for error in errors: console.print(f"[red] - {error.message}[/red]") console.print("\n[yellow]请修正错误后再试,或输入 'cancel' 取消编辑[/yellow]\n") continue
console.print("[green]✓ 验证通过[/green]\n") return chapters
elif cmd == "cancel": console.print("[yellow]已取消编辑[/yellow]\n") return None
elif cmd == "l": display_chapters_table(chapters) console.print()
elif cmd == "a": if add_chapter(chapters, duration): display_chapters_table(chapters) console.print()
elif cmd.startswith("d") and len(cmd) > 1: try: index = int(cmd[1:]) - 1 if delete_chapter(chapters, index): display_chapters_table(chapters) console.print() except ValueError: console.print("[red]✗ 无效的命令格式,使用 'd数字' 删除章节 (如: d2)[/red]\n")
elif cmd.isdigit(): index = int(cmd) - 1 if edit_chapter(chapters, index, duration): display_chapters_table(chapters) console.print()
elif cmd: console.print("[red]✗ 无效的命令,输入 'l' 查看帮助[/red]\n")
def confirm_chapters(chapters: list[Chapter], skip_confirm: bool = False) -> list[Chapter] | None: """确认章节配置
参数: chapters: 章节列表 skip_confirm: 是否跳过确认(--yes 参数)
返回: 确认或编辑后的章节列表,如果用户退出则返回 None """ if skip_confirm: return chapters
console.print("\n[bold]请选择操作:[/bold]") console.print(" [y] 确认并生成视频") console.print(" [e] 编辑章节") console.print(" [q] 退出\n")
while True: choice = input("> ").strip().lower()
if choice == "y": console.print("[green]✓ 已确认,开始生成视频...[/green]\n") return chapters
elif choice == "e": # 获取视频时长(从最后一个章节) duration = chapters[-1].end_time if chapters else 0 edited_chapters = interactive_edit_chapters(chapters, duration)
if edited_chapters is None: # 用户取消编辑,回到确认界面 console.print("\n[bold]请选择操作:[/bold]") console.print(" [y] 确认并生成视频") console.print(" [e] 编辑章节") console.print(" [q] 退出\n") continue
return edited_chapters
elif choice == "q": console.print("[yellow]已退出[/yellow]") return None
else: console.print("[red]✗ 无效的选择,请输入 y/e/q[/red]\n")12345678910111213141516171819202122232425262728"""日志配置模块
使用 loguru 提供统一的日志记录功能。"""
import sys
from loguru import logger
# 移除默认的 handlerlogger.remove()
# 添加自定义 handler# 格式:时间 | 级别 | 文件:行号 | 消息logger.add( sys.stderr, format=( "<green>{time:YYYY-MM-DD HH:mm:ss}</green> | " "<level>{level: <8}</level> | " "<cyan>{name}</cyan>:<cyan>{line}</cyan> | " "<level>{message}</level>" ), level="INFO", colorize=True,)
# 导出 logger 供其他模块使用__all__ = ["logger"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""SRT 字幕文件解析器"""
import refrom dataclasses import dataclass
@dataclassclass SubtitleEntry: """字幕条目"""
index: int start_time: float # 秒 end_time: float # 秒 text: str
def parse_timestamp(timestamp: str) -> float: """将 HH:MM:SS,mmm 格式转换为秒数
Args: timestamp: 时间戳字符串,如 "00:01:23,456"
Returns: float: 秒数 """ # 匹配格式:HH:MM:SS,mmm match = re.match(r"(\d{2}):(\d{2}):(\d{2}),(\d{3})", timestamp) if not match: raise ValueError(f"无效的时间戳格式: {timestamp}")
hours, minutes, seconds, milliseconds = map(int, match.groups()) total_seconds = hours * 3600 + minutes * 60 + seconds + milliseconds / 1000 return total_seconds
def parse_srt(file_path: str) -> list[SubtitleEntry]: """解析 SRT 字幕文件
Args: file_path: SRT 文件路径
Returns: List[SubtitleEntry]: 字幕条目列表 """ with open(file_path, encoding="utf-8") as f: content = f.read()
entries = [] # 按空行分割字幕块 blocks = content.strip().split("\n\n")
for block in blocks: lines = block.strip().split("\n") if len(lines) < 3: continue
# 第一行是序号 try: index = int(lines[0]) except ValueError: continue
# 第二行是时间戳 timestamp_line = lines[1] match = re.match(r"(.+?)\s*-->\s*(.+)", timestamp_line) if not match: continue
start_str, end_str = match.groups() start_time = parse_timestamp(start_str.strip()) end_time = parse_timestamp(end_str.strip())
# 剩余行是文本内容 text = " ".join(lines[2:])
entries.append(SubtitleEntry(index=index, start_time=start_time, end_time=end_time, text=text))
return entries123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202# This file was autogenerated by uv via the following command:# uv export --no-hashes --no-dev -o requirements.txtaiofiles==24.1.0 # via gradioannotated-doc==0.0.4 # via fastapiannotated-types==0.7.0 # via pydanticanyio==4.11.0 # via # gradio # httpx # openai # starlette # via gradiobrotli==1.2.0 # via gradiocertifi==2025.11.12 # via # httpcore # httpxclick==8.3.0 # via # typer # typer-slim # uvicorncolorama==0.4.6 ; sys_platform == 'win32' # via # click # loguru # tqdmdecorator==5.2.1 # via moviepydistro==1.9.0 # via openaifastapi==0.121.2 # via gradioffmpy==1.0.0 # via gradiofilelock==3.20.0 # via huggingface-hubfsspec==2025.10.0 # via # gradio-client # huggingface-hubgradio==5.49.1 # via auto-chapter-bargradio-client==1.13.3 # via gradiogroovy==0.1.2 # via gradioh11==0.16.0 # via # httpcore # uvicornhf-xet==1.2.0 ; platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64' # via huggingface-hubhttpcore==1.0.9 # via httpxhttpx==0.28.1 # via # gradio # gradio-client # huggingface-hub # openai # safehttpxhuggingface-hub==1.1.4 # via # gradio # gradio-clientidna==3.11 # via # anyio # httpximageio==2.37.2 # via moviepyimageio-ffmpeg==0.6.0 # via moviepyjinja2==3.1.6 # via gradiojiter==0.12.0 # via openailoguru==0.7.3 # via auto-chapter-barmarkdown-it-py==4.0.0 # via richmarkupsafe==3.0.3 # via # gradio # jinja2mdurl==0.1.2 # via markdown-it-pymoviepy==2.2.1 # via auto-chapter-barnumpy==2.3.4 # via # gradio # imageio # moviepy # pandasopenai==2.8.0 # via auto-chapter-barorjson==3.11.4 # via gradiopackaging==25.0 # via # gradio # gradio-client # huggingface-hubpandas==2.3.3 # via gradiopillow==11.3.0 # via # auto-chapter-bar # gradio # imageio # moviepyproglog==0.1.12 # via moviepypydantic==2.11.10 # via # fastapi # gradio # openaipydantic-core==2.33.2 # via pydanticpydub==0.25.1 # via gradiopygments==2.19.2 # via richpython-dateutil==2.9.0.post0 # via pandaspython-dotenv==1.2.1 # via moviepypython-multipart==0.0.20 # via gradiopytz==2025.2 # via pandaspyyaml==6.0.3 # via # auto-chapter-bar # gradio # huggingface-hubrich==14.2.0 # via # auto-chapter-bar # typerruff==0.14.5 # via gradiosafehttpx==0.1.7 # via gradiosemantic-version==2.10.0 # via gradioshellingham==1.5.4 # via # huggingface-hub # typersix==1.17.0 # via python-dateutilsniffio==1.3.1 # via # anyio # openaistarlette==0.49.3 # via # fastapi # gradiotomlkit==0.13.3 # via gradiotqdm==4.67.1 # via # huggingface-hub # openai # proglogtyper==0.20.0 # via # auto-chapter-bar # gradiotyper-slim==0.20.0 # via huggingface-hubtyping-extensions==4.15.0 # via # fastapi # gradio # gradio-client # huggingface-hub # openai # pydantic # pydantic-core # typer # typer-slim # typing-inspectiontyping-inspection==0.4.2 # via pydantictzdata==2025.2 # via pandasuvicorn==0.38.0 # via gradiowebsockets==15.0.1 # via gradio-clientwin32-setctime==1.2.0 ; sys_platform == 'win32' # via loguru.gitignoreAdded+7
LICENSEAdded+201
README.mdAdded+50
app.pyAdded+407
chapterbar/__init__.pyAdded+3
chapterbar/chapter_extractor.pyAdded+198
chapterbar/chapter_loader.pyAdded+141
chapterbar/chapter_validator.pyAdded+234
chapterbar/cli.pyAdded+181
chapterbar/generator.pyAdded+469
chapterbar/interactive_editor.pyAdded+260
chapterbar/logger.pyAdded+28
chapterbar/parser.pyAdded+78
requirements.txtAdded+202