From 01706c9f5784a05ce13df1c04a49f3df36a59962 Mon Sep 17 00:00:00 2001 From: sc57 Date: Fri, 2 Oct 2026 00:56:54 +0800 Subject: [PATCH 01/14] =?UTF-8?q?docs(refactor):=20=E5=85=A8=E9=87=8F?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=AE=A1=E8=AE=A1=E6=8A=A5=E5=91=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 基于 7f7f047(与 desktop-vnext-dev 一致)的只读审计,结论:整体不是屎山, 技术债集中在桌面主窗口上帝类、流水线参数透传、边界规则链、Web 上帝模块、 绕过护栏的改名复制,以及当前未通过的架构快照、私有 patch 上限与发布扫描。 报告给出证据、严重度、建议与分阶段重构顺序,未修改业务代码。 Co-Authored-By: Claude Opus 5.5 --- docs/refactor/AUDIT.md | 270 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 270 insertions(+) create mode 100644 docs/refactor/AUDIT.md diff --git a/docs/refactor/AUDIT.md b/docs/refactor/AUDIT.md new file mode 100644 index 0000000..c7e092a --- /dev/null +++ b/docs/refactor/AUDIT.md @@ -0,0 +1,270 @@ +# 代码审计报告(desktop-vnext-refactor) + +审计对象为 `desktop-vnext-refactor` 分支 `7f7f047`,与当时的 `desktop-vnext-dev` 完全一致。审计只读代码,没有修改业务代码。文中的行号、行数和计数都是这个 commit 的快照,代码变化后需要重新核对。 + +## 1. 结论 + +**整体不是“屎山”。** 后端已经按 [架构重构说明](../架构重构.md) 做过一轮有护栏的重构,基本功扎实: + +- **依赖关系干净**:import 图无环,每项职责有唯一的实现模块,兼容层只做别名转发。 +- **错误处理规矩**:67 处宽泛异常捕获里,61 处会记录上报或转换后重新抛出,真正悄悄吞掉的只有 2 处。 +- **重复代码少**:跨位置重复约 730 行,占源码 1% 多一点。 +- **死代码少**:确认无人调用的函数只有 5 个,约 70 行。 +- **低级错误少**:ruff 的潜在缺陷类规则几乎没有命中,抽查的几处也都不会出错。 + +**技术债集中在少数几处:** + +1. **护栏当前是红的**:架构快照过期,测试里替换私有符号的次数超过上限,公开发布扫描也不通过(§3)。 +2. **桌面端主窗口是上帝类**:`DesktopWindow` 一个类 2268 行、119 个方法,继承自演示用的预览窗口,旧 Tk 壳也还在(H1、M5、M6)。 +3. **流水线参数层层透传**:阶段函数有 28、29 个参数;重试状态恢复函数圈复杂度 87(H2、H3)。 +4. **边界扩展是一长串规则**:核心算法函数圈复杂度 79,并大量跨模块调用别人的私有函数(H4、M1)。 +5. **Web 主程序是上帝模块**:`web/app.py` 3019 行;7 个后台任务函数开头和结尾的写法重复;还有 9 处经兼容层导入(M2、M3)。 +6. **改了名的复制粘贴绕过了护栏**:字幕断行算法、校对状态序列化、两个 Flask 程序的安全后处理(M4)。 +7. **前端有千行内联脚本**:主工作台模板里内联了 1061 行脚本,不在 CI 检查范围内(M7)。 + +## 2. 范围与方法 + +**范围** + +- **源码**:`src/`、`scripts/` 和根目录兼容入口,共 209 个文件、约 60,000 行(含 JS、HTML、CSS)。架构快照统计的生产 Python 是 204 个模块、51,044 行。 +- **测试**:119 个测试文件只看结构和覆盖缺口,不逐行审。 + +**方法** + +1. **自动扫描全部文件**,没有安装新工具: + - ruff 扩展规则:复杂度、参数、分支、宽泛异常、可简化写法、潜在缺陷。 + - 自写的 AST 度量:逐函数统计行数、圈复杂度、嵌套深度、参数数和内嵌函数。 + - 自写的 6 行窗口重复代码检测。 + - 死代码候选检测。 + - 宽泛异常的处理方式分类。 + - 跨模块使用私有符号的统计。 + - git 改动热点统计。 + - 测试引用覆盖统计。 + - 仓库自带的 `scripts/architecture_snapshot.py --check` 和架构测试。 +2. **人工精读热点**: + - `desktop/qt_app/window.py` + - `qt_preview/window.py` + - `pipeline.py` 和 `pipeline_retry.py` + - `analysis/boundaries.py` + - `web/app.py` + - `subtitle_workflow.py` 和 `transcription/segments.py` + - `desktop/subtitles.py` + - `autoslice_cover/app.py` + - `topic_v2.html` +3. **判断标准以项目文档为准**:[架构重构说明](../架构重构.md) 的依赖方向和唯一 owner 规则、[Desktop 架构](../desktop-vnext/ARCHITECTURE.md) 的迁移边界。不按个人偏好判断,也不把“函数长”单独当成问题。 + +**局限** + +- 没有逐行精读的模块,结论只来自自动扫描。 +- 我自写的圈复杂度会把内嵌函数也算进外层函数,所以 `create_app` 等函数的数值偏高,正文已经单独说明。 +- 没有运行真实媒体、模型或 LLM。 + +## 3. 护栏状态(最先处理) + +| 项 | 现状 | 影响 | +|---|---|---| +| 架构快照 | `architecture_snapshot.py --check` 报告快照过期 | CI 的“Check architecture snapshot”步骤会失败 | +| 未登记模块 | `desktop.commands`、`desktop.selection`、`desktop.snap`、`desktop.subtitle_preview`、`desktop.waveform` 共 5 个新模块不在基线里 | 同上 | +| 私有 patch 计数 | 测试对私有符号的 patch 从 17 增加到 20,超过基线上限 | 架构测试的私有 patch 上限检查会失败 | +| 规模变化 | 生产模块 199→204,生产行数 49,030→51,044,import 边 517→524 | 需要审阅后重新生成快照 | +| 公开发布扫描 | `scan_public_release.py` 报告非测试用途的 Windows 绝对路径:`src/autoslice/desktop/projects.py` 和 `docs/desktop-vnext/` 下 3 份文档 | 发布门禁不通过(见 M9) | + +建议:先审阅新增的 3 处私有 patch。确有理由就保留并重新生成基线,否则改成通过公开接口测试。之后按项目规定,用脚本重新生成 `architecture_baseline.json`,不能手工修改。另外,桌面端测试在装了 PySide6 的本地环境里有一处稳定崩溃和一处收尾异常,修复见 PR #1。 + +## 4. 问题清单 + +严重程度:**高** 表示结构性问题,持续拖累后续开发,或者关系核心业务正确性;**中** 表示局部的组织或一致性问题;**低** 表示清理项。工作量:S 不到半天,M 1~3 天,L 3 天以上,按分步提交估算。 + +### 高 + +#### H1 桌面主窗口 `DesktopWindow` 是上帝类 + +- **位置**:`src/autoslice/desktop/qt_app/window.py:366`,类本身 2268 行,含 119 个方法。 +- **证据**: + - 一个类同时承担 9 类职责:界面搭建(约 500 行)、AI 校对流程、项目扫描与载入、字幕编辑与行内编辑器、时间轴交互、试听与循环、播放器状态、草稿/保存/压制、撤销重做和会话持久化。 + - AI 的撤销重做栈这类业务状态,直接放在窗口对象上。 + - `__init__` 有 127 行。 + - 父类 `PreviewWindow` 在构造时就回调子类重写的界面搭建方法,所以子类必须在 `super().__init__()` 之前先设好 33 个属性;全文件还有 12 处 `hasattr(self, ...)` 防御初始化顺序。 + - 父类 21 个方法中有 12 个被重写,继承基本只用来复用页面骨架。 +- **建议**: + - 窗口改为“组装根”,只负责创建控件和连接信号。 + - 按职责逐个抽出控制器:AI 复核、项目载入、字幕编辑(含行内编辑器)、时间轴(含试听与循环)、播放、压制、会话持久化。每个控制器单独一个提交,测试先行。 + - 不再继承预览窗口,改用组合(见 M6)。 +- **风险**:中高,涉及界面行为。目前桌面端有 70 条测试可以兜底。 +- **工作量**:L。 +- **注意**:`desktop-ui-opus55v2` 分支正在大量修改 `window.py`、`timeline.py`、`theme.py`,两边同时改会产生大量合并冲突,需要先约定先后顺序(§6)。 + +#### H2 流水线阶段函数参数层层透传 + +- **位置**: + - `pipeline_reporting.py:39 prepare_pipeline_report`,29 个参数。 + - `pipeline_artifacts.py:6 persist_pipeline_artifacts`,28 个参数。 + - `pipeline_retry_reporting.py:10 prepare_retry_report`,28 个参数。 + - 还有 `prepare_retry_decisions`(20 个)、`review_pipeline_candidates`(18 个)、`review_retry_candidates_and_titles`(17 个)。 +- **证据**: + - `pipeline.py` 把主流程的局部变量和服务函数一项项摊开传给阶段函数;主流程和重试流程各传一遍,几乎相同(`pipeline.py:737-803` 和 `pipeline.py:1027-1093` 有 11~17 行重复)。 + - 产物路径(`artifact_layout`、各 checkpoint 路径、manifest 路径)、阈值策略(`CLIP_*`、`TOPIC_*` 常量)、服务函数(写产物、写 manifest、更新队列)总是成组出现。 +- **建议**: + - 引入三个参数对象:`PipelineArtifactPaths`(不可变 dataclass)、`ClipPolicy`(阈值)、`PipelineServices`(注入的服务函数)。 + - 这不是项目文档里拒绝过的“统一 `PipelineStage` 类框架”,只是把成组的参数打包,阶段函数的契约不变。 +- **风险**:中。签名改动面大,要配合架构测试里的对象身份检查。 +- **工作量**:M。 + +#### H3 重试状态恢复函数过于复杂 + +- **位置**:`src/autoslice/pipeline_retry.py:9 prepare_retry_pipeline_state`。 +- **证据**: + - 308 行,圈复杂度 87(其中内嵌的 `merge_completed_review_with_baseline` 占 36),嵌套 7 层,16 个参数,其中 11 个是注入的函数。 + - 一个函数里混了四件事:产物定位、旧布局迁移、人工时间轴重建,以及复核检查点的复用和过期判断。 +- **建议**: + - 把“检查点与最新分析的合并、过期判定”抽成 `analysis/checkpoints` 里的纯函数,用数据驱动的单元测试覆盖各种续跑场景。 + - 剩下的部分只做编排。 +- **风险**:中高,关系续跑语义。 +- **工作量**:M。 + +#### H4 边界扩展规则链 + +- **位置**:`src/autoslice/analysis/boundaries.py:139 _expand_clip_mark_with_context`。 +- **证据**: + - 267 行,圈复杂度 79。 + - 依次叠加十几条规则:相关上下文、语义焦点、SC/礼物触发、引入段、画面引入、裁剪、时长上下限、字幕对齐、视频时长截断,最后写元数据。 + - 规则之间靠十几个局部变量互相影响,单条规则没法单独测试,也看不出边界为什么被这样调整。 + - 全文件有 79 处跨模块调用私有函数(M1)。 +- **建议**: + - 先补“刻画测试”:用典型和边缘的 mark/字幕组合,固定当前输出。 + - 再拆成按顺序执行的规则步骤,作用于一个小的边界草稿对象(起止时间、硬结束点、调整原因)。 + - 每一步记录调整原因,方便排查切片边界问题。 +- **风险**:高,直接关系 [架构重构说明 §6](../架构重构.md) 的切片业务契约。 +- **工作量**:M~L。 +- **建议放在最后做。** + +### 中 + +#### M1 跨模块调用私有函数 + +- **证据**: + - 生产代码共有 472 处跨模块使用以下划线开头的私有符号,涉及 151 个符号、27 个文件。 + - 去掉两个按设计就要重新导出私有符号的兼容层(`topic_engine` 147 处、`analysis.candidates` 107 处),仍有约 200 处,集中在 `analysis/boundaries.py`(79)、`analysis/review/context_ranges.py`(17)、`pipeline.py`(15)、`analysis/topic/analysis.py`(13)。 + - 被跨模块访问最多的是 `title_analysis`、`danmaku_analysis`、`context_evidence`、`transition_analysis`、`trigger_analysis` 和 `finalization`。 +- **问题**:这些函数其实是包内公共接口,名字却标成私有。改函数的人无法判断它有没有外部调用方。 +- **建议**:被跨模块调用的函数改成公开名称,兼容层保留旧名作为别名,保证对象身份不变。纯机械改动,可以按模块分批提交。 +- **风险**:低中。工作量:M。 + +#### M2 `web/app.py` 是上帝模块 + +- **位置**:`src/autoslice/web/app.py`,3019 行,38 个路由,100 个顶层函数。 +- **证据**: + - 7 个后台任务函数(`run_subtitle_review_task` 等,从 1405 行起)的开头完全一样:检查是否已取消、状态置为运行中、定义进度回调。异常收尾也是同一套。 + - `update_task`(615 行)圈复杂度 44。 + - 模块级的锁和事件队列都有正确保护,没有发现并发问题。 +- **建议**: + - 后台任务的固定套路抽成一个统一包装,放进 `web/tasks.py`。 + - 路由按领域拆成 Blueprint:流水线和时间轴、字幕、任务和事件、结果和媒体。 +- **风险**:中。工作量:M。 + +#### M3 生产代码经兼容层导入 + +- **证据**: + - 生产代码有 9 处经 `autoslice.topic_engine` 导入:`web/app.py` 1512、1567、1677、1726、1769、2786、2862 行,`launcher.py:553`,`core.py:27`。 + - 这违反了依赖方向的第 2 条硬规则:生产代码应直接依赖真实实现。 + - 有 21 个测试文件引用 `topic_engine`,部分可能是在这里替换函数做测试,属于测试接缝。 +- **建议**:改为直接导入真实实现,同步调整测试的替换位置。 +- **风险**:低中。工作量:S~M。 + +#### M4 改了名的复制粘贴绕过了护栏 + +- **证据**: + - `subtitle_workflow.py:2090 _split_subtitle_text_for_ass` 和 `transcription/segments.py:206 split_subtitle_text_for_display` 逐行相同,各自计算字宽的函数(`_subtitle_display_text_size` 和 `subtitle_text_size`)也相同。这违反唯一 owner 规则。 + - 校对状态的 JSON 结构在 `subtitle_workflow.py:788-813` 和 `subtitle_workflow.py:889-914` 各拼了一遍。 + - `web/app.py:405` 和 `autoslice_cover/app.py:686` 各写了一份相同的“签发本机会话 Cookie + 局域网模式脱敏”响应后处理。这是安全逻辑,两份一旦不同步,两个程序的脱敏行为就会不一致。 +- **建议**: + - 字幕断行统一由 `transcription.segments` 提供。 + - 状态序列化收成一个函数。 + - 响应后处理收进 `SecurityPolicy`,例如 `finalize_response`。 + - 架构护栏目前只检查同名顶层定义,可以考虑补一项“函数体 AST 相同”的检测。 +- **风险**:低。工作量:S。 + +#### M5 旧 Tk 桌面壳仍是默认入口 + +- **证据**: + - Qt 版已经完成 Desktop-04.6 及之后的阶段,但 `src/autoslice/desktop/app.py`(Tk,387 行)还在。 + - `桌面端.py` 和 `python -m autoslice.desktop` 默认启动的仍是 Tk 版,Qt 版要走 `Qt桌面端.py` 或 `python -m autoslice.desktop.qt_app`。 + - Tk 测试和 Qt 测试在同一个进程里跑时,偶尔触发 `Tcl_AsyncDelete`,进程中止。 +- **建议**:由维护者决定退役 Tk 壳,或者至少把默认入口切到 Qt。退役时一并清理 Tk 测试。 +- **风险**:低,属于产品决策。工作量:S。 + +#### M6 正式代码依赖“预览”包 + +- **证据**: + - 正式窗口用的主题、图标和窗口骨架都放在 `desktop/qt_preview` 里。 + - `qt_preview/window.py` 里还带着写死的示例项目数据,又被当作正式窗口的父类。 + - UI 分支还在往这个包里继续加 `motion`、`popups`、`fonts`、`glyphs` 等正式模块。 +- **建议**:把公共主题、图标、动效和窗口骨架移到 `desktop/qt_common`(名称待定),`qt_preview` 只保留一个很薄的演示入口。和 H1 一起做。 +- **风险**:低中,主要是导入路径的改动。工作量:S~M。 + +#### M7 主工作台模板内联千行脚本 + +- **位置**:`src/autoslice/resources/templates/topic_v2.html`,1286 行,其中内联脚本 1061 行。 +- **证据**: + - 129 个顶层变量、80 个函数,15 个写在标签上的事件属性(`onclick` 等)。 + - CI 只对独立 JS 文件跑 `node --check`,这段脚本不在任何语法检查范围内。 + - 拼接 `innerHTML` 时统一用了 `esc()` 转义,抽查没有发现注入问题。 +- **建议**:参照 `subtitle_workflow.js`,抽到 `static/topic_v2.js`,事件改成 `addEventListener` 绑定,并加入 CI 的 `node --check`。 +- **风险**:低。工作量:S~M。 + +#### M9 桌面端写死本机投稿目录,并且重复解析配置 + +- **位置**:`src/autoslice/desktop/projects.py:13`。 +- **证据**: + - `DEFAULT_SUBMISSION_ROOT` 写死成维护者本机的绝对路径(F 盘下的投稿目录)。 + - `configured_submission_root()` 自己再解析一遍 `AUTOSLICE_SUBMISSION_DIR`,没有复用 `runtime_config.SUBMISSION_DIR`。后者已经是这个配置的唯一 owner,默认值是仓库内的 `submissions`。 + - 结果是同一个配置项有两个默认值,Web 端和桌面端行为不一致。 + - 其他人的电脑上没有这个目录,桌面端首次打开就显示“目录不存在”。 + - 公开发布扫描因此失败;`docs/desktop-vnext/CURRENT.md`、`MIGRATION_MAP.md`、`PRODUCT.md` 也写了同一路径。 +- **建议**:桌面端改为使用 `runtime_config.SUBMISSION_DIR`。本机目录通过 `autoslice.local.json` 或环境变量配置;文档里的本机路径改成配置示例。 +- **风险**:低。工作量:S。 + +#### M8 AutoCover `create_app` 塞了所有路由 + +- **位置**:`src/autoslice_cover/app.py:624`,481 行,25 个路由和 7 个钩子写成闭包。 +- **说明**:这是 Flask 常见的应用工厂写法,单个路由都不长(最长的 `preview` 68 行)。圈复杂度 69 主要来自内嵌路由。 +- **建议**:按资源、贴图、工作区和任务、渲染和导出拆成 Blueprint。旧 AutoCover UI 已冻结、不再迁移,所以优先级靠后。 +- **风险**:低。工作量:S~M。 + +### 低 + +| ID | 位置 | 问题 | 建议 | +|---|---|---|---| +| L1 | `subtitle_workflow.py:444 _split_subtitle_cues`(30 行)、`autoslice_cover/app.py:541 _render_task`(20 行)、`desktop/qt_app/timeline.py:190 follow_playback`、`desktop/selection.py:41 retain`、`runtime_config.py:133 template_defaults` | 全仓无任何调用 | 确认无用后删除 | +| L2 | `analysis/topic/normalization.py:139 is_meta_body_line`(圈复杂度 60);`normalization.py:101/102/209` 集合字面量里有重复元素 | 一长串启发式判断写死在代码里 | 改成规则表,去掉重复项 | +| L3 | `analysis/topic/analysis.py:246`(`except Exception: continue`)、`analysis/manual/timebase.py:232`(返回默认值) | 宽泛捕获后没有任何记录 | 收窄异常类型,加 debug 日志 | +| L4 | `llm/transport.py:852-859` | 闭包引用循环变量 `active_prompt`、`active_tokens`。目前是同步调用,不会出错 | 用默认参数显式绑定,防止以后改成异步调用时出错 | +| L5 | `desktop/waveform.py`(114 行) | 测试里没有任何引用 | 补缓存键和失败路径的单元测试 | +| L6 | ruff 扩展规则共 458 条,绝大多数是复杂度和参数类 | 不宜整体清零 | 遵守项目规定,不做无关格式化,随相关重构逐步消除 | + +## 5. 不建议做的事 + +- **不按行数拆文件**,不建只搬运参数的空壳模块(项目文档的硬规则)。 +- **不引入流水线阶段框架**:H2 只做参数对象。 +- **不批量格式化**,不为了清零 ruff 告警做无关改动。 +- **不改变兼容层的对象身份**:兼容层继续是同一对象的别名。 +- **不重构已冻结的旧字幕 UI 和旧 AutoCover UI**,只为桌面端抽取需要的后端能力。 + +## 6. 建议的重构顺序 + +每一步都遵守项目流程:一次只动一个 owner、一个逻辑提交、重新生成架构快照、跑 hermetic 测试、等 Windows/Linux CI 双绿。 + +| 阶段 | 内容 | 前置条件 | +|---|---|---| +| 0 让护栏变绿 | §3:审阅新增的私有 patch、重新生成快照;M9 去掉写死的本机路径,让发布扫描通过;合并 PR #1 的测试修复 | 无 | +| 1 低风险清理 | M4 去重、L1 删死代码、L3/L4、M3 改为直接导入真实实现、M7 抽出内联脚本、M5 由维护者决策 | 阶段 0 | +| 2 桌面端结构 | H1 逐个抽控制器,M6 迁出预览包 | 先和 `desktop-ui-opus55v2` 约定顺序:建议 UI 分支先合入 dev,再做 H1,或者 H1 期间冻结 UI 分支对 `window.py` 的修改 | +| 3 后端组织 | H2 参数对象、M2 Web 任务包装和 Blueprint、M1 私有接口改名、M8 | 阶段 1 | +| 4 核心算法 | H3 检查点合并抽成纯函数、H4 边界规则链 | 先补刻画测试;这一阶段的改动需要单独授权有限真实录播验收 | + +## 7. 附:度量摘要 + +- **函数**:共 1,764 个。超过 100 行的 52 个,超过 200 行的 6 个;圈复杂度超过 20 的 85 个,超过 40 的 10 个;嵌套 5 层及以上的 19 个;参数 8 个及以上的 47 个。 +- **最大的类**:`DesktopWindow` 2268 行,`CoverWorkspace` 647 行,`SubtitleTimeline` 604 行,`SecurityPolicy` 538 行,`TaskStore` 538 行。 +- **改动最频繁的仍然很大的文件**:`pipeline.py`(50 次提交),`web/app.py`(15 次),`analysis/boundaries.py`(13 次),`reporting.py`(13 次)。 +- **测试覆盖**:只有 5 个生产模块在测试中完全没有被引用,其中 `media_preview` 实际上经路由和类名被间接测试,真正的缺口只有 `desktop/waveform.py`。 From 0e98942437753016ced5fbcea72dc7c1bd6312bc Mon Sep 17 00:00:00 2001 From: sc57 Date: Wed, 30 Sep 2026 20:22:33 +0800 Subject: [PATCH 02/14] =?UTF-8?q?test(desktop):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E4=B8=A4=E4=B8=AA=E6=A1=8C=E9=9D=A2=E7=AB=AF=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=9A=84=E5=B4=A9=E6=BA=83=E4=B8=8E=E6=94=B6=E5=B0=BE=E5=BC=82?= =?UTF-8?q?=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - test_discard_unsaved_edit_reopens_from_formally_saved_subtitle: 构造第二个窗口时用 patch.object 替换 DesktopWindow 类属性 _start_waveform, 在已有窗口存活时会让 PySide 在 _appbar 设置图标处 access violation,用例稳定崩溃; 且该 patch 只在构造期间生效,拦不到异步载入后才发生的调用。 改为构造后在实例上替换,并由 addCleanup 覆盖整个用例。 - test_explicit_seek_ignores_stale_player_position_and_playing_highlight: FakePlayer 缺少 close(),收尾关窗时 closeEvent 调用 player.close() 抛出 AttributeError, 后续 Qt 事件再进入 Python 重写时处于异常状态;补一个空的 close()。 Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 00d177cd218e2e670cb8b07728c9cef12c96f49f) --- tests/unit/test_desktop_render.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_desktop_render.py b/tests/unit/test_desktop_render.py index 17f6a70..5fbfd1f 100644 --- a/tests/unit/test_desktop_render.py +++ b/tests/unit/test_desktop_render.py @@ -164,9 +164,13 @@ def test_discard_unsaved_edit_reopens_from_formally_saved_subtitle(self): from autoslice.desktop.qt_app.window import DesktopWindow with patch("autoslice.desktop.qt_app.window.MpvAdapter", - side_effect=OSError("测试无播放器")), \ - patch.object(DesktopWindow, "_start_waveform"): + side_effect=OSError("测试无播放器")): reopened = DesktopWindow(SubmissionProjectService(self.root), self.storage) + # _start_waveform 在异步载入完成后才调用,须在实例上替换并覆盖整个用例; + # 构造期间 patch 类属性既拦不到这次调用,还会让 PySide 在构造第二个窗口时崩溃。 + waveform = patch.object(reopened, "_start_waveform") + waveform.start() + self.addCleanup(waveform.stop) reopened.show() def close_reopened(): @@ -322,6 +326,10 @@ def __init__(self): def seek(self, position, pause=True): self.seeks.append((position, pause)) + def close(self): + # 用例收尾关窗时 closeEvent 会调用 player.close() + pass + self.window.player = FakePlayer() self.window._media_ready = True self.window._player_duration = 20.0 From f2acb63d3e2b5ed4f336d4cbc5885f5c2f6c22d1 Mon Sep 17 00:00:00 2001 From: sc57 Date: Sun, 4 Oct 2026 00:31:25 +0800 Subject: [PATCH 03/14] test(desktop): replace private patches with public seams Bring the test private-patch count back to the 17 allowed by the architecture contract: - SubtitlePreviewService accepts an injectable probe_video, so the canvas test no longer patches subtitle_preview._probe_video_info. - The reopened-window test stubs waveform_cache.load_or_generate instead of the private DesktopWindow._start_waveform. - The bottom-click seek test asserts player and timeline results with a fake player instead of patching DesktopWindow._seek_to. Co-Authored-By: Claude Opus 5.5 --- src/autoslice/desktop/subtitle_preview.py | 6 +++-- tests/unit/test_desktop_interaction.py | 12 ++++------ tests/unit/test_desktop_render.py | 28 ++++++++++++++++++----- 3 files changed, 31 insertions(+), 15 deletions(-) diff --git a/src/autoslice/desktop/subtitle_preview.py b/src/autoslice/desktop/subtitle_preview.py index 956a315..f178e4a 100644 --- a/src/autoslice/desktop/subtitle_preview.py +++ b/src/autoslice/desktop/subtitle_preview.py @@ -13,8 +13,10 @@ class SubtitlePreviewService: - def __init__(self, storage): + def __init__(self, storage, probe_video=None): self.storage = storage + # 可注入视频探测,测试无需 patch 私有函数 + self._probe_video = probe_video or _probe_video_info self._canvas_cache = {} def _canvas_size(self, video_path: str | Path) -> tuple[int, int]: @@ -24,7 +26,7 @@ def _canvas_size(self, video_path: str | Path) -> tuple[int, int]: cached = self._canvas_cache.get(key) if cached is not None: return cached - info = _probe_video_info(path) + info = self._probe_video(path) size = (int(info["width"]), int(info["height"])) self._canvas_cache = {key: size} return size diff --git a/tests/unit/test_desktop_interaction.py b/tests/unit/test_desktop_interaction.py index 174ed64..6690a69 100644 --- a/tests/unit/test_desktop_interaction.py +++ b/tests/unit/test_desktop_interaction.py @@ -2,7 +2,6 @@ import tempfile import unittest -from unittest.mock import patch from types import SimpleNamespace from pathlib import Path @@ -64,14 +63,13 @@ def test_preview_uses_detected_video_canvas(self): root = Path(directory) source = root / "video.mp4" source.touch() - service = SubtitlePreviewService(DesktopStorage(root / "app-data")) + service = SubtitlePreviewService( + DesktopStorage(root / "app-data"), + probe_video=lambda _path: {"width": 1280, "height": 720}, + ) entries = [SimpleNamespace(index=1, start="00:00:00,000", end="00:00:01,000", text="测试")] - with patch( - "autoslice.desktop.subtitle_preview._probe_video_info", - return_value={"width": 1280, "height": 720}, - ): - preview = service.render(source, entries) + preview = service.render(source, entries) document = preview.read_text(encoding="utf-8") self.assertIn("PlayResX: 1280", document) self.assertIn("PlayResY: 720", document) diff --git a/tests/unit/test_desktop_render.py b/tests/unit/test_desktop_render.py index 5fbfd1f..516c5d7 100644 --- a/tests/unit/test_desktop_render.py +++ b/tests/unit/test_desktop_render.py @@ -166,9 +166,10 @@ def test_discard_unsaved_edit_reopens_from_formally_saved_subtitle(self): with patch("autoslice.desktop.qt_app.window.MpvAdapter", side_effect=OSError("测试无播放器")): reopened = DesktopWindow(SubmissionProjectService(self.root), self.storage) - # _start_waveform 在异步载入完成后才调用,须在实例上替换并覆盖整个用例; - # 构造期间 patch 类属性既拦不到这次调用,还会让 PySide 在构造第二个窗口时崩溃。 - waveform = patch.object(reopened, "_start_waveform") + # 波形在异步载入完成后才生成,须在实例上替换并覆盖整个用例;构造期间 patch + # DesktopWindow 类属性既拦不到这次调用,还会让 PySide 在构造第二个窗口时崩溃。 + waveform = patch.object(reopened.waveform_cache, "load_or_generate", + side_effect=RuntimeError("测试不生成波形")) waveform.start() self.addCleanup(waveform.stop) reopened.show() @@ -351,12 +352,27 @@ def close(self): self.assertIsNone(self.window._seek_guard_target) def test_bottom_subtitle_click_keeps_seek_behavior(self): + class FakePlayer: + def __init__(self): + self.seeks = [] + + def seek(self, position, pause=True): + self.seeks.append((position, pause)) + + def close(self): + pass + + player = FakePlayer() + self.window.player = player + self.window._media_ready = True + self.window._player_duration = 20.0 index = self.window.model.index(0, 0) self.window._player_position = 9.0 self.window._player_paused = True - with patch.object(self.window, "_seek_to") as seek_to: - self.window._cue_clicked(index) - seek_to.assert_called_once_with(0.0) + self.window._cue_clicked(index) + # 从播放器与时间轴的结果验证跳转,不替换私有 _seek_to + self.assertEqual(player.seeks, [(0.0, True)]) + self.assertAlmostEqual(self.window.timeline.playhead, 0.0, delta=0.001) self.assertEqual(self.window.selection.active, 1) def test_timeline_selection_preserves_manual_view(self): From 172d8187d5ec94aac8a71e862e3f1a8b60a4985e Mon Sep 17 00:00:00 2001 From: sc57 Date: Sun, 4 Oct 2026 00:32:06 +0800 Subject: [PATCH 04/14] test(architecture): compare function count with generated baseline Two owner tests pinned the repository-wide top-level function count to a hand-written 1059, which already disagreed with the generated baseline (1060) and broke whenever unrelated modules gained a function. Compare with architecture_baseline.json instead: growth still has to go through a reviewed snapshot regeneration, which the CI step `architecture_snapshot.py --check` enforces, without hard-coding a volatile number. Co-Authored-By: Claude Opus 5.5 --- tests/architecture/test_architecture_contracts.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/architecture/test_architecture_contracts.py b/tests/architecture/test_architecture_contracts.py index f909894..e686fe4 100644 --- a/tests/architecture/test_architecture_contracts.py +++ b/tests/architecture/test_architecture_contracts.py @@ -2669,7 +2669,12 @@ def test_manual_domain_has_one_owner_and_direct_consumers(self): import_edges, ) - self.assertEqual(current["summary"]["top_level_function_count"], 1059) + # 全仓函数总数以脚本生成的基线为准:增长须重新生成基线并审阅,不写死常量 + baseline = json.loads(BASELINE_PATH.read_text(encoding="utf-8")) + self.assertEqual( + current["summary"]["top_level_function_count"], + baseline["summary"]["top_level_function_count"], + ) self.assertEqual(current["dependency_cycles"], []) self.assertEqual(current["duplicate_top_level_definitions"], []) self.assertEqual( @@ -5419,9 +5424,11 @@ def test_report_cleanup_has_one_owner_and_direct_consumers(self): import_edges, ) + # 全仓函数总数以脚本生成的基线为准:增长须重新生成基线并审阅,不写死常量 + baseline = json.loads(BASELINE_PATH.read_text(encoding="utf-8")) self.assertEqual( current["summary"]["top_level_function_count"], - 1059, + baseline["summary"]["top_level_function_count"], ) self.assertEqual(current["dependency_cycles"], []) self.assertEqual(current["duplicate_top_level_definitions"], []) From 015fcf7dcb4e659a2ba075e434ddb7146b721e88 Mon Sep 17 00:00:00 2001 From: sc57 Date: Sun, 4 Oct 2026 00:35:04 +0800 Subject: [PATCH 05/14] fix(desktop): resolve submission root through runtime_config MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit projects.py hard-coded the maintainer's local submission folder as the fallback and re-parsed AUTOSLICE_SUBMISSION_DIR on its own. That left two defaults for one setting (the web workbench falls back to the repository `submissions` folder), showed "目录不存在" on any other machine and made scripts/scan_public_release.py fail. configured_submission_root() now delegates to runtime_config.configured_path(), the existing owner of this setting, so the precedence stays environment > autoslice.local.json > repository default, still resolved at call time. Machines that configure the folder in autoslice.local.json keep the same behaviour. Desktop docs describe the configured folder instead of a literal local path. Co-Authored-By: Claude Opus 5.5 --- docs/desktop-vnext/ADR-001-desktop-gui-and-player.md | 2 +- docs/desktop-vnext/ARCHITECTURE.md | 2 +- docs/desktop-vnext/BACKLOG.md | 2 +- docs/desktop-vnext/CURRENT.md | 10 +++++----- docs/desktop-vnext/MIGRATION_MAP.md | 2 +- docs/desktop-vnext/PRODUCT.md | 2 +- src/autoslice/desktop/projects.py | 11 ++--------- tests/unit/test_desktop_projects.py | 10 +++++++--- 8 files changed, 19 insertions(+), 22 deletions(-) diff --git a/docs/desktop-vnext/ADR-001-desktop-gui-and-player.md b/docs/desktop-vnext/ADR-001-desktop-gui-and-player.md index 6367020..98634f1 100644 --- a/docs/desktop-vnext/ADR-001-desktop-gui-and-player.md +++ b/docs/desktop-vnext/ADR-001-desktop-gui-and-player.md @@ -28,7 +28,7 @@ Desktop-03/04 的 `桌面端.py` → `autoslice.desktop.app.main()` 使用 Tkint ## 技术验证 - **Qt 壳**:隔离 PySide6 6.11.2 实例显示深色三页布局和字幕三区骨架;Windows 截图目视通过。Qt 官方说明 Qt Widgets/Graphics View 和自动 DPI 抽象:[Qt Widgets](https://doc.qt.io/qtforpython-6/PySide6/QtWidgets/)、[High DPI](https://doc.qt.io/qtforpython-6/overviews/qtdoc-highdpi.html)。本机实验设备像素比为 1.0,不能当作高 DPI 通过。 -- **mpv**:本机原无 `mpv`/libmpv。下载 [mpv Windows 发布页](https://github.com/shinchiro/mpv-winbuild-cmake/releases/tag/20260926) 的 x86-64 开发包并核对 SHA-256 后,在隔离 Qt `QWidget` 的原生 HWND 上用 libmpv API 加载 `F:\Videos\投稿` 下含 Emoji 的 H.264/AAC MP4。初始化/载入/精确定位返回 0,暂停 `time-pos=30.0` 秒、`hwdec-current=d3d11va`。mpv 官方手册明确 Windows `wid` 接收 HWND、`hwdec=auto` 不可用时回退软件解码、`hr-seek` 可用于精确定位:[mpv 手册](https://mpv.io/manual/stable/)。这只是 124 秒样本,未做数小时/多编码矩阵。 +- **mpv**:本机原无 `mpv`/libmpv。下载 [mpv Windows 发布页](https://github.com/shinchiro/mpv-winbuild-cmake/releases/tag/20260926) 的 x86-64 开发包并核对 SHA-256 后,在隔离 Qt `QWidget` 的原生 HWND 上用 libmpv API 加载本机投稿目录下含 Emoji 的 H.264/AAC MP4。初始化/载入/精确定位返回 0,暂停 `time-pos=30.0` 秒、`hwdec-current=d3d11va`。mpv 官方手册明确 Windows `wid` 接收 HWND、`hwdec=auto` 不可用时回退软件解码、`hr-seek` 可用于精确定位:[mpv 手册](https://mpv.io/manual/stable/)。这只是 124 秒样本,未做数小时/多编码矩阵。 - **QtMultimedia**:同一文件 `QMediaPlayer` + `QVideoWidget` 加载,时长 124435 ms、可 seek,30 秒定位后继续播放约两秒读到 31857 ms,未报告错误。[Qt QMediaPlayer](https://doc.qt.io/qtforpython-6/PySide6/QtMultimedia/QMediaPlayer.html)提供 `setPosition()`;真实 seek 质量仍须比较。 - **EXE**:隔离 PyInstaller 6.22.3 构建 Qt Widgets `onedir/windowed` 小程序。误收宿主 Poppler 的 ICU 后导入 QtCore 失败;移走误收 DLL 后 EXE 退出码 0、启动标记成功,PE 子系统 2。说明路线可行,也说明正式构建必须清理 `PATH` 与校验收集清单。Inno Setup、完整应用和 mpv 合包尚未验证。 diff --git a/docs/desktop-vnext/ARCHITECTURE.md b/docs/desktop-vnext/ARCHITECTURE.md index 14969e9..ee4c2c6 100644 --- a/docs/desktop-vnext/ARCHITECTURE.md +++ b/docs/desktop-vnext/ARCHITECTURE.md @@ -21,7 +21,7 @@ ## 边界规则 -- `F:\Videos\投稿` 是本机默认投稿根目录,不写死为底层扫描函数的唯一合法目录;沿用已有配置/路径边界。桌面项目层按标题文件夹组织项目,复用现有视频/SRT 扫描与配对规则,并统一供两个功能页使用。当前扫描是请求驱动的刷新,不能假定有文件监听。 +- 投稿根目录沿用已有配置/路径边界(`AUTOSLICE_SUBMISSION_DIR` 或本机 `autoslice.local.json`,未配置时为仓库内 `submissions`),维护者本机在私有配置中指定实际投稿目录;不写死为底层扫描函数的默认值或唯一合法目录。桌面项目层按标题文件夹组织项目,复用现有视频/SRT 扫描与配对规则,并统一供两个功能页使用。当前扫描是请求驱动的刷新,不能假定有文件监听。 - 项目文件夹是项目事实来源;数据库或草稿状态只补充编辑、缓存与任务信息。状态缺失时仍能扫描并打开项目。 - 草稿与正式结果分层:字幕编辑自动保存草稿,显式保存才通过现有契约写校对 SRT;封面编辑状态落盘并能恢复,导出沿用渲染器的暂存提交机制。 - AI 检查结果字段可复用,但建议处理状态须由新应用层管理;模型 transport 可复用,不能把话题分析 prompt 或整条切片流水线带入字幕/封面功能。封面 AI 生成结构化、可编辑布局,由本地渲染器实现成图。 diff --git a/docs/desktop-vnext/BACKLOG.md b/docs/desktop-vnext/BACKLOG.md index 40f60bc..c9c2d32 100644 --- a/docs/desktop-vnext/BACKLOG.md +++ b/docs/desktop-vnext/BACKLOG.md @@ -4,7 +4,7 @@ | 任务 | 单一交付切片 / 验收点 | | --- | --- | -| Desktop-03(已完成) | 新 Desktop 最小壳与统一投稿项目服务:首次进入字幕页;两个功能页从默认 `F:\Videos\投稿` 刷新同一批标题文件夹项目,无需手动添加。上次页面恢复延后。 | +| Desktop-03(已完成) | 新 Desktop 最小壳与统一投稿项目服务:首次进入字幕页;两个功能页从配置的投稿根目录刷新同一批标题文件夹项目,无需手动添加。上次页面恢复延后。 | | Desktop-04(已完成) | 基础字幕列表:按现有契约加载 SRT、单击编辑与 Delete 删除、内存级撤销/重做;明确保存后产生校对 SRT,原始 SRT 不被键入覆盖。自动恢复草稿见下方补项。 | | Desktop-04.5(已完成) | 审查 Tk 真实入口,隔离验证 Qt 壳、libmpv/QtMultimedia 单样本播放与 PyInstaller 最小无控制台 EXE;固定桌面数据/恢复协议与选型。证据见 [DESKTOP_FOUNDATION.md](DESKTOP_FOUNDATION.md)。 | | Desktop-04.55(已完成) | 独立可停留 Qt 视觉预览:窄左导航、共享示例项目列、视频/薄时间轴/字幕列表占位、可收起 AI 栏、可拖动 splitter 与集中深色主题。视觉契约见 [VISUAL_SYSTEM.md](VISUAL_SYSTEM.md);不接业务。 | diff --git a/docs/desktop-vnext/CURRENT.md b/docs/desktop-vnext/CURRENT.md index 4dabfe7..ca9cc1b 100644 --- a/docs/desktop-vnext/CURRENT.md +++ b/docs/desktop-vnext/CURRENT.md @@ -3,7 +3,7 @@ 更新日期:2026-09-28;来源:Desktop-01 对当前 AutoSlice 仓库的静态代码审计。详细实现位置、输入输出和迁移判断见 [MIGRATION_MAP.md](MIGRATION_MAP.md)。 - 当前生产实现位于 `src/autoslice/` 和 `src/autoslice_cover/`;旧 Web 页面分别调用 Python 字幕工作流与 AutoCover 工作区/渲染器。 -- 投稿根目录由配置或页面输入确定。本机配置的 `F:\Videos\投稿` 已确认存在。字幕工作台递归扫描 `.flv/.mp4/.mkv/.mov/.avi`,优先配对同目录同名 SRT;缺字幕视频仍出现在队列中。 +- 投稿根目录由配置或页面输入确定。本机配置的投稿目录已确认存在。字幕工作台递归扫描 `.flv/.mp4/.mkv/.mov/.avi`,优先配对同目录同名 SRT;缺字幕视频仍出现在队列中。 - SRT 解析、删除/合并/时间修改、校对 SRT 与编辑状态保存已有独立 Python 函数;源 SRT 不会被校对保存覆盖。 - AI 字幕检查按批处理并缓存建议,不直接写源字幕;建议包含 cue 序号、原文、修正文、理由、置信度和时间。采纳、忽略、手工保护与撤销状态主要保存在旧页面内存中。 - 字幕压制由 SRT 生成 ASS,经 FFmpeg 输出新 MP4;默认样式与导出参数集中定义,并要求精确字体。字幕页当前只提供指定时间的静帧预览,没有连续视频播放器或点击 cue 后播放的实现。 @@ -18,7 +18,7 @@ ## Desktop-03 实现与验证 - 独立入口为仓库根目录 `python 桌面端.py`;已安装项目也可用 `python -m autoslice.desktop`。它只启动 Tk 桌面壳,不启动旧 Web、AutoCover、自动分析或自动切片。首次显示“字幕校对”,顶部一级入口为“字幕校对 / 封面制作 / 设置”,无首页。 -- `src/autoslice/desktop/projects.py` 是统一项目服务。投稿路径优先取 `AUTOSLICE_SUBMISSION_DIR`,其次取现有本机配置,默认 `F:\Videos\投稿`;设置页显示实际路径。刷新按根目录下一层标题文件夹建立项目,并调用旧 `scan_submission_pairs` 识别其视频、SRT 和校对状态。两个功能页只读取同一服务的 `ProjectSnapshot`,各自保留当前选中项目。 +- `src/autoslice/desktop/projects.py` 是统一项目服务。投稿路径优先取 `AUTOSLICE_SUBMISSION_DIR`,其次取现有本机配置,未配置时与 Web 端一致回退到仓库内 `submissions`(同一 `runtime_config` owner);设置页显示实际路径。刷新按根目录下一层标题文件夹建立项目,并调用旧 `scan_submission_pairs` 识别其视频、SRT 和校对状态。两个功能页只读取同一服务的 `ProjectSnapshot`,各自保留当前选中项目。 - 旧扫描器返回逐视频记录,而产品契约要求每个标题文件夹为一个项目;桌面服务只做分组适配。即使文件夹为空或缺少字幕,也显示项目及简短状态。根目录下散放的文件不构成项目。扫描是手动刷新,不使用文件监听。 - 已运行项目服务单元测试,覆盖默认路径/配置、旧配对和生成视频排除、项目与文件变化、空目录、缺失目录及不可读根目录;实际本机目录刷新得到 4 个项目。已实例化桌面窗口并切换三个一级页面,确认封面页复用同一个项目快照。旧启动器、字幕工作流及 AutoCover 工作区定向回归通过。GUI 布局仍需在用户实际桌面上目视检查。 - 当前限制:工作区只有项目基本状态和后续任务占位内容;不加载字幕、不播放视频、不制作封面。上次页面恢复尚未实现,已记入 [BACKLOG.md](BACKLOG.md)。 @@ -77,7 +77,7 @@ - 用户实机反馈的焦点与快捷键不稳来自仅在窗口注册 Delete/撤销/重做、播放没有键盘入口,以及文字编辑器会优先处理组合键。现将窗口命令统一注册为 `WindowShortcut`,文字编辑时保留普通字符、Space、Delete、Shift+Enter;`Enter` 提交,`Ctrl+Z` / `Ctrl+Y` 先提交再操作字幕文档。`Ctrl+Space` 在编辑态也控制播放;非编辑态 Space 同样控制播放。列表 `↑` / `↓` 切行后同步选中和定位。 - 单击正文保持立即编辑;编辑器使用不透明背景并在绘制时隐藏原单元格正文,结束后恢复正常行高。时间轴的 selected、current playback、hover 分色绘制,主选中仅一块。列表当前播放行采用弱于选中行的背景色。 - 点击字幕列表或时间轴块现在定位到字幕开始时间并暂停;再次点击已选字幕也重新定位。时间轴细竖线只表示视频时间;点击空白轨道可 seek。播放器按钮等媒体实际就绪才启用,命令发出时立即更新按钮意图状态,旧轮询结果不会覆盖新播放/暂停/定位命令。错误和超时保留明确提示。拖动 playhead scrub 尚未实现,留在 BACKLOG。 -- 本机真实 `F:\Videos\投稿` 读取 6 个项目之一的 104.234 秒 MP4 与 55 条 SRT:鼠标连续点击 10 次不同字幕、键盘切行、空白轨道定位、10 轮播放→暂停→seek、Space/Ctrl+Space、编辑态与非编辑态快捷键、Delete/撤销/重做均通过;播放器报告的时间在每轮播放后实际前进。隔离副本使用同一真实 MP4 的硬链接及真实 SRT 内容完成草稿写入、重载恢复、正式保存、再次加载,源 SRT 字节未变。真实投稿目录未执行正式保存。运行桌面回归、编译及本轮 Ruff 检查通过;音频听感和其他编码仍需用户实机亲测。 +- 本机真实投稿目录读取 6 个项目之一的 104.234 秒 MP4 与 55 条 SRT:鼠标连续点击 10 次不同字幕、键盘切行、空白轨道定位、10 轮播放→暂停→seek、Space/Ctrl+Space、编辑态与非编辑态快捷键、Delete/撤销/重做均通过;播放器报告的时间在每轮播放后实际前进。隔离副本使用同一真实 MP4 的硬链接及真实 SRT 内容完成草稿写入、重载恢复、正式保存、再次加载,源 SRT 字节未变。真实投稿目录未执行正式保存。运行桌面回归、编译及本轮 Ruff 检查通过;音频听感和其他编码仍需用户实机亲测。 ## Desktop-07 AI 字幕检查后台任务与待确认队列(已完成) @@ -97,7 +97,7 @@ - playhead 可见竖线仍为 2px,逻辑命中宽 14px、覆盖时间轴完整高度;三角、竖线中段/下段 hover 均显示水平拖动光标。空白轨道按下立即定位、继续移动进入 scrub;字幕块中部和左右边缘保持原移动/改时优先级。scrub 继续约 150ms 节流,松手精确 seek,不改变选中字幕。 - 主题在 `qt_preview/theme.py` 汇总背景、文字、强调色、选中/播放状态、控件及字体尺寸。窄导航换成统一线性 SVG;项目列保持双行紧凑列表;顶栏突出当前项目,单视频在工作栏显示文件名而不保留冗长下拉;字幕 `QTableView` 保留编辑模型,去网格并用序号/时间弱化与 14px 正文建立阅读层级。AI 侧栏让差异和采纳成为重点,无建议时隐藏空明细与按钮;播放器按钮/音量图标统一,保存后短暂显示成功状态。没有新增缩略图、压制、封面能力或动画系统。 -- 本机真实 Qt 窗口扫描 `F:\Videos\投稿` 的 6 个项目,读取 104.234 秒 MP4 和 55 条真实 SRT。于 2560×1440 物理屏幕(Qt 逻辑窗口约 2051×1132,截图 2564×1415)和 1366×768 逻辑窗口检查 AI 展开/收起、324→380px splitter、播放器/时间轴/列表可用高度。真实 mpv `time-pos` 验证三角、竖线中段、竖线下段、空白轨道四种 scrub 到达目标;下段从约 20.5 秒连续拖到 30.5 秒只发出 2 次途中预览 seek,松手落在 30.49 秒。真实窗口内验证字幕块移动和两侧边缘命中、播放/暂停、行内编辑、内存假 AI 采纳/跳过、Delete、Undo/Redo。Qt 截图对原生 mpv 视频子窗口只能显示黑色区域,截图用于评审周边界面;声音听感、其他编码与用户主观长时间阅读仍需亲测。未调用真实 AI,未保存投稿原件。 +- 本机真实 Qt 窗口扫描投稿目录的 6 个项目,读取 104.234 秒 MP4 和 55 条真实 SRT。于 2560×1440 物理屏幕(Qt 逻辑窗口约 2051×1132,截图 2564×1415)和 1366×768 逻辑窗口检查 AI 展开/收起、324→380px splitter、播放器/时间轴/列表可用高度。真实 mpv `time-pos` 验证三角、竖线中段、竖线下段、空白轨道四种 scrub 到达目标;下段从约 20.5 秒连续拖到 30.5 秒只发出 2 次途中预览 seek,松手落在 30.49 秒。真实窗口内验证字幕块移动和两侧边缘命中、播放/暂停、行内编辑、内存假 AI 采纳/跳过、Delete、Undo/Redo。Qt 截图对原生 mpv 视频子窗口只能显示黑色区域,截图用于评审周边界面;声音听感、其他编码与用户主观长时间阅读仍需亲测。未调用真实 AI,未保存投稿原件。 - 桌面 Qt 定向单元、编译及 Ruff 通过;截图交付于本轮工作目录的 `outputs/`。下一阶段恢复 Desktop-08 字幕压制。 ## Desktop-08 字幕压制闭环(已完成) @@ -119,7 +119,7 @@ ## Desktop-08.6 字幕工作台独立验收与稳定性验证(2026-09-29) -- 正式 Qt 入口 启动Qt桌面端.cmd 已在本机启动;真实 F:\Videos\投稿 扫描得到 6 个项目。服务连续刷新两次仍为 6 个,项目 ID 无重复;窗口控件树显示实际中文、Emoji、【】标题、真实 MP4、字幕列表和播放器。当前 Python Qt 窗口截图被原生 mpv 子窗口捕获超时,沿用既有三张 2560×1440 / 1366×768 截图完成视觉复核。 +- 正式 Qt 入口 启动Qt桌面端.cmd 已在本机启动;真实投稿目录扫描得到 6 个项目。服务连续刷新两次仍为 6 个,项目 ID 无重复;窗口控件树显示实际中文、Emoji、【】标题、真实 MP4、字幕列表和播放器。当前 Python Qt 窗口截图被原生 mpv 子窗口捕获超时,沿用既有三张 2560×1440 / 1366×768 截图完成视觉复核。 - 真实播放器窗口上对播放/暂停连续按键 20 次,按钮状态每次交替正确;播放约 1.5 秒后暂停,时间码实际前进。字幕定位、时间轴顶部/中段/下段 playhead、空白轨道 scrub、字幕块中部与左右边缘优先级由 Qt 专用离屏测试覆盖;选中字幕、播放字幕和 hover 的状态保持独立。 - 隔离副本完成字幕编辑契约、撤销/重做、删除、草稿恢复、正式保存和冲突保护;Qt 专用环境的 Desktop、旧字幕工作流和启动器/项目扫描合计 105 项通过,未调用真实 AI。额外 fake 检查生成 3 条建议(高置信、低置信、长文本),采纳只改目标 cue,跳过和手工保护不覆盖正文,建议会话可重载。 - 真实压制只写 work/desktop-08.6-isolated-real:104.23 秒短片完成首次输出与第二次 (2) 避让;638.57 秒长片完成前/中/后字幕样本压制。两类输出都含 H.264 视频流与 AAC 音频流,时长与源一致;源视频、原始 SRT、校对 SRT 哈希保持不变,压制临时目录清空。FFmpeg 取消返回“字幕压制已取消”且没有残留新成片。输出抽帧与源帧比较显示字幕时刻的下方画面差异明显,无字幕时刻没有同等级变化。 diff --git a/docs/desktop-vnext/MIGRATION_MAP.md b/docs/desktop-vnext/MIGRATION_MAP.md index e0fea9c..4545452 100644 --- a/docs/desktop-vnext/MIGRATION_MAP.md +++ b/docs/desktop-vnext/MIGRATION_MAP.md @@ -4,7 +4,7 @@ ## 范围与边界 -- 投稿目录由 `AUTOSLICE_SUBMISSION_DIR`、本机配置或仓库内 `submissions` 默认值决定,页面也可提交 `root_dir`;不是源码中固定路径。本次确认的本机目录 `F:\Videos\投稿` 存在,且与本机配置一致。[配置](../../src/autoslice/runtime_config.py#L84-L113) · [路由](../../src/autoslice/web/app.py#L2204-L2234) +- 投稿目录由 `AUTOSLICE_SUBMISSION_DIR`、本机配置或仓库内 `submissions` 默认值决定,页面也可提交 `root_dir`;不是源码中固定路径。本次确认的本机投稿目录存在,且与本机配置一致。[配置](../../src/autoslice/runtime_config.py#L84-L113) · [路由](../../src/autoslice/web/app.py#L2204-L2234) - AutoCover 在本仓库的生产代码为 `src/autoslice_cover/`;`autocover_tool/` 保留旧启动和数据兼容用途。[项目结构](../../README.md) - 下表的建议针对能力与契约,不包含旧 HTML/CSS/JavaScript 页面的迁入。 diff --git a/docs/desktop-vnext/PRODUCT.md b/docs/desktop-vnext/PRODUCT.md index fb417b1..be6e1c7 100644 --- a/docs/desktop-vnext/PRODUCT.md +++ b/docs/desktop-vnext/PRODUCT.md @@ -4,7 +4,7 @@ - AutoSlice Desktop vNext 是个人视频后处理工作台:接收剪映导出的视频和字幕,服务于上传 B 站之前的处理。 - 主流程只有两项高频工作:字幕校对与字幕压制、封面制作。用户可直接进入任一工作台,不依赖自动分析或自动切片。 -- 默认投稿根目录为 `F:\Videos\投稿`;每个标题文件夹是一个项目。刷新扫描后自动出现在功能页项目列表,不要求手动“添加项目”。目录是项目事实来源,应用状态只补充草稿、任务等信息。 +- 投稿根目录由本机配置指定(维护者本机为 F 盘投稿目录),未配置时为仓库内 `submissions`;每个标题文件夹是一个项目。刷新扫描后自动出现在功能页项目列表,不要求手动“添加项目”。目录是项目事实来源,应用状态只补充草稿、任务等信息。 - 自动分析录播与自动切片旧能力冻结;可保留旧实现供参考和过渡,未来仅考虑作为高级/实验工具,不进入 vNext 主界面。 - 不建设发布准备流程,也不管理 B 站标题、简介和标签;沿用 B 站已有功能。 diff --git a/src/autoslice/desktop/projects.py b/src/autoslice/desktop/projects.py index e7b258b..ce02631 100644 --- a/src/autoslice/desktop/projects.py +++ b/src/autoslice/desktop/projects.py @@ -3,24 +3,17 @@ from __future__ import annotations import hashlib -import os from dataclasses import dataclass from pathlib import Path from autoslice import runtime_config from autoslice.subtitle_workflow import scan_submission_pairs -DEFAULT_SUBMISSION_ROOT = Path(r"F:\Videos\投稿") - def configured_submission_root() -> Path: - """显式环境、本机配置依次覆盖 Desktop 的默认投稿目录。""" + """与 Web 端同一配置 owner:显式环境、本机配置,最后是仓库内 submissions。""" - value = ( - str(os.environ.get("AUTOSLICE_SUBMISSION_DIR", "")).strip() - or runtime_config.LOCAL_ENVIRONMENT.get("AUTOSLICE_SUBMISSION_DIR", "") - ) - return Path(value).expanduser() if value else DEFAULT_SUBMISSION_ROOT + return runtime_config.configured_path("AUTOSLICE_SUBMISSION_DIR", "submissions") @dataclass(frozen=True) diff --git a/tests/unit/test_desktop_projects.py b/tests/unit/test_desktop_projects.py index e17fc3c..7f65a61 100644 --- a/tests/unit/test_desktop_projects.py +++ b/tests/unit/test_desktop_projects.py @@ -8,8 +8,8 @@ from pathlib import Path from unittest.mock import patch +from autoslice import runtime_config from autoslice.desktop.projects import ( - DEFAULT_SUBMISSION_ROOT, SubmissionProjectService, configured_submission_root, ) @@ -19,9 +19,13 @@ class SubmissionProjectServiceTests(unittest.TestCase): def test_default_root_and_existing_configuration(self): with patch.dict(os.environ, {"AUTOSLICE_SUBMISSION_DIR": ""}): with patch("autoslice.desktop.projects.runtime_config.LOCAL_ENVIRONMENT", {}): - self.assertEqual(configured_submission_root(), DEFAULT_SUBMISSION_ROOT) + # 未配置时与 Web 端一致回退到仓库内 submissions,不写死本机路径 + self.assertEqual( + configured_submission_root(), + (runtime_config.PROJECT_DIR / "submissions").resolve(), + ) with patch.dict(os.environ, {"AUTOSLICE_SUBMISSION_DIR": r"D:\投稿"}): - self.assertEqual(configured_submission_root(), Path(r"D:\投稿")) + self.assertEqual(configured_submission_root(), Path(r"D:\投稿").resolve()) def test_refresh_groups_existing_scan_pairs_by_title_folder(self): with tempfile.TemporaryDirectory() as directory: From 7e171ccc55e0eaa804467b616d9859a5ec3559e7 Mon Sep 17 00:00:00 2001 From: sc57 Date: Sun, 4 Oct 2026 00:39:34 +0800 Subject: [PATCH 06/14] refactor(subtitles): reuse segment owner and share edit-state fields - _split_subtitle_text_for_ass and _subtitle_display_text_size were line-for-line copies of transcription.segments.split_subtitle_text_for_display and subtitle_text_size under different names, so the duplicate-definition guard could not see them. The ASS wrapper now calls the segment owner. - save_corrected_srt and load_subtitle_edit_state built the same five structure fields (deleted, merge pairs/overrides, time overrides, split groups) independently; both now use _edit_structure_payload, keeping key order so written state files are byte-for-byte unchanged. Co-Authored-By: Claude Opus 5.5 --- src/autoslice/subtitle_workflow.py | 148 +++++++------------- tests/integration/test_subtitle_workflow.py | 3 +- 2 files changed, 55 insertions(+), 96 deletions(-) diff --git a/src/autoslice/subtitle_workflow.py b/src/autoslice/subtitle_workflow.py index a020650..309e3e0 100644 --- a/src/autoslice/subtitle_workflow.py +++ b/src/autoslice/subtitle_workflow.py @@ -20,6 +20,7 @@ from autoslice.media_formats import SUPPORTED_VIDEO_EXTENSIONS from autoslice.streamer_profiles import StreamerProfile, merge_profile_subtitle_glossary from autoslice.transcription import background_filter as background_filter_contract +from autoslice.transcription import segments as subtitle_segments from autoslice.transcription.contracts import ( DEFAULT_MAX_PUBLISH_TITLE_CHARS, DEFAULT_SUBTITLE_GLOSSARY, @@ -691,6 +692,41 @@ def reflow_subtitle_srt_for_display( } +def _edit_structure_payload( + deleted, previous_by_child, normalized_merge_overrides, + normalized_time_overrides, normalized_split_groups): + """保存与读取共用的编辑结构字段;字段顺序与旧状态文件保持一致。""" + return { + "deleted_indices": sorted(deleted), + "merge_pairs": [ + {"first": first, "second": second} + for second, first in sorted(previous_by_child.items()) + ], + "merge_overrides": { + str(index): text + for index, text in sorted(normalized_merge_overrides.items()) + }, + "time_overrides": { + str(index): { + "start": timing["start_seconds"], + "end": timing["end_seconds"], + } + for index, timing in sorted(normalized_time_overrides.items()) + }, + "split_groups": [ + { + "source": source, + "segments": [ + {"id": item["id"], "start": item["start_seconds"], + "end": item["end_seconds"], "text": item["text"]} + for item in segments + ], + } + for source, segments in sorted(normalized_split_groups.items()) + ], + } + + def save_corrected_srt( source_srt_path, corrections, output_path=None, *, deleted_indices=None, merge_pairs=None, merge_overrides=None, time_overrides=None, @@ -785,33 +821,13 @@ def save_corrected_srt( } for index, corrected in sorted(updates.items()) ], - "deleted_indices": sorted(deleted), - "merge_pairs": [ - {"first": first, "second": second} - for second, first in sorted(previous_by_child.items()) - ], - "merge_overrides": { - str(index): text - for index, text in sorted(normalized_merge_overrides.items()) - }, - "time_overrides": { - str(index): { - "start": timing["start_seconds"], - "end": timing["end_seconds"], - } - for index, timing in sorted(normalized_time_overrides.items()) - }, - "split_groups": [ - { - "source": source, - "segments": [ - {"id": item["id"], "start": item["start_seconds"], - "end": item["end_seconds"], "text": item["text"]} - for item in segments - ], - } - for source, segments in sorted(normalized_split_groups.items()) - ], + **_edit_structure_payload( + deleted, + previous_by_child, + normalized_merge_overrides, + normalized_time_overrides, + normalized_split_groups, + ), } _atomic_write_text( _subtitle_edit_state_path(source_srt_path), @@ -886,33 +902,13 @@ def load_subtitle_edit_state(source_srt_path): "state_path": str(state_path), "corrected_srt_path": str(corrected), "corrections": corrections, - "deleted_indices": sorted(deleted), - "merge_pairs": [ - {"first": first, "second": second} - for second, first in sorted(previous_by_child.items()) - ], - "merge_overrides": { - str(index): text - for index, text in sorted(normalized_merge_overrides.items()) - }, - "time_overrides": { - str(index): { - "start": timing["start_seconds"], - "end": timing["end_seconds"], - } - for index, timing in sorted(normalized_time_overrides.items()) - }, - "split_groups": [ - { - "source": source, - "segments": [ - {"id": item["id"], "start": item["start_seconds"], - "end": item["end_seconds"], "text": item["text"]} - for item in segments - ], - } - for source, segments in sorted(normalized_split_groups.items()) - ], + **_edit_structure_payload( + deleted, + previous_by_child, + normalized_merge_overrides, + normalized_time_overrides, + normalized_split_groups, + ), } except (OSError, TypeError, ValueError, json.JSONDecodeError): return None @@ -2074,10 +2070,6 @@ def _escape_ass_text(text): ) -def _subtitle_display_text_size(text): - return len(re.sub(r"\s+", "", str(text or ""))) - - def _subtitle_display_char_limit(width, geometry): """按输出画布、字号和描边估算一行字幕的安全字数。""" usable_width = max(1.0, float(width) - geometry["margin"] * 2) @@ -2088,46 +2080,12 @@ def _subtitle_display_char_limit(width, geometry): return max(6, min(32, int(usable_width / glyph_width))) -def _split_subtitle_text_for_ass(text, max_chars): - """将显示过长的单条字幕拆为安全行,优先保留词间空格。""" - remaining = re.sub(r"\s+", " ", str(text or "")).strip() - parts = [] - while _subtitle_display_text_size(remaining) > max_chars: - visible_count = 0 - hard_cut = len(remaining) - for index, char in enumerate(remaining): - if not char.isspace(): - visible_count += 1 - if visible_count >= max_chars: - hard_cut = index + 1 - break - preferred_cut = remaining.rfind(" ", 0, hard_cut) - if ( - preferred_cut > 0 - and _subtitle_display_text_size(remaining[:preferred_cut]) - >= max(2, int(max_chars * 0.55))): - cut = preferred_cut - else: - cut = hard_cut - part = remaining[:cut].strip() - if not part: - part = remaining[:hard_cut].strip() - cut = hard_cut - if not part: - break - parts.append(part) - remaining = remaining[cut:].lstrip() - if remaining: - parts.append(remaining) - return parts - - def _wrap_subtitle_text_for_ass(text, max_chars): """只做视觉换行,不改变 cue 的时间范围;显式换行也必须保留。""" source = str(text or "").replace("\r\n", "\n").replace("\r", "\n") wrapped_lines = [] for source_line in source.split("\n"): - parts = _split_subtitle_text_for_ass(source_line, max_chars) + parts = subtitle_segments.split_subtitle_text_for_display(source_line, max_chars=max_chars) if parts: wrapped_lines.extend(parts) elif source_line == "": @@ -2137,7 +2095,7 @@ def _wrap_subtitle_text_for_ass(text, max_chars): def _split_cue_for_ass(cue, max_chars): """把一条 SRT cue 拆成连续事件;仅供显式 SRT 重排使用。""" - parts = _split_subtitle_text_for_ass(cue.text, max_chars) + parts = subtitle_segments.split_subtitle_text_for_display(cue.text, max_chars=max_chars) if not parts: return [] start = cue.start_seconds @@ -2148,7 +2106,7 @@ def _split_cue_for_ass(cue, max_chars): if len(parts) == 1: return [(start, end, parts[0])] - weights = [max(1, _subtitle_display_text_size(part)) for part in parts] + weights = [max(1, subtitle_segments.subtitle_text_size(part)) for part in parts] total_weight = sum(weights) duration = end - start minimum_duration = min(0.05, duration / len(parts)) diff --git a/tests/integration/test_subtitle_workflow.py b/tests/integration/test_subtitle_workflow.py index bb9ba45..b46e27f 100644 --- a/tests/integration/test_subtitle_workflow.py +++ b/tests/integration/test_subtitle_workflow.py @@ -12,6 +12,7 @@ from autoslice import subtitle_workflow from autoslice.llm import transport as llm_gateway from autoslice.transcription import contracts as transcription_contracts +from autoslice.transcription import segments as subtitle_segments from autoslice.streamer_profiles import resolve_streamer_profile from autoslice.subtitle_workflow import ( DEFAULT_SUBTITLE_GLOSSARY, @@ -1395,7 +1396,7 @@ def test_ass_wraps_oversized_cue_without_retiming(self): ) ass_safe_limit = subtitle_workflow._subtitle_display_char_limit(1920, geometry) self.assertTrue(all( - subtitle_workflow._subtitle_display_text_size(line) <= ass_safe_limit + subtitle_segments.subtitle_text_size(line) <= ass_safe_limit for line in visual_lines )) self.assertIn(r"{\an5\pos(960,966)}", events[0]) From 7ca99c9cfa7b99a98966637a7a8f203dd442b219 Mon Sep 17 00:00:00 2001 From: sc57 Date: Sun, 4 Oct 2026 00:43:13 +0800 Subject: [PATCH 07/14] refactor(security): share Flask response finalization autoslice.web.app and autoslice_cover.app each carried an identical after_request hook that issues the local session cookie and redacts LAN responses. Security behaviour duplicated across two apps can silently drift, so move it into SecurityPolicy.finalize_flask_response, next to the existing duck-typed authorize_flask_request helpers. Both hooks now delegate with their own bootstrap paths and JSON encoder; behaviour is unchanged. Co-Authored-By: Claude Opus 5.5 --- src/autoslice/security_policy.py | 30 ++++++++++++++++++++++++++++++ src/autoslice/web/app.py | 28 ++++++---------------------- src/autoslice_cover/app.py | 29 ++++++----------------------- 3 files changed, 42 insertions(+), 45 deletions(-) diff --git a/src/autoslice/security_policy.py b/src/autoslice/security_policy.py index adea145..b4942ce 100644 --- a/src/autoslice/security_policy.py +++ b/src/autoslice/security_policy.py @@ -805,6 +805,36 @@ def attach_session_cookie( response.headers["Cache-Control"] = "no-store" return True + def finalize_flask_response( + self, + flask_request: Any, + response: Any, + *, + bootstrap_paths: object, + json_dumps: Any, + ) -> Any: + """两个本机 Flask 程序共用的响应收尾:签发会话 Cookie,LAN 模式下脱敏正文。""" + + if ( + flask_request.method == "GET" + and flask_request.path in bootstrap_paths + and response.status_code < 400 + ): + self.attach_session_cookie( + response, + scheme=flask_request.scheme, + host_header=flask_request.host, + secure=flask_request.is_secure, + ) + if self.settings().lan_mode: + if response.is_json: + payload = response.get_json(silent=True) + if payload is not None: + response.set_data(json_dumps(self.redact_lan_payload(payload))) + elif response.mimetype in {"text/html", "text/plain", "text/markdown"}: + response.set_data(self.redact_lan_text(response.get_data(as_text=True))) + return response + __all__ = [ "DEFAULT_PATH_FIELDS", diff --git a/src/autoslice/web/app.py b/src/autoslice/web/app.py index 7e451f2..06da443 100644 --- a/src/autoslice/web/app.py +++ b/src/autoslice/web/app.py @@ -404,28 +404,12 @@ def _template_directory(value): def issue_local_browser_session(response): """页面或显式 bootstrap GET 仅通过 HttpOnly Cookie 建立本机会话。""" - if ( - request.method == "GET" - and request.path in _SESSION_BOOTSTRAP_PATHS - and response.status_code < 400): - security_policy.attach_session_cookie( - response, - scheme=request.scheme, - host_header=request.host, - secure=request.is_secure, - ) - if security_policy.settings().lan_mode: - if response.is_json: - payload = response.get_json(silent=True) - if payload is not None: - response.set_data(app.json.dumps( - security_policy.redact_lan_payload(payload) - )) - elif response.mimetype in {"text/html", "text/plain", "text/markdown"}: - response.set_data(security_policy.redact_lan_text( - response.get_data(as_text=True) - )) - return response + return security_policy.finalize_flask_response( + request, + response, + bootstrap_paths=_SESSION_BOOTSTRAP_PATHS, + json_dumps=app.json.dumps, + ) def _redact_task_error_text(value): diff --git a/src/autoslice_cover/app.py b/src/autoslice_cover/app.py index e9d3f4c..b071e54 100644 --- a/src/autoslice_cover/app.py +++ b/src/autoslice_cover/app.py @@ -682,29 +682,12 @@ def enforce_local_request_boundary(): @app.after_request def issue_local_browser_session(response): - if ( - request.method == "GET" - and request.path in SESSION_BOOTSTRAP_PATHS - and response.status_code < 400 - ): - security_policy.attach_session_cookie( - response, - scheme=request.scheme, - host_header=request.host, - secure=request.is_secure, - ) - if security_policy.settings().lan_mode: - if response.is_json: - payload = response.get_json(silent=True) - if payload is not None: - response.set_data(app.json.dumps( - security_policy.redact_lan_payload(payload) - )) - elif response.mimetype in {"text/html", "text/plain", "text/markdown"}: - response.set_data(security_policy.redact_lan_text( - response.get_data(as_text=True) - )) - return response + return security_policy.finalize_flask_response( + request, + response, + bootstrap_paths=SESSION_BOOTSTRAP_PATHS, + json_dumps=app.json.dumps, + ) @app.errorhandler(ApiError) def handle_api_error(error: ApiError): From ad546139b8f70ce63b532dbadc00bf38697cfdcc Mon Sep 17 00:00:00 2001 From: sc57 Date: Sun, 4 Oct 2026 00:44:37 +0800 Subject: [PATCH 08/14] chore: remove unreferenced helpers Delete functions that nothing in src/, tests/, scripts/, templates or JS references: subtitle_workflow._split_subtitle_cues, autoslice_cover.app._render_task, CueSelection.retain and runtime_config.template_defaults. SubtitleTimeline.follow_playback is also unused but is left in place because desktop-ui-opus55v2 edits it; it can go when that branch lands. Co-Authored-By: Claude Opus 5.5 --- src/autoslice/desktop/selection.py | 8 -------- src/autoslice/runtime_config.py | 10 ---------- src/autoslice/subtitle_workflow.py | 32 ------------------------------ src/autoslice_cover/app.py | 22 -------------------- 4 files changed, 72 deletions(-) diff --git a/src/autoslice/desktop/selection.py b/src/autoslice/desktop/selection.py index 59cf442..45aa078 100644 --- a/src/autoslice/desktop/selection.py +++ b/src/autoslice/desktop/selection.py @@ -37,11 +37,3 @@ def replace(self, cue_ids: set[int], order: list[int]) -> None: self.active = next(item for item in order if item in self.selected) if self.selected: self.anchor = self.active - - def retain(self, order: list[int]) -> None: - allowed = set(order) - self.selected &= allowed - if self.active not in allowed: - self.active = next((item for item in order if item in self.selected), None) - if self.anchor not in allowed: - self.anchor = self.active diff --git a/src/autoslice/runtime_config.py b/src/autoslice/runtime_config.py index c0cd1fb..e7cbbdb 100644 --- a/src/autoslice/runtime_config.py +++ b/src/autoslice/runtime_config.py @@ -128,13 +128,3 @@ def apply_local_environment(environ: dict[str, str] | None = None) -> dict[str, else (PROJECT_DIR / "title_style_profile.example.json").resolve() ) ) - - -def template_defaults() -> dict[str, str]: - """返回 Web 页面需要的公开路径默认值。""" - return { - "default_video_dir": str(VIDEO_DIR), - "default_output_dir": str(OUTPUT_DIR), - "default_timeline_dir": str(TIMELINE_DIR), - "default_submission_dir": str(SUBMISSION_DIR), - } diff --git a/src/autoslice/subtitle_workflow.py b/src/autoslice/subtitle_workflow.py index 309e3e0..3a265f7 100644 --- a/src/autoslice/subtitle_workflow.py +++ b/src/autoslice/subtitle_workflow.py @@ -442,38 +442,6 @@ def _normalise_split_groups(cues, split_groups, deleted_indices): return result -def _split_subtitle_cues(cues, text_updates, deleted_indices, split_groups): - """把拆分段展开成输出 SRT cue;首段沿用源序号,后续段使用稳定新序号。""" - used = {cue.index for cue in cues} - next_index = max(used, default=0) + 1 - output = [] - for cue in cues: - if cue.index in deleted_indices: - continue - segments = split_groups.get(cue.index) - if not segments: - output.append(SubtitleCue( - cue.index, - cue.start, - cue.end, - cue.settings, - text_updates.get(cue.index, cue.text), - )) - continue - for position, segment in enumerate(segments): - index = cue.index if position == 0 else next_index - if position: - next_index += 1 - output.append(SubtitleCue( - index, - segment["start"], - segment["end"], - cue.settings, - segment["text"], - )) - return output - - def serialise_srt( cues, text_updates=None, deleted_indices=None, *, merge_pairs=None, merge_overrides=None, time_overrides=None, split_groups=None): diff --git a/src/autoslice_cover/app.py b/src/autoslice_cover/app.py index b071e54..57d8c08 100644 --- a/src/autoslice_cover/app.py +++ b/src/autoslice_cover/app.py @@ -538,28 +538,6 @@ def _render_task_result( ) -def _render_task( - app: Flask, - workspace: CoverWorkspace, - task: CoverTask, - canvas_key: str, - output_path: Path, - payload: dict[str, Any], - *, - include_background: bool = False, -) -> dict[str, Any]: - result = _render_task_result( - app, - workspace, - task, - canvas_key, - output_path, - payload, - include_background=include_background, - ) - return _render_result_payload(workspace, result) - - def _save_task( app: Flask, workspace: CoverWorkspace, From a0afcd51ed414b4ec8788cd88b6cf8766a21950a Mon Sep 17 00:00:00 2001 From: sc57 Date: Sun, 4 Oct 2026 00:50:12 +0800 Subject: [PATCH 09/14] fix: narrow swallowed exceptions and tidy small hazards - analysis/topic/analysis.py: skip malformed LLM timecodes on ValueError and IndexError only, instead of hiding every exception. - analysis/manual/timebase.py: the zip fallback for .docx timelines only swallows OSError, KeyError and BadZipFile; the outer python-docx fallback stays as designed. - llm/transport.py: bind active_prompt/active_tokens explicitly in the retry closure (B023), so a future deferred call cannot see a later loop iteration's values. - analysis/topic/normalization.py: drop duplicate items from set literals (B033); the sets' contents are unchanged. The project has no logging setup, so these keep their current silent fallbacks rather than introducing new log output. Co-Authored-By: Claude Opus 5.5 --- src/autoslice/analysis/manual/timebase.py | 2 +- src/autoslice/analysis/topic/analysis.py | 2 +- src/autoslice/analysis/topic/normalization.py | 6 +++--- src/autoslice/llm/transport.py | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/autoslice/analysis/manual/timebase.py b/src/autoslice/analysis/manual/timebase.py index f8a172a..e3fdc43 100644 --- a/src/autoslice/analysis/manual/timebase.py +++ b/src/autoslice/analysis/manual/timebase.py @@ -229,7 +229,7 @@ def read_docx_lines(docx_path): if current: merged.append("".join(current).strip()) return [line for line in merged if line] - except Exception: + except (OSError, KeyError, zipfile.BadZipFile): return [] diff --git a/src/autoslice/analysis/topic/analysis.py b/src/autoslice/analysis/topic/analysis.py index 3d07b35..9dc82af 100644 --- a/src/autoslice/analysis/topic/analysis.py +++ b/src/autoslice/analysis/topic/analysis.py @@ -243,7 +243,7 @@ def parse_json_topics_response( end_str = str(item.get("end", "")).strip() start_s = timecode.parse_hms(start_str) end_s = timecode.parse_hms(end_str) - except Exception: + except (ValueError, IndexError): continue if not is_topic_in_chunk( start_s, diff --git a/src/autoslice/analysis/topic/normalization.py b/src/autoslice/analysis/topic/normalization.py index ff29d49..260cc60 100644 --- a/src/autoslice/analysis/topic/normalization.py +++ b/src/autoslice/analysis/topic/normalization.py @@ -98,8 +98,8 @@ "要点", "补充细节", "具体要点", "另一个事件", "例如", "例如:", "例如:", "等等。", "等等", "内容要点", "内容要点:", "内容要点:", "输出", "主播", "加盟商", "店主", "连麦者", "但", "但是", "然后", "因为", "所以", "因此", "不过", "最后", "另外", "同时", "继续", - "现在规划", "具体要点", "具体要点:", "具体要点:", "比如", "比如:", "比如:", - "points", "points:", "points:", "title", "title:", "title:", "要点", "要点:", "要点:", + "现在规划", "具体要点:", "具体要点:", "比如", "比如:", "比如:", + "points", "points:", "points:", "title", "title:", "title:", "要点:", "要点:", "更好的划分", "更好的划分:", "那么我们定义", "那么我们定义:", "整体时间段", "整体时间段:", "观察内容", "观察内容:", "更仔细看", "更仔细看:", "划分建议", "划分建议:", "整体看", "整体看,内容涉及:", "我们试着划分", "我们试着划分:", @@ -206,7 +206,7 @@ def is_meta_body_line(line): return True if re.match(r'^["“”]?(start|end|title|can_slice|points|topics)["“”]?\s*[::]', clean, re.IGNORECASE): return True - if clean in {"{", "}", "[", "]", "},", "],", "{"}: + if clean in {"{", "}", "[", "]", "},", "],"}: return True if re.match(r'^\[\d{1,2}:\d{2}(?::\d{2})?\s*/\s*\d{4}-\d{2}-\d{2}', clean): return True diff --git a/src/autoslice/llm/transport.py b/src/autoslice/llm/transport.py index 27cedc5..cd88417 100644 --- a/src/autoslice/llm/transport.py +++ b/src/autoslice/llm/transport.py @@ -847,7 +847,7 @@ def call_llm_with_retry( active_prompt = compact_prompt if use_compact else prompt active_tokens = compact_max_tokens if use_compact else max_tokens - def request_once(): + def request_once(active_prompt=active_prompt, active_tokens=active_tokens): call_kwargs = { "max_tokens": active_tokens, "json_mode": require_json, From f327be197f3f36ddf7c28bf2a35c749119f12516 Mon Sep 17 00:00:00 2001 From: sc57 Date: Sun, 4 Oct 2026 00:57:53 +0800 Subject: [PATCH 10/14] refactor(web): import real owners instead of topic_engine facade MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit docs/架构重构.md requires production consumers to depend on the real owner rather than compatibility modules. web/app.py (7 call sites) and launcher.py still imported ensure_srt, funasr_public_status, optimize_manual_timeline_for_video, retry_clip_review_from_artifacts, run_pipeline, slice_from_marks and subtitle_title_services through autoslice.topic_engine. They now import from autoslice.pipeline, autoslice.slicing, autoslice.transcription.workflow and autoslice.transcription.model_runtime. Tests that drive the web tasks patch those owners instead of the facade. core.py stays a compatibility forwarder, so its tests (including the core.generate_srt case in test_app.py) keep patching topic_engine. Co-Authored-By: Claude Opus 5.5 --- src/autoslice/launcher.py | 2 +- src/autoslice/web/app.py | 16 ++++++++------- tests/integration/test_app.py | 28 +++++++++++++-------------- tests/integration/test_core_compat.py | 2 +- 4 files changed, 25 insertions(+), 23 deletions(-) diff --git a/src/autoslice/launcher.py b/src/autoslice/launcher.py index b5aa600..29417c6 100644 --- a/src/autoslice/launcher.py +++ b/src/autoslice/launcher.py @@ -550,7 +550,7 @@ def main(argv=None): print(" 按 Ctrl+C 同时停止本次启动的服务\n") print("=" * 50 + "\n") - from autoslice.topic_engine import funasr_public_status + from autoslice.transcription.model_runtime import funasr_public_status from autoslice.web.app import app asr_status = funasr_public_status() diff --git a/src/autoslice/web/app.py b/src/autoslice/web/app.py index 06da443..594140f 100644 --- a/src/autoslice/web/app.py +++ b/src/autoslice/web/app.py @@ -1492,8 +1492,8 @@ def callback(msg, step, total): ) try: + from autoslice.pipeline import subtitle_title_services from autoslice.subtitle_workflow import generate_subtitle_reference_titles - from autoslice.topic_engine import subtitle_title_services with streamer_profile_context(streamer_profile): _raise_if_task_cancelled(task_id) @@ -1548,7 +1548,7 @@ def callback(msg, step, total): try: from autoslice.subtitle_workflow import transcribe_submission_video - from autoslice.topic_engine import ensure_srt + from autoslice.transcription.workflow import ensure_srt _raise_if_task_cancelled(task_id) result = transcribe_submission_video( @@ -1658,7 +1658,7 @@ def callback(msg, step, total): ) try: - from autoslice.topic_engine import optimize_manual_timeline_for_video + from autoslice.pipeline import optimize_manual_timeline_for_video _raise_if_task_cancelled(task_id) result = optimize_manual_timeline_for_video( @@ -1707,7 +1707,8 @@ def callback(msg, step, total): ) try: - from autoslice.topic_engine import retry_clip_review_from_artifacts, slice_from_marks + from autoslice.pipeline import retry_clip_review_from_artifacts + from autoslice.slicing import slice_from_marks _raise_if_task_cancelled(task_id) result = retry_clip_review_from_artifacts( @@ -1750,7 +1751,7 @@ def callback(msg, step, total): try: with streamer_profile_context(streamer_profile, flv_path): - from autoslice.topic_engine import slice_from_marks + from autoslice.slicing import slice_from_marks _raise_if_task_cancelled(task_id) count, out_dir = slice_from_marks( flv_path, @@ -2767,7 +2768,7 @@ def streamer_profiles_contract(): def asr_status_contract(): """展示当前 FunASR 模型与调整入口,不返回任何本机模型路径。""" - from autoslice.topic_engine import funasr_public_status + from autoslice.transcription.model_runtime import funasr_public_status return jsonify(funasr_public_status()) @@ -2843,7 +2844,8 @@ def run(): if _task_cancellation_requested(task_id): return try: - from autoslice.topic_engine import run_pipeline, slice_from_marks + from autoslice.pipeline import run_pipeline + from autoslice.slicing import slice_from_marks def cb(msg, step, total): _raise_if_task_cancelled(task_id) diff --git a/tests/integration/test_app.py b/tests/integration/test_app.py index c357c1d..490db2f 100644 --- a/tests/integration/test_app.py +++ b/tests/integration/test_app.py @@ -1546,7 +1546,7 @@ def test_asr_status_contract_is_public_and_path_free(self): "analysis_background_filter_default": "off", "background_filter_limit": "单音轨无法保证 100% 分离同时人声", } - with patch("autoslice.topic_engine.funasr_public_status", return_value=public_status): + with patch("autoslice.transcription.model_runtime.funasr_public_status", return_value=public_status): response = self.client.get("/api/asr-status") self.assertEqual(response.status_code, 200) @@ -2869,7 +2869,7 @@ def test_json_timeline_reslice_uses_existing_slice_from_marks_path(self): with ( patch.object(app_module.threading, "Thread", ImmediateThread), patch( - "autoslice.topic_engine.slice_from_marks", + "autoslice.slicing.slice_from_marks", return_value=(1, str(output_dir / "录播_话题切片")), ) as slicer, ): @@ -3045,15 +3045,15 @@ def test_optimize_manual_timeline_is_independent_from_pipeline_and_slicing(self) with ( patch.object(app_module.threading, "Thread", ImmediateThread), patch( - "autoslice.topic_engine.optimize_manual_timeline_for_video", + "autoslice.pipeline.optimize_manual_timeline_for_video", return_value=expected, ) as optimize, patch( - "autoslice.topic_engine.run_pipeline", + "autoslice.pipeline.run_pipeline", side_effect=AssertionError("独立优化不应运行完整分析"), ), patch( - "autoslice.topic_engine.slice_from_marks", + "autoslice.slicing.slice_from_marks", side_effect=AssertionError("独立优化不应自动切片"), ), ): @@ -3101,9 +3101,9 @@ def test_start_pipeline_reuses_selected_optimized_timeline(self): with ( patch.object(app_module.threading, "Thread", ImmediateThread), - patch("autoslice.topic_engine.run_pipeline", return_value=pipeline_result) as run_pipeline, + patch("autoslice.pipeline.run_pipeline", return_value=pipeline_result) as run_pipeline, patch( - "autoslice.topic_engine.slice_from_marks", + "autoslice.slicing.slice_from_marks", side_effect=AssertionError("没有切片标记时不应调用切片"), ), ): @@ -3171,11 +3171,11 @@ def test_start_pipeline_persists_compact_summary_for_large_result(self): with ( patch.object(app_module.threading, "Thread", ImmediateThread), patch( - "autoslice.topic_engine.run_pipeline", + "autoslice.pipeline.run_pipeline", return_value=pipeline_result, ), patch( - "autoslice.topic_engine.slice_from_marks", + "autoslice.slicing.slice_from_marks", return_value=(12, str(slice_dir)), ), ): @@ -3234,11 +3234,11 @@ def test_retry_clip_review_reuses_artifacts_reslices_and_blocks_pipeline(self): with ( patch.object(app_module.threading, "Thread", ImmediateThread), patch( - "autoslice.topic_engine.retry_clip_review_from_artifacts", + "autoslice.pipeline.retry_clip_review_from_artifacts", return_value=result, ) as retry, patch( - "autoslice.topic_engine.slice_from_marks", + "autoslice.slicing.slice_from_marks", return_value=(1, str(output_dir / "录播_话题切片")), ) as slicer, ): @@ -3317,7 +3317,7 @@ def test_json_timeline_reslice_uses_explicit_mark_range(self): with ( patch.object(app_module.threading, "Thread", ImmediateThread), patch( - "autoslice.topic_engine.slice_from_marks", + "autoslice.slicing.slice_from_marks", return_value=(1, str(output_dir / "录播_话题切片")), ) as slicer, ): @@ -3851,7 +3851,7 @@ def test_pipeline_ids_are_unique_and_duplicate_running_source_is_rejected(self): } with ( patch.object(app_module.threading, "Thread", ImmediateThread), - patch("autoslice.topic_engine.run_pipeline", return_value=pipeline_result), + patch("autoslice.pipeline.run_pipeline", return_value=pipeline_result), ): first = self.client.post( "/api/start-pipeline", @@ -3930,7 +3930,7 @@ def test_pipeline_error_result_redacts_secrets_paths_and_traceback(self): with ( patch.object(app_module.threading, "Thread", ImmediateThread), patch( - "autoslice.topic_engine.run_pipeline", + "autoslice.pipeline.run_pipeline", side_effect=RuntimeError( "token=test-private-value 位于 X:\\fixtures\\api_config.json" ), diff --git a/tests/integration/test_core_compat.py b/tests/integration/test_core_compat.py index 3fdf310..b7e11b7 100644 --- a/tests/integration/test_core_compat.py +++ b/tests/integration/test_core_compat.py @@ -202,7 +202,7 @@ def record_update(task_id, **changes): return_value=nullcontext(), ), patch( - "autoslice.topic_engine.slice_from_marks", + "autoslice.slicing.slice_from_marks", return_value=(1, r"X:\output\录播_话题切片"), ) as slice_from_marks, ): From 8ed7860ebd9d04917ddd04b3255ba5afe119c69c Mon Sep 17 00:00:00 2001 From: sc57 Date: Sun, 4 Oct 2026 01:07:42 +0800 Subject: [PATCH 11/14] refactor(web): move topic workbench script out of the template The topic_v2 page carried a 1,061-line inline script that no CI step syntax-checked. Move it to static/topic_v2.js, following the existing subtitle_workflow.js layout: - Default directories are injected through a JSON data block instead of Jinja expressions inside the script; LAN mode still renders them empty. - The 15 inline on* attributes become addEventListener bindings, bound right after restoreWorkspacePaths() so the Node behaviour tests keep executing only the definitions. - Page tests fetch the script through the Flask static route. - CI runs node --check on topic_v2.js and subtitle_workflow.js, and the packaging smoke checks list the new resource. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/tests.yml | 8 + scripts/smoke_packaging.py | 1 + scripts/verify_distribution.py | 1 + src/autoslice/resources/static/topic_v2.js | 1092 ++++++++++++++++ .../resources/templates/topic_v2.html | 1094 +---------------- tests/integration/test_app.py | 82 +- 6 files changed, 1160 insertions(+), 1118 deletions(-) create mode 100644 src/autoslice/resources/static/topic_v2.js diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index c2c9deb..12bdde4 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -124,6 +124,14 @@ jobs: shell: pwsh run: node --check src/autoslice_cover/resources/static/app.js + - name: Check AutoSlice JavaScript + shell: pwsh + run: | + foreach ($script in 'src/autoslice/resources/static/topic_v2.js', 'src/autoslice/resources/static/subtitle_workflow.js') { + node --check $script + if ($LASTEXITCODE) { exit $LASTEXITCODE } + } + linux-logic-only: name: Linux logic only (no media support) / Python 3.10 runs-on: ubuntu-latest diff --git a/scripts/smoke_packaging.py b/scripts/smoke_packaging.py index b6077e0..bd6d271 100644 --- a/scripts/smoke_packaging.py +++ b/scripts/smoke_packaging.py @@ -65,6 +65,7 @@ def main() -> int: required_resources = ( package_root / "resources" / "templates" / "topic_v2.html", package_root / "resources" / "static" / "workbench.css", + package_root / "resources" / "static" / "topic_v2.js", package_root / "streamer_profiles.json", package_root / "title_style_profile.example.json", ) diff --git a/scripts/verify_distribution.py b/scripts/verify_distribution.py index b2c86c3..f961c0b 100644 --- a/scripts/verify_distribution.py +++ b/scripts/verify_distribution.py @@ -229,6 +229,7 @@ def _verify_source_runtime( required = ( importlib.resources.files("autoslice") / "resources" / "templates" / "topic_v2.html", importlib.resources.files("autoslice") / "resources" / "static" / "workbench.css", + importlib.resources.files("autoslice") / "resources" / "static" / "topic_v2.js", importlib.resources.files("autoslice") / "streamer_profiles.json", importlib.resources.files("autoslice") / "title_style_profile.example.json", importlib.resources.files("autoslice_cover") / "resources" / "templates" / "index.html", diff --git a/src/autoslice/resources/static/topic_v2.js b/src/autoslice/resources/static/topic_v2.js new file mode 100644 index 0000000..4c11093 --- /dev/null +++ b/src/autoslice/resources/static/topic_v2.js @@ -0,0 +1,1092 @@ +let selVideo=null,selAss=null,selectedVideoMeta=null,sse=null,optimizedTimeline=null,resultTaskId=null,currentTaskId=null,currentTaskSnapshot=null,currentTaskResult=null,contextTaskId=null,readonlyTimeline=null,selectedTimelineKey='',timelinePreviewRequestId=0,scanBusy=false,taskBusy=false,cancelBusy=false,acceptUnboundTask=true; +const STREAMER_PROFILE_STORAGE_KEY='autoslice.streamer-profile'; +const VIDEO_DIR_STORAGE_KEY='autoslice.video-dir'; +const OUTPUT_DIR_STORAGE_KEY='autoslice.output-dir'; +const LAST_VALID_VIDEO_DIR_STORAGE_KEY='autoslice.last-valid-video-dir'; + +function byId(id){return document.getElementById(id)} +function esc(value){return String(value??'').replace(/[&<>"']/g,char=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[char]))} +function safeFileName(value,fallback='未选择录播'){ + const name=String(value??'').split(/[\\/]/).pop().trim(); + return name||fallback; +} +function taskSourceName(data){ + const sources=[]; + if(Array.isArray(data?.source_paths))sources.push(...data.source_paths); + else if(data?.source_paths)sources.push(data.source_paths); + sources.push(data?.source_path); + for(const source of sources){ + const name=safeFileName(source,''); + if(name)return name; + } + return '当前任务视频'; +} +function taskStreamerLabel(data){ + const profile=data?.streamer_profile; + return String(profile?.label||data?.streamer_profile_label||'').trim(); +} +function selectedStreamerLabel(data=null){ + const select=byId('streamerProfile'); + if(select&&select.value!=='auto'&&select.value){ + return String(select.selectedOptions?.[0]?.textContent||select.options?.[select.selectedIndex]?.text||select.value).trim()||'自动识别'; + } + return taskStreamerLabel(data)||'自动识别'; +} +function taskContextState(){ + const status=currentTaskSnapshot?.status; + const ownsTask=Boolean(status&¤tTaskId&¤tTaskId===contextTaskId); + const video=selVideo + ?safeFileName(selectedVideoMeta?.name||selVideo) + :ownsTask?taskSourceName(currentTaskSnapshot):'未选择录播'; + let phase='未选择',previous='尚无产物',next='选择录播'; + if(selVideo){ + phase='等待启动'; + previous=optimizedTimeline?.jsonPath?'优化时间轴':selectedVideoMeta?.has_srt?'原视频与源 SRT':'原视频'; + next='开始分析+切片'; + } + if(ownsTask){ + phase={queued:'排队中',running:'进行中',done:'已完成',error:'失败',cancelled:'已取消',interrupted:'已中断'}[status]||'失败'; + if(status==='queued')previous='任务已提交'; + else if(status==='running')previous=optimizedTimeline?.jsonPath?'优化时间轴':'已选录播与分析配置'; + else if(status==='done')previous=currentTaskResult?.kind==='timeline'?'优化时间轴':currentTaskResult?'整理包与切片结果':'任务已完成(结果待恢复)'; + else previous='已选录播与任务记录'; + if(status==='queued'||status==='running')next='等待任务完成'; + else if(status==='done'&¤tTaskResult?.kind==='timeline')next='开始分析+切片'; + else if(status==='done'&&resultTaskId)next='打开结果目录'; + else if(status==='done')next='检查任务结果'; + else next='检查状态后重新启动'; + } + return {video,phase,previous,next,streamer:selectedStreamerLabel(ownsTask?currentTaskSnapshot:null),hasResult:Boolean(resultTaskId)}; +} +function updateCurrentTaskContext(){ + const context=taskContextState(); + const values={contextVideo:context.video,contextPhase:context.phase,contextPrevious:context.previous,contextNext:context.next,contextStreamer:context.streamer,contextResult:context.hasResult?'任务结果目录':'暂无结果'}; + for(const [id,value] of Object.entries(values)){ + const element=byId(id); + if(!element)continue; + element.textContent=value; + element.title=value; + } + const openButton=byId('contextOpenResultButton'); + if(openButton){openButton.disabled=!context.hasResult;openButton.setAttribute?.('aria-disabled',String(!context.hasResult));} +} +function replaceFileExtension(path,extension){ + const separatorIndex=Math.max(path.lastIndexOf('/'),path.lastIndexOf('\\')); + const dotIndex=path.lastIndexOf('.'); + if(dotIndex<=separatorIndex)return path+extension; + return path.slice(0,dotIndex)+extension; +} + +function setNotice(message,kind=''){ + const notice=byId('pageNotice'); + notice.textContent=message; + notice.className=`notice ${kind}`.trim(); +} + +async function loadAsrStatus(){ + const box=byId('asrStatus'); + try{ + const data=await jsonRequest('/api/asr-status'); + byId('asrStatusTitle').textContent=`${data.display_name} · ${data.device}`; + byId('asrStatusHint').textContent=[data.summary,data.recommendation,data.hotword_hint,data.correction_hint].filter(Boolean).join(' '); + box.classList.toggle('warning',Boolean(data.needs_setup)); + box.classList.toggle('success',Boolean(data.recommended)); + }catch(error){ + byId('asrStatusTitle').textContent='FunASR 状态读取失败'; + byId('asrStatusHint').textContent=error.message; + box.classList.add('warning'); + } +} + +async function jsonRequest(url,options={}){ + const response=await fetch(url,{headers:{'Content-Type':'application/json'},...options}); + const result=await response.json().catch(()=>({error:`服务返回了无效数据 (${response.status})`})); + if(!response.ok||result.error)throw new Error(result.error||`请求失败 (${response.status})`); + return result; +} + +// 服务端默认目录由页面 JSON 数据块注入,LAN 模式下为空串 +function workspaceDefaults(){ + try{ + const config=JSON.parse(byId('topicPageConfig')?.textContent||'{}'); + return {videoDir:config.default_video_dir||'',outputDir:config.default_output_dir||''}; + }catch(error){ + return {videoDir:'',outputDir:''}; + } +} + +function restoreWorkspacePaths(){ + const defaults=workspaceDefaults(); + try{ + byId('videoDir').value=localStorage.getItem(VIDEO_DIR_STORAGE_KEY)||defaults.videoDir; + byId('outputDir').value=localStorage.getItem(OUTPUT_DIR_STORAGE_KEY)||defaults.outputDir; + }catch(error){ + byId('videoDir').value=defaults.videoDir; + byId('outputDir').value=defaults.outputDir; + } +} + +function rememberWorkspacePaths(){ + try{ + localStorage.setItem(VIDEO_DIR_STORAGE_KEY,byId('videoDir').value); + localStorage.setItem(OUTPUT_DIR_STORAGE_KEY,byId('outputDir').value); + }catch(error){} +} + +function rememberLastValidVideoDir(){ + try{ + const directory=byId('videoDir').value.trim(); + if(directory)localStorage.setItem(LAST_VALID_VIDEO_DIR_STORAGE_KEY,directory); + }catch(error){} +} + +function lastValidVideoDir(){ + try{return String(localStorage.getItem(LAST_VALID_VIDEO_DIR_STORAGE_KEY)||'').trim()}catch(error){return ''} +} + +function showScanRecovery(kind){ + const recovery=byId('scanRecovery'); + const message=byId('scanRecoveryMessage'); + const restore=byId('restoreLastValidDirButton'); + if(!recovery||!message||!restore)return; + message.textContent=kind==='error' + ?'当前没有可执行的旧录播选择。请重新扫描当前目录,或恢复上次有效目录后再选择录播。' + :'当前没有可执行的录播选择。请重新扫描当前目录,或恢复上次有效目录后再选择录播。'; + restore.hidden=!lastValidVideoDir(); + recovery.hidden=false; +} + +function hideScanRecovery(){ + const recovery=byId('scanRecovery'); + if(recovery)recovery.hidden=true; +} + +function restoreLastValidDirectory(){ + const directory=lastValidVideoDir(); + if(!directory){ + setNotice('没有可恢复的上次有效目录,请重新扫描当前目录','warning'); + showScanRecovery('empty'); + return; + } + byId('videoDir').value=directory; + scan(); +} + +function renderReport(markdown){ + const sliceTag='已切片'; + return String(markdown||'').split(/\r?\n/).map(raw=>{ + const line=esc(raw).replace(/✂️/g,sliceTag); + if(raw.startsWith('# '))return `

${line.slice(2)}

`; + if(raw.startsWith('## '))return `

${line.slice(3)}

`; + return line?`
${line}
`:'
'; + }).join(''); +} + +function updateActions(){ + const manualReady=byId('timelineMode').value==='manual'&&Boolean(byId('timelinePath').value.trim()); + byId('startButton').disabled=!selVideo||taskBusy||scanBusy; + const actionHint=byId('primaryActionHint'); + if(actionHint)actionHint.textContent=scanBusy + ?'正在扫描录播,扫描期间不会启动任务。' + :taskBusy + ?'任务已启动,右侧会持续显示进度;完成或失败后再执行下一步。' + :selVideo + ?'已选择录播;可直接执行完整分析与切片,辅助时间轴为可选项。' + :'先扫描录播并选择一个文件;检查通过后即可执行完整分析与切片。'; + byId('retryButton').disabled=!selVideo||taskBusy||scanBusy; + byId('optimizeButton').disabled=!selVideo||!manualReady||taskBusy||scanBusy; + byId('scanButton').disabled=scanBusy||taskBusy; + byId('videoDir').disabled=scanBusy; + byId('streamerProfile').disabled=scanBusy; + byId('timelineMode').disabled=scanBusy; + byId('refreshTimelineButton').disabled=scanBusy; + byId('timelineSelect').disabled=scanBusy; + byId('timelinePath').disabled=scanBusy; + document.querySelectorAll('.video-item').forEach(item=>{item.disabled=scanBusy}); + const cancelButton=byId('cancelTaskButton'); + const cancellable=Boolean(currentTaskId)&&taskBusy&&(currentTaskSnapshot?.status==='queued'||currentTaskSnapshot?.status==='running'); + cancelButton.hidden=!cancellable; + cancelButton.disabled=!cancellable||cancelBusy; + cancelButton.textContent=cancelBusy?'正在取消...':'取消任务'; + updateCurrentTaskContext(); +} + +function clearResultArtifact(clearTaskResult=true){ + resultTaskId=null; + if(clearTaskResult)currentTaskResult=null; + byId('resultArtifact').hidden=true; + byId('resultPaths').textContent=''; + updateCurrentTaskContext(); +} + +function clearQualityOverview(){ + const quality=byId('qualityOverview'); + quality.hidden=true; + quality.textContent=''; + quality.innerHTML=''; +} + +function clearReadonlyTimeline(){ + readonlyTimeline=null; + selectedTimelineKey=''; + closeTimelinePreview(); + const section=byId('readonlyTimeline'); + if(section)section.hidden=true; + const integrity=byId('timelineIntegrity'); + if(integrity){integrity.hidden=true;integrity.textContent='';integrity.innerHTML='';} + const state=byId('timelineState'); + if(state)state.textContent='未加载'; + const count=byId('timelineCount'); + if(count)count.textContent='0 条记录'; + ['timelineScale','timelineTrack','timelineDetails','timelineCards'].forEach(id=>{ + const element=byId(id); + if(!element)return; + element.textContent=''; + element.innerHTML=''; + if(id==='timelineDetails')element.hidden=true; + }); +} + +function stableTimelineIdentifier(value){ + if(typeof value!=='string')return ''; + const text=value.trim(); + if(!text||text!==value||text.length>200||/[\\/\x00\r\n]/.test(text))return ''; + return text; +} + +function timelinePreviewTaskId(){ + return stableTimelineIdentifier(readonlyTimeline?.task_id||currentTaskId); +} + +function timelinePreviewClipId(record){ + if(record?.kind!=='clip')return ''; + // T1-MEDIA 只接受时间轴明确登记的 manifest 片段 ID;不能把时间轴 + // 的展示 ID 猜成媒体 ID,否则旧数据可能意外触发文件访问请求。 + return stableTimelineIdentifier(record.clip_id); +} + +function closeTimelinePreview(){ + timelinePreviewRequestId+=1; + const video=byId('timelinePreviewVideo'); + if(video){ + try{video.pause?.()}catch(error){} + video.onerror=null; + video.removeAttribute?.('src'); + video.src=''; + video.hidden=true; + } + const preview=byId('timelinePreview'); + if(preview)preview.hidden=true; + const state=byId('timelinePreviewState'); + if(state)state.textContent=''; +} + +function showTimelinePreviewState(message,kind=''){ + const preview=byId('timelinePreview'); + const state=byId('timelinePreviewState'); + if(!preview||!state)return; + preview.hidden=false; + state.className=`timeline-preview-state ${kind}`.trim(); + state.textContent=message; +} + +function timelinePreviewStillCurrent(taskId,key,requestId){ + return timelinePreviewRequestId===requestId + &¤tTaskId===taskId + &&selectedTimelineKey===key + &&stableTimelineIdentifier(readonlyTimeline?.task_id||taskId)===taskId; +} + +function safeTimelineMediaUrl(value,taskId,clipId){ + const origin=typeof window!=='undefined'&&window.location?.origin + ?window.location.origin:'http://autoslice.local'; + const expectedPath=`/api/tasks/${encodeURIComponent(taskId)}/clips/${encodeURIComponent(clipId)}/media`; + try{ + const parsed=new URL(String(value||''),origin); + if(parsed.origin!==origin||parsed.pathname!==expectedPath)return ''; + const keys=[...parsed.searchParams.keys()]; + if(keys.length!==1||keys[0]!=='token'||!parsed.searchParams.get('token'))return ''; + return `${parsed.pathname}?${parsed.searchParams.toString()}`; + }catch(error){return ''} +} + +function timelinePreviewFailureMessage(status){ + if(status===403)return '短片预览不可用:当前任务没有可播放的登记产物。'; + if(status===404)return '短片预览不可用:短片不存在或访问令牌已失效。'; + if(status===409)return '短片预览暂不可用:短片尚未完成登记。'; + return '短片预览失败:安全媒体地址暂时不可用,请稍后重试。'; +} + +async function openTimelinePreview(record,key){ + closeTimelinePreview(); + const requestId=timelinePreviewRequestId; + const taskId=timelinePreviewTaskId(); + const clipId=timelinePreviewClipId(record); + if(!taskId||!clipId){ + showTimelinePreviewState('暂无可预览短片'); + return; + } + showTimelinePreviewState('正在获取安全预览地址...'); + try{ + const response=await fetch( + `/api/tasks/${encodeURIComponent(taskId)}/clips/${encodeURIComponent(clipId)}/media-token`, + {method:'POST',headers:{'Content-Type':'application/json'}} + ); + const data=await response.json().catch(()=>({})); + if(!timelinePreviewStillCurrent(taskId,key,requestId))return; + if(!response.ok){ + const error=new Error('media token request failed'); + error.status=response.status; + throw error; + } + const mediaUrl=safeTimelineMediaUrl(data?.media_url,taskId,clipId); + if(!mediaUrl){ + const error=new Error('unsafe media url'); + error.status=0; + throw error; + } + if(!timelinePreviewStillCurrent(taskId,key,requestId))return; + const video=byId('timelinePreviewVideo'); + if(!video)return; + video.onerror=()=>{ + if(timelinePreviewStillCurrent(taskId,key,requestId)){ + showTimelinePreviewState('短片播放器加载失败:媒体暂时不可用,请稍后重试。','error'); + } + }; + video.src=mediaUrl; + video.hidden=false; + byId('timelinePreviewState').className='timeline-preview-state success'; + byId('timelinePreviewState').textContent='已打开安全短片预览,可使用播放器控件播放。'; + video.load?.(); + }catch(error){ + if(!timelinePreviewStillCurrent(taskId,key,requestId))return; + showTimelinePreviewState(timelinePreviewFailureMessage(Number(error?.status)||0),'error'); + } +} + +function clearTaskArtifacts(){ + clearResultArtifact(); + clearQualityOverview(); + clearReadonlyTimeline(); + const report=byId('report'); + report.hidden=true; + report.textContent=''; + report.innerHTML=''; +} + +function formatQualityDuration(value){ + const seconds=Math.max(0,Math.round(Number(value)||0)); + const minutes=Math.floor(seconds/60); + const rest=seconds%60; + return minutes?`${minutes}分${String(rest).padStart(2,'0')}秒`:`${rest}秒`; +} + +function formatQualityNumber(value,suffix=''){ + if(value===null||value===undefined||value==='')return null; + const number=Number(value); + if(!Number.isFinite(number))return null; + return `${Number.isInteger(number)?number:number.toFixed(1)}${suffix}`; +} + +function renderQualityOverview(overview){ + if(!overview||typeof overview!=='object'){ + clearQualityOverview(); + return; + } + const quality=byId('qualityOverview'); + const duration=overview.duration_distribution||{}; + const durationBuckets=duration.buckets||{}; + const scores=overview.score_distribution||{}; + const anchors=overview.anchor_source_counts&&typeof overview.anchor_source_counts==='object' + ?Object.entries(overview.anchor_source_counts):[]; + const clips=Array.isArray(overview.clips)?overview.clips:[]; + const edgeCandidates=Array.isArray(overview.edge_candidates)?overview.edge_candidates:[]; + const clipRows=clips.map((clip,index)=>{ + const score=formatQualityNumber(clip?.score,' 分')||'投稿价值未记录'; + const peak=formatQualityNumber(clip?.peak_density,' 条/分钟')||'峰值未记录'; + return `
  • +
    ${index+1}${esc(clip?.title||'未命名切片')}
    +
    + ${esc(formatQualityDuration(clip?.duration))} + ${esc(score)} + ${esc(peak)} + ${esc(clip?.anchor_source||'锚点未记录')} +
    +

    ${esc(clip?.reason||'投稿价值理由未记录')}

    +
  • `; + }).join(''); + const edgeRows=edgeCandidates.map(candidate=>` +
  • +
    ${esc(candidate?.title||'未命名候选')}${esc(candidate?.time_range||'时间未记录')} · ${esc(formatQualityNumber(candidate?.score,' 分')||'分数未记录')}
    +

    ${esc(candidate?.reason||'投稿价值理由未记录')}

    +
  • `).join(''); + const anchorText=anchors.length + ?anchors.map(([source,count])=>`${esc(source)} ${Math.max(0,Number(count)||0)}`).join(' · ') + :'锚点来源未记录'; + const clipsTruncated=Math.max(0,Number(overview.clips_truncated_count)||0); + const edgesTruncated=Math.max(0,Number(overview.edge_candidates_truncated_count)||0); + quality.innerHTML=` +
    +

    结果质量概览

    仅用于排序和选择,不代表每小时配额。

    +
    +
    + 最终切片 ${Math.max(0,Number(overview.final_slice_count)||0)} 个 + 总时长 ${esc(formatQualityDuration(duration.total_seconds))} + 有评分 ${Math.max(0,Number(scores.scored_count)||0)} 个 + 含弹幕峰值 ${Math.max(0,Number(overview.danmaku_peak_count)||0)} 个 + 边缘候选 ${Math.max(0,Number(overview.edge_candidate_count)||0)} 个 +
    +
    +
    时长分布短于 1分30秒 ${Math.max(0,Number(durationBuckets.under_90_seconds)||0)} · 1分30秒–3分钟 ${Math.max(0,Number(durationBuckets.from_90_to_179_seconds)||0)} · 至少 3分钟 ${Math.max(0,Number(durationBuckets.at_least_180_seconds)||0)}
    +
    时长范围${esc(formatQualityDuration(duration.minimum_seconds))}–${esc(formatQualityDuration(duration.maximum_seconds))},平均 ${esc(formatQualityDuration(duration.average_seconds))}
    +
    锚点来源${anchorText}
    +
    +

    最终切片 · 投稿价值降序

    ${clipsTruncated?`另有 ${clipsTruncated} 条未在紧凑摘要中展示`:''}
    + ${clipRows?`
      ${clipRows}
    `:'
    本次没有最终切片。
    '} +

    边缘候选 ${Math.max(0,Number(overview.edge_candidate_count)||0)} 个

    60 ≤ 投稿价值 < 75${edgesTruncated?` · 另有 ${edgesTruncated} 条未展示`:''}
    + ${edgeRows?`
      ${edgeRows}
    `:'
    没有接近当前过线门槛的候选。
    '}`; + quality.hidden=false; +} + +function formatTimelineTime(value){ + const seconds=Math.max(0,Math.round(Number(value)||0)); + const hours=Math.floor(seconds/3600); + const minutes=Math.floor((seconds%3600)/60); + const rest=seconds%60; + return hours + ?`${hours}:${String(minutes).padStart(2,'0')}:${String(rest).padStart(2,'0')}` + :`${minutes}:${String(rest).padStart(2,'0')}`; +} + +function timelineRecords(data){ + const clips=Array.isArray(data?.clips)?data.clips:[]; + const candidates=Array.isArray(data?.edge_candidates)?data.edge_candidates:[]; + return [ + ...clips.map(record=>({...record,kind:'clip',kindLabel:'最终切片'})), + ...candidates.map(record=>({...record,kind:'candidate',kindLabel:'边缘候选'})), + ].filter(record=>String(record?.id||'').trim()&&Number.isFinite(Number(record?.start))&&Number.isFinite(Number(record?.end))&&Number(record.end)>Number(record.start)); +} + +function timelineIntegrityReasons(reasons){ + const labels={ + clips_missing:'最终切片数据缺失', + edge_candidates_missing:'边缘候选数据缺失', + video_duration_invalid:'整场时长缺失或无效', + clips_limit:'最终切片数量达到展示上限', + edge_candidates_limit:'边缘候选数量达到展示上限', + payload_limit:'时间轴响应达到大小上限', + text_limit:'部分说明文字达到长度上限', + invalid_record:'存在无法读取的记录', + duplicate_id:'存在重复记录 ID', + }; + return [...new Set((Array.isArray(reasons)?reasons:[]).map(reason=>labels[reason]||String(reason)).filter(Boolean))]; +} + +function setTimelineIntegrity(data){ + const integrity=byId('timelineIntegrity'); + if(!integrity)return; + const reasons=timelineIntegrityReasons(data?.incomplete_reasons); + const messages=[]; + if(data?.complete===false)messages.push('数据不完整,未记录的时间不会被猜测。'); + if(data?.truncated)messages.push('数据已截断,当前只展示已返回记录。'); + if(reasons.length)messages.push(`原因:${reasons.join('、')}`); + integrity.textContent=messages.join(' '); + integrity.classList.toggle('warning',messages.length>0); + integrity.hidden=messages.length===0; +} + +function selectTimelineRecord(key){ + if(!readonlyTimeline)return; + const record=timelineRecords(readonlyTimeline).find(item=>`${item.kind}:${item.id}`===String(key)); + if(!record)return; + selectedTimelineKey=`${record.kind}:${record.id}`; + document.querySelectorAll('[data-timeline-key]').forEach(element=>{ + const selected=element.dataset.timelineKey===selectedTimelineKey; + element.classList.toggle('selected',selected); + element.setAttribute('aria-pressed',String(selected)); + }); + const details=byId('timelineDetails'); + if(!details)return; + details.innerHTML=` +
    ${esc(record.kindLabel)}${esc(record.title||'未命名')}
    +
    ID:${esc(record.id)}start:${esc(formatTimelineTime(record.start))} · end:${esc(formatTimelineTime(record.end))}
    +
    来源
    ${esc(record.source||'未知来源')}
    原因
    ${esc(record.reason||'未记录原因')}
    `; + details.hidden=false; + openTimelinePreview(record,selectedTimelineKey); +} + +function renderReadonlyTimeline(data){ + const section=byId('readonlyTimeline'); + if(!section)return; + readonlyTimeline=data&&typeof data==='object'?data:null; + section.hidden=false; + const duration=Number(data?.video_duration); + const validDuration=Number.isFinite(duration)&&duration>0; + const records=timelineRecords(data); + const filter=byId('timelineFilter')?.value||'all'; + const visibleRecords=filter==='all'?records:records.filter(record=>record.kind===filter); + const selectedIsVisible=visibleRecords.some(record=>`${record.kind}:${record.id}`===selectedTimelineKey); + if(selectedTimelineKey&&!selectedIsVisible){ + selectedTimelineKey=''; + closeTimelinePreview(); + const details=byId('timelineDetails'); + if(details){details.hidden=true;details.textContent='';details.innerHTML='';} + } + const state=byId('timelineState'); + if(state)state.textContent=data?.complete===false?'不完整':data?.truncated?'已截断':'完整'; + setTimelineIntegrity(data); + const count=byId('timelineCount'); + if(count)count.textContent=`${visibleRecords.length} 条记录 · 全场 ${validDuration?formatTimelineTime(duration):'时长未记录'}`; + + const scale=byId('timelineScale'); + const track=byId('timelineTrack'); + const plot=track?.parentElement; + if(scale)scale.innerHTML=validDuration + ?[0,.25,.5,.75,1].map(ratio=>`${esc(formatTimelineTime(duration*ratio))}`).join('') + :'缺少整场时长,无法绘制比例刻度'; + if(plot)plot.classList.toggle('timeline-plot-invalid',!validDuration); + if(track)track.innerHTML=validDuration&&visibleRecords.length + ?visibleRecords.map(record=>{ + const left=Math.max(0,Math.min(100,Number(record.start)/duration*100)); + const width=Math.max(0,Math.min(100-left,(Number(record.end)-Number(record.start))/duration*100)); + const key=`${record.kind}:${record.id}`; + return ``; + }).join('') + :`
    ${validDuration?'当前筛选没有记录':'缺少整场时长,暂不绘制时间块'}
    `; + const cards=byId('timelineCards'); + if(cards)cards.innerHTML=visibleRecords.length + ?visibleRecords.map(record=>{ + const key=`${record.kind}:${record.id}`; + return ``; + }).join('') + :'
    当前筛选没有可展示的记录。
    '; + document.querySelectorAll('[data-timeline-key]').forEach(element=>{ + element.addEventListener('click',()=>selectTimelineRecord(element.dataset.timelineKey)); + }); + if(selectedTimelineKey)selectTimelineRecord(selectedTimelineKey); +} + +function renderTimelineFailure(message){ + const section=byId('readonlyTimeline'); + if(!section)return; + readonlyTimeline=null; + selectedTimelineKey=''; + closeTimelinePreview(); + section.hidden=false; + byId('timelineState').textContent='读取失败'; + byId('timelineIntegrity').textContent=message||'独立时间轴读取失败'; + byId('timelineIntegrity').className='timeline-integrity warning'; + byId('timelineIntegrity').hidden=false; + byId('timelineScale').textContent=''; + byId('timelineTrack').innerHTML='
    当前任务没有可读取的时间轴。
    '; + byId('timelineCards').innerHTML=''; + byId('timelineDetails').hidden=true; +} + +async function loadReadonlyTimeline(taskId){ + clearReadonlyTimeline(); + const section=byId('readonlyTimeline'); + if(!section||!taskId)return; + section.hidden=false; + byId('timelineState').textContent='读取中'; + const filter=byId('timelineFilter'); + if(filter&&!filter.dataset.bound){ + filter.addEventListener('change',()=>{if(readonlyTimeline)renderReadonlyTimeline(readonlyTimeline)}); + filter.dataset.bound='true'; + } + try{ + const response=await fetch(`/api/tasks/${encodeURIComponent(taskId)}/timeline`); + const data=await response.json().catch(()=>({})); + if(!response.ok)throw new Error(data.error||`时间轴读取失败 (${response.status})`); + if(currentTaskId!==taskId)return; + renderReadonlyTimeline(data); + }catch(error){ + if(currentTaskId===taskId)renderTimelineFailure(`独立时间轴读取失败:${error.message}`); + } +} + +function renderResultArtifact(taskId,result){ + if(!result||!result.artifact_dir){clearResultArtifact(!taskId?.startsWith('timeline_opt_'));return} + resultTaskId=typeof taskId==='string'&&taskId.trim()?taskId:null; + currentTaskResult={kind:taskId?.startsWith('timeline_opt_')?'timeline':'pipeline'}; + const lines=[`整理包:${result.artifact_dir}`]; + if(result.overview_path)lines.push(`优先查看:${result.overview_path}`); + if(result.slice_dir)lines.push(`实际切片:${result.slice_dir}`); + byId('resultPaths').textContent=lines.join('\n'); + byId('resultPaths').title=lines.join('\n'); + byId('resultArtifact').hidden=false; + updateCurrentTaskContext(); +} + +async function loadTaskResult(taskId){ + const response=await fetch(`/api/tasks/${encodeURIComponent(taskId)}/result`); + if(!response.ok){const data=await response.json().catch(()=>({}));throw new Error(data.error||'任务结果读取失败')} + return response.json(); +} + +async function renderCompletedReport(taskId,result){ + if(currentTaskId!==taskId)return; + const report=byId('report'); + if(!result?.report_available){report.hidden=true;report.textContent='';report.innerHTML='';return} + report.hidden=false; + report.textContent='正在读取完整话题分析报告...'; + try{ + const response=await fetch(`/api/tasks/${encodeURIComponent(taskId)}/report`); + if(currentTaskId!==taskId)return; + if(!response.ok){const data=await response.json().catch(()=>({}));throw new Error(data.error||'完整报告读取失败')} + const markdown=await response.text(); + if(currentTaskId!==taskId)return; + report.innerHTML=renderReport(markdown); + }catch(error){ + if(currentTaskId===taskId)report.textContent=`完整报告读取失败:${error.message}`; + } +} + +async function openResultDirectory(){ + if(!resultTaskId){setNotice('当前没有可打开的结果目录','warning');return} + try{ + await jsonRequest('/api/open-result-directory',{method:'POST',body:JSON.stringify({task_id:resultTaskId})}); + setNotice('已在资源管理器中打开结果目录','success'); + }catch(error){setNotice(`结果目录打开失败:${error.message}`,'error')} +} + +function taskTypeLabel(taskId){ + if(taskId?.startsWith('timeline_opt_'))return '人工时间轴优化'; + if(taskId?.startsWith('clip_review_'))return '候选片段复核'; + return '智能分析与切片'; +} + +const TASK_STATUS_UI={ + queued:{label:'排队中',visual:'running'}, + running:{label:'进行中',visual:'running'}, + done:{label:'已完成',visual:'done'}, + error:{label:'失败',visual:'error'}, + cancelled:{label:'已取消',visual:'error'}, + interrupted:{label:'已中断',visual:'error'}, +}; + +function isRelevantTask(data,taskId=''){ + const id=String(data?.task_id||taskId||''); + return id.startsWith('pipeline_')||id.startsWith('timeline_opt_')||id.startsWith('clip_review_'); +} + +function taskTimestamp(data,key){ + const value=Number(data?.[key]); + if(Number.isFinite(value))return value; + if(key==='updated_at'){ + const created=Number(data?.created_at); + if(Number.isFinite(created))return created; + } + return 0; +} + +function isActiveTask(data){ + return data?.status==='queued'||data?.status==='running'; +} + +function shouldAcceptTaskSnapshot(data){ + if(!currentTaskId||!currentTaskSnapshot)return true; + if(data.task_id===currentTaskId)return true; + const incomingActive=isActiveTask(data); + const currentActive=isActiveTask(currentTaskSnapshot); + if(incomingActive!==currentActive)return incomingActive; + return taskTimestamp(data,'updated_at')>taskTimestamp(currentTaskSnapshot,'updated_at'); +} + +function newestTask(tasks){ + return tasks.reduce((latest,task)=>{ + if(!latest)return task; + const updatedDiff=taskTimestamp(task,'updated_at')-taskTimestamp(latest,'updated_at'); + if(updatedDiff!==0)return updatedDiff>0?task:latest; + const createdDiff=taskTimestamp(task,'created_at')-taskTimestamp(latest,'created_at'); + if(createdDiff!==0)return createdDiff>0?task:latest; + return String(task.task_id).localeCompare(String(latest.task_id))>0?task:latest; + },null); +} + +function selectInitTask(snapshot){ + const entries=Array.isArray(snapshot) + ?snapshot.map(task=>[task?.task_id,task]) + :Object.entries(snapshot||{}); + const related=entries.map(([taskId,task])=>({...task,task_id:task?.task_id||taskId})).filter(task=>isRelevantTask(task)); + const active=newestTask(related.filter(task=>task.status==='queued'||task.status==='running')); + if(active)return active; + const interrupted=newestTask(related.filter(task=>task.status==='interrupted')); + if(interrupted)return interrupted; + return newestTask(related.filter(task=>task.status==='done'||task.status==='error'||task.status==='cancelled')); +} + +function taskDetailLines(data){ + const lines=[]; + const add=value=>{ + if(typeof value!=='string')return; + const text=value.trim(); + if(text&&!lines.includes(text))lines.push(text); + }; + add(data.progress); + add(data.message); + add(data.error); + add(data.error_summary); + if(data.status==='interrupted'){ + const recovery=data.metadata?.startup_recovery||data.startup_recovery; + add(recovery?.previous_message); + const checkpoint=recovery?.checkpoint; + if(checkpoint&&typeof checkpoint==='object'){ + const checkpointProgress=typeof checkpoint.progress==='string'?checkpoint.progress.trim():''; + const counters=Number.isFinite(Number(checkpoint.step))&&Number.isFinite(Number(checkpoint.total))&&Number(checkpoint.total)>0 + ?`(${Number(checkpoint.step)}/${Number(checkpoint.total)})`:''; + if(checkpointProgress)add(`中断前检查点:${checkpointProgress}${counters}`); + } + add(recovery?.next_action); + add('续跑提示:保留原资源与主播配置重新发起任务时,可由既有流程检查可用检查点;页面不会自动恢复或绕过校验。'); + } + return lines.length?lines:['等待任务状态...']; +} + +function renderTaskProgress(data){ + const percent=data.total>0?Math.max(0,Math.min(100,Math.round(data.step/data.total*100))):0; + const status=TASK_STATUS_UI[data.status]?data.status:'error'; + const presentation=TASK_STATUS_UI[status]; + const active=status==='queued'||status==='running'; + const details=taskDetailLines({...data,status}).map(line=>`
    ${esc(line)}
    `).join(''); + if(currentTaskId!==data.task_id){ + cancelBusy=false; + clearTaskArtifacts(); + } + if(!selVideo&&acceptUnboundTask&&(!currentTaskId||!contextTaskId||contextTaskId===currentTaskId))contextTaskId=data.task_id||null; + currentTaskId=data.task_id||null; + currentTaskSnapshot={...data,status,task_id:currentTaskId}; + byId('progressBox').innerHTML=` +
    +
    + ${esc(taskTypeLabel(data.task_id))} + ${presentation.label} +
    + ${status==='running'?`
    `:''} +
    ${details}
    +
    `; + byId('activityState').textContent=status==='running'?`${percent}% · 正在处理`:presentation.label; + taskBusy=active; + if(!active)cancelBusy=false; + updateActions(); +} + +async function restoreCompletedTask(data){ + const taskId=data.task_id; + try{ + const result=await loadTaskResult(data.task_id); + if(currentTaskId!==taskId)return; + if(taskId.startsWith('timeline_opt_')){ + optimizedTimeline={videoPath:result.video_path,sourcePath:(result.manual_timeline||{}).path,jsonPath:result.optimized_json_path,mdPath:result.optimized_md_path,profileId:result.streamer_profile_id}; + currentTaskResult={kind:'timeline'}; + renderOptimizedTimeline(); + }else{ + await renderCompletedReport(taskId,result); + } + if(currentTaskId!==taskId)return; + renderQualityOverview(result?.quality_overview); + renderResultArtifact(taskId,result); + if(taskId.startsWith('pipeline_')||taskId.startsWith('clip_review_'))await loadReadonlyTimeline(taskId); + setNotice(`${taskTypeLabel(taskId)}已完成`,'success'); + }catch(error){ + if(currentTaskId===taskId)setNotice(`任务已完成,但结果入口恢复失败:${error.message}`,'warning'); + } +} + +async function handleTaskSnapshot(data){ + if(!selVideo&&!acceptUnboundTask&&!contextTaskId)return; + if(!isRelevantTask(data)||!shouldAcceptTaskSnapshot(data))return; + renderTaskProgress(data); + if(data.status==='done')await restoreCompletedTask(data); + else if(data.status==='error')setNotice(data.progress||data.error||data.error_summary||'任务执行失败','error'); + else if(data.status==='cancelled')setNotice(data.message||data.progress||'任务已取消','warning'); + else if(data.status==='interrupted')setNotice('检测到上次未完成的任务,请查看中断原因和检查点续跑提示。','warning'); +} + +async function cancelCurrentTask(){ + if(!currentTaskId||!taskBusy||cancelBusy)return; + const taskId=currentTaskId; + cancelBusy=true; + updateActions(); + try{ + const response=await fetch(`/api/tasks/${encodeURIComponent(taskId)}/cancel`,{method:'POST',headers:{'Content-Type':'application/json'}}); + const result=await response.json().catch(()=>({})); + if(!response.ok||result.error){ + if(response.status===404)throw new Error('任务不存在,可能已被清理或服务已重启'); + if(response.status===409){ + if(result.status&&TASK_STATUS_UI[result.status])renderTaskProgress({...currentTaskSnapshot,status:result.status,progress:result.error||currentTaskSnapshot?.progress}); + throw new Error(result.error||'任务状态已变化,当前不能取消'); + } + throw new Error(result.error||`取消请求失败 (${response.status})`); + } + if(result.task)renderTaskProgress({task_id:taskId,...result.task}); + setNotice('取消请求已提交,后台会在安全检查点停止任务','success'); + }catch(error){ + setNotice(`取消任务失败:${error.message}`,'error'); + }finally{ + cancelBusy=false; + updateActions(); + } +} + +function connectSSE(){ + if(sse)return; + const source=new EventSource('/api/events'); + sse=source; + source.addEventListener('init',async event=>{ + const selected=selectInitTask(JSON.parse(event.data)); + if(selected)await handleTaskSnapshot(selected); + }); + source.addEventListener('task_update',async event=>{ + const data=JSON.parse(event.data); + await handleTaskSnapshot(data); + }); + source.onopen=()=>{if(sse===source&&byId('activityState').textContent==='连接恢复中')byId('activityState').textContent=currentTaskSnapshot?TASK_STATUS_UI[currentTaskSnapshot.status]?.label||'已连接':'等待启动'}; + source.onerror=()=>{if(sse===source)byId('activityState').textContent='连接恢复中'}; +} + +function renderVideoList(videos){ + const list=byId('vlist'); + list.replaceChildren(); + videos.forEach(video=>{ + const item=document.createElement('button'); + item.type='button'; + item.className='video-item'; + item.dataset.videoPath=video.path; + item.title=video.path; + item.addEventListener('click',()=>pick(item,video)); + const name=document.createElement('span'); + name.className='video-name'; + name.textContent=video.name; + const ass=document.createElement('span'); + ass.className=`badge ${video.has_ass?'info':''}`; + ass.textContent=video.has_ass?'有弹幕':'无弹幕'; + const srt=document.createElement('span'); + srt.className=`badge ${video.has_srt?'success':''}`; + srt.textContent=video.has_srt?'有字幕':'无字幕'; + item.append(name,ass,srt); + list.appendChild(item); + }); + if(!videos.length)list.innerHTML='
    目录中没有可分析的录播文件。
    '; +} + +function clearSelectionState(){ + acceptUnboundTask=false; + selVideo=null; + selAss=null; + selectedVideoMeta=null; + contextTaskId=null; + currentTaskId=null; + currentTaskSnapshot=null; + taskBusy=false; + cancelBusy=false; + clearOptimizedTimeline(); + clearTaskArtifacts(); + byId('selectedName').textContent=''; + byId('selectedName').title=''; + byId('selectedPath').textContent=''; + byId('selectedPath').title=''; + byId('selectedSummary').hidden=true; + byId('selectionState').textContent='未选择录播'; + byId('selectionState').title=''; + byId('progressBox').innerHTML='
    选择录播后显示任务进度
    '; + byId('activityState').textContent='等待选择'; +} + +function videoPathKey(path){ + return String(path||'').replace(/[\\/]+/g,'/').replace(/\/$/,'').toLocaleLowerCase(); +} + +function restoreSelectionIfPresent(videos,previousPath){ + const previousKey=videoPathKey(previousPath); + if(!previousKey)return false; + const match=videos.find(video=>videoPathKey(video.path)===previousKey); + if(!match)return false; + const item=[...document.querySelectorAll('.video-item')].find(candidate=>videoPathKey(candidate.dataset.videoPath)===previousKey); + if(!item)return false; + pick(item,match); + return true; +} + +async function scan(){ + if(scanBusy||taskBusy)return; + rememberWorkspacePaths(); + const previousPath=selVideo; + scanBusy=true; + clearSelectionState(); + updateActions(); + hideScanRecovery(); + setNotice('正在扫描录播目录...'); + byId('vlist').innerHTML='
    正在读取视频、字幕和弹幕文件...
    '; + try{ + const result=await jsonRequest('/api/scan',{method:'POST',body:JSON.stringify({video_dir:byId('videoDir').value})}); + const videos=result.videos||[]; + renderVideoList(videos); + byId('videoCount').textContent=`${videos.length} 个可用文件`; + if(videos.length){ + rememberLastValidVideoDir(); + restoreSelectionIfPresent(videos,previousPath); + setNotice(`扫描完成,找到 ${videos.length} 个录播文件`,'success'); + }else{ + showScanRecovery('empty'); + setNotice('扫描完成,但目录中没有找到录播。当前没有可执行选择,请重新扫描或恢复上次有效目录','warning'); + } + }catch(error){ + renderVideoList([]); + byId('videoCount').textContent='0 个可用文件'; + showScanRecovery('error'); + setNotice(`扫描失败:${error.message}`,'error'); + }finally{scanBusy=false;updateActions()} +} + +async function loadTimelines(){ + try{ + const result=await jsonRequest('/api/timelines'); + const select=byId('timelineSelect'); + select.replaceChildren(new Option('选择 DOCX','')); + (result.files||[]).forEach(file=>select.add(new Option(file.name,file.path))); + if(byId('timelineMode').value==='manual')setNotice(`已载入 ${(result.files||[]).length} 个人工时间轴`,'success'); + }catch(error){setNotice(`时间轴列表加载失败:${error.message}`,'error')} +} + +async function loadStreamerProfiles(){ + const select=byId('streamerProfile'); + try{ + const result=await jsonRequest('/api/streamer-profiles'); + const remembered=localStorage.getItem(STREAMER_PROFILE_STORAGE_KEY)||'auto'; + select.replaceChildren(); + (result.profiles||[]).forEach(profile=>select.add(new Option(profile.label,profile.id))); + select.value=[...select.options].some(option=>option.value===remembered)?remembered:'auto'; + }catch(error){select.replaceChildren(new Option('自动识别','auto'))} + updateCurrentTaskContext(); +} + +function selectedStreamerProfile(){return byId('streamerProfile').value||'auto'} +function onStreamerProfileChange(){try{localStorage.setItem(STREAMER_PROFILE_STORAGE_KEY,selectedStreamerProfile())}catch(error){}clearOptimizedTimeline();updateCurrentTaskContext()} + +function toggleTimelineMode(){ + const mode=byId('timelineMode').value; + byId('timelineManualRow').hidden=mode!=='manual'; + if(mode!=='manual')clearOptimizedTimeline(); + if(mode==='manual')loadTimelines(); + updateActions(); +} + +function pick(element,video){ + document.querySelectorAll('.video-item').forEach(item=>item.classList.remove('selected')); + element.classList.add('selected'); + selVideo=video.path; + selectedVideoMeta={...video,name:safeFileName(video.name||video.path)}; + contextTaskId=null; + selAss=video.has_ass?replaceFileExtension(video.path,'.ass'):''; + byId('selectedName').textContent=video.name; + byId('selectedName').title=video.name; + byId('selectedPath').textContent=video.path; + byId('selectedPath').title=video.path; + byId('selectedSummary').hidden=false; + byId('selectionState').textContent=video.name; + byId('selectionState').title=video.path; + clearOptimizedTimeline(); + clearTaskArtifacts(); + setNotice(`已选择:${video.name}`,'success'); + updateActions(); +} + +function onTimelineSelection(path){byId('timelinePath').value=path;clearOptimizedTimeline();updateActions()} +function clearOptimizedTimeline(){optimizedTimeline=null;byId('timelineArtifact').hidden=true;byId('timelineArtifact').textContent='';updateCurrentTaskContext()} +function renderOptimizedTimeline(){ + if(!optimizedTimeline?.jsonPath){clearOptimizedTimeline();return} + const text=`优化 JSON:${optimizedTimeline.jsonPath}\n审阅文档:${optimizedTimeline.mdPath||'未生成'}`; + byId('timelineArtifact').textContent=text; + byId('timelineArtifact').title=text; + byId('timelineArtifact').hidden=false; + updateCurrentTaskContext(); +} + +async function runAction({url,body,starting,failure}){ + contextTaskId=null; + taskBusy=true; + updateActions(); + byId('progressBox').innerHTML=`
    ${esc(starting)}
    `; + byId('activityState').textContent='正在启动'; + setNotice(starting); + try{ + const result=await jsonRequest(url,{method:'POST',body:JSON.stringify(body)}); + if(result.task_id&¤tTaskSnapshot?.task_id!==result.task_id){ + contextTaskId=result.task_id; + renderTaskProgress({task_id:result.task_id,status:'queued',progress:starting,step:0,total:100,created_at:Date.now()/1000,updated_at:Date.now()/1000}); + }else if(result.task_id){ + contextTaskId=result.task_id; + updateCurrentTaskContext(); + } + setNotice('任务已启动,可在右侧查看实时进度','success'); + }catch(error){ + contextTaskId=null; + taskBusy=false; + updateActions(); + byId('activityState').textContent='启动失败'; + setNotice(`${failure}:${error.message}`,'error'); + } +} + +async function optimizeTimeline(){ + if(!selVideo){setNotice('请先从列表选择录播','warning');return} + rememberWorkspacePaths(); + const timelinePath=byId('timelinePath').value.trim(); + if(byId('timelineMode').value!=='manual'||!timelinePath){setNotice('仅优化时间轴需要手动选择 DOCX 文件','warning');return} + clearOptimizedTimeline();clearTaskArtifacts(); + await runAction({url:'/api/optimize-manual-timeline',starting:'正在启动人工时间轴优化...',failure:'时间轴优化启动失败',body:{flv_path:selVideo,ass_path:selAss,manual_timeline_path:timelinePath,output_dir:document.getElementById('outputDir').value,streamer_profile_id:selectedStreamerProfile()}}); +} + +async function startPipeline(){ + if(!selVideo){setNotice('请先从列表选择录播','warning');return} + rememberWorkspacePaths(); + const mode=byId('timelineMode').value; + const timelinePath=byId('timelinePath').value.trim(); + if(mode==='manual'&&!timelinePath){setNotice('请选择或填写辅助时间轴 DOCX','warning');return} + const optimizedPath=optimizedTimeline&&optimizedTimeline.videoPath===selVideo&&optimizedTimeline.sourcePath===timelinePath&&optimizedTimeline.profileId===selectedStreamerProfile()?optimizedTimeline.jsonPath:''; + clearTaskArtifacts(); + await runAction({url:'/api/start-pipeline',starting:'正在启动完整分析与切片...',failure:'完整分析启动失败',body:{flv_path:selVideo,ass_path:selAss,output_dir:document.getElementById('outputDir').value,manual_timeline_mode:mode,manual_timeline_path:timelinePath,optimized_timeline_path:optimizedPath,streamer_profile_id:selectedStreamerProfile()}}); +} + +async function retryClipReview(){ + if(!selVideo){setNotice('请先从列表选择录播','warning');return} + rememberWorkspacePaths(); + clearTaskArtifacts(); + await runAction({url:'/api/retry-clip-review',starting:'正在启动候选片段复核...',failure:'候选复核启动失败',body:{flv_path:selVideo,ass_path:selAss,output_dir:document.getElementById('outputDir').value,streamer_profile_id:selectedStreamerProfile()}}); +} + +// 页面控件事件统一在脚本内绑定,模板不写事件属性 +function bindPageEvents(){ + const bindings=[ + ['contextOpenResultButton','click',()=>openResultDirectory()], + ['rescanButton','click',()=>scan()], + ['restoreLastValidDirButton','click',()=>restoreLastValidDirectory()], + ['optimizeButton','click',()=>optimizeTimeline()], + ['retryButton','click',()=>retryClipReview()], + ['startButton','click',()=>startPipeline()], + ['scanButton','click',()=>scan()], + ['streamerProfile','change',()=>onStreamerProfileChange()], + ['timelineMode','change',()=>toggleTimelineMode()], + ['refreshTimelineButton','click',()=>loadTimelines()], + ['timelineSelect','change',event=>onTimelineSelection(event.currentTarget.value)], + ['timelinePath','input',()=>{clearOptimizedTimeline();updateActions()}], + ['cancelTaskButton','click',()=>cancelCurrentTask()], + ['closeTimelinePreviewButton','click',()=>closeTimelinePreview()], + ['openResultButton','click',()=>openResultDirectory()], + ]; + for(const [id,type,handler] of bindings)byId(id).addEventListener(type,handler); +} + +restoreWorkspacePaths(); +bindPageEvents(); +connectSSE(); +loadStreamerProfiles(); +loadAsrStatus(); +toggleTimelineMode(); +scan(); diff --git a/src/autoslice/resources/templates/topic_v2.html b/src/autoslice/resources/templates/topic_v2.html index abdb86a..9a051e9 100644 --- a/src/autoslice/resources/templates/topic_v2.html +++ b/src/autoslice/resources/templates/topic_v2.html @@ -32,7 +32,7 @@
    结果目录
    暂无结果
    - + 字幕校对 AutoCover
    @@ -52,8 +52,8 @@

    智能分析与切片

    @@ -66,11 +66,11 @@

    智能分析与切片

    更多操作
    - - + +
    - + @@ -91,7 +91,7 @@

    新建分析任务

    - +
    @@ -128,28 +128,28 @@

    新建分析任务

    -
    - - +
    @@ -167,7 +167,7 @@

    任务与结果

    任务启动后,这里会持续显示分析和切片进度。
    - +
    @@ -219,1067 +219,7 @@

    只读时间轴

    - + + diff --git a/tests/integration/test_app.py b/tests/integration/test_app.py index 490db2f..df858db 100644 --- a/tests/integration/test_app.py +++ b/tests/integration/test_app.py @@ -89,6 +89,21 @@ def _temporary_path_suffix(path): return None +def _topic_page_html_and_script(test_case, client): + """主工作台页面及其外置脚本,都经 Flask 路由读取。""" + + response = client.get("/topic-v2") + test_case.assertEqual(response.status_code, 200) + html = response.get_data(as_text=True) + match = re.search(r'', html) + test_case.assertIsNotNone(match) + script_response = client.get(match.group(1)) + test_case.assertEqual(script_response.status_code, 200) + script = script_response.get_data(as_text=True) + script_response.close() + return html, script + + class ResourcePathTests(unittest.TestCase): def test_templates_and_static_files_do_not_depend_on_current_directory(self): previous = Path.cwd() @@ -230,6 +245,9 @@ def test_f1_context_fixed_mock_covers_long_content_zoom_and_desktop_action(self) topic_html = ( project_root / "src" / "autoslice" / "resources" / "templates" / "topic_v2.html" ).read_text(encoding="utf-8") + topic_script = ( + project_root / "src" / "autoslice" / "resources" / "static" / "topic_v2.js" + ).read_text(encoding="utf-8") subtitle_html = ( project_root / "src" @@ -267,7 +285,9 @@ def test_f1_context_fixed_mock_covers_long_content_zoom_and_desktop_action(self) workspace = topic_html.index('
    ') self.assertLess(summary, workspace) self.assertEqual(topic_html.count('id="startButton"'), 1) - self.assertIn("已选择录播;可直接执行完整分析与切片", topic_html) + self.assertIn("已选择录播;可直接执行完整分析与切片", topic_script) + self.assertNotIn("", html, flags=re.S) - self.assertTrue(matches) - return html, matches[-1] + return _topic_page_html_and_script(self, self.client) @unittest.skipUnless(shutil.which("node"), "需要 Node.js 检查扫描状态行为") def test_topic_page_scan_state_clears_stale_selection_and_restores_only_present_path(self): @@ -1576,8 +1591,10 @@ def test_workspace_paths_are_generic_configurable_and_browser_persisted(self): self.assertNotIn("personal-recordings", html) self.assertNotIn("private-capture-tool", html) self.assertNotIn(r"X:\personal\recordings", html) - self.assertIn("autoslice.video-dir", html) - self.assertIn("autoslice.output-dir", html) + self.assertIn('id="topicPageConfig"', html) + _html, script = _topic_page_html_and_script(self, self.client) + self.assertIn("autoslice.video-dir", script) + self.assertIn("autoslice.output-dir", script) class SubtitleWorkflowPageTests(unittest.TestCase): @@ -3516,24 +3533,22 @@ def test_open_result_directory_rejects_missing_directory(self): popen.assert_not_called() def test_topic_v2_page_exposes_artifact_paths_and_safe_open_action(self): - response = self.client.get("/topic-v2") - html = response.get_data(as_text=True) + html, script = _topic_page_html_and_script(self, self.client) - self.assertEqual(response.status_code, 200) self.assertIn("打开结果目录", html) - self.assertIn("/api/open-result-directory", html) - self.assertIn("/api/retry-clip-review", html) + self.assertIn("/api/open-result-directory", script) + self.assertIn("/api/retry-clip-review", script) self.assertIn("仅重新复核候选", html) - self.assertIn("result.overview_path", html) - self.assertIn("result.artifact_dir", html) + self.assertIn("result.overview_path", script) + self.assertIn("result.artifact_dir", script) self.assertIn('id="streamerProfile"', html) - self.assertIn("/api/streamer-profiles", html) - self.assertIn("autoslice.streamer-profile", html) + self.assertIn("/api/streamer-profiles", script) + self.assertIn("autoslice.streamer-profile", script) self.assertIn('id="asrStatus"', html) - self.assertIn("'/api/asr-status'", html) - self.assertEqual(html.count("streamer_profile_id:selectedStreamerProfile()"), 3) + self.assertIn("'/api/asr-status'", script) + self.assertEqual(script.count("streamer_profile_id:selectedStreamerProfile()"), 3) self.assertGreaterEqual( - html.count("output_dir:document.getElementById('outputDir').value"), + script.count("output_dir:document.getElementById('outputDir').value"), 2, ) @@ -3567,14 +3582,10 @@ def test_streamer_profiles_api_is_public_only_and_unknown_id_is_rejected(self): @unittest.skipUnless(shutil.which("node"), "需要 Node.js 检查页面脚本语法") def test_topic_v2_page_script_compiles(self): - response = self.client.get("/topic-v2") - scripts = re.findall( - r"", response.get_data(as_text=True), flags=re.S - ) - self.assertTrue(scripts) + _html, script = _topic_page_html_and_script(self, self.client) result = subprocess.run( ["node", "-e", "new Function(require('fs').readFileSync(0,'utf8'))"], - input=scripts[-1], + input=script, text=True, encoding="utf-8", capture_output=True, @@ -3585,13 +3596,7 @@ def test_topic_v2_page_script_compiles(self): @unittest.skipUnless(shutil.which("node"), "需要 Node.js 检查只读时间轴行为") def test_topic_page_renders_independent_timeline_and_explicit_incomplete_state(self): - response = self.client.get("/topic-v2") - self.assertEqual(response.status_code, 200) - scripts = re.findall( - r"", response.get_data(as_text=True), flags=re.S - ) - self.assertTrue(scripts) - script = scripts[-1] + _html, script = _topic_page_html_and_script(self, self.client) script_prefix = script.split("restoreWorkspacePaths();", 1)[0] runtime_assertions = r""" const makeNode=()=>({ @@ -3658,13 +3663,8 @@ def test_topic_page_renders_independent_timeline_and_explicit_incomplete_state(s @unittest.skipUnless(shutil.which("node"), "需要 Node.js 检查时间轴与短片预览联动") def test_topic_page_links_timeline_selection_to_safe_clip_preview_without_stale_responses(self): - response = self.client.get("/topic-v2") - self.assertEqual(response.status_code, 200) - scripts = re.findall( - r"", response.get_data(as_text=True), flags=re.S - ) - self.assertTrue(scripts) - script_prefix = scripts[-1].split("restoreWorkspacePaths();", 1)[0] + _html, script = _topic_page_html_and_script(self, self.client) + script_prefix = script.split("restoreWorkspacePaths();", 1)[0] runtime_assertions = r""" const makeClassList=()=>({ values:new Set(), From dbb899c0a4750f55b9ca1402403446274833f86d Mon Sep 17 00:00:00 2001 From: sc57 Date: Sun, 4 Oct 2026 01:09:02 +0800 Subject: [PATCH 12/14] chore(architecture): refresh snapshot after audit cleanup The baseline on desktop-vnext-dev already lagged the code (199 modules recorded, 204 present), so architecture_snapshot.py --check failed before this branch. Regenerate it after the audit stage 0/1 changes; the private patch total stays at 17. Co-Authored-By: Claude Opus 5.5 --- architecture_baseline.json | 1347 +++++++++++++++++++++--------------- 1 file changed, 808 insertions(+), 539 deletions(-) diff --git a/architecture_baseline.json b/architecture_baseline.json index 7fc67a2..832714f 100644 --- a/architecture_baseline.json +++ b/architecture_baseline.json @@ -2293,7 +2293,7 @@ "autoslice.runtime_config" ], "lines": [ - 10 + 9 ], "to": "autoslice.runtime_config" }, @@ -2303,7 +2303,7 @@ "autoslice.subtitle_workflow.scan_submission_pairs" ], "lines": [ - 11 + 10 ], "to": "autoslice.subtitle_workflow" }, @@ -2341,11 +2341,21 @@ { "from": "autoslice.desktop.qt_app.timeline", "imports": [ - "autoslice.desktop.subtitles.SubtitleDocument" + "autoslice.desktop.snap.SnapEngine" ], "lines": [ 12 ], + "to": "autoslice.desktop.snap" + }, + { + "from": "autoslice.desktop.qt_app.timeline", + "imports": [ + "autoslice.desktop.subtitles.SubtitleDocument" + ], + "lines": [ + 13 + ], "to": "autoslice.desktop.subtitles" }, { @@ -2354,7 +2364,7 @@ "autoslice.transcription.contracts.srt_timestamp_seconds" ], "lines": [ - 13 + 14 ], "to": "autoslice.transcription.contracts" }, @@ -2365,17 +2375,27 @@ "autoslice.desktop.ai_review.document_hash" ], "lines": [ - 49 + 54 ], "to": "autoslice.desktop.ai_review" }, + { + "from": "autoslice.desktop.qt_app.window", + "imports": [ + "autoslice.desktop.commands.CommandDispatcher" + ], + "lines": [ + 55 + ], + "to": "autoslice.desktop.commands" + }, { "from": "autoslice.desktop.qt_app.window", "imports": [ "autoslice.desktop.foundation.DesktopStorage" ], "lines": [ - 50 + 56 ], "to": "autoslice.desktop.foundation" }, @@ -2387,7 +2407,7 @@ "autoslice.desktop.projects.SubmissionProjectService" ], "lines": [ - 51 + 57 ], "to": "autoslice.desktop.projects" }, @@ -2397,17 +2417,18 @@ "autoslice.desktop.qt_app.player.MpvAdapter" ], "lines": [ - 60 + 69 ], "to": "autoslice.desktop.qt_app.player" }, { "from": "autoslice.desktop.qt_app.window", "imports": [ - "autoslice.desktop.qt_app.timeline.SubtitleTimeline" + "autoslice.desktop.qt_app.timeline.SubtitleTimeline", + "autoslice.desktop.qt_app.timeline.TimelineSidePanController" ], "lines": [ - 61 + 70 ], "to": "autoslice.desktop.qt_app.timeline" }, @@ -2417,7 +2438,7 @@ "autoslice.desktop.qt_preview.icons.icon" ], "lines": [ - 52 + 58 ], "to": "autoslice.desktop.qt_preview.icons" }, @@ -2428,7 +2449,7 @@ "autoslice.desktop.qt_preview.theme.SIZES" ], "lines": [ - 53 + 59 ], "to": "autoslice.desktop.qt_preview.theme" }, @@ -2441,17 +2462,37 @@ "autoslice.desktop.qt_preview.window.line" ], "lines": [ - 54 + 60 ], "to": "autoslice.desktop.qt_preview.window" }, + { + "from": "autoslice.desktop.qt_app.window", + "imports": [ + "autoslice.desktop.selection.CueSelection" + ], + "lines": [ + 61 + ], + "to": "autoslice.desktop.selection" + }, + { + "from": "autoslice.desktop.qt_app.window", + "imports": [ + "autoslice.desktop.subtitle_preview.SubtitlePreviewService" + ], + "lines": [ + 62 + ], + "to": "autoslice.desktop.subtitle_preview" + }, { "from": "autoslice.desktop.qt_app.window", "imports": [ "autoslice.desktop.subtitle_render.SubtitleRenderService" ], "lines": [ - 55 + 63 ], "to": "autoslice.desktop.subtitle_render" }, @@ -2461,17 +2502,27 @@ "autoslice.desktop.subtitles.SubtitleDocument" ], "lines": [ - 56 + 64 ], "to": "autoslice.desktop.subtitles" }, + { + "from": "autoslice.desktop.qt_app.window", + "imports": [ + "autoslice.desktop.waveform.WaveformCache" + ], + "lines": [ + 65 + ], + "to": "autoslice.desktop.waveform" + }, { "from": "autoslice.desktop.qt_app.window", "imports": [ "autoslice.subtitle_workflow.DEFAULT_SUBTITLE_STYLE" ], "lines": [ - 57 + 66 ], "to": "autoslice.subtitle_workflow" }, @@ -2481,7 +2532,7 @@ "autoslice.transcription.contracts.srt_timestamp_seconds" ], "lines": [ - 58 + 67 ], "to": "autoslice.transcription.contracts" }, @@ -2537,6 +2588,27 @@ ], "to": "autoslice.desktop.qt_preview.theme" }, + { + "from": "autoslice.desktop.subtitle_preview", + "imports": [ + "autoslice.subtitle_workflow._probe_video_info", + "autoslice.subtitle_workflow.build_ass_document" + ], + "lines": [ + 11 + ], + "to": "autoslice.subtitle_workflow" + }, + { + "from": "autoslice.desktop.subtitle_preview", + "imports": [ + "autoslice.transcription.contracts.SubtitleCue" + ], + "lines": [ + 12 + ], + "to": "autoslice.transcription.contracts" + }, { "from": "autoslice.desktop.subtitle_render", "imports": [ @@ -2640,12 +2712,12 @@ { "from": "autoslice.launcher", "imports": [ - "autoslice.topic_engine.funasr_public_status" + "autoslice.transcription.model_runtime.funasr_public_status" ], "lines": [ 553 ], - "to": "autoslice.topic_engine" + "to": "autoslice.transcription.model_runtime" }, { "from": "autoslice.launcher", @@ -3623,11 +3695,21 @@ "autoslice.transcription.contracts.srt_timestamp_seconds" ], "lines": [ - 23, - 31 + 24, + 32 ], "to": "autoslice.transcription.contracts" }, + { + "from": "autoslice.subtitle_workflow", + "imports": [ + "autoslice.transcription.segments" + ], + "lines": [ + 23 + ], + "to": "autoslice.transcription.segments" + }, { "from": "autoslice.task_registry", "imports": [ @@ -4616,6 +4698,22 @@ ], "to": "autoslice.paths" }, + { + "from": "autoslice.web.app", + "imports": [ + "autoslice.pipeline.optimize_manual_timeline_for_video", + "autoslice.pipeline.retry_clip_review_from_artifacts", + "autoslice.pipeline.run_pipeline", + "autoslice.pipeline.subtitle_title_services" + ], + "lines": [ + 1495, + 1661, + 1710, + 2847 + ], + "to": "autoslice.pipeline" + }, { "from": "autoslice.web.app", "imports": [ @@ -4640,6 +4738,18 @@ ], "to": "autoslice.security_policy" }, + { + "from": "autoslice.web.app", + "imports": [ + "autoslice.slicing.slice_from_marks" + ], + "lines": [ + 1711, + 1754, + 2848 + ], + "to": "autoslice.slicing" + }, { "from": "autoslice.web.app", "imports": [ @@ -4677,18 +4787,18 @@ ], "lines": [ 44, - 874, - 1430, - 1511, - 1566, - 1634, - 2206, - 2222, - 2238, - 2251, - 2314, - 2493, - 2537 + 858, + 1414, + 1496, + 1550, + 1618, + 2191, + 2207, + 2223, + 2236, + 2299, + 2478, + 2522 ], "to": "autoslice.subtitle_workflow" }, @@ -4742,34 +4852,32 @@ { "from": "autoslice.web.app", "imports": [ - "autoslice.topic_engine.ensure_srt", - "autoslice.topic_engine.funasr_public_status", - "autoslice.topic_engine.optimize_manual_timeline_for_video", - "autoslice.topic_engine.retry_clip_review_from_artifacts", - "autoslice.topic_engine.run_pipeline", - "autoslice.topic_engine.slice_from_marks", - "autoslice.topic_engine.subtitle_title_services" + "autoslice.transcription.background_filter" ], "lines": [ - 1512, - 1567, - 1677, - 1726, - 1769, - 2786, - 2862 + 61 ], - "to": "autoslice.topic_engine" + "to": "autoslice.transcription.background_filter" }, { "from": "autoslice.web.app", "imports": [ - "autoslice.transcription.background_filter" + "autoslice.transcription.model_runtime.funasr_public_status" ], "lines": [ - 61 + 2771 ], - "to": "autoslice.transcription.background_filter" + "to": "autoslice.transcription.model_runtime" + }, + { + "from": "autoslice.web.app", + "imports": [ + "autoslice.transcription.workflow.ensure_srt" + ], + "lines": [ + 1551 + ], + "to": "autoslice.transcription.workflow" }, { "from": "autoslice_cover.app", @@ -5508,10 +5616,10 @@ ], "longest_functions": [ { - "end_line": 1104, + "end_line": 1065, "kind": "function", - "line": 624, - "line_count": 481, + "line": 602, + "line_count": 464, "module": "autoslice_cover.app", "path": "src/autoslice_cover/app.py", "qualname": "create_app" @@ -5625,9 +5733,9 @@ "qualname": "load_funasr_model" }, { - "end_line": 1498, + "end_line": 1594, "kind": "function", - "line": 1348, + "line": 1444, "line_count": 151, "module": "autoslice.subtitle_workflow", "path": "src/autoslice/subtitle_workflow.py", @@ -5679,9 +5787,9 @@ "qualname": "slice_from_marks_impl" }, { - "end_line": 747, + "end_line": 731, "kind": "function", - "line": 615, + "line": 599, "line_count": 133, "module": "autoslice.web.app", "path": "src/autoslice/web/app.py", @@ -5724,13 +5832,13 @@ "qualname": "call_compatible_api" }, { - "end_line": 450, + "end_line": 496, "kind": "function", - "line": 326, - "line_count": 125, - "module": "autoslice.analysis.topic.analysis", - "path": "src/autoslice/analysis/topic/analysis.py", - "qualname": "parse_llm_response" + "line": 370, + "line_count": 127, + "module": "autoslice.desktop.qt_app.window", + "path": "src/autoslice/desktop/qt_app/window.py", + "qualname": "DesktopWindow.__init__" } ], "modules": [ @@ -6600,7 +6708,7 @@ }, "module": "autoslice.analysis.manual.timebase", "path": "src/autoslice/analysis/manual/timebase.py", - "sha256": "d1df77e95915faeb01ccdc82635a161c28d00598b66e01ff6c818c0b5f1344f7", + "sha256": "150ecdd0dab70564de84891b0d9a3bdf3de8dadf37c17939ea2e3a504bdc57e5", "top_level_classes": [], "top_level_functions": [ { @@ -7713,7 +7821,7 @@ }, "module": "autoslice.analysis.topic.analysis", "path": "src/autoslice/analysis/topic/analysis.py", - "sha256": "a8899af30e215fd4571cc907c1c404154e454578e5aedb5ab4feec63865e3a13", + "sha256": "5328fe9c49020cb7447d2d7494b211012fa484b8c209f24f4d63e49d3973edef", "top_level_classes": [], "top_level_functions": [ { @@ -7819,7 +7927,7 @@ }, "module": "autoslice.analysis.topic.normalization", "path": "src/autoslice/analysis/topic/normalization.py", - "sha256": "51266eb3cda93aa61203233c19f497832067bb7ac7f400f01b5df40814da187c", + "sha256": "9a2ee0eb5a5a140db389ba18c1b542316ee1ff35d0b642b7d71da86ab41ab875", "top_level_classes": [], "top_level_functions": [ { @@ -8502,6 +8610,35 @@ } ] }, + { + "duplicate_top_level_definitions": [], + "line_count": 31, + "longest_function": { + "end_line": 28, + "kind": "function", + "line": 23, + "line_count": 6, + "qualname": "CommandDispatcher.dispatch" + }, + "module": "autoslice.desktop.commands", + "path": "src/autoslice/desktop/commands.py", + "sha256": "2737631454cc9fe796bc744fb02853311b6cb88afc67e64f4fa5091baac20ee8", + "top_level_classes": [ + { + "end_line": 13, + "kind": "class", + "line": 10, + "name": "Command" + }, + { + "end_line": 31, + "kind": "class", + "line": 16, + "name": "CommandDispatcher" + } + ], + "top_level_functions": [] + }, { "duplicate_top_level_definitions": [], "line_count": 236, @@ -8533,48 +8670,48 @@ }, { "duplicate_top_level_definitions": [], - "line_count": 127, + "line_count": 120, "longest_function": { - "end_line": 127, + "end_line": 120, "kind": "function", - "line": 81, + "line": 74, "line_count": 47, "qualname": "SubmissionProjectService.refresh" }, "module": "autoslice.desktop.projects", "path": "src/autoslice/desktop/projects.py", - "sha256": "ac245f2a84a87aee727300638c8294dfc556068f48f6deeb351c0b530ab4d372", + "sha256": "a6b4f2df5380341d1c17ce6d2fc6903c66a848ae3ac23f1db6700a6927376b07", "top_level_classes": [ { - "end_line": 36, + "end_line": 29, "kind": "class", - "line": 27, + "line": 20, "name": "ProjectVideo" }, { - "end_line": 61, + "end_line": 54, "kind": "class", - "line": 40, + "line": 33, "name": "SubmissionProject" }, { - "end_line": 71, + "end_line": 64, "kind": "class", - "line": 65, + "line": 58, "name": "ProjectSnapshot" }, { - "end_line": 127, + "end_line": 120, "kind": "class", - "line": 74, + "line": 67, "name": "SubmissionProjectService" } ], "top_level_functions": [ { - "end_line": 23, + "end_line": 16, "kind": "function", - "line": 16, + "line": 13, "name": "configured_submission_root" } ] @@ -8614,20 +8751,20 @@ }, { "duplicate_top_level_definitions": [], - "line_count": 208, + "line_count": 247, "longest_function": { - "end_line": 124, + "end_line": 142, "kind": "function", - "line": 99, - "line_count": 26, + "line": 115, + "line_count": 28, "qualname": "MpvAdapter._load" }, "module": "autoslice.desktop.qt_app.player", "path": "src/autoslice/desktop/qt_app/player.py", - "sha256": "8fce45fe22934135820337c93559d7f624c1cb5b1e9abcf5d59752dc0f4dcecd", + "sha256": "175b648779ea376d632cf96cc2a223ced05f6b38b8876bcf6dc2e24f997f5b1c", "top_level_classes": [ { - "end_line": 208, + "end_line": 247, "kind": "class", "line": 26, "name": "MpvAdapter" @@ -8644,75 +8781,93 @@ }, { "duplicate_top_level_definitions": [], - "line_count": 308, + "line_count": 681, "longest_function": { - "end_line": 172, + "end_line": 408, "kind": "function", - "line": 115, - "line_count": 58, + "line": 317, + "line_count": 92, "qualname": "SubtitleTimeline.paintEvent" }, "module": "autoslice.desktop.qt_app.timeline", "path": "src/autoslice/desktop/qt_app/timeline.py", - "sha256": "d0ed3d8cbd69293314724a2e319429a7514be64d56a1085d082916c01e09f31b", + "sha256": "35604555b891a827d9014e5ff262c7b4a7e71b29bbc26c4d613e9c7b5d81e21d", "top_level_classes": [ { - "end_line": 308, + "end_line": 620, "kind": "class", - "line": 16, + "line": 17, "name": "SubtitleTimeline" + }, + { + "end_line": 681, + "kind": "class", + "line": 623, + "name": "TimelineSidePanController" } ], "top_level_functions": [] }, { "duplicate_top_level_definitions": [], - "line_count": 1633, + "line_count": 2633, "longest_function": { - "end_line": 584, + "end_line": 496, "kind": "function", - "line": 506, - "line_count": 79, - "qualname": "DesktopWindow._ai_panel" + "line": 370, + "line_count": 127, + "qualname": "DesktopWindow.__init__" }, "module": "autoslice.desktop.qt_app.window", "path": "src/autoslice/desktop/qt_app/window.py", - "sha256": "6db64bc51b78de80fa303986383aacab25863f1eb2d30cfedd43c641bfdb1404", + "sha256": "233a95c4ee0091b04ed4c8b7c17ae06e4323c172ff20fe87fd965800303a8381", "top_level_classes": [ { - "end_line": 69, + "end_line": 78, "kind": "class", - "line": 64, + "line": 73, "name": "_StatusLabel" }, { - "end_line": 73, + "end_line": 113, "kind": "class", - "line": 72, + "line": 81, + "name": "_ElidedQueueButton" + }, + { + "end_line": 117, + "kind": "class", + "line": 116, "name": "_Signals" }, { - "end_line": 86, + "end_line": 130, "kind": "class", - "line": 76, + "line": 120, "name": "_Job" }, { - "end_line": 163, + "end_line": 237, "kind": "class", - "line": 89, + "line": 133, "name": "SubtitleTableModel" }, { - "end_line": 219, + "end_line": 270, "kind": "class", - "line": 166, + "line": 240, + "name": "InlineSubtitleEditor" + }, + { + "end_line": 363, + "kind": "class", + "line": 273, "name": "SubtitleTextDelegate" }, { - "end_line": 1633, + "end_line": 2633, "kind": "class", - "line": 222, + "line": 366, "name": "DesktopWindow" } ], @@ -8776,17 +8931,17 @@ }, { "duplicate_top_level_definitions": [], - "line_count": 163, + "line_count": 180, "longest_function": { - "end_line": 163, + "end_line": 180, "kind": "function", "line": 80, - "line_count": 84, + "line_count": 101, "qualname": "stylesheet" }, "module": "autoslice.desktop.qt_preview.theme", "path": "src/autoslice/desktop/qt_preview/theme.py", - "sha256": "3bd6639842fa6f9dda55a8dcec54fa2aad2af19a79e2e74397941e667b11b7e4", + "sha256": "62065e434a27db97ff39acea3d20b449e8d5bf7e968abb5a42780d04d754616f", "top_level_classes": [ { "end_line": 36, @@ -8803,7 +8958,7 @@ ], "top_level_functions": [ { - "end_line": 163, + "end_line": 180, "kind": "function", "line": 80, "name": "stylesheet" @@ -8870,6 +9025,82 @@ } ] }, + { + "duplicate_top_level_definitions": [], + "line_count": 39, + "longest_function": { + "end_line": 32, + "kind": "function", + "line": 15, + "line_count": 18, + "qualname": "CueSelection.choose" + }, + "module": "autoslice.desktop.selection", + "path": "src/autoslice/desktop/selection.py", + "sha256": "78e63741a3350b1332dbf8ac080be2c7c2ce37fc411b0a7dfa496cc3be85122f", + "top_level_classes": [ + { + "end_line": 39, + "kind": "class", + "line": 6, + "name": "CueSelection" + } + ], + "top_level_functions": [] + }, + { + "duplicate_top_level_definitions": [], + "line_count": 27, + "longest_function": { + "end_line": 24, + "kind": "function", + "line": 12, + "line_count": 13, + "qualname": "SnapEngine.snap" + }, + "module": "autoslice.desktop.snap", + "path": "src/autoslice/desktop/snap.py", + "sha256": "7c3cc5298b31aeab9c2f996d248149d8a21a4fc5831201d293cef67c8e3b354e", + "top_level_classes": [ + { + "end_line": 27, + "kind": "class", + "line": 6, + "name": "SnapEngine" + } + ], + "top_level_functions": [] + }, + { + "duplicate_top_level_definitions": [], + "line_count": 98, + "longest_function": { + "end_line": 72, + "kind": "function", + "line": 34, + "line_count": 39, + "qualname": "SubtitlePreviewService.render" + }, + "module": "autoslice.desktop.subtitle_preview", + "path": "src/autoslice/desktop/subtitle_preview.py", + "sha256": "49436cfdb664b0a07082fd216fddd8531a2f8bac3e70a0f684c7319135dc4b54", + "top_level_classes": [ + { + "end_line": 92, + "kind": "class", + "line": 15, + "name": "SubtitlePreviewService" + } + ], + "top_level_functions": [ + { + "end_line": 98, + "kind": "function", + "line": 95, + "name": "_seconds" + } + ] + }, { "duplicate_top_level_definitions": [], "line_count": 110, @@ -8895,28 +9126,28 @@ }, { "duplicate_top_level_definitions": [], - "line_count": 371, + "line_count": 492, "longest_function": { - "end_line": 371, + "end_line": 492, "kind": "function", - "line": 309, - "line_count": 63, + "line": 407, + "line_count": 86, "qualname": "SubtitleDocument.save" }, "module": "autoslice.desktop.subtitles", "path": "src/autoslice/desktop/subtitles.py", - "sha256": "54c50bcde5ced72e751424e21264bb8d20bd0c7dd9b4fecb8eefb3c2c3b63c26", + "sha256": "a0c48d34de7b3e7f880732628b6ebb1e90e2ed2b29d1daa6a7bf614615d50474", "top_level_classes": [ { - "end_line": 39, + "end_line": 40, "kind": "class", "line": 32, "name": "SubtitleEntry" }, { - "end_line": 371, + "end_line": 492, "kind": "class", - "line": 42, + "line": 43, "name": "SubtitleDocument" } ], @@ -8935,6 +9166,42 @@ } ] }, + { + "duplicate_top_level_definitions": [], + "line_count": 114, + "longest_function": { + "end_line": 114, + "kind": "function", + "line": 79, + "line_count": 36, + "qualname": "generate_waveform" + }, + "module": "autoslice.desktop.waveform", + "path": "src/autoslice/desktop/waveform.py", + "sha256": "6dac5df8b5a976c0b55665801740f981cc7099bc39c1e24c735732e2756f32a2", + "top_level_classes": [ + { + "end_line": 20, + "kind": "class", + "line": 17, + "name": "WaveformData" + }, + { + "end_line": 76, + "kind": "class", + "line": 23, + "name": "WaveformCache" + } + ], + "top_level_functions": [ + { + "end_line": 114, + "kind": "function", + "line": 79, + "name": "generate_waveform" + } + ] + }, { "duplicate_top_level_definitions": [], "line_count": 580, @@ -8947,7 +9214,7 @@ }, "module": "autoslice.launcher", "path": "src/autoslice/launcher.py", - "sha256": "f569b42ade671304b29209124314e4a0ffeca00f28bb7d0632e6425ef94c167c", + "sha256": "ae533ad9fcdded27e0421bc9e742d3ad6872a5cc89edff7c9a9923790f85c629", "top_level_classes": [], "top_level_functions": [ { @@ -9418,7 +9685,7 @@ }, "module": "autoslice.llm.transport", "path": "src/autoslice/llm/transport.py", - "sha256": "2b445fe65a390c73a8438dad4bd2c9dac7007534b58b5a05b1626bbf11320b2b", + "sha256": "f7f5870f819c07e1c054ef9e9a50da8422d15c8424d0c4e760459f7a037695a5", "top_level_classes": [ { "end_line": 66, @@ -10539,7 +10806,7 @@ }, { "duplicate_top_level_definitions": [], - "line_count": 140, + "line_count": 130, "longest_function": { "end_line": 79, "kind": "function", @@ -10549,7 +10816,7 @@ }, "module": "autoslice.runtime_config", "path": "src/autoslice/runtime_config.py", - "sha256": "6461943550a3db03fb695f1240c6b077143cb0b3b1e1bc3daac77b1cc6519b15", + "sha256": "3f6289096fdfee132bf5d744dd53fedc8b74f59b72d38553d90fb4128deb7880", "top_level_classes": [], "top_level_functions": [ { @@ -10581,18 +10848,12 @@ "kind": "function", "line": 101, "name": "apply_local_environment" - }, - { - "end_line": 140, - "kind": "function", - "line": 133, - "name": "template_defaults" } ] }, { "duplicate_top_level_definitions": [], - "line_count": 817, + "line_count": 847, "longest_function": { "end_line": 487, "kind": "function", @@ -10602,7 +10863,7 @@ }, "module": "autoslice.security_policy", "path": "src/autoslice/security_policy.py", - "sha256": "5f12c48b87478b0162c0a1dba8268236e39ccfbeaeacab7b312e23f5d831bd49", + "sha256": "4cd7ef8c0e438f37ea11b49f034e599c9501ad93a3aff3c3ff708249b84774b6", "top_level_classes": [ { "end_line": 67, @@ -10629,7 +10890,7 @@ "name": "_SessionTokenStore" }, { - "end_line": 806, + "end_line": 836, "kind": "class", "line": 269, "name": "SecurityPolicy" @@ -11188,497 +11449,503 @@ }, { "duplicate_top_level_definitions": [], - "line_count": 2444, + "line_count": 2519, "longest_function": { - "end_line": 1498, + "end_line": 1594, "kind": "function", - "line": 1348, + "line": 1444, "line_count": 151, "qualname": "suggest_subtitle_corrections" }, "module": "autoslice.subtitle_workflow", "path": "src/autoslice/subtitle_workflow.py", - "sha256": "574a8a1fe911312d8761b4b94ae8230de1b763e6899cc39c9da6bff158a25bf2", + "sha256": "55128aa545fa8c5d1c606d533429f0b1f3e5f9b24bb747bfc085481f2a61d738", "top_level_classes": [], "top_level_functions": [ { - "end_line": 95, + "end_line": 96, "kind": "function", - "line": 93, + "line": 94, "name": "_generic_title_style_prompt" }, { - "end_line": 108, + "end_line": 109, "kind": "function", - "line": 98, + "line": 99, "name": "_generic_title_hook_prompt_guide" }, { - "end_line": 124, + "end_line": 125, "kind": "function", - "line": 119, + "line": 120, "name": "_resolve_title_services" }, { - "end_line": 135, + "end_line": 136, "kind": "function", - "line": 127, + "line": 128, "name": "_read_subtitle_text" }, { - "end_line": 186, + "end_line": 187, "kind": "function", - "line": 138, + "line": 139, "name": "parse_srt_document" }, { - "end_line": 208, + "end_line": 209, "kind": "function", - "line": 189, + "line": 190, "name": "_normalise_deleted_indices" }, { - "end_line": 240, + "end_line": 241, "kind": "function", - "line": 211, + "line": 212, "name": "_normalise_merge_pairs" }, { - "end_line": 268, + "end_line": 269, "kind": "function", - "line": 243, + "line": 244, "name": "_normalise_merge_overrides" }, { - "end_line": 326, + "end_line": 327, "kind": "function", - "line": 271, + "line": 272, "name": "_normalise_time_overrides" }, { - "end_line": 341, + "end_line": 342, "kind": "function", - "line": 329, + "line": 330, "name": "_join_subtitle_text" }, { - "end_line": 383, + "end_line": 384, "kind": "function", - "line": 344, + "line": 345, "name": "_merged_subtitle_cues" }, { - "end_line": 410, + "end_line": 442, "kind": "function", - "line": 386, + "line": 387, + "name": "_normalise_split_groups" + }, + { + "end_line": 483, + "kind": "function", + "line": 445, "name": "serialise_srt" }, { - "end_line": 415, + "end_line": 488, "kind": "function", - "line": 413, + "line": 486, "name": "_corrected_srt_path" }, { - "end_line": 420, + "end_line": 493, "kind": "function", - "line": 418, + "line": 491, "name": "_reflowed_srt_path" }, { - "end_line": 425, + "end_line": 498, "kind": "function", - "line": 423, + "line": 496, "name": "_subtitle_edit_state_path" }, { - "end_line": 429, + "end_line": 502, "kind": "function", - "line": 428, + "line": 501, "name": "_subtitle_content_fingerprint" }, { - "end_line": 437, + "end_line": 510, "kind": "function", - "line": 432, + "line": 505, "name": "_srt_timestamp" }, { - "end_line": 454, + "end_line": 527, "kind": "function", - "line": 453, + "line": 526, "name": "_visible_subtitle_char_count" }, { - "end_line": 462, + "end_line": 535, "kind": "function", - "line": 457, + "line": 530, "name": "_short_clause_prefix" }, { - "end_line": 485, + "end_line": 558, "kind": "function", - "line": 465, + "line": 538, "name": "_continuation_suffix_to_shift" }, { - "end_line": 529, + "end_line": 602, "kind": "function", - "line": 488, + "line": 561, "name": "_rebalance_short_leading_subtitle_fragments" }, { - "end_line": 587, + "end_line": 660, "kind": "function", - "line": 532, + "line": 605, "name": "reflow_subtitle_srt_for_display" }, { - "end_line": 702, + "end_line": 695, "kind": "function", - "line": 590, + "line": 663, + "name": "_edit_structure_payload" + }, + { + "end_line": 804, + "kind": "function", + "line": 698, "name": "save_corrected_srt" }, { - "end_line": 786, + "end_line": 882, "kind": "function", - "line": 705, + "line": 807, "name": "load_subtitle_edit_state" }, { - "end_line": 795, + "end_line": 891, "kind": "function", - "line": 789, + "line": 885, "name": "_is_generated_stem" }, { - "end_line": 804, + "end_line": 900, "kind": "function", - "line": 798, + "line": 894, "name": "_path_timestamps" }, { - "end_line": 852, + "end_line": 948, "kind": "function", - "line": 807, + "line": 903, "name": "_pair_result" }, { - "end_line": 895, + "end_line": 991, "kind": "function", - "line": 855, + "line": 951, "name": "scan_submission_pairs" }, { - "end_line": 980, + "end_line": 1076, "kind": "function", - "line": 898, + "line": 994, "name": "transcribe_submission_video" }, { - "end_line": 1005, + "end_line": 1101, "kind": "function", - "line": 983, + "line": 1079, "name": "normalise_subtitle_review_dictionary" }, { - "end_line": 1025, + "end_line": 1121, "kind": "function", - "line": 1008, + "line": 1104, "name": "subtitle_review_profile_rules" }, { - "end_line": 1041, + "end_line": 1137, "kind": "function", - "line": 1028, + "line": 1124, "name": "_subtitle_source_fingerprint" }, { - "end_line": 1046, + "end_line": 1142, "kind": "function", - "line": 1044, + "line": 1140, "name": "_review_cache_path" }, { - "end_line": 1113, + "end_line": 1209, "kind": "function", - "line": 1049, + "line": 1145, "name": "_validated_cached_review" }, { - "end_line": 1156, + "end_line": 1252, "kind": "function", - "line": 1116, + "line": 1212, "name": "_review_prompt" }, { - "end_line": 1174, + "end_line": 1270, "kind": "function", - "line": 1159, + "line": 1255, "name": "_default_llm_runner" }, { - "end_line": 1187, + "end_line": 1283, "kind": "function", - "line": 1177, + "line": 1273, "name": "_build_default_llm_runner" }, { - "end_line": 1196, + "end_line": 1292, "kind": "function", - "line": 1190, + "line": 1286, "name": "_normalise_review_payload" }, { - "end_line": 1200, + "end_line": 1296, "kind": "function", - "line": 1199, + "line": 1295, "name": "_semantic_text" }, { - "end_line": 1244, + "end_line": 1340, "kind": "function", - "line": 1203, + "line": 1299, "name": "_normalise_suggestion" }, { - "end_line": 1308, + "end_line": 1404, "kind": "function", - "line": 1247, + "line": 1343, "name": "_review_batch" }, { - "end_line": 1324, + "end_line": 1420, "kind": "function", - "line": 1311, + "line": 1407, "name": "_apply_fixed_replacements" }, { - "end_line": 1345, + "end_line": 1441, "kind": "function", - "line": 1327, + "line": 1423, "name": "_fixed_replacement_suggestions" }, { - "end_line": 1498, + "end_line": 1594, "kind": "function", - "line": 1348, + "line": 1444, "name": "suggest_subtitle_corrections" }, { - "end_line": 1544, + "end_line": 1640, "kind": "function", - "line": 1501, + "line": 1597, "name": "high_confidence_corrections" }, { - "end_line": 1568, + "end_line": 1664, "kind": "function", - "line": 1547, + "line": 1643, "name": "_subtitle_title_evidence" }, { - "end_line": 1605, + "end_line": 1701, "kind": "function", - "line": 1571, + "line": 1667, "name": "_subtitle_title_generation_prompt" }, { - "end_line": 1638, + "end_line": 1734, "kind": "function", - "line": 1608, + "line": 1704, "name": "_normalise_subtitle_title_payload" }, { - "end_line": 1668, + "end_line": 1764, "kind": "function", - "line": 1641, + "line": 1737, "name": "_subtitle_title_judge_prompt" }, { - "end_line": 1709, + "end_line": 1805, "kind": "function", - "line": 1671, + "line": 1767, "name": "_normalise_subtitle_title_judgement" }, { - "end_line": 1723, + "end_line": 1819, "kind": "function", - "line": 1712, + "line": 1808, "name": "_default_subtitle_title_runner" }, { - "end_line": 1792, + "end_line": 1888, "kind": "function", - "line": 1726, + "line": 1822, "name": "generate_subtitle_reference_titles" }, { - "end_line": 1820, + "end_line": 1916, "kind": "function", - "line": 1795, + "line": 1891, "name": "normalise_subtitle_style" }, { - "end_line": 1856, + "end_line": 1952, "kind": "function", - "line": 1823, + "line": 1919, "name": "normalise_video_export" }, { - "end_line": 1901, + "end_line": 1997, "kind": "function", - "line": 1859, + "line": 1955, "name": "_probe_video_info" }, { - "end_line": 1916, + "end_line": 2012, "kind": "function", - "line": 1904, + "line": 2000, "name": "_parse_frame_rate" }, { - "end_line": 1922, + "end_line": 2018, "kind": "function", - "line": 1919, + "line": 2015, "name": "_html_color_to_ass" }, { - "end_line": 1930, + "end_line": 2026, "kind": "function", - "line": 1925, + "line": 2021, "name": "_ass_timestamp" }, { - "end_line": 1942, + "end_line": 2038, "kind": "function", - "line": 1933, + "line": 2029, "name": "_escape_ass_text" }, { - "end_line": 1946, + "end_line": 2048, "kind": "function", - "line": 1945, - "name": "_subtitle_display_text_size" - }, - { - "end_line": 1956, - "kind": "function", - "line": 1949, + "line": 2041, "name": "_subtitle_display_char_limit" }, { - "end_line": 1990, + "end_line": 2061, "kind": "function", - "line": 1959, - "name": "_split_subtitle_text_for_ass" + "line": 2051, + "name": "_wrap_subtitle_text_for_ass" }, { - "end_line": 2023, + "end_line": 2094, "kind": "function", - "line": 1993, + "line": 2064, "name": "_split_cue_for_ass" }, { - "end_line": 2035, + "end_line": 2106, "kind": "function", - "line": 2026, + "line": 2097, "name": "_style_geometry" }, { - "end_line": 2069, + "end_line": 2144, "kind": "function", - "line": 2038, + "line": 2109, "name": "build_ass_document" }, { - "end_line": 2074, + "end_line": 2149, "kind": "function", - "line": 2072, + "line": 2147, "name": "_ass_output_path" }, { - "end_line": 2079, + "end_line": 2154, "kind": "function", - "line": 2077, + "line": 2152, "name": "_style_output_path" }, { - "end_line": 2104, + "end_line": 2179, "kind": "function", - "line": 2082, + "line": 2157, "name": "_atomic_write_text" }, { - "end_line": 2133, + "end_line": 2208, "kind": "function", - "line": 2107, + "line": 2182, "name": "write_ass_from_srt" }, { - "end_line": 2139, + "end_line": 2214, "kind": "function", - "line": 2136, + "line": 2211, "name": "_ffmpeg_filter_path" }, { - "end_line": 2143, + "end_line": 2218, "kind": "function", - "line": 2142, + "line": 2217, "name": "_ass_filter" }, { - "end_line": 2178, + "end_line": 2253, "kind": "function", - "line": 2147, + "line": 2222, "name": "verify_exact_subtitle_font" }, { - "end_line": 2188, + "end_line": 2263, "kind": "function", - "line": 2181, + "line": 2256, "name": "_ensure_exact_subtitle_font" }, { - "end_line": 2202, + "end_line": 2277, "kind": "function", - "line": 2191, + "line": 2266, "name": "_video_filter_chain" }, { - "end_line": 2245, + "end_line": 2320, "kind": "function", - "line": 2205, + "line": 2280, "name": "render_subtitle_preview" }, { - "end_line": 2259, + "end_line": 2334, "kind": "function", - "line": 2249, + "line": 2324, "name": "_nvenc_available" }, { - "end_line": 2264, + "end_line": 2339, "kind": "function", - "line": 2262, + "line": 2337, "name": "_output_video_path" }, { - "end_line": 2280, + "end_line": 2355, "kind": "function", - "line": 2267, + "line": 2342, "name": "_encoder_arguments" }, { - "end_line": 2331, + "end_line": 2406, "kind": "function", - "line": 2283, + "line": 2358, "name": "_run_subtitle_encode" }, { - "end_line": 2444, + "end_line": 2519, "kind": "function", - "line": 2334, + "line": 2409, "name": "burn_subtitles" } ] @@ -12876,17 +13143,17 @@ }, { "duplicate_top_level_definitions": [], - "line_count": 3019, + "line_count": 3005, "longest_function": { - "end_line": 747, + "end_line": 731, "kind": "function", - "line": 615, + "line": 599, "line_count": 133, "qualname": "update_task" }, "module": "autoslice.web.app", "path": "src/autoslice/web/app.py", - "sha256": "effc240b284434ac29d936c94ce03c6a59fd065b658198ae22ccbfc465ef3272", + "sha256": "faf14e2a79b13601485ebdcad98ccb1e2f9c54a70f825fff9fd33aac4422de75", "top_level_classes": [ { "end_line": 319, @@ -12895,9 +13162,9 @@ "name": "_TaskMappingView" }, { - "end_line": 1217, + "end_line": 1201, "kind": "class", - "line": 1216, + "line": 1200, "name": "_TaskCancelled" } ], @@ -12963,543 +13230,543 @@ "name": "_template_directory" }, { - "end_line": 428, + "end_line": 412, "kind": "function", "line": 404, "name": "issue_local_browser_session" }, { - "end_line": 447, + "end_line": 431, "kind": "function", - "line": 431, + "line": 415, "name": "_redact_task_error_text" }, { - "end_line": 453, + "end_line": 437, "kind": "function", - "line": 450, + "line": 434, "name": "_is_sse_path_key" }, { - "end_line": 469, + "end_line": 453, "kind": "function", - "line": 456, + "line": 440, "name": "_sse_path_display" }, { - "end_line": 533, + "end_line": 517, "kind": "function", - "line": 472, + "line": 456, "name": "_sanitize_sse_value" }, { - "end_line": 541, + "end_line": 525, "kind": "function", - "line": 536, + "line": 520, "name": "_format_sse_event" }, { - "end_line": 550, + "end_line": 534, "kind": "function", - "line": 544, + "line": 528, "name": "_prune_event_history_locked" }, { - "end_line": 578, + "end_line": 562, "kind": "function", - "line": 553, + "line": 537, "name": "broadcast" }, { - "end_line": 589, + "end_line": 573, "kind": "function", - "line": 581, + "line": 565, "name": "_prune_tasks_locked" }, { - "end_line": 612, + "end_line": 596, "kind": "function", - "line": 592, + "line": 576, "name": "_console_print" }, { - "end_line": 747, + "end_line": 731, "kind": "function", - "line": 615, + "line": 599, "name": "update_task" }, { - "end_line": 754, + "end_line": 738, "kind": "function", - "line": 750, + "line": 734, "name": "_pipeline_completion_progress" }, { - "end_line": 811, + "end_line": 795, "kind": "function", - "line": 757, + "line": 741, "name": "_complete_pipeline_task" }, { - "end_line": 834, + "end_line": 818, "kind": "function", - "line": 814, + "line": 798, "name": "_reserve_task" }, { - "end_line": 850, + "end_line": 834, "kind": "function", - "line": 837, + "line": 821, "name": "_reserve_source_task" }, { - "end_line": 860, + "end_line": 844, "kind": "function", - "line": 853, + "line": 837, "name": "_set_task_output_dir" }, { - "end_line": 868, + "end_line": 852, "kind": "function", - "line": 863, + "line": 847, "name": "_request_streamer_profile" }, { - "end_line": 876, + "end_line": 860, "kind": "function", - "line": 871, + "line": 855, "name": "_subtitle_review_rules" }, { - "end_line": 904, + "end_line": 888, "kind": "function", - "line": 879, + "line": 863, "name": "_subtitle_review_profile_summary" }, { - "end_line": 912, + "end_line": 896, "kind": "function", - "line": 907, + "line": 891, "name": "_topic_task_output_paths" }, { - "end_line": 954, + "end_line": 938, "kind": "function", - "line": 915, + "line": 899, "name": "_completed_task_artifact_dir" }, { - "end_line": 974, + "end_line": 958, "kind": "function", - "line": 957, + "line": 941, "name": "_completed_task_report_path" }, { - "end_line": 981, + "end_line": 965, "kind": "function", - "line": 977, + "line": 961, "name": "_timeline_result_mapping" }, { - "end_line": 1013, + "end_line": 997, "kind": "function", - "line": 984, + "line": 968, "name": "_timeline_artifact_path" }, { - "end_line": 1028, + "end_line": 1012, "kind": "function", - "line": 1016, + "line": 1000, "name": "_read_registered_timeline_json" }, { - "end_line": 1050, + "end_line": 1034, "kind": "function", - "line": 1031, + "line": 1015, "name": "_timeline_number_matches" }, { - "end_line": 1130, + "end_line": 1114, "kind": "function", - "line": 1053, + "line": 1037, "name": "_attach_registered_timeline_clip_ids" }, { - "end_line": 1146, + "end_line": 1130, "kind": "function", - "line": 1133, + "line": 1117, "name": "_timeline_records" }, { - "end_line": 1159, + "end_line": 1143, "kind": "function", - "line": 1149, + "line": 1133, "name": "_timeline_video_duration" }, { - "end_line": 1207, + "end_line": 1191, "kind": "function", - "line": 1162, + "line": 1146, "name": "_load_registered_timeline_inputs" }, { - "end_line": 1213, + "end_line": 1197, "kind": "function", - "line": 1210, + "line": 1194, "name": "_safe_task_error" }, { - "end_line": 1224, + "end_line": 1208, "kind": "function", - "line": 1220, + "line": 1204, "name": "_task_cancellation_requested" }, { - "end_line": 1229, + "end_line": 1213, "kind": "function", - "line": 1227, + "line": 1211, "name": "_raise_if_task_cancelled" }, { - "end_line": 1245, + "end_line": 1229, "kind": "function", - "line": 1232, + "line": 1216, "name": "_record_task_error" }, { - "end_line": 1258, + "end_line": 1242, "kind": "function", - "line": 1248, + "line": 1232, "name": "_validated_upload_filename" }, { - "end_line": 1293, + "end_line": 1277, "kind": "function", - "line": 1261, + "line": 1245, "name": "_save_uploaded_file" }, { - "end_line": 1308, + "end_line": 1292, "kind": "function", - "line": 1296, + "line": 1280, "name": "_reserve_subtitle_review_task" }, { - "end_line": 1322, + "end_line": 1306, "kind": "function", - "line": 1311, + "line": 1295, "name": "_reserve_subtitle_title_task" }, { - "end_line": 1331, + "end_line": 1315, "kind": "function", - "line": 1325, + "line": 1309, "name": "_validate_subtitle_video" }, { - "end_line": 1363, + "end_line": 1347, "kind": "function", - "line": 1334, + "line": 1318, "name": "_reserve_subtitle_transcription_task" }, { - "end_line": 1371, + "end_line": 1355, "kind": "function", - "line": 1366, + "line": 1350, "name": "_validate_subtitle_path" }, { - "end_line": 1389, + "end_line": 1373, "kind": "function", - "line": 1374, + "line": 1358, "name": "_validate_subtitle_pair" }, { - "end_line": 1402, + "end_line": 1386, "kind": "function", - "line": 1392, + "line": 1376, "name": "_validate_subtitle_output_path" }, { - "end_line": 1484, + "end_line": 1468, "kind": "function", - "line": 1405, + "line": 1389, "name": "run_subtitle_review_task" }, { - "end_line": 1532, + "end_line": 1516, "kind": "function", - "line": 1487, + "line": 1471, "name": "run_subtitle_title_task" }, { - "end_line": 1606, + "end_line": 1590, "kind": "function", - "line": 1535, + "line": 1519, "name": "run_subtitle_transcription_task" }, { - "end_line": 1655, + "end_line": 1639, "kind": "function", - "line": 1609, + "line": 1593, "name": "run_subtitle_render_task" }, { - "end_line": 1698, + "end_line": 1682, "kind": "function", - "line": 1658, + "line": 1642, "name": "run_timeline_optimization_task" }, { - "end_line": 1752, + "end_line": 1737, "kind": "function", - "line": 1701, + "line": 1685, "name": "run_clip_review_retry_task" }, { - "end_line": 1783, + "end_line": 1768, "kind": "function", - "line": 1755, + "line": 1740, "name": "run_slice_task" }, { - "end_line": 1797, + "end_line": 1782, "kind": "function", - "line": 1789, + "line": 1774, "name": "_task_init_snapshot" }, { - "end_line": 1822, + "end_line": 1807, "kind": "function", - "line": 1800, + "line": 1785, "name": "_replay_events_locked" }, { - "end_line": 1863, + "end_line": 1848, "kind": "function", - "line": 1826, + "line": 1811, "name": "sse_events" }, { - "end_line": 1888, + "end_line": 1873, "kind": "function", - "line": 1867, + "line": 1852, "name": "cancel_task" }, { - "end_line": 1899, + "end_line": 1884, "kind": "function", - "line": 1894, + "line": 1879, "name": "index" }, { - "end_line": 1910, + "end_line": 1895, "kind": "function", - "line": 1903, + "line": 1888, "name": "direct_slice_page" }, { - "end_line": 1937, + "end_line": 1922, "kind": "function", - "line": 1914, + "line": 1899, "name": "scan" }, { - "end_line": 2011, + "end_line": 1996, "kind": "function", - "line": 1941, + "line": 1926, "name": "slice_start" }, { - "end_line": 2037, + "end_line": 2022, "kind": "function", - "line": 2015, + "line": 2000, "name": "open_result_directory" }, { - "end_line": 2060, + "end_line": 2045, "kind": "function", - "line": 2041, + "line": 2026, "name": "completed_task_report" }, { - "end_line": 2080, + "end_line": 2065, "kind": "function", - "line": 2064, + "line": 2049, "name": "completed_task_result" }, { - "end_line": 2130, + "end_line": 2115, "kind": "function", - "line": 2084, + "line": 2069, "name": "completed_task_timeline" }, { - "end_line": 2158, + "end_line": 2143, "kind": "function", - "line": 2137, + "line": 2122, "name": "issue_task_clip_media_token" }, { - "end_line": 2199, + "end_line": 2184, "kind": "function", - "line": 2165, + "line": 2150, "name": "preview_task_clip_media" }, { - "end_line": 2217, + "end_line": 2202, "kind": "function", - "line": 2205, + "line": 2190, "name": "subtitle_defaults" }, { - "end_line": 2233, + "end_line": 2218, "kind": "function", - "line": 2221, + "line": 2206, "name": "subtitle_scan" }, { - "end_line": 2246, + "end_line": 2231, "kind": "function", - "line": 2237, + "line": 2222, "name": "subtitle_cues" }, { - "end_line": 2263, + "end_line": 2248, "kind": "function", - "line": 2250, + "line": 2235, "name": "subtitle_edit_state" }, { - "end_line": 2308, + "end_line": 2293, "kind": "function", - "line": 2267, + "line": 2252, "name": "subtitle_transcribe" }, { - "end_line": 2338, + "end_line": 2323, "kind": "function", - "line": 2312, + "line": 2297, "name": "subtitle_reflow" }, { - "end_line": 2414, + "end_line": 2399, "kind": "function", - "line": 2342, + "line": 2327, "name": "subtitle_review" }, { - "end_line": 2444, + "end_line": 2429, "kind": "function", - "line": 2418, + "line": 2403, "name": "subtitle_profile_replacements" }, { - "end_line": 2488, + "end_line": 2473, "kind": "function", - "line": 2448, + "line": 2433, "name": "subtitle_generate_title" }, { - "end_line": 2532, + "end_line": 2517, "kind": "function", - "line": 2492, + "line": 2477, "name": "subtitle_save" }, { - "end_line": 2604, + "end_line": 2589, "kind": "function", - "line": 2536, + "line": 2521, "name": "subtitle_preview" }, { - "end_line": 2656, + "end_line": 2641, "kind": "function", - "line": 2608, + "line": 2593, "name": "subtitle_render" }, { - "end_line": 2673, + "end_line": 2658, "kind": "function", - "line": 2660, + "line": 2645, "name": "list_json_timelines" }, { - "end_line": 2691, + "end_line": 2676, "kind": "function", - "line": 2677, + "line": 2662, "name": "upload_json_timeline" }, { - "end_line": 2703, + "end_line": 2688, "kind": "function", - "line": 2695, + "line": 2680, "name": "list_timelines" }, { - "end_line": 2719, + "end_line": 2704, "kind": "function", - "line": 2707, + "line": 2692, "name": "upload_timeline" }, { - "end_line": 2730, + "end_line": 2715, "kind": "function", - "line": 2725, + "line": 2710, "name": "topic_v2_page" }, { - "end_line": 2735, + "end_line": 2720, "kind": "function", - "line": 2734, + "line": 2719, "name": "subtitle_workflow_page" }, { - "end_line": 2750, + "end_line": 2735, "kind": "function", - "line": 2739, + "line": 2724, "name": "autocover_page" }, { - "end_line": 2758, + "end_line": 2743, "kind": "function", - "line": 2754, + "line": 2739, "name": "bootstrap_security_session" }, { - "end_line": 2770, + "end_line": 2755, "kind": "function", - "line": 2762, + "line": 2747, "name": "service_contract" }, { - "end_line": 2779, + "end_line": 2764, "kind": "function", - "line": 2774, + "line": 2759, "name": "streamer_profiles_contract" }, { - "end_line": 2788, + "end_line": 2773, "kind": "function", - "line": 2783, + "line": 2768, "name": "asr_status_contract" }, { - "end_line": 2902, + "end_line": 2888, "kind": "function", - "line": 2792, + "line": 2777, "name": "start_pipeline" }, { - "end_line": 2950, + "end_line": 2936, "kind": "function", - "line": 2906, + "line": 2892, "name": "retry_clip_review" }, { - "end_line": 3015, + "end_line": 3001, "kind": "function", - "line": 2954, + "line": 2940, "name": "optimize_manual_timeline" } ] @@ -13516,17 +13783,17 @@ }, { "duplicate_top_level_definitions": [], - "line_count": 1111, + "line_count": 1072, "longest_function": { - "end_line": 1104, + "end_line": 1065, "kind": "function", - "line": 624, - "line_count": 481, + "line": 602, + "line_count": 464, "qualname": "create_app" }, "module": "autoslice_cover.app", "path": "src/autoslice_cover/app.py", - "sha256": "1fd87232913d736b3ae6e5f0b9039317101cdb8f1a17d9e9e1a794389d74a79c", + "sha256": "eb6ea32deb7841e42a8c9ddaa8c9e8ab1984f0c33b15e6afc1b70168d7aff279", "top_level_classes": [ { "end_line": 61, @@ -13651,21 +13918,15 @@ "name": "_render_task_result" }, { - "end_line": 560, + "end_line": 599, "kind": "function", "line": 541, - "name": "_render_task" - }, - { - "end_line": 621, - "kind": "function", - "line": 563, "name": "_save_task" }, { - "end_line": 1104, + "end_line": 1065, "kind": "function", - "line": 624, + "line": 602, "name": "create_app" } ] @@ -15459,21 +15720,21 @@ }, { "duplicate_top_level_definitions": [], - "line_count": 93, + "line_count": 94, "longest_function": { - "end_line": 89, + "end_line": 90, "kind": "function", "line": 15, - "line_count": 75, + "line_count": 76, "qualname": "main" }, "module": "scripts.smoke_packaging", "path": "scripts/smoke_packaging.py", - "sha256": "1268ef7727228afb282012d247e40f6ac1c03b4f2199a402d80383a148097a0c", + "sha256": "27352a2c28dfaf1ffb8ca426df2f917357381bf6568097492a852b22f59a6f2a", "top_level_classes": [], "top_level_functions": [ { - "end_line": 89, + "end_line": 90, "kind": "function", "line": 15, "name": "main" @@ -15606,17 +15867,17 @@ }, { "duplicate_top_level_definitions": [], - "line_count": 551, + "line_count": 552, "longest_function": { - "end_line": 393, + "end_line": 394, "kind": "function", - "line": 335, + "line": 336, "line_count": 59, "qualname": "_verify_bad_wheel" }, "module": "scripts.verify_distribution", "path": "scripts/verify_distribution.py", - "sha256": "46e3590a8ac34181973e163f2df25e887bcb753eb3436b9e61cd935ba509948c", + "sha256": "357bd7f33128684a805d738632b083572885c0da55d1b22fb5bf5768517bba89", "top_level_classes": [], "top_level_functions": [ { @@ -15692,63 +15953,63 @@ "name": "_assert_imported_from_source" }, { - "end_line": 241, + "end_line": 242, "kind": "function", "line": 211, "name": "_verify_source_runtime" }, { - "end_line": 263, + "end_line": 264, "kind": "function", - "line": 244, + "line": 245, "name": "_install_editable" }, { - "end_line": 318, + "end_line": 319, "kind": "function", - "line": 266, + "line": 267, "name": "_build_and_install_wheel" }, { - "end_line": 332, + "end_line": 333, "kind": "function", - "line": 321, + "line": 322, "name": "_make_bad_wheel" }, { - "end_line": 393, + "end_line": 394, "kind": "function", - "line": 335, + "line": 336, "name": "_verify_bad_wheel" }, { - "end_line": 427, + "end_line": 428, "kind": "function", - "line": 396, + "line": 397, "name": "_verify_installed_runtime" }, { - "end_line": 453, + "end_line": 454, "kind": "function", - "line": 430, + "line": 431, "name": "_verify_cli_and_resources" }, { - "end_line": 475, + "end_line": 476, "kind": "function", - "line": 456, + "line": 457, "name": "_verify_editable_runtime" }, { - "end_line": 528, + "end_line": 529, "kind": "function", - "line": 478, + "line": 479, "name": "_verify_distribution" }, { - "end_line": 547, + "end_line": 548, "kind": "function", - "line": 531, + "line": 532, "name": "main" } ] @@ -16031,10 +16292,15 @@ "src/autoslice/desktop/__main__.py", "src/autoslice/desktop/ai_review.py", "src/autoslice/desktop/app.py", + "src/autoslice/desktop/commands.py", "src/autoslice/desktop/foundation.py", "src/autoslice/desktop/projects.py", + "src/autoslice/desktop/selection.py", + "src/autoslice/desktop/snap.py", + "src/autoslice/desktop/subtitle_preview.py", "src/autoslice/desktop/subtitle_render.py", "src/autoslice/desktop/subtitles.py", + "src/autoslice/desktop/waveform.py", "src/autoslice/desktop/qt_app/__init__.py", "src/autoslice/desktop/qt_app/__main__.py", "src/autoslice/desktop/qt_app/player.py", @@ -16144,9 +16410,12 @@ "tests/unit/test_desktop_ai_review.py", "tests/unit/test_desktop_app.py", "tests/unit/test_desktop_foundation.py", + "tests/unit/test_desktop_interaction.py", + "tests/unit/test_desktop_player.py", "tests/unit/test_desktop_projects.py", "tests/unit/test_desktop_render.py", "tests/unit/test_desktop_subtitles.py", + "tests/unit/test_desktop_timeline.py", "tests/unit/test_llm_client.py", "tests/unit/test_llm_contracts.py", "tests/unit/test_media_formats.py", @@ -16201,12 +16470,12 @@ }, "summary": { "duplicate_top_level_definition_count": 0, - "import_edge_count": 517, - "production_line_count": 49030, - "production_module_count": 199, + "import_edge_count": 528, + "production_line_count": 50926, + "production_module_count": 204, "test_private_patch_count": 17, - "top_level_class_count": 138, - "top_level_function_count": 1060 + "top_level_class_count": 148, + "top_level_function_count": 1061 }, "test_private_patches": { "by_target_module": { From b0f16c5dd6f94dd82c07b5c35e8009f27671608c Mon Sep 17 00:00:00 2001 From: sc57 Date: Sun, 4 Oct 2026 01:09:02 +0800 Subject: [PATCH 13/14] =?UTF-8?q?docs(refactor):=20=E8=AE=B0=E5=BD=95?= =?UTF-8?q?=E5=AE=A1=E8=AE=A1=E9=98=B6=E6=AE=B5=200=E3=80=811=20=E7=9A=84?= =?UTF-8?q?=E5=A4=84=E7=90=86=E7=BB=93=E6=9E=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- docs/refactor/AUDIT.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/docs/refactor/AUDIT.md b/docs/refactor/AUDIT.md index c7e092a..8e1e0a3 100644 --- a/docs/refactor/AUDIT.md +++ b/docs/refactor/AUDIT.md @@ -268,3 +268,22 @@ - **最大的类**:`DesktopWindow` 2268 行,`CoverWorkspace` 647 行,`SubtitleTimeline` 604 行,`SecurityPolicy` 538 行,`TaskStore` 538 行。 - **改动最频繁的仍然很大的文件**:`pipeline.py`(50 次提交),`web/app.py`(15 次),`analysis/boundaries.py`(13 次),`reporting.py`(13 次)。 - **测试覆盖**:只有 5 个生产模块在测试中完全没有被引用,其中 `media_preview` 实际上经路由和类名被间接测试,真正的缺口只有 `desktop/waveform.py`。 + +## 8. 处理记录 + +阶段 0 和阶段 1 已在 `desktop-vnext-refactor` 上完成,提交到 `desktop-vnext-dev` 等待合并: + +| 项 | 处理 | +|---|---| +| §3 护栏 | 合入 PR #1 的测试修复;新增的私有 patch 改为依赖注入或替身对象,回到上限 17;函数计数断言改为读取快照;重新生成快照 | +| M9 | 桌面端改由 `runtime_config` 解析投稿目录,去掉写死的本机路径;文档改为配置说明;发布扫描通过 | +| M4 | 字幕断行和字宽改用 `transcription.segments`;校对状态的结构字段由一个函数生成;两个 Flask 程序的响应收尾移到 `SecurityPolicy.finalize_flask_response` | +| L1 | 删除 `_split_subtitle_cues`、`_render_task`、`retain`、`template_defaults`;`follow_playback` 暂时保留,避免和 UI 分支冲突 | +| L2 | 只去掉集合里的重复项;改成规则表留到以后 | +| L3 | 两处改为只捕获具体异常;项目没有使用 `logging`,不加日志 | +| L4 | 闭包改用默认参数绑定 | +| M3 | Web 主程序和启动器改为直接从真实模块导入,测试的 patch 目标同步修改 | +| M7 | 脚本抽到 `static/topic_v2.js`,默认目录经 JSON 数据块注入,事件改为 `addEventListener` 绑定;CI 对两个外置脚本跑 `node --check` | +| M5 | 等维护者决定 | + +阶段 2~4 尚未开始。 From 75ee9e6db2f43ac431e1879228595a68403be137 Mon Sep 17 00:00:00 2001 From: sc57 Date: Sun, 4 Oct 2026 03:29:40 +0800 Subject: [PATCH 14/14] test: stabilize three desktop-vnext tests on the Windows runner These tests came with desktop-vnext-dev and never ran in CI, because the architecture snapshot check failed first. Once it passed, the Windows job exposed them: - The launcher media-tool test and the subtitle render service test compared resolved long paths with the runner's 8.3 short temp path (RUNNER~1). Resolve the temp root before building expectations. - The draft baseline test rewrites the source with content of the same byte size (42 bytes). On the runner both writes landed in one mtime tick, so the size + mtime signature did not change and the draft read back as ready. Push the mtime forward explicitly. Co-Authored-By: Claude Opus 5.5 --- tests/integration/test_launcher.py | 3 ++- tests/unit/test_desktop_foundation.py | 4 ++++ tests/unit/test_desktop_render.py | 3 ++- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/integration/test_launcher.py b/tests/integration/test_launcher.py index 5b99f6d..874900a 100644 --- a/tests/integration/test_launcher.py +++ b/tests/integration/test_launcher.py @@ -67,7 +67,8 @@ def test_gpu_runtime_path_stays_outside_repository(self): def test_media_tools_are_added_from_migrated_workspace_parent(self): with TemporaryDirectory() as directory: - drive_root = Path(directory) / "F盘" + # CI 临时目录是 8.3 短路径,候选目录经 resolve 后为长路径 + drive_root = Path(directory).resolve() / "F盘" project_dir = drive_root / "MyCode" / "AutoSlice" media_dir = drive_root / "ffmpeg" / "bin" project_dir.mkdir(parents=True) diff --git a/tests/unit/test_desktop_foundation.py b/tests/unit/test_desktop_foundation.py index 562ce89..0a0a871 100644 --- a/tests/unit/test_desktop_foundation.py +++ b/tests/unit/test_desktop_foundation.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import os import tempfile import unittest from pathlib import Path @@ -82,6 +83,9 @@ def test_baseline_from_editor_open_detects_change_before_first_autosave(self): self.source, dependencies=[self.corrected], ) self.source.write_text("外部修改发生在首次自动保存前", encoding="utf-8") + # 新内容恰与原文同为 42 字节;粗粒度文件时间下 mtime 可能不变,显式推后 + changed = self.source.stat() + os.utime(self.source, ns=(changed.st_atime_ns, baseline["source"]["mtime_ns"] + 10**9)) self.storage.save_draft( "subtitle", self.project, self.source, {"text": "编辑器内容"}, dependencies=[self.corrected], baseline=baseline, diff --git a/tests/unit/test_desktop_render.py b/tests/unit/test_desktop_render.py index 516c5d7..c71e7d7 100644 --- a/tests/unit/test_desktop_render.py +++ b/tests/unit/test_desktop_render.py @@ -29,7 +29,8 @@ class SubtitleRenderServiceTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) - self.root = Path(self.temp.name) + # CI 临时目录是 8.3 短路径,服务内部 resolve 后为长路径 + self.root = Path(self.temp.name).resolve() folder = self.root / "【中文】😊" folder.mkdir() self.video = folder / "短片.mp4"