chenyuxiaojin/xiaochen-skills / plugins/cyxj-subfix/skills/cyxj-subfix
cyxj-subfix
Verified达芬奇字幕修正工具:SRT 清理、Sonnet 语义初修、Opus 审查把关。 触发词:/字幕修正、修正字幕、字幕错别字、SRT 修正、达芬奇字幕。 当用户提供 SRT 文件路径需要修正时使用此 skill。
| File | Kind | Size |
|---|---|---|
| .gitignore | other | 13 B |
| README.md | markdown | 3.8 KB |
| README_zh.md | markdown | 3.6 KB |
| SKILL.md | skill md | 8.9 KB |
| dictionary.json | config | 10.9 KB |
| requirements.txt | manifest | 12 B |
| srt_cleaner.py | script | 21.7 KB |
| srt_corrector.py | script | 12.1 KB |
srt_corrector.py
View on GitHub#!/usr/bin/env python3
"""SRT 字幕语义修正工具 - 达芬奇字幕修正 Skill v5
通过本机 Claude Code(claude -p)用 Sonnet 做初修,输出修正后的 SRT 和修改清单。
依赖:Claude Code CLI, pysrt
"""
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path
import pysrt
# ── 配置 ──────────────────────────────────────────────────────────────────
DEFAULT_MODEL = "sonnet" # Claude Code 的模型别名,始终指向当前的 Sonnet
EFFORT = "medium"
BATCH_SIZE = 40 # 每批字幕条数
MAX_RETRIES = 3
RETRY_DELAY = 2 # 秒
CLI_TIMEOUT = 300 # 单批超时(秒)
# 在 Claude Code 对话里运行时,这些变量会让子进程以为自己嵌套在当前会话里
CHILD_ENV_DROP = {
"CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CLAUDE_CODE_SESSION_ID",
"CLAUDE_CODE_CHILD_SESSION", "CLAUDE_PID", "CLAUDE_EFFORT",
"CLAUDE_CODE_MESSAGING_SOCKET", "CLAUDE_CODE_MESSAGING_TOKEN",
"CLAUDE_CODE_SESSION_ATTENDED", "CLAUDE_CODE_PLUGIN_DIRS", "CLAUDE_PLUGIN_DATA",
}
SKILL_DIR = Path(__file__).parent
DICTIONARY_PATH = SKILL_DIR / "dictionary.json"
# ── 词典加载 ──────────────────────────────────────────────────────────────
def load_dictionary() -> dict:
"""加载词典,构建 错误词→正确词 的映射。"""
if not DICTIONARY_PATH.exists():
return {}
with open(DICTIONARY_PATH, "r", encoding="utf-8") as f:
data = json.load(f)
# 反转词典:corrections 格式是 正确词→[错误变体列表]
error_to_correct = {}
for correct, variants in data.get("corrections", {}).items():
for variant in variants:
error_to_correct[variant] = correct
# user_additions 同理
for correct, variants in data.get("user_additions", {}).items():
for variant in variants:
error_to_correct[variant] = correct
return error_to_correct
def format_dictionary_for_prompt(error_map: dict) -> str:
"""将词典格式化为 prompt 中的参考列表。"""
if not error_map:
return "(无已知词典映射)"
# 按正确词分组
correct_to_errors = {}
for error, correct in error_map.items():
correct_to_errors.setdefault(correct, []).append(error)
lines = []
for correct, errors in sorted(correct_to_errors.items()):
errors_str = "、".join(errors)
lines.append(f" {errors_str} → {correct}")
return "\n".join(lines)
# ── Sonnet 调用 ───────────────────────────────────────────────────────────
def build_system_prompt(topic: str, dict_text: str) -> str:
"""构建系统提示词。"""
return f"""你是一个专业的中文字幕校对员。你的任务是修正语音识别(ASR)产生的错误。
## 视频主题
{topic}
## 已知错误词典(ASR 常见错误 → 正确写法)
{dict_text}
## 修正规则
1. **同音字/近音字修正**:ASR 经常把专业术语识别成同音的常见词,结合主题语境判断并修正
2. **去口吃重复**:如"我说的我说的我说的"→"我说的"
3. **去填充词**:删除"嗯""啊""那个""就是说"等口头禅(如果整条都是填充词,文字留空)
4. **保持口语化**:不要书面化改写,保留说话人的自然表达风格
5. **不确定就不改**:如果不确定某个词是否有误,保持原样
## 输出格式
只返回一个 JSON 数组,包含你修改过的条目。未修改的条目不要包含。
每个元素格式:
{{"index": 条目编号, "original": "原文", "fixed": "修正后", "reason": "修正原因"}}
如果这批字幕没有需要修正的内容,返回空数组 []
重要:只返回 JSON 数组,不要有任何其他文字。"""
def build_batch_prompt(subs_batch: list[tuple[int, str]]) -> str:
"""构建单批字幕的用户提示词。"""
lines = []
for idx, text in subs_batch:
lines.append(f"[{idx}] {text}")
return "请检查以下字幕并修正错误:\n\n" + "\n".join(lines)
def parse_model_response(response_text: str) -> list[dict] | None:
"""解析模型返回的 JSON 修改清单。解析失败返回 None(区别于"无需修正"的 [])。"""
text = response_text.strip()
# 去掉可能的 markdown 代码块标记
if text.startswith("```"):
text = re.sub(r"^```(?:json)?\s*\n?", "", text)
text = re.sub(r"\n?```\s*$", "", text)
text = text.strip()
if not text:
return []
try:
result = json.loads(text)
if isinstance(result, list):
return result
return None
except json.JSONDecodeError:
# 尝试提取 JSON 数组
match = re.search(r'\[.*\]', text, re.DOTALL)
if match:
try:
return json.loads(match.group())
except json.JSONDecodeError:
pass
print(f" ⚠ 无法解析模型响应,跳过此批", file=sys.stderr)
return None
def call_sonnet_batch(model: str, system_prompt: str,
batch: list[tuple[int, str]], workdir: str) -> list[dict] | None:
"""用 claude -p 处理一批字幕。失败(重试耗尽/解析失败)返回 None。"""
user_prompt = build_batch_prompt(batch)
# 只让模型改字:不给工具,不加载设置、插件和 MCP
cmd = ["claude", "-p", "--model", model, "--effort", EFFORT,
"--output-format", "json", "--no-session-persistence",
"--tools", "", "--disable-slash-commands", "--strict-mcp-config",
"--setting-sources", "", "--system-prompt", system_prompt]
env = {k: v for k, v in os.environ.items() if k not in CHILD_ENV_DROP}
for attempt in range(MAX_RETRIES):
try:
proc = subprocess.run(cmd, input=user_prompt, capture_output=True, text=True,
timeout=CLI_TIMEOUT, env=env, cwd=workdir)
if proc.returncode != 0:
detail = (proc.stderr or proc.stdout).strip()[:300]
raise RuntimeError(f"claude 退出码 {proc.returncode}: {detail}")
data = json.loads(proc.stdout)
result = data.get("result")
if data.get("is_error") or not isinstance(result, str) or not result.strip():
raise RuntimeError(f"claude 没有返回有效结果: {str(result)[:300]}")
return parse_model_response(result)
except Exception as e:
if attempt < MAX_RETRIES - 1:
print(f" ⚠ 调用出错 (重试 {attempt + 1}/{MAX_RETRIES}): {e}",
file=sys.stderr)
time.sleep(RETRY_DELAY * (attempt + 1))
else:
print(f" ✗ 调用失败,跳过此批: {e}", file=sys.stderr)
return None
# ── 主处理流程 ────────────────────────────────────────────────────────────
def process_srt(input_path: str, topic: str, model: str = DEFAULT_MODEL,
batch_size: int = BATCH_SIZE) -> tuple[str, str]:
"""处理 SRT 文件,返回 (输出SRT路径, 修改清单路径)。"""
if not shutil.which("claude"):
print("✗ 未找到 claude 命令,请先安装 Claude Code", file=sys.stderr)
sys.exit(1)
# 加载文件和词典
subs = pysrt.open(input_path, encoding="utf-8-sig")
error_map = load_dictionary()
dict_text = format_dictionary_for_prompt(error_map)
system_prompt = build_system_prompt(topic, dict_text)
print(f"📝 输入: {input_path} ({len(subs)} 条字幕)")
print(f"🤖 模型: {model}")
print(f"📖 词典: {len(error_map)} 个已知错误映射")
print(f"📦 批次大小: {batch_size}")
print()
# 准备批次
all_items = [(sub.index, sub.text.strip()) for sub in subs]
batches = []
for i in range(0, len(all_items), batch_size):
batches.append(all_items[i:i + batch_size])
# 逐批处理
all_changes = []
total_fixed = 0
failed_batches = 0
# 在空的临时目录里运行,不读当前项目的 CLAUDE.md
with tempfile.TemporaryDirectory() as workdir:
for batch_idx, batch in enumerate(batches):
start_idx = batch[0][0]
end_idx = batch[-1][0]
print(f" 处理批次 {batch_idx + 1}/{len(batches)} "
f"(#{start_idx}-#{end_idx})...", end=" ", flush=True)
changes = call_sonnet_batch(model, system_prompt, batch, workdir)
if changes is None:
failed_batches += 1
print("✗ 本批处理失败,字幕保持原样")
elif changes:
all_changes.extend(changes)
total_fixed += len(changes)
print(f"✓ {len(changes)} 处修正")
else:
print("✓ 无需修正")
print()
print(f"📊 总计: {total_fixed} 处修正 / {len(subs)} 条字幕")
if failed_batches:
print(f"⚠ {failed_batches}/{len(batches)} 批未处理"
f"(JSON 解析失败或重试耗尽),对应字幕保持原样", file=sys.stderr)
# 应用修正到 SRT
changes_map = {}
for change in all_changes:
idx = change.get("index")
if idx is not None:
changes_map[idx] = change
for sub in subs:
if sub.index in changes_map:
change = changes_map[sub.index]
fixed = change.get("fixed")
if not isinstance(fixed, str):
print(f" ⚠ #{sub.index} 缺少有效的 fixed 字段,跳过", file=sys.stderr)
continue
original = change.get("original")
# 宽松的包含性校验:original 与当前字幕文本对不上说明 index 错位,跳过防误伤
if isinstance(original, str) and original.strip() \
and original.strip() not in sub.text:
print(f" ⚠ #{sub.index} original 与当前字幕文本不符,跳过: {original}",
file=sys.stderr)
continue
sub.text = fixed
# 输出文件
p = Path(input_path)
output_srt = str(p.parent / (p.stem.replace("_cleaned", "") + "_sonnet_fixed" + p.suffix))
output_json = str(p.parent / (p.stem.replace("_cleaned", "") + "_changes.json"))
subs.save(output_srt, encoding="utf-8")
changes_output = {
"model": model,
"topic": topic,
"total_subtitles": len(subs),
"total_changes": len(all_changes),
"failed_batches": failed_batches,
"changes": all_changes,
}
with open(output_json, "w", encoding="utf-8") as f:
json.dump(changes_output, f, ensure_ascii=False, indent=2)
print(f"✅ 修正后字幕: {output_srt}")
print(f"📋 修改清单: {output_json}")
return output_srt, output_json
# ── CLI ───────────────────────────────────────────────────────────────────
def main():
parser = argparse.ArgumentParser(
description="SRT 字幕语义修正工具 (Claude Code + Sonnet)")
parser.add_argument("input", help="输入 SRT 文件路径(通常是 _cleaned.srt)")
parser.add_argument("--topic", required=True,
help="视频主题(用于语境判断,如 'Claude Code教程')")
parser.add_argument("--model", default=DEFAULT_MODEL,
help=f"Claude Code 模型名(默认: {DEFAULT_MODEL})")
parser.add_argument("--batch-size", type=int, default=BATCH_SIZE,
help=f"每批处理条数(默认: {BATCH_SIZE})")
args = parser.parse_args()
process_srt(args.input, args.topic, args.model, args.batch_size)
if __name__ == "__main__":
main()
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |