Compare commits
8 Commits
996c25af3f
..
v1.5
| Author | SHA1 | Date | |
|---|---|---|---|
| d039537f1d | |||
| a2ca45523b | |||
| 0752f8b38f | |||
| 4d2645876b | |||
| 9e007432eb | |||
| 7ac4937c48 | |||
| 1f599f0c60 | |||
| 7903690882 |
@@ -0,0 +1,60 @@
|
||||
# Semantic Segmentation for SRT Processing
|
||||
|
||||
**Status:** Backlog
|
||||
**Priority:** Medium
|
||||
**Source:** User feedback during v1.5 testing
|
||||
|
||||
## Problem
|
||||
|
||||
Current `SemanticSegmenter` uses simple heuristic rules:
|
||||
- Time gap > 3 seconds
|
||||
- Paragraph length > 500 characters
|
||||
|
||||
This approach cannot identify **semantic topic transitions**.
|
||||
|
||||
### Example Case
|
||||
|
||||
Video: BV1MiPSz2ErY (科学透镜 - 5 topics in one video)
|
||||
1. 银河系中心的超大黑洞人马座A*其实不是黑洞
|
||||
2. 银河系和仙女座星系等构成的本星系群陷入巨大物质薄片
|
||||
3. 科学家为世界上97%的建筑生成3D模型
|
||||
4. 雷暴的形成
|
||||
5. 闪电的形成
|
||||
|
||||
Current segmentation mixes these topics together.
|
||||
|
||||
## Potential Solutions
|
||||
|
||||
### Option 1: Transition Keyword Detection (Simple)
|
||||
- Detect common transition phrases: "接下来", "另外", "第二个", etc.
|
||||
- **Pros:** Fast, no API calls
|
||||
- **Cons:** Low accuracy, many videos lack explicit transitions
|
||||
|
||||
### Option 2: LLM-Based Segmentation (Accurate)
|
||||
- Ask LLM to analyze entire subtitle and identify topic boundaries
|
||||
- **Pros:** Highest accuracy, understands semantics
|
||||
- **Cons:** Extra API cost, token limits for long videos
|
||||
|
||||
### Option 3: Two-Stage Approach (Balanced)
|
||||
- Stage 1: Simple rule-based segmentation (current)
|
||||
- Stage 2: LLM checks paragraph beginnings for new topics
|
||||
- **Pros:** Most cases use simple rules, LLM only for key decisions
|
||||
- **Cons:** More complex implementation
|
||||
|
||||
### Option 4: Embedding-Based Similarity
|
||||
- Calculate semantic similarity between adjacent paragraphs
|
||||
- Low similarity = topic boundary
|
||||
- **Pros:** No LLM API calls, runs locally
|
||||
- **Cons:** Requires embedding model, implementation complexity
|
||||
|
||||
## Recommendation
|
||||
|
||||
**Phase 1 (Quick Win):** Transition keyword detection + improve prompt
|
||||
|
||||
**Phase 2 (Full Solution):** Two-stage approach with optional LLM semantic segmentation
|
||||
|
||||
## Success Criteria
|
||||
|
||||
1. Topics are separated correctly
|
||||
2. Each paragraph covers a single coherent topic
|
||||
3. No false splits within a topic
|
||||
@@ -0,0 +1,146 @@
|
||||
---
|
||||
status: awaiting_human_verify
|
||||
trigger: "DeepAnalyzer: (1) 禁用思考模式后准确性下降(鲜合器→银河系),(2) 摘要部分只是重复开头文字需移除,(3) 元数据 title/author 仍不正确"
|
||||
created: 2026-03-20T00:00:00Z
|
||||
updated: 2026-03-21T02:45:00Z
|
||||
---
|
||||
|
||||
## Current Focus
|
||||
|
||||
hypothesis: |
|
||||
**修复已完成,单元测试通过,等待用户端到端验证**
|
||||
|
||||
修复1: 移除 thinking.type="disabled" 参数
|
||||
- 文件:kb_workflow/deep_analyzer/__init__.py (第91-122行)
|
||||
- 修改:移除 `"thinking": {"type": "disabled"}` 参数
|
||||
- 效果:AI 将使用默认思考模式,提高 ASR 纠错准确性
|
||||
|
||||
修复2: SRTProcessor metadata 扁平化
|
||||
- 文件:kb_workflow/pipeline/processors/srt.py (第162-195行)
|
||||
- 修改:添加扁平化逻辑,处理嵌套结构 {metadata: {...}}
|
||||
- 效果:正确提取 title/author 等元数据字段
|
||||
|
||||
修复3: 移除 SRTProcessor 摘要部分
|
||||
- 文件:kb_workflow/pipeline/processors/srt.py (第195-230行)
|
||||
- 修改:移除摘要部分生成代码
|
||||
- 效果:不再生成低质量的摘要部分
|
||||
|
||||
修复4: duration 字段类型处理
|
||||
- 文件:kb_workflow/pipeline/processors/srt.py (第276-284行)
|
||||
- 修改:添加类型检查,支持字符串和整数格式
|
||||
- 效果:正确处理 "05:42" 字符串格式的时长
|
||||
|
||||
test: |
|
||||
单元测试通过:
|
||||
- ✅ metadata 扁平化逻辑正确
|
||||
- ✅ frontmatter 生成正确(title, author, bvid 都正确)
|
||||
- ✅ duration 字段类型处理正确
|
||||
|
||||
等待端到端测试:
|
||||
1. 重新运行 Bilibili pipeline 处理 BV1MiPSz2ErY
|
||||
2. 检查生成的 analysis.md 文件
|
||||
expecting: |
|
||||
1. ASR纠错准确性提高("银河系"不应被误写为"鲜合器")
|
||||
2. 输出不再包含摘要部分
|
||||
3. 元数据正确显示标题:"新研究表明,银心的能量来源可能是暗物质,而非黑洞,【科学快报】第263期"
|
||||
4. 元数据正确显示作者:"科学透镜"
|
||||
next_action: |
|
||||
等待用户重新运行 pipeline 并验证结果
|
||||
|
||||
## Symptoms
|
||||
expected: |
|
||||
1. ASR纠错准确(如"银河系"不会被误写为"鲜合器")
|
||||
2. 摘要是真正的总结提炼,不是重复开头文字(或直接移除摘要部分)
|
||||
3. 元数据正确显示标题、作者等
|
||||
actual: |
|
||||
1. 第18行显示"我们的鲜合器其实是被吸引进了一个明天数千万光年..." - 识别错误
|
||||
2. 第8-10行摘要只是重复视频开头文字,非真正总结
|
||||
3. 第2-4行显示 title: "未命名", author: "未知"
|
||||
errors: |
|
||||
- ASR纠错准确性下降
|
||||
- 摘要质量问题
|
||||
- 元数据未正确填充
|
||||
reproduction: |
|
||||
参考:~/work/zq/30.资源/AI分析/bilibili/20260321_BV1MiPSz2ErY_analysis.md
|
||||
started: 2026-03-21,用户验证修复后报告新问题
|
||||
|
||||
## Eliminated
|
||||
|
||||
## Evidence
|
||||
|
||||
[... previous evidence ...]
|
||||
|
||||
- timestamp: 2026-03-21T02:45:00Z
|
||||
checked: 单元测试结果
|
||||
found: |
|
||||
1. ✅ metadata 扁平化逻辑正确
|
||||
2. ✅ frontmatter 生成正确
|
||||
3. ✅ title: "新研究表明,银心的能量来源可能是暗物质,而非黑洞,【科学快报】第263期"
|
||||
4. ✅ author: "科学透镜"
|
||||
5. ✅ bvid: "BV1MiPSz2ErY"
|
||||
6. ✅ duration: "05:42"
|
||||
implication: |
|
||||
**修复验证:**
|
||||
1. metadata 扁平化逻辑正确处理嵌套结构
|
||||
2. frontmatter 生成正确包含所有字段
|
||||
3. duration 类型处理正确(字符串和整数都支持)
|
||||
|
||||
## Resolution
|
||||
|
||||
root_cause: |
|
||||
1. **thinking.type=disabled 导致ASR纠错准确性下降**
|
||||
- SimpleAIClient._call_zhipu() 禁用思考模式
|
||||
- 影响 ASRCorrector 纠错质量
|
||||
|
||||
2. **SRTProcessor 未扁平化嵌套 metadata 结构**
|
||||
- metadata.json: {metadata: {title: "xxx", author: "xxx"}}
|
||||
- SRTProcessor._generate_frontmatter() 直接访问 metadata.get('title')
|
||||
- 返回 None,使用默认值"未命名"
|
||||
|
||||
3. **SRTProcessor 自动生成低质量摘要**
|
||||
- 第219-226行简单复制第一段开头200字符
|
||||
- 用户要求移除摘要部分
|
||||
|
||||
4. **duration 字段类型处理不当**
|
||||
- metadata 中 duration 是字符串 "05:42"
|
||||
- _format_duration 期望整数秒数
|
||||
- 导致 TypeError
|
||||
|
||||
fix: |
|
||||
1. **kb_workflow/deep_analyzer/__init__.py (第91-122行)**
|
||||
- 修改 _call_zhipu() 方法
|
||||
- 移除 `"thinking": {"type": "disabled"}` 参数
|
||||
- 让AI使用默认思考模式以提高准确性
|
||||
- 同时处理 reasoning_content 字段作为后备
|
||||
|
||||
2. **kb_workflow/pipeline/processors/srt.py (第162-195行)**
|
||||
- 修改 _load_metadata() 方法
|
||||
- 添加扁平化逻辑,与 AnalyzeProcessor._normalize_metadata() 一致
|
||||
- 处理嵌套结构 {metadata: {...}}
|
||||
|
||||
3. **kb_workflow/pipeline/processors/srt.py (第195-230行)**
|
||||
- 修改 _generate_markdown() 方法
|
||||
- 移除摘要部分生成代码(原第219-226行)
|
||||
|
||||
4. **kb_workflow/pipeline/processors/srt.py (第276-284行)**
|
||||
- 修改 _generate_frontmatter() 方法
|
||||
- 添加 duration 类型检查
|
||||
- 支持字符串和整数格式
|
||||
|
||||
verification: |
|
||||
单元验证完成:
|
||||
1. ✅ metadata 扁平化逻辑正确
|
||||
2. ✅ frontmatter 生成正确
|
||||
3. ✅ duration 类型处理正确
|
||||
4. ✅ title/author/bvid 都正确显示
|
||||
|
||||
等待用户端到端验证:
|
||||
1. 重新运行 Bilibili pipeline 处理 BV1MiPSz2ErY
|
||||
2. 检查生成的 analysis.md 文件
|
||||
3. 验证 title/author 是否正确显示
|
||||
4. 验证是否不再包含摘要部分
|
||||
5. 验证 ASR 纠错准确性("银河系"不应被误写为"鲜合器")
|
||||
|
||||
files_changed:
|
||||
- kb_workflow/deep_analyzer/__init__.py (修改 _call_zhipu 方法)
|
||||
- kb_workflow/pipeline/processors/srt.py (修改 _load_metadata, _generate_markdown, _generate_frontmatter 方法)
|
||||
@@ -0,0 +1,90 @@
|
||||
---
|
||||
status: awaiting_human_verify
|
||||
trigger: "调查并修复 SRTProcessor 的 ASR 纠错问题:启用思考模式后输出 AI 的思考过程而非纠错后的字幕内容,以及文件命名缺少标题"
|
||||
created: 2026-03-21T22:00:00.000000
|
||||
updated: 2026-03-21T22:30:00.000000
|
||||
---
|
||||
|
||||
## Current Focus
|
||||
hypothesis: 修复已完成并通过测试
|
||||
test: 所有自动化测试通过(4/4)
|
||||
expecting: ASR 纠错将使用禁用思考模式,文件命名将包含标题
|
||||
next_action: 用户需要在实际环境中验证修复效果
|
||||
|
||||
## 自我验证结果
|
||||
- ✓ SimpleAIClient 支持 disable_reasoning 参数
|
||||
- ✓ ASRCorrector 使用 disable_reasoning=True
|
||||
- ✓ ArchiveProcessor 从 frontmatter 提取标题
|
||||
- ✓ _call_zhipu 在 disable_reasoning=True 时添加 thinking.type=disabled
|
||||
|
||||
## Symptoms
|
||||
expected: |
|
||||
1. ASR 纠错后输出纠正和润色后的完整字幕内容
|
||||
2. 文件命名包含视频标题
|
||||
actual: |
|
||||
1. 输出包含 AI 的思考过程(Analyze the Request, 分析请求等)
|
||||
2. 文件命名格式:20260321_BV1MiPSz2ErY_analysis.md(缺少标题)
|
||||
errors: |
|
||||
- AI 返回 reasoning_content 而非 content
|
||||
- 文件命名未包含标题
|
||||
reproduction: |
|
||||
参考:~/work/zq/30.资源/AI分析/bilibili/20260321_BV1MiPSz2ErY_analysis.md
|
||||
文件内容显示AI的思考分析过程而非纠错后的字幕
|
||||
started: |
|
||||
2026-03-21,修复 DeepAnalyzer 后重新启用思考模式,但 SRTProcessor 也受到相同问题影响
|
||||
|
||||
## Eliminated
|
||||
|
||||
## Evidence
|
||||
- timestamp: 2026-03-21T22:00:00
|
||||
checked: 实际输出文件 ~/work/zq/30.资源/AI分析/bilibili/20260321_BV1MiPSz2ErY_analysis.md
|
||||
found: 文件内容包含 AI 的思考分析过程("Analyze the Request", "分析请求" 等),而非纠错后的字幕
|
||||
implication: 修复代码没有生效,问题仍然存在
|
||||
|
||||
- timestamp: 2026-03-21T22:00:00
|
||||
checked: DeepAnalyzer._call_zhipu 的修复逻辑(第 110-124 行)
|
||||
found: 代码逻辑是"优先返回 content 字段,如果 content 为空才使用 reasoning_content"
|
||||
implication: 这个逻辑是错误的!当启用思考模式时,content 不为空但包含的是 AI 的分析过程
|
||||
|
||||
- timestamp: 2026-03-21T22:00:00
|
||||
checked: 智谱 API 文档
|
||||
found: thinking.type 参数控制是否启用思考模式:enabled(默认)或 disabled
|
||||
implication: 解决方案是在调用 API 时显式设置 thinking.type="disabled" 来禁用思考模式
|
||||
|
||||
- timestamp: 2026-03-21T22:00:00
|
||||
checked: 提交 7ac4937 的 diff
|
||||
found: 该提交移除了 thinking.type="disabled" 参数,导致启用默认的思考模式
|
||||
implication: 这就是问题的根源!移除 thinking.type="disabled" 后,AI 返回分析过程而非直接答案
|
||||
|
||||
- timestamp: 2026-03-21T22:00:00
|
||||
checked: 之前的提交 7903690
|
||||
found: 这个提交添加了 thinking.type="disabled" 参数来禁用思考模式
|
||||
implication: 但提交 7ac4937 又移除了它,导致问题重新出现
|
||||
|
||||
## Resolution
|
||||
root_cause: |
|
||||
提交 7ac4937 移除了 thinking.type="disabled" 参数,导致智谱 API 使用默认的思考模式。
|
||||
当启用思考模式时,AI 返回的内容(content 字段)包含了详细的分析过程(如 "Analyze the Request"),
|
||||
而非我们期望的直接纠错后的字幕。ASR 纠错需要的是直接结果,不需要分析过程。
|
||||
|
||||
fix: |
|
||||
1. 在 SimpleAIClient 中添加 disable_reasoning 参数(默认 False)
|
||||
2. 在 ASRCorrector 调用时设置 disable_reasoning=True
|
||||
3. 在 _call_zhipu 方法中,当 disable_reasoning=True 时添加 thinking.type="disabled" 参数
|
||||
4. 在 ArchiveProcessor 中从 frontmatter 提取标题并添加到文件名
|
||||
files_changed: []
|
||||
- kb_workflow/deep_analyzer/__init__.py: 添加 disable_reasoning 参数支持
|
||||
- kb_workflow/srt/corrector.py: ASRCorrector 使用 disable_reasoning=True
|
||||
- kb_workflow/pipeline/processors/archive.py: 从文件提取标题并添加到文件名
|
||||
|
||||
verification: |
|
||||
自动化测试全部通过(4/4):
|
||||
|
||||
1. ✓ SimpleAIClient 默认 disable_reasoning=False
|
||||
2. ✓ 可以设置 disable_reasoning=True
|
||||
3. ✓ generate 方法有 disable_reasoning 参数
|
||||
4. ✓ ASRCorrector._correct_batch 使用 disable_reasoning=True
|
||||
5. ✓ _extract_title_from_file 正确提取标题
|
||||
6. ✓ _sanitize_title 清理标题
|
||||
7. ✓ _call_zhipu 在 disable_reasoning=True 时添加 thinking.type=disabled
|
||||
8. ✓ _call_zhipu 返回 content 字段
|
||||
@@ -12,3 +12,6 @@ export KB_BASE_PATH="~/work/knowledge-base"
|
||||
# 可选: Git 配置
|
||||
# export KB_GIT_USER="Your Name"
|
||||
# export KB_GIT_EMAIL="your@email.com"
|
||||
|
||||
# 可选: 工作流行为配置
|
||||
# export KB_OVERWRITE_ARCHIVES="false" # 非交互模式下是否覆盖已存在的归档文件(true/false)
|
||||
|
||||
@@ -37,20 +37,25 @@ class AnalysisResult:
|
||||
class SimpleAIClient:
|
||||
"""AI 客户端"""
|
||||
|
||||
def __init__(self, api_key: str = None, provider: str = None, model: str = None, base_url: str = None):
|
||||
def __init__(self, api_key: str = None, provider: str = None, model: str = None, base_url: str = None, disable_reasoning: bool = False):
|
||||
self.api_key = api_key or os.environ.get("AI_API_KEY", "")
|
||||
self.provider = provider or os.environ.get("AI_PROVIDER", "")
|
||||
self.model = model or os.environ.get("AI_MODEL", "glm-5")
|
||||
self.base_url = base_url or os.environ.get("AI_BASE_URL", "")
|
||||
self.max_retries = 3
|
||||
self.disable_reasoning = disable_reasoning
|
||||
|
||||
def generate(self, prompt: str, max_tokens: int = 16000) -> str:
|
||||
def generate(self, prompt: str, max_tokens: int = 16000, disable_reasoning: bool = None) -> str:
|
||||
"""生成文本"""
|
||||
api_key = os.environ.get("AI_API_KEY", self.api_key)
|
||||
provider = os.environ.get("AI_PROVIDER", self.provider)
|
||||
model = os.environ.get("AI_MODEL", self.model)
|
||||
base_url = os.environ.get("AI_BASE_URL", self.base_url)
|
||||
|
||||
# 确定 disable_reasoning 的值:优先使用参数,否则使用实例变量
|
||||
if disable_reasoning is None:
|
||||
disable_reasoning = self.disable_reasoning
|
||||
|
||||
if not api_key:
|
||||
raise ValueError("AI_API_KEY 未设置")
|
||||
|
||||
@@ -63,7 +68,7 @@ class SimpleAIClient:
|
||||
if provider == "openai":
|
||||
result = self._call_openai(prompt, max_tokens, api_key, model, base_url)
|
||||
elif provider == "zhipu":
|
||||
result = self._call_zhipu(prompt, max_tokens, api_key, model, base_url)
|
||||
result = self._call_zhipu(prompt, max_tokens, api_key, model, base_url, disable_reasoning)
|
||||
elif provider == "minimax":
|
||||
result = self._call_minimax(prompt, max_tokens, api_key, model, base_url)
|
||||
else:
|
||||
@@ -88,24 +93,53 @@ class SimpleAIClient:
|
||||
response.raise_for_status()
|
||||
return response.json()['choices'][0]['message']['content']
|
||||
|
||||
def _call_zhipu(self, prompt: str, max_tokens: int, api_key: str, model: str, base_url: str) -> str:
|
||||
def _call_zhipu(self, prompt: str, max_tokens: int, api_key: str, model: str, base_url: str, disable_reasoning: bool = False) -> str:
|
||||
import requests
|
||||
import sys
|
||||
|
||||
base_url = base_url or "https://open.bigmodel.cn/api/coding/paas/v4"
|
||||
url = f"{base_url}/chat/completions"
|
||||
headers = {"Authorization": f"Bearer {api_key}"}
|
||||
payload = {"model": model, "messages": [{"role": "user", "content": prompt}], "max_tokens": max_tokens}
|
||||
# GLM-4.5/4.6/4.7/5 默认启用thinking mode
|
||||
# 通过 disable_reasoning 参数控制是否禁用思考模式
|
||||
payload = {
|
||||
"model": model,
|
||||
"messages": [{"role": "user", "content": prompt}],
|
||||
"max_tokens": max_tokens
|
||||
}
|
||||
|
||||
# 如果明确要求禁用思考模式,添加 thinking 参数
|
||||
if disable_reasoning:
|
||||
payload["thinking"] = {"type": "disabled"}
|
||||
response = requests.post(url, headers=headers, json=payload, timeout=600)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
message = data.get('choices', [{}])[0].get('message', {})
|
||||
|
||||
# 调试:打印完整的 API 响应结构
|
||||
print(f"[DEBUG] disable_reasoning={disable_reasoning}", file=sys.stderr)
|
||||
print(f"[DEBUG] message keys: {list(message.keys())}", file=sys.stderr)
|
||||
if 'content' in message:
|
||||
print(f"[DEBUG] content 长度: {len(message['content'])}, 前200字符: {message['content'][:200]}", file=sys.stderr)
|
||||
if 'reasoning_content' in message:
|
||||
print(f"[DEBUG] reasoning_content 长度: {len(message['reasoning_content'])}, 前200字符: {message['reasoning_content'][:200]}", file=sys.stderr)
|
||||
|
||||
# 返回 content 字段
|
||||
# 当禁用思考模式时,content 包含直接答案
|
||||
# 当启用思考模式时,content 可能包含思考过程和分析
|
||||
content = message.get('content', '')
|
||||
reasoning = message.get('reasoning_content', '')
|
||||
if not content and reasoning:
|
||||
sentences = reasoning.strip().split('。')
|
||||
useful = [s.strip() for s in sentences if s.strip() and len(s.strip()) > 10]
|
||||
if useful:
|
||||
return '。'.join(useful[-3:]) + '。'
|
||||
return reasoning.strip()[:500]
|
||||
|
||||
if not content:
|
||||
# 如果 content 为空,检查是否有 reasoning_content
|
||||
reasoning = message.get('reasoning_content', '')
|
||||
if reasoning:
|
||||
print(f"[DEBUG] Zhipu API返回空的content,使用reasoning_content。", file=sys.stderr)
|
||||
print(f"[DEBUG] reasoning_content前200字符: {reasoning[:200]}", file=sys.stderr)
|
||||
content = reasoning
|
||||
|
||||
if not content:
|
||||
raise ValueError(f"Zhipu API返回空内容。请检查API配置和模型参数。响应数据: {data}")
|
||||
|
||||
return content
|
||||
|
||||
def _call_minimax(self, prompt: str, max_tokens: int, api_key: str, model: str, base_url: str) -> str:
|
||||
|
||||
@@ -58,6 +58,11 @@ class KBSettings(BaseSettings):
|
||||
default=SecretStr(""), description="B站 Cookie (for video download)"
|
||||
)
|
||||
|
||||
# 工作流行为配置
|
||||
overwrite_archives: bool = Field(
|
||||
default=False, description="覆盖已存在的归档文件(非交互模式)"
|
||||
)
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> KBSettings:
|
||||
|
||||
@@ -7,6 +7,7 @@ to the archive directory organized by platform.
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
@@ -46,6 +47,8 @@ class ArchiveProcessor(BaseProcessor):
|
||||
Archive 处理结果
|
||||
"""
|
||||
try:
|
||||
import sys
|
||||
|
||||
# Step 1: 检查是否已完成(幂等执行)
|
||||
if self.state_manager:
|
||||
state = self.state_manager.load()
|
||||
@@ -63,9 +66,14 @@ class ArchiveProcessor(BaseProcessor):
|
||||
platform_dir = archive_base / input_data.platform
|
||||
platform_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 文件命名: {YYYYMMDD}_{content_id}_analysis.md
|
||||
# 从源文件中提取标题(用于文件命名)
|
||||
title = self._extract_title_from_file(Path(input_data.analysis_file))
|
||||
# 清理标题:移除特殊字符,限制长度
|
||||
safe_title = self._sanitize_title(title) if title else input_data.content_id
|
||||
|
||||
# 文件命名: {YYYYMMDD}_{content_id}_{title}_analysis.md
|
||||
timestamp = datetime.now().strftime("%Y%m%d")
|
||||
archive_filename = f"{timestamp}_{input_data.content_id}_analysis.md"
|
||||
archive_filename = f"{timestamp}_{input_data.content_id}_{safe_title}_analysis.md"
|
||||
archive_path = platform_dir / archive_filename
|
||||
|
||||
# Step 3: 检查重复
|
||||
@@ -73,7 +81,9 @@ class ArchiveProcessor(BaseProcessor):
|
||||
platform_dir, input_data.content_id
|
||||
)
|
||||
if existing_file:
|
||||
should_overwrite = self._ask_overwrite(existing_file)
|
||||
# 检测是否为非交互式环境
|
||||
is_non_interactive = not sys.stdin.isatty()
|
||||
should_overwrite = self._ask_overwrite(existing_file, is_non_interactive)
|
||||
if not should_overwrite:
|
||||
logger.info(f"User chose not to overwrite, skipping archive")
|
||||
return ArchiveOutput(
|
||||
@@ -143,17 +153,86 @@ class ArchiveProcessor(BaseProcessor):
|
||||
matches = list(platform_dir.glob(pattern))
|
||||
return matches[0] if matches else None
|
||||
|
||||
def _ask_overwrite(self, existing_file: Path) -> bool:
|
||||
def _extract_title_from_file(self, file_path: Path) -> Optional[str]:
|
||||
"""从 Markdown 文件的 frontmatter 中提取标题
|
||||
|
||||
Args:
|
||||
file_path: Markdown 文件路径
|
||||
|
||||
Returns:
|
||||
标题字符串,如果未找到返回 None
|
||||
"""
|
||||
try:
|
||||
content = file_path.read_text(encoding='utf-8')
|
||||
|
||||
# 查找 frontmatter 中的 title 字段
|
||||
# 格式:title: "标题内容" 或 title: 标题内容
|
||||
title_match = re.search(r'^title:\s*(?:"([^"]*)"|(.+))$', content, re.MULTILINE)
|
||||
|
||||
if title_match:
|
||||
# 优先使用引号内的内容,否则使用第二个捕获组
|
||||
title = title_match.group(1) or title_match.group(2)
|
||||
return title.strip() if title else None
|
||||
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to extract title from {file_path}: {e}")
|
||||
return None
|
||||
|
||||
def _sanitize_title(self, title: str) -> str:
|
||||
"""清理标题用于文件命名
|
||||
|
||||
移除特殊字符,限制长度,转换为安全的文件名。
|
||||
|
||||
Args:
|
||||
title: 原始标题
|
||||
|
||||
Returns:
|
||||
清理后的标题
|
||||
"""
|
||||
# 移除或替换不适合文件名的字符
|
||||
# 保留中文、字母、数字、下划线、连字符
|
||||
# 替换所有特殊字符(包括标点符号和常见符号)
|
||||
safe = re.sub(r'[\\/:*?"<>|,。!?、;:""\'\'\s@#$%&*+\-=\[\]{}()<>]+', '_', title)
|
||||
|
||||
# 移除连续的下划线
|
||||
safe = re.sub(r'_+', '_', safe)
|
||||
|
||||
# 去除首尾下划线和空格
|
||||
safe = safe.strip('_')
|
||||
|
||||
# 限制长度(避免文件名过长)
|
||||
if len(safe) > 50:
|
||||
safe = safe[:50]
|
||||
|
||||
# 如果清理后为空,返回默认值
|
||||
if not safe:
|
||||
safe = "untitled"
|
||||
|
||||
return safe
|
||||
|
||||
def _ask_overwrite(self, existing_file: Path, is_non_interactive: bool = False) -> bool:
|
||||
"""询问用户是否覆盖已存在的文件
|
||||
|
||||
使用 rich.prompt.Confirm 模式(与 Pipeline._ask_rerun_step 相同)
|
||||
|
||||
Args:
|
||||
existing_file: 已存在的文件路径
|
||||
is_non_interactive: 是否为非交互式环境(stdin不是tty)
|
||||
|
||||
Returns:
|
||||
True 如果用户选择覆盖
|
||||
"""
|
||||
# 非交互式模式:使用配置决定
|
||||
if is_non_interactive:
|
||||
if self.settings.overwrite_archives:
|
||||
logger.info(f"Non-interactive mode: Overwriting existing archive (KB_OVERWRITE_ARCHIVES=true): {existing_file.name}")
|
||||
return True
|
||||
else:
|
||||
logger.info(f"Non-interactive mode: Skipping existing archive (KB_OVERWRITE_ARCHIVES=false): {existing_file.name}")
|
||||
return False
|
||||
|
||||
# 交互式模式:询问用户
|
||||
try:
|
||||
from rich.console import Console
|
||||
from rich.prompt import Confirm
|
||||
|
||||
@@ -166,7 +166,7 @@ class SRTProcessor(BaseProcessor):
|
||||
metadata_file: 元数据文件路径
|
||||
|
||||
Returns:
|
||||
元数据字典
|
||||
元数据字典(扁平化后的)
|
||||
"""
|
||||
path = Path(metadata_file)
|
||||
if not path.exists():
|
||||
@@ -174,7 +174,21 @@ class SRTProcessor(BaseProcessor):
|
||||
return {}
|
||||
|
||||
with open(path, 'r', encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
raw_metadata = json.load(f)
|
||||
|
||||
# 扁平化嵌套结构(与 AnalyzeProcessor._normalize_metadata 一致)
|
||||
if not raw_metadata:
|
||||
return {}
|
||||
|
||||
# 如果已经是扁平结构(顶层有 title)
|
||||
if 'title' in raw_metadata:
|
||||
return raw_metadata
|
||||
|
||||
# 处理嵌套结构 {metadata: {...}, stats: {...}}
|
||||
if 'metadata' in raw_metadata:
|
||||
return raw_metadata['metadata'].copy()
|
||||
|
||||
return raw_metadata
|
||||
|
||||
def _extract_tags(self, paragraphs: List[str]) -> List[str]:
|
||||
"""从段落中提取标签
|
||||
@@ -216,16 +230,7 @@ class SRTProcessor(BaseProcessor):
|
||||
# 构建内容
|
||||
content_parts = [frontmatter, ""]
|
||||
|
||||
# 添加摘要(可选)
|
||||
if paragraphs:
|
||||
content_parts.append("## 摘要")
|
||||
content_parts.append("")
|
||||
# 使用第一段作为简单摘要
|
||||
first_para = paragraphs[0][:200] if len(paragraphs[0]) > 200 else paragraphs[0]
|
||||
content_parts.append(first_para + ("..." if len(paragraphs[0]) > 200 else ""))
|
||||
content_parts.append("")
|
||||
|
||||
# 添加内容
|
||||
# 直接添加内容,不生成摘要部分
|
||||
content_parts.append("## 内容")
|
||||
content_parts.append("")
|
||||
for para in paragraphs:
|
||||
@@ -271,7 +276,12 @@ class SRTProcessor(BaseProcessor):
|
||||
# 时长(视频)
|
||||
duration = metadata.get('duration', 0)
|
||||
if duration:
|
||||
duration_str = self._format_duration(duration)
|
||||
# 如果 duration 已经是字符串格式(如 "05:42"),直接使用
|
||||
# 否则(整数秒数)调用 _format_duration 转换
|
||||
if isinstance(duration, str):
|
||||
duration_str = duration
|
||||
else:
|
||||
duration_str = self._format_duration(duration)
|
||||
lines.append(f'duration: {duration_str}')
|
||||
|
||||
# BVID
|
||||
|
||||
@@ -26,7 +26,11 @@ class AIClientProtocol(Protocol):
|
||||
|
||||
# 纠错 Prompt 模板
|
||||
CORRECTION_PROMPT = """你是一个文本校对专家。以下是语音识别生成的字幕,可能包含识别错误。
|
||||
请只纠正明显的错误(如同音字、漏字、错字),不要改变原意和风格。
|
||||
|
||||
请执行以下任务:
|
||||
1. 纠正明显的错误(如同音字、漏字、错字)
|
||||
2. 添加适当的标点符号(逗号、句号、顿号等)
|
||||
3. 不要改变原意和风格
|
||||
|
||||
原文:
|
||||
{text}
|
||||
@@ -100,7 +104,8 @@ class ASRCorrector:
|
||||
"""
|
||||
try:
|
||||
prompt = CORRECTION_PROMPT.format(text=text)
|
||||
result = self.ai_client.generate(prompt, max_tokens=len(text) + 500)
|
||||
# ASR 纠错需要直接结果,不需要 AI 的分析过程,因此禁用思考模式
|
||||
result = self.ai_client.generate(prompt, max_tokens=len(text) + 500, disable_reasoning=True)
|
||||
return result.strip()
|
||||
except Exception as e:
|
||||
logger.warning(f"ASR correction failed: {e}, returning original text")
|
||||
|
||||
Reference in New Issue
Block a user