docs: complete v1.6 semantic segmentation research
This commit is contained in:
@@ -1437,3 +1437,499 @@ class ContentSkill:
|
||||
*Architecture research for: Skill-based Workflow Orchestration System*
|
||||
*Original research: 2026-03-13*
|
||||
*Updated for v1.3 Anti-Crawler: 2026-03-18*
|
||||
|
||||
---
|
||||
|
||||
## v1.6 语义分段架构研究
|
||||
|
||||
**Milestone:** LLM-based Semantic Segmentation
|
||||
**Researched:** 2026-03-21
|
||||
**Focus:** 使用 LLM 替代基于规则的语义分段,实现智能章节识别和标题生成
|
||||
|
||||
---
|
||||
|
||||
### Executive Summary
|
||||
|
||||
本文档研究如何将 LLM 语义分段集成到现有的 SRT 处理架构中。基于对现有代码(`kb_workflow/srt/` 模块和 `SRTProcessor`)的分析,推荐采用 **渐进式迁移模式**,保留现有 RuleBasedSegmenter 作为 fallback,新增 LLMBasedSegmenter 作为主分段器。
|
||||
|
||||
关键架构决策:
|
||||
1. **新增 SemanticSegmenter 组件** — 替代/增强现有的 `segmenter.py`
|
||||
2. **单次 LLM 调用策略** — 完整上下文分析,避免边界拼接问题
|
||||
3. **三层降级策略** — LLM 失败 → 响应解析失败 → AI 不可用 → RuleBasedSegmenter
|
||||
4. **渐进式集成** — 不破坏现有功能,新组件作为可选增强
|
||||
|
||||
---
|
||||
|
||||
### Current Architecture (v1.5)
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ SRTProcessor │
|
||||
│ ┌─────────────┐ ┌──────────────┐ ┌─────────────┐ │
|
||||
│ │ parser.py │→ │segmenter.py │→ │corrector.py │ │
|
||||
│ │ (SRT解析) │ │ (规则分段) │ │ (ASR纠错) │ │
|
||||
│ └─────────────┘ └──────────────┘ └─────────────┘ │
|
||||
│ │ │ │ │
|
||||
│ ↓ ↓ ↓ │
|
||||
│ List[Segment] List[str] List[str] │
|
||||
│ (时间戳+文本) (段落) (纠错后) │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**现有组件:**
|
||||
- `parser.py`: 解析 SRT → Segment(id, start_time, end_time, text)
|
||||
- `segmenter.py`: SemanticSegmenter (基于时间间隔3s + 长度500字符规则)
|
||||
- `corrector.py`: ASRCorrector (使用 SimpleAIClient 纠错)
|
||||
|
||||
---
|
||||
|
||||
### Recommended Architecture (v1.6)
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ SRTProcessor │
|
||||
│ ┌─────────────┐ │
|
||||
│ │ parser.py │ │
|
||||
│ │ (SRT解析) │ │
|
||||
│ └──────┬──────┘ │
|
||||
│ │ │
|
||||
│ ↓ List[Segment] (id, start_time, end_time, text) │
|
||||
│ ┌──────────────────────────────────────────────────────────┐ │
|
||||
│ │ semantic_segmenter.py (NEW) │ │
|
||||
│ │ ┌────────────────────────────────────────────────────┐ │ │
|
||||
│ │ │ 1. 构建 Prompt (视频信息 + 字幕内容) │ │ │
|
||||
│ │ └──────────────────┬─────────────────────────────────┘ │ │
|
||||
│ │ ↓ │ │
|
||||
│ │ ┌────────────────────────────────────────────────────┐ │ │
|
||||
│ │ │ 2. 调用 LLM (SimpleAIClient.generate) │ │ │
|
||||
│ │ └──────────────────┬─────────────────────────────────┘ │ │
|
||||
│ │ ↓ │ │
|
||||
│ │ ┌────────────────────────────────────────────────────┐ │ │
|
||||
│ │ │ 3. 解析响应 (## 标题 + 内容) │ │ │
|
||||
│ │ └──────────────────┬─────────────────────────────────┘ │ │
|
||||
│ │ ↓ │ │
|
||||
│ │ ┌────────────────────────────────────────────────────┐ │ │
|
||||
│ │ │ 4. 返回 List[SemanticParagraph] │ │ │
|
||||
│ │ │ - title: str (章节标题) │ │ │
|
||||
│ │ │ - content: str (段落内容) │ │ │
|
||||
│ │ │ - time_range: (start, end) (可选) │ │ │
|
||||
│ │ └──────────────────┬─────────────────────────────────┘ │ │
|
||||
│ └─────────────────────┼─────────────────────────────────────┘ │
|
||||
│ ↓ │
|
||||
│ List[SemanticParagraph] │
|
||||
│ (标题 + 结构化内容) │
|
||||
│ ↓ │
|
||||
│ ┌──────────────────────────────────────────────────────────┐ │
|
||||
│ │ Fallback Strategy │ │
|
||||
│ │ LLM 失败 → 响应解析失败 → AI 不可用 │ │
|
||||
│ │ ↓ │ │
|
||||
│ │ segmenter.py (RuleBasedSegmenter) - 保留作为 fallback │ │
|
||||
│ └────────────────────┬─────────────────────────────────────┘ │
|
||||
│ ↓ │
|
||||
│ List[str] (向后兼容) │
|
||||
│ ↓ │
|
||||
│ ┌─────────────┐ ┌──────────────┐ │
|
||||
│ │corrector.py │ │ Markdown生成 │ │
|
||||
│ │ (ASR纠错) │ │ (标题+内容) │ │
|
||||
│ └─────────────┘ └──────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Component Boundaries
|
||||
|
||||
| Component | Responsibility | Communicates With |
|
||||
|-----------|---------------|-------------------|
|
||||
| **parser.py** | 解析 SRT 格式 → Segment 对象 | 无(输入层) |
|
||||
| **semantic_segmenter.py** (NEW) | LLM 语义分析 → 结构化段落 | parser (输入), corrector (输出), SimpleAIClient |
|
||||
| **segmenter.py** (EXIST) | 基于规则的分段(fallback) | semantic_segmenter (降级) |
|
||||
| **corrector.py** | ASR 纠错 | semantic_segmenter (输入), SimpleAIClient |
|
||||
| **SRTProcessor** | 编排处理流程 | 所有模块 |
|
||||
|
||||
---
|
||||
|
||||
### Data Flow Changes
|
||||
|
||||
**旧流程 (v1.5):**
|
||||
```
|
||||
SRT File → parser.parse_srt_file() → List[Segment]
|
||||
↓
|
||||
segmenter.segment() (基于规则)
|
||||
↓
|
||||
List[str] (段落)
|
||||
↓
|
||||
corrector.correct() (逐段落纠错)
|
||||
↓
|
||||
生成 Markdown
|
||||
```
|
||||
|
||||
**新流程 (v1.6):**
|
||||
```
|
||||
SRT File → parser.parse_srt_file() → List[Segment]
|
||||
↓
|
||||
[NEW] semantic_segmenter.segment()
|
||||
├─ 构建 Prompt (视频信息 + 字幕文本)
|
||||
├─ 调用 LLM (SimpleAIClient)
|
||||
├─ 解析响应 (## 标题 + 内容)
|
||||
└─ 返回 List[SemanticParagraph]
|
||||
├─ title: str
|
||||
├─ content: str
|
||||
└─ time_range: (float, float) (可选)
|
||||
↓
|
||||
[FALLBACK] segmenter.segment() (LLM 失败时)
|
||||
↓
|
||||
List[SemanticParagraph] → flatten → List[str]
|
||||
↓
|
||||
corrector.correct() (逐段落纠错)
|
||||
↓
|
||||
生成 Markdown (标题 + 内容结构)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Response Parsing Strategy
|
||||
|
||||
**LLM 响应格式要求:**
|
||||
```
|
||||
## 第一部分:机器学习基础概念
|
||||
段落内容1...
|
||||
段落内容2...
|
||||
|
||||
## 第二部分:深度学习原理
|
||||
段落内容3...
|
||||
段落内容4...
|
||||
```
|
||||
|
||||
**解析方法:**
|
||||
```python
|
||||
@dataclass
|
||||
class SemanticParagraph:
|
||||
"""语义分段结果"""
|
||||
title: str # 章节标题
|
||||
content: str # 段落内容
|
||||
start_time: float # 开始时间(可选)
|
||||
end_time: float # 结束时间(可选)
|
||||
|
||||
def parse_llm_response(response: str) -> List[SemanticParagraph]:
|
||||
"""解析 LLM 响应为结构化段落"""
|
||||
paragraphs = []
|
||||
current_title = "无标题"
|
||||
current_content = []
|
||||
|
||||
for line in response.split('\n'):
|
||||
if line.startswith('##'):
|
||||
# 保存上一个段落
|
||||
if current_content:
|
||||
content = '\n'.join(current_content).strip()
|
||||
if content:
|
||||
paragraphs.append(SemanticParagraph(
|
||||
title=current_title,
|
||||
content=content
|
||||
))
|
||||
# 开始新段落
|
||||
current_title = line.lstrip('#').strip()
|
||||
current_content = []
|
||||
else:
|
||||
current_content.append(line)
|
||||
|
||||
# 保存最后一个段落
|
||||
if current_content:
|
||||
content = '\n'.join(current_content).strip()
|
||||
if content:
|
||||
paragraphs.append(SemanticParagraph(
|
||||
title=current_title,
|
||||
content=content
|
||||
))
|
||||
|
||||
return paragraphs
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### LLM Call Strategy
|
||||
|
||||
**推荐:单次调用**
|
||||
|
||||
**原因:**
|
||||
1. **上下文完整性** — LLM 理解完整视频内容,分段更准确
|
||||
2. **避免边界问题** — 多次调用的拼接处容易出现语义不连贯
|
||||
3. **简化实现** — 单次调用更容易测试和调试
|
||||
|
||||
**Prompt 设计:**
|
||||
```python
|
||||
SEGMENTATION_PROMPT = """你是一个视频内容分析师。请将以下字幕内容按语义分段,并为每个段落生成标题。
|
||||
|
||||
【视频信息】
|
||||
标题:{video_title}
|
||||
时长:{duration}
|
||||
|
||||
【字幕内容】
|
||||
{concatenated_segments}
|
||||
|
||||
【输出要求】
|
||||
1. 按语义完整性分段(保持话题/论点完整)
|
||||
2. 识别主题变化边界
|
||||
3. 为每个段落生成简洁标题(不超过20字)
|
||||
4. 输出格式:
|
||||
|
||||
## 第一部分:{标题}
|
||||
{段落内容}
|
||||
|
||||
## 第二部分:{标题}
|
||||
{段落内容}
|
||||
|
||||
...(以此类推)
|
||||
|
||||
注意:
|
||||
- 段落长度建议 200-800 字符
|
||||
- 在自然句号处分段
|
||||
- 标题要概括该段核心内容
|
||||
"""
|
||||
```
|
||||
|
||||
**输入处理选项:**
|
||||
|
||||
**选项 1: 纯文本(推荐)**
|
||||
```python
|
||||
# 合并所有 Segment.text
|
||||
full_text = '\n'.join(seg.text for seg in segments)
|
||||
```
|
||||
|
||||
**选项 2: 带时间戳标记(可选,用于辅助理解)**
|
||||
```python
|
||||
# 添加时间戳辅助 LLM 理解结构
|
||||
marked_text = '\n'.join(
|
||||
f"[{format_time(seg.start_time)}] {seg.text}"
|
||||
for seg in segments
|
||||
)
|
||||
```
|
||||
|
||||
**替代方案:流式调用**
|
||||
- 用于超长视频(>1小时字幕)
|
||||
- 分块调用 LLM,每块 10-15 分钟字幕
|
||||
- 需要额外的边界拼接逻辑
|
||||
- **建议:** 初期使用单次调用,后续根据实际需求优化
|
||||
|
||||
---
|
||||
|
||||
### Fallback Strategy
|
||||
|
||||
**三层降级策略:**
|
||||
|
||||
```python
|
||||
class LLMBasedSegmenter:
|
||||
def __init__(self, ai_client: SimpleAIClient):
|
||||
self.ai_client = ai_client
|
||||
self.rule_based = SemanticSegmenter() # Fallback
|
||||
|
||||
def segment(self, segments: List[Segment]) -> List[SemanticParagraph]:
|
||||
# Level 3: AI 客户端不可用
|
||||
if not self.ai_client or not self.ai_client.api_key:
|
||||
logger.info("AI client not available, using rule-based")
|
||||
return self._to_semantic_paragraphs(
|
||||
self.rule_based.segment(segments)
|
||||
)
|
||||
|
||||
try:
|
||||
# Level 1: LLM 调用
|
||||
prompt = self._build_prompt(segments)
|
||||
response = self.ai_client.generate(prompt)
|
||||
|
||||
# Level 2: 响应解析
|
||||
try:
|
||||
paragraphs = self._parse_llm_response(response)
|
||||
if not paragraphs:
|
||||
raise ValueError("Empty parsed result")
|
||||
return paragraphs
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to parse LLM response: {e}")
|
||||
return self._to_semantic_paragraphs(
|
||||
self.rule_based.segment(segments)
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"LLM call failed: {e}, using rule-based")
|
||||
return self._to_semantic_paragraphs(
|
||||
self.rule_based.segment(segments)
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Suggested Build Order
|
||||
|
||||
**Phase 1: 基础组件(不影响现有功能)**
|
||||
1. 创建 `kb_workflow/srt/semantic_segmenter.py`
|
||||
2. 实现 `SemanticParagraph` 数据类
|
||||
3. 实现 `parse_llm_response()` 方法(独立于 LLM 调用)
|
||||
4. 编写单元测试(mock LLM 响应,测试解析逻辑)
|
||||
|
||||
**Phase 2: LLM 集成**
|
||||
5. 实现 `_build_prompt()` 方法
|
||||
6. 集成 SimpleAIClient
|
||||
7. 实现 `segment()` 主方法
|
||||
8. 实现降级策略(fallback)
|
||||
9. 编写集成测试(使用真实 LLM 或 mock)
|
||||
|
||||
**Phase 3: 处理器集成**
|
||||
10. 修改 `SRTProcessor.__init__()`:
|
||||
- 添加 `use_llm_segmenter: bool = False` 参数
|
||||
- 条件性初始化 `llm_segmenter`
|
||||
11. 修改 `SRTProcessor.process()`:
|
||||
- 调用新分段器或保留旧分段器
|
||||
- 处理 `SemanticParagraph` 输出
|
||||
12. 更新 `_generate_markdown()`:
|
||||
- 处理标题和内容结构
|
||||
- 生成带层级的 Markdown
|
||||
13. 保留 RuleBasedSegmenter 作为 fallback
|
||||
|
||||
**Phase 4: 输出优化**
|
||||
14. 优化 Markdown 格式(标题层级 `###`)
|
||||
15. 添加时间戳(可选,在段落中标注时间范围)
|
||||
16. 更新文档和测试
|
||||
|
||||
---
|
||||
|
||||
### Schema Changes
|
||||
|
||||
**新增数据类:**
|
||||
```python
|
||||
@dataclass
|
||||
class SemanticParagraph:
|
||||
"""语义分段结果"""
|
||||
title: str # 章节标题
|
||||
content: str # 段落内容
|
||||
start_time: Optional[float] = None # 开始时间(可选)
|
||||
end_time: Optional[float] = None # 结束时间(可选)
|
||||
```
|
||||
|
||||
**修改 SRTOutput (向后兼容):**
|
||||
```python
|
||||
class SRTOutput(BaseModel):
|
||||
success: bool
|
||||
output_file: str
|
||||
paragraphs: List[str] # 保留向后兼容
|
||||
semantic_paragraphs: Optional[List[SemanticParagraph]] = None # 新增
|
||||
tags: List[str]
|
||||
corrected: bool
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Patterns to Follow
|
||||
|
||||
#### Pattern 1: 渐进式迁移
|
||||
**What:** 保留现有组件,新组件作为可选增强
|
||||
**When:** 重构关键路径时
|
||||
**Example:**
|
||||
```python
|
||||
class SRTProcessor:
|
||||
def __init__(self, use_llm_segmenter: bool = False):
|
||||
self.rule_based_segmenter = SemanticSegmenter() # 保留
|
||||
if use_llm_segmenter:
|
||||
self.llm_segmenter = LLMBasedSegmenter() # 新增
|
||||
|
||||
async def process(self, input_data):
|
||||
# 优先使用 LLM,失败时降级
|
||||
if hasattr(self, 'llm_segmenter'):
|
||||
try:
|
||||
paragraphs = self.llm_segmenter.segment(segments)
|
||||
except Exception:
|
||||
paragraphs = self.rule_based_segmenter.segment(segments)
|
||||
else:
|
||||
paragraphs = self.rule_based_segmenter.segment(segments)
|
||||
```
|
||||
|
||||
#### Pattern 2: 协议兼容性
|
||||
**What:** 新旧组件共享相同接口
|
||||
**When:** 替换组件时
|
||||
**Example:**
|
||||
```python
|
||||
# 两个分段器实现相同接口
|
||||
class Segmenter(Protocol):
|
||||
def segment(self, segments: List[Segment]) -> List[str]:
|
||||
...
|
||||
|
||||
class RuleBasedSegmenter:
|
||||
def segment(self, segments: List[Segment]) -> List[str]:
|
||||
# 基于规则
|
||||
...
|
||||
|
||||
class LLMBasedSegmenter:
|
||||
def segment(self, segments: List[Segment]) -> List[str]:
|
||||
# 基于 LLM
|
||||
# 内部使用 SemanticParagraph,输出时合并标题和内容
|
||||
return [
|
||||
f"## {p.title}\n\n{p.content}"
|
||||
for p in self._segment_internal(segments)
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Anti-Patterns to Avoid
|
||||
|
||||
#### Anti-Pattern 1: 破坏性替换
|
||||
**What:** 直接删除 RuleBasedSegmenter
|
||||
**Why bad:** LLM 可能失败,失去降级选项
|
||||
**Instead:** 保留旧组件作为 fallback
|
||||
|
||||
#### Anti-Pattern 2: 紧耦合 Prompt 逻辑
|
||||
**What:** 将 prompt 构建硬编码在 segmenter 中
|
||||
**Why bad:** 难以测试和优化
|
||||
**Instead:** 提取为独立方法或模板,便于测试
|
||||
|
||||
#### Anti-Pattern 3: 忽略时间戳信息
|
||||
**What:** 仅传递文本给 LLM,忽略时间信息
|
||||
**Why bad:** LLM 无法理解视频结构(停顿、章节)
|
||||
**Instead:** 在 prompt 中包含时间戳标记或视频时长信息
|
||||
|
||||
---
|
||||
|
||||
### Scalability Considerations
|
||||
|
||||
| Concern | At 100 videos | At 10K videos | At 1M videos |
|
||||
|---------|--------------|--------------|-------------|
|
||||
| **LLM 调用延迟** | 可接受(~10-30s/视频) | 需要并发处理 | 需要队列+批处理 |
|
||||
| **LLM 成本** | 可忽略 | 需要监控 | 需要缓存+降级策略 |
|
||||
| **错误率** | 低,手动处理 | 需要自动重试 | 需要监控告警 |
|
||||
| **响应解析** | 简单 | 需要容错增强 | 需要多模型支持 |
|
||||
|
||||
**建议:**
|
||||
- 初期:单线程处理,完整错误日志
|
||||
- 中期:添加并发处理(asyncio.Semaphore 限制并发数)
|
||||
- 长期:分布式队列(Celery/RQ)+ 结果缓存
|
||||
|
||||
---
|
||||
|
||||
### Integration Points Summary
|
||||
|
||||
**新增集成点:**
|
||||
1. `SRTProcessor.__init__()` → 条件性初始化 `LLMBasedSegmenter`
|
||||
2. `SRTProcessor.process()` → 调用新分段器或旧分段器
|
||||
3. `_generate_markdown()` → 处理 `SemanticParagraph` 结构
|
||||
|
||||
**保留集成点:**
|
||||
1. `parser.parse_srt_file()` — 不变
|
||||
2. `corrector.correct()` — 不变(处理 `List[str]`)
|
||||
3. `WorkflowStateManager` — 不变
|
||||
|
||||
**修改点:**
|
||||
1. `kb_workflow/srt/__init__.py` — 导出 `SemanticParagraph`
|
||||
2. `kb_workflow/pipeline/schemas.py` — 更新 `SRTOutput`
|
||||
|
||||
---
|
||||
|
||||
### v1.6 Sources
|
||||
|
||||
- 现有架构分析: `kb_workflow/srt/` 模块
|
||||
- SRTProcessor 实现: `kb_workflow/pipeline/processors/srt.py`
|
||||
- SimpleAIClient 实现: `kb_workflow/deep_analyzer/__init__.py`
|
||||
- 测试用例: `tests/test_srt_processor.py`
|
||||
- 项目上下文: `.planning/PROJECT.md`
|
||||
|
||||
---
|
||||
|
||||
*Architecture research for: LLM-based Semantic Segmentation*
|
||||
*Research date: 2026-03-21*
|
||||
|
||||
Reference in New Issue
Block a user