earshot-cli 0.5.0__tar.gz → 0.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/PKG-INFO +11 -1
  2. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/README.md +8 -0
  3. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/pyproject.toml +6 -2
  4. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/src/earshot/cli.py +119 -4
  5. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/src/earshot/compose.py +22 -1
  6. earshot_cli-0.6.0/src/earshot/hardsub.py +379 -0
  7. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/src/earshot/subtitle.py +4 -1
  8. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/tests/test_compose.py +24 -0
  9. earshot_cli-0.6.0/tests/test_hardsub.py +221 -0
  10. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/tests/test_wizard.py +16 -0
  11. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/uv.lock +465 -1
  12. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/.github/workflows/ci.yml +0 -0
  13. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/.github/workflows/publish.yml +0 -0
  14. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/.gitignore +0 -0
  15. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/LICENSE +0 -0
  16. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/scripts/download_models.sh +0 -0
  17. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/src/earshot/__init__.py +0 -0
  18. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/src/earshot/auth.py +0 -0
  19. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/src/earshot/capture.py +0 -0
  20. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/src/earshot/config.py +0 -0
  21. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/src/earshot/deliver.py +0 -0
  22. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/src/earshot/extract.py +0 -0
  23. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/src/earshot/live.py +0 -0
  24. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/src/earshot/models.py +0 -0
  25. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/src/earshot/transcribe.py +0 -0
  26. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/src/earshot/transcribe_cloud.py +0 -0
  27. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/tests/conftest.py +0 -0
  28. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/tests/test_auth.py +0 -0
  29. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/tests/test_config.py +0 -0
  30. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/tests/test_credential_lifecycle.py +0 -0
  31. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/tests/test_deliver.py +0 -0
  32. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/tests/test_deliver_api.py +0 -0
  33. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/tests/test_do_deliver.py +0 -0
  34. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/tests/test_extract.py +0 -0
  35. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/tests/test_live.py +0 -0
  36. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/tests/test_me.py +0 -0
  37. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/tests/test_subtitle.py +0 -0
  38. {earshot_cli-0.5.0 → earshot_cli-0.6.0}/tests/test_ua.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: earshot-cli
3
- Version: 0.5.0
3
+ Version: 0.6.0
4
4
  Summary: 旁听剪藏:跨平台桌面端系统声录制 → 本地转写 → 投递知识库(默认 ExoMind,可插拔)
5
5
  Project-URL: Homepage, https://github.com/helloworldtang/earshot
6
6
  Project-URL: Repository, https://github.com/helloworldtang/earshot
@@ -29,6 +29,8 @@ Requires-Dist: sherpa-onnx>=1.13.8
29
29
  Requires-Dist: soundcard>=0.4.3
30
30
  Requires-Dist: soxr>=0.5
31
31
  Requires-Dist: yt-dlp>=2025.1
32
+ Provides-Extra: ocr
33
+ Requires-Dist: rapidocr>=3.10; extra == 'ocr'
32
34
  Description-Content-Type: text/markdown
33
35
 
34
36
  # earshot
@@ -164,6 +166,9 @@ uv tool install "earshot-cli @ https://github.com/helloworldtang/earshot/archive
164
166
  ```
165
167
 
166
168
  - **零系统依赖**:ffmpeg 已随 Python wheel 内置([imageio-ffmpeg](https://pypi.org/project/imageio-ffmpeg),MoviePy 同款),无需 brew/apt。
169
+ - **硬字幕 OCR 为可选依赖**(`earshot ocr`,字幕烧在画面里、无音轨的视频用):装主包后补一条
170
+ `uv tool install --force --with "earshot-cli[ocr]" earshot-cli`(或首装就用 `uv tool install "earshot-cli[ocr]"`),
171
+ 约多下载 100MB(含 PP-OCR ONNX 模型,复用主依赖 onnxruntime 运行时,不引入 paddlepaddle)。
167
172
  - **模型首次运行自动下载**:SenseVoice int8 + silero VAD(~230MB,默认走 hf-mirror,`HF_ENDPOINT` 可覆盖),装完不再下。
168
173
  - **投递免装 CLI**:默认直连 ExoMind HTTP API(复用 `~/.exomind/config.json` 凭据);没有凭据但有 exomind CLI 时自动回退;也支持任意 webhook。
169
174
  - **独立登录免装 emcli**:`earshot login` 设备流浏览器授权,直接写入 `~/.exomind/config.json`(与 emcli 共用同一凭据文件);已装 emcli 且登录过则无需再登。
@@ -198,6 +203,11 @@ earshot listen --note "B站·xxx第3期"
198
203
  # B站等视频链接直拉字幕(高信噪比:无环境噪音/打断;AI 字幕需登录态)
199
204
  earshot video "https://www.bilibili.com/video/BVxxxx" --cookies-from-browser chrome
200
205
 
206
+ # 硬字幕视频 OCR 提取(字幕烧在画面里、无音轨;本地文件或链接均可,链接模式下载完即删不留全片)
207
+ earshot ocr ./录屏.mp4
208
+ earshot ocr "https://www.bilibili.com/video/BVxxxx"
209
+ # 长视频可降采样:--fps 0.5(<1 会漏短字幕);字幕不在底部条带时:--region full
210
+
201
211
  # 已有音视频文件(录屏 mp4 / 语音 m4a / 播客 mp3)
202
212
  earshot audio recording.mp4 --title "通勤听书笔记" --deliver none
203
213
 
@@ -131,6 +131,9 @@ uv tool install "earshot-cli @ https://github.com/helloworldtang/earshot/archive
131
131
  ```
132
132
 
133
133
  - **零系统依赖**:ffmpeg 已随 Python wheel 内置([imageio-ffmpeg](https://pypi.org/project/imageio-ffmpeg),MoviePy 同款),无需 brew/apt。
134
+ - **硬字幕 OCR 为可选依赖**(`earshot ocr`,字幕烧在画面里、无音轨的视频用):装主包后补一条
135
+ `uv tool install --force --with "earshot-cli[ocr]" earshot-cli`(或首装就用 `uv tool install "earshot-cli[ocr]"`),
136
+ 约多下载 100MB(含 PP-OCR ONNX 模型,复用主依赖 onnxruntime 运行时,不引入 paddlepaddle)。
134
137
  - **模型首次运行自动下载**:SenseVoice int8 + silero VAD(~230MB,默认走 hf-mirror,`HF_ENDPOINT` 可覆盖),装完不再下。
135
138
  - **投递免装 CLI**:默认直连 ExoMind HTTP API(复用 `~/.exomind/config.json` 凭据);没有凭据但有 exomind CLI 时自动回退;也支持任意 webhook。
136
139
  - **独立登录免装 emcli**:`earshot login` 设备流浏览器授权,直接写入 `~/.exomind/config.json`(与 emcli 共用同一凭据文件);已装 emcli 且登录过则无需再登。
@@ -165,6 +168,11 @@ earshot listen --note "B站·xxx第3期"
165
168
  # B站等视频链接直拉字幕(高信噪比:无环境噪音/打断;AI 字幕需登录态)
166
169
  earshot video "https://www.bilibili.com/video/BVxxxx" --cookies-from-browser chrome
167
170
 
171
+ # 硬字幕视频 OCR 提取(字幕烧在画面里、无音轨;本地文件或链接均可,链接模式下载完即删不留全片)
172
+ earshot ocr ./录屏.mp4
173
+ earshot ocr "https://www.bilibili.com/video/BVxxxx"
174
+ # 长视频可降采样:--fps 0.5(<1 会漏短字幕);字幕不在底部条带时:--region full
175
+
168
176
  # 已有音视频文件(录屏 mp4 / 语音 m4a / 播客 mp3)
169
177
  earshot audio recording.mp4 --title "通勤听书笔记" --deliver none
170
178
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "earshot-cli"
3
- version = "0.5.0"
3
+ version = "0.6.0"
4
4
  description = "旁听剪藏:跨平台桌面端系统声录制 → 本地转写 → 投递知识库(默认 ExoMind,可插拔)"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -36,6 +36,10 @@ dependencies = [
36
36
  "yt-dlp>=2025.1",
37
37
  ]
38
38
 
39
+ [project.optional-dependencies]
40
+ # ocr 命令:硬字幕画面 OCR(PP-OCR ONNX 模型内置,复用主依赖 onnxruntime 运行时,不引 paddlepaddle)
41
+ ocr = ["rapidocr>=3.10"]
42
+
39
43
  [project.urls]
40
44
  Homepage = "https://github.com/helloworldtang/earshot"
41
45
  Repository = "https://github.com/helloworldtang/earshot"
@@ -73,7 +77,7 @@ strict = true
73
77
  files = ["src", "tests"]
74
78
  # sherpa-onnx / soundcard 未随 wheel 提供 py.typed —— 与其假装,不如显式忽略
75
79
  [[tool.mypy.overrides]]
76
- module = ["sherpa_onnx.*", "soundcard.*", "onnxruntime.*", "imageio_ffmpeg.*", "soxr.*", "yt_dlp.*"]
80
+ module = ["sherpa_onnx.*", "soundcard.*", "onnxruntime.*", "imageio_ffmpeg.*", "soxr.*", "yt_dlp.*", "rapidocr.*"]
77
81
  ignore_missing_imports = true
78
82
 
79
83
  [[tool.mypy.overrides]]
@@ -1,4 +1,4 @@
1
- """earshot CLI:listen / audio / devices / doctor。"""
1
+ """earshot CLI:listen / audio / video / ocr / devices / doctor。"""
2
2
 
3
3
  from __future__ import annotations
4
4
 
@@ -15,10 +15,19 @@ import numpy as np
15
15
  from earshot import __version__
16
16
  from earshot.auth import clear_credentials, device_login, save_credentials, verify_key
17
17
  from earshot.capture import blackhole_missing_hint, list_capture_devices, pick_device, record_to_wav
18
- from earshot.compose import NoteMeta, add_punctuation, derive_title, group_paragraphs, outbox_path, render_markdown
18
+ from earshot.compose import (
19
+ NoteMeta,
20
+ add_punctuation,
21
+ derive_title,
22
+ drop_cta,
23
+ group_paragraphs,
24
+ outbox_path,
25
+ render_markdown,
26
+ )
19
27
  from earshot.config import DEFAULT_EXOMIND_BASE_URL, Settings, load_settings
20
28
  from earshot.deliver import DeliveryResult, deliver_exomind, deliver_exomind_api, deliver_webhook
21
29
  from earshot.extract import ExtractError, ffmpeg_available, to_wav16k, wav_duration
30
+ from earshot.hardsub import FrameOcr, HardsubError, download_video, extract_hardsub, is_url, make_rapidocr_engine
22
31
  from earshot.live import LiveSession
23
32
  from earshot.models import ensure_models
24
33
  from earshot.subtitle import SubtitleError, fetch_video_note
@@ -69,6 +78,16 @@ def build_parser() -> argparse.ArgumentParser:
69
78
  help="浏览器名(chrome/safari/firefox/edge),拉 AI 字幕(ai-zh)通常需要登录态",
70
79
  )
71
80
 
81
+ p_ocr = sub.add_parser("ocr", help="硬字幕视频 OCR 提取(字幕烧在画面里、无音轨的场景)")
82
+ _add_common(p_ocr)
83
+ p_ocr.add_argument("path_or_url", nargs="?", help="视频文件路径或链接(B站等;缺省时交互询问)")
84
+ p_ocr.add_argument("--fps", type=float, default=1.0, help="抽帧采样率(默认 1;长视频可 0.5,<1 会漏短字幕)")
85
+ p_ocr.add_argument(
86
+ "--region", choices=["bottom", "full"], default="bottom", help="识别区域(默认 bottom 底部字幕条带)"
87
+ )
88
+ p_ocr.add_argument("--min-score", type=float, default=0.55, help="行级置信度阈值,低于则丢弃(默认 0.55)")
89
+ p_ocr.add_argument("--cookies-from-browser", help="浏览器名(chrome/safari/firefox/edge),下载需要登录态的视频时用")
90
+
72
91
  p_deliver = sub.add_parser("deliver", help="补投/重投 outbox 里的笔记")
73
92
  p_deliver.add_argument("file", type=Path, help="笔记 md 路径")
74
93
  p_deliver.add_argument("--title", help="标题(默认取首行 # 标题)")
@@ -125,6 +144,10 @@ def _run_pipeline(
125
144
  chapter_breaks: list[float] | None = None,
126
145
  ) -> int:
127
146
  """组装 md → 落 outbox → 投递,返回退出码。"""
147
+ kept = drop_cta(segments) # 滤粉丝互动话术(求三连/关注),四路统一
148
+ if dropped := len(segments) - len(kept):
149
+ print(f"已滤除 {dropped} 句粉丝互动话术(三连/关注类)")
150
+ segments = kept
128
151
  if not any(s.text.strip() for s in segments):
129
152
  print("未识别到语音内容(检查系统输出/设备,或音频本身无人声)")
130
153
  return EXIT_NO_CONTENT
@@ -436,6 +459,90 @@ def cmd_video(args: argparse.Namespace, settings: Settings) -> int:
436
459
  return _run_pipeline(segments, note_meta, args, settings, chapter_breaks=meta.chapter_starts)
437
460
 
438
461
 
462
+ def cmd_ocr(args: argparse.Namespace, settings: Settings) -> int:
463
+ target = args.path_or_url
464
+ if not target:
465
+ if not _interactive():
466
+ print("✗ 缺少视频路径或链接:earshot ocr <file|url>(或交互模式直接 earshot)")
467
+ return EXIT_FAIL
468
+ clip = _clipboard_text()
469
+ if clip.lower().startswith("http"):
470
+ target = _prompt("视频路径或链接", default=_short_url(clip), prefill=True)
471
+ else:
472
+ target = _prompt("视频路径或链接(本地文件 / B站链接)")
473
+ if not target:
474
+ print("✗ 未提供视频路径或链接")
475
+ return EXIT_FAIL
476
+ url_mode = is_url(target)
477
+ title, uploader, source_url = "", "-", ""
478
+ if not url_mode: # 本地文件先校验存在性(免费检查,先于引擎构建与报「引擎未安装」)
479
+ video_path = Path(target).expanduser()
480
+ if not video_path.is_file():
481
+ print(f"✗ 文件不存在: {video_path}")
482
+ return EXIT_FAIL
483
+ title = video_path.stem
484
+ try:
485
+ engine = make_rapidocr_engine() # 引擎先建:未装 [ocr] extra 时尽早失败,别等下载完
486
+ except HardsubError as e:
487
+ print(f"✗ {e}")
488
+ return EXIT_FAIL
489
+
490
+ tmp_dir = settings.home / "tmp"
491
+ tmp_dir.mkdir(parents=True, exist_ok=True)
492
+ if url_mode:
493
+ try:
494
+ dl = download_video(target, tmp_dir, cookies_browser=args.cookies_from_browser)
495
+ except HardsubError as e:
496
+ print(f"✗ {e}")
497
+ return EXIT_FAIL
498
+ video_path = dl.path
499
+ title, uploader, source_url = dl.title, dl.uploader, target
500
+ print(f"→ 已下载:{title}(UP:{uploader})")
501
+ print(f"→ 硬字幕 OCR 中({args.fps}fps,区域 {args.region})…")
502
+
503
+ def _progress(done: int, total: int) -> None:
504
+ print(f"\r→ OCR 中… {done}/{total} 帧({done / total * 100:3.0f}%)", end="", flush=True)
505
+
506
+ last_text = ""
507
+
508
+ def _show(frame: FrameOcr) -> None:
509
+ # 实时字幕上屏(listen 同款):新字幕行出现即回显,不用等整片跑完才知道内容对不对
510
+ nonlocal last_text
511
+ if not frame.text or frame.text == last_text:
512
+ return
513
+ last_text = frame.text
514
+ print(f"\r\033[K ↪ {frame.text}", flush=True) # 清掉进度行再上屏,进度随后 \r 重绘
515
+
516
+ try:
517
+ duration_s, segments = extract_hardsub(
518
+ video_path,
519
+ tmp_dir,
520
+ fps=args.fps,
521
+ region=args.region,
522
+ min_score=args.min_score,
523
+ engine=engine,
524
+ on_progress=_progress,
525
+ on_frame=_show,
526
+ )
527
+ print()
528
+ if not args.title:
529
+ args.title = title
530
+ if not args.note:
531
+ args.note = source_url or f"本地文件 {video_path.name}"
532
+ note_meta = NoteMeta(
533
+ started_at=datetime.now(),
534
+ duration_s=duration_s,
535
+ device=uploader,
536
+ source="ocr",
537
+ note=args.note,
538
+ source_url=source_url,
539
+ )
540
+ return _run_pipeline(segments, note_meta, args, settings)
541
+ finally:
542
+ if url_mode:
543
+ video_path.unlink(missing_ok=True) # URL 模式不留全片(磁盘紧张;确认/放弃已在上方完成)
544
+
545
+
439
546
  def cmd_deliver(args: argparse.Namespace, settings: Settings) -> int:
440
547
  md_path = args.file
441
548
  if not md_path.is_file():
@@ -477,6 +584,13 @@ def cmd_doctor(_args: argparse.Namespace, settings: Settings) -> int:
477
584
  print(f"{'✓' if fine else '✗'} {label}" + ("" if fine else f" → {fix}"))
478
585
 
479
586
  check("ffmpeg(系统或内置)", ffmpeg_available(), "重装 earshot 依赖(imageio-ffmpeg 应自带)")
587
+ try:
588
+ import rapidocr # noqa: F401,PLC0415 轻量探测:不实例化,doctor 不加载模型
589
+
590
+ print("✓ OCR 引擎(RapidOCR,硬字幕提取)")
591
+ except ImportError:
592
+ # 可选能力,缺失不算失败:降级为提示
593
+ print('○ OCR 引擎:未安装,硬字幕提取(earshot ocr)需 uv tool install "earshot-cli[ocr]"')
480
594
  try:
481
595
  devices = list_capture_devices()
482
596
  loopbacks = [n for n, lb in devices if lb]
@@ -605,6 +719,7 @@ def main(argv: list[str] | None = None) -> int:
605
719
  "listen": cmd_listen,
606
720
  "audio": cmd_audio,
607
721
  "video": cmd_video,
722
+ "ocr": cmd_ocr,
608
723
  "deliver": cmd_deliver,
609
724
  "login": cmd_login,
610
725
  "update": cmd_update,
@@ -627,10 +742,10 @@ def main(argv: list[str] | None = None) -> int:
627
742
  if not _interactive():
628
743
  parser.print_help()
629
744
  return EXIT_FAIL
630
- choice = _prompt("earshot 模式 [1]听录 [2]视频字幕 [3]本地文件(回车=1;输入 q 退出)", default="1")
745
+ choice = _prompt("earshot 模式 [1]听录 [2]视频字幕 [3]本地文件 [4]硬字幕OCR(回车=1;输入 q 退出)", default="1")
631
746
  if choice == "q":
632
747
  return EXIT_OK
633
- mapping = {"1": "listen", "2": "video", "3": "audio"}
748
+ mapping = {"1": "listen", "2": "video", "3": "audio", "4": "ocr"}
634
749
  sub = mapping.get(choice)
635
750
  if sub is None:
636
751
  print(f"✗ 无效选择: {choice}")
@@ -14,7 +14,28 @@ PARAGRAPH_MAX_CHARS = 400 # 单段上限,超出在句号处拆(口播字幕无
14
14
  SENTENCE_MAX_CHARS = 60 # 句长预算:连续无句号超过该字数,强制断句
15
15
  TITLE_MAX_CHARS = 40
16
16
 
17
- SOURCE_LABELS = {"listen": "旁听录音", "audio": "音频文件", "video": "视频字幕"}
17
+ SOURCE_LABELS = {"listen": "旁听录音", "audio": "音频文件", "video": "视频字幕", "ocr": "硬字幕OCR"}
18
+
19
+ # 粉丝互动话术(求三连/关注/下期再见):不是知识内容,入库只会污染实体抽取。
20
+ # 严格模式控制误杀:须「命中模式 且 整段 ≤50 字」才丢(知识视频真讨论"点赞机制"时多为长句)。
21
+ CTA_MAX_CHARS = 50
22
+ CTA_PATTERNS = (
23
+ re.compile(r"三连|投币"),
24
+ re.compile(r"点赞.{0,8}(收藏|关注|转发|加购)"),
25
+ re.compile(r"(关注|订阅).{0,6}(我|频道|账号|公众号)"),
26
+ re.compile(r"下期(再?见|再见)|不见不散|不迷路"),
27
+ re.compile(r"(谢谢|感谢)观看"),
28
+ )
29
+
30
+
31
+ def drop_cta(segments: list[Segment]) -> list[Segment]:
32
+ """滤除粉丝互动话术段(纯函数,listen/audio/video/ocr 四路统一)。"""
33
+ return [s for s in segments if not _is_cta(s.text)]
34
+
35
+
36
+ def _is_cta(text: str) -> bool:
37
+ t = text.strip()
38
+ return len(t) <= CTA_MAX_CHARS and any(p.search(t) for p in CTA_PATTERNS)
18
39
 
19
40
 
20
41
  @dataclass(frozen=True, slots=True)
@@ -0,0 +1,379 @@
1
+ """硬字幕 OCR 抽帧:无音轨且字幕烧在画面里的视频 → Segment 列表。
2
+
3
+ listen(ASR)与 video(字幕轨)都走不通的场景:ASR 无输入、字幕轨 API 返回 0 条
4
+ 是正确结果。本模块走纯视觉路线:ffmpeg 按采样率抽底部字幕条带帧 → RapidOCR
5
+ 识别 → 相邻同文本去重合并 → 带时间轴的 Segment,复用既有 _run_pipeline 入库。
6
+
7
+ RapidOCR 延迟导入(可选依赖 [ocr] extra),不用 ocr 命令不加载。
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import difflib
13
+ import re
14
+ import shutil
15
+ import subprocess
16
+ from collections.abc import Callable
17
+ from dataclasses import dataclass
18
+ from datetime import datetime
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from earshot.extract import ffmpeg_exe
23
+ from earshot.transcribe import Segment
24
+
25
+ DEFAULT_FPS = 1.0 # 抽帧采样率:字幕停留通常 ≥1s,1fps 够用
26
+ BOTTOM_BAND_FRAC = 0.22 # 底部字幕条带高度占比(画面下方 22%)
27
+ DEFAULT_MIN_SCORE = 0.55 # 行级置信度过滤阈值:清晰硬字幕 >0.9,深底低对比落 0.5-0.7
28
+ MERGE_GAP_FRAMES = 2 # 相同文本允许的最大丢帧数,桥接零星漏识别
29
+ MERGE_SIMILARITY = 0.8 # 相邻帧文本相似度阈值:OCR 标点变体(‘/“、?/?)不破去重
30
+ MAX_FRAMES = 21600 # 抽帧硬上限(fps=1 时 6 小时),防长视频失控
31
+
32
+ _DURATION_RE = re.compile(r"Duration:\s*(\d+):(\d{2}):(\d{2})\.(\d+)")
33
+
34
+ OcrEngine = Callable[[Path], list[tuple[str, float]]] # 帧图路径 → [(文本, 置信度), ...]
35
+ ProgressFn = Callable[[int, int], None] # (已完成帧数, 总帧数)
36
+
37
+
38
+ class HardsubError(RuntimeError):
39
+ """硬字幕 OCR 提取失败(引擎缺失/下载/ffmpeg/识别)。"""
40
+
41
+
42
+ @dataclass(frozen=True, slots=True)
43
+ class FrameOcr:
44
+ """一帧的 OCR 结果。
45
+
46
+ Attributes:
47
+ t_s: 帧时间戳(秒,由帧号/采样率推出)。
48
+ text: 该帧全部识别行拼接后、归一化的文本。
49
+ score: 该帧最弱行得分(整帧质量取短板)。
50
+ """
51
+
52
+ t_s: float
53
+ text: str
54
+ score: float
55
+
56
+
57
+ @dataclass(frozen=True, slots=True)
58
+ class DownloadedVideo:
59
+ """URL 模式下载产物(不复用 VideoMeta:subtitle_lang 对 OCR 场景无意义)。
60
+
61
+ Attributes:
62
+ path: 已下载视频文件路径。
63
+ title: 视频标题。
64
+ uploader: UP主/作者。
65
+ duration_s: 时长(秒,缺失为 0)。
66
+ """
67
+
68
+ path: Path
69
+ title: str
70
+ uploader: str
71
+ duration_s: float
72
+
73
+
74
+ def is_url(s: str) -> bool:
75
+ """输入是否为 http(s) 链接(纯函数)。"""
76
+ return s.lower().startswith(("http://", "https://"))
77
+
78
+
79
+ def build_vf_chain(fps: float, region: str) -> str:
80
+ """组 ffmpeg -vf 滤镜链(纯函数)。
81
+
82
+ Args:
83
+ fps: 抽帧采样率。
84
+ region: ``bottom``(底部字幕条带,裁剪后 2x 放大——小字笔画高度是
85
+ PP-OCR det 的关键输入条件)或 ``full``(整帧,不放大)。
86
+
87
+ Returns:
88
+ 滤镜链字符串。
89
+
90
+ Raises:
91
+ HardsubError: region 非法。
92
+ """
93
+ if region == "bottom":
94
+ top = 1.0 - BOTTOM_BAND_FRAC
95
+ return f"fps={fps},crop=iw:ih*{BOTTOM_BAND_FRAC}:0:ih*{top},scale=iw*2:-1"
96
+ if region == "full":
97
+ return f"fps={fps}"
98
+ msg = f"未知字幕区域: {region}(可选 bottom/full)"
99
+ raise HardsubError(msg)
100
+
101
+
102
+ def normalize_ocr_text(s: str) -> str:
103
+ """归一化 OCR 文本:去半角/全角空格与换行(纯函数)。
104
+
105
+ 中文 OCR 常在字间插空格,去掉后相邻帧文本一致性更高,利于去重合并。
106
+ """
107
+ return s.replace(" ", "").replace(" ", "").replace("\n", "").replace("\r", "")
108
+
109
+
110
+ def parse_ffmpeg_duration(stderr: str) -> float:
111
+ """从 ffmpeg stderr 解析 Duration 行(纯函数)。
112
+
113
+ Returns:
114
+ 时长秒数;解析不到返回 0.0(时长只影响进度显示,不值得抛错)。
115
+ """
116
+ m = _DURATION_RE.search(stderr)
117
+ if not m:
118
+ return 0.0
119
+ h, mn, s, cs = m.groups()
120
+ return int(h) * 3600 + int(mn) * 60 + int(s) + int(cs) / 100.0
121
+
122
+
123
+ def _parse_ocr_result(raw: Any) -> list[tuple[str, float]]:
124
+ """适配 RapidOCR 调用结果为 [(文本, 置信度), ...](纯函数,wire 契约)。
125
+
126
+ 兼容两种形态:rapidocr 3.x 的结果对象(有 txts/scores 属性;检测为空时
127
+ txts 为 None)与老包 rapidocr-onnxruntime 1.x 的 ``[[box, text, score], ...]``
128
+ 列表;识别失败(无文本)返回空列表。
129
+ """
130
+ if raw is None:
131
+ return []
132
+ if hasattr(raw, "txts"): # rapidocr 3.x:检测为空的帧 txts=None
133
+ txts = raw.txts or ()
134
+ scores = getattr(raw, "scores", None) or ()
135
+ return [(str(t), float(s)) for t, s in zip(txts, scores, strict=False)]
136
+ out: list[tuple[str, float]] = []
137
+ for item in raw:
138
+ if isinstance(item, (list, tuple)) and len(item) >= 3:
139
+ out.append((str(item[1]), float(item[2])))
140
+ return out
141
+
142
+
143
+ def merge_frame_ocr(results: list[FrameOcr], fps: float, gap_frames: int = MERGE_GAP_FRAMES) -> list[Segment]:
144
+ """相邻同文本帧去重合并为 Segment(纯函数,核心算法)。
145
+
146
+ 文本相同或相似(相似度 ≥ MERGE_SIMILARITY,吸收 OCR 标点变体 ‘/“、?/?)
147
+ 且间隔 ≤ (gap_frames+1)/fps → 延长当前段(至多 gap_frames 个采样点漏识别被
148
+ 自动桥接,保留首见文本);否则切段。``end_s = last_t + 1/fps``(帧时刻代表该
149
+ 瞬间画面,字幕至少持续到下一个采样点),并与下一段起点取 min 防微重叠。
150
+
151
+ Args:
152
+ results: 按时间升序、已滤除空文本的帧结果。
153
+ fps: 抽帧采样率(帧间隔 = 1/fps)。
154
+ gap_frames: 桥接容差(允许的最多漏识别帧数;漏 N 帧时间戳间隔为 (N+1)/fps)。
155
+
156
+ Returns:
157
+ 合并后的 Segment 列表(按时间排序)。
158
+ """
159
+ if not results:
160
+ return []
161
+ max_gap = (gap_frames + 1) / fps
162
+ segments: list[Segment] = []
163
+ cur_text = results[0].text
164
+ cur_first = results[0].t_s
165
+ cur_last = results[0].t_s
166
+ for r in results[1:]:
167
+ similar = r.text == cur_text or difflib.SequenceMatcher(None, cur_text, r.text).ratio() >= MERGE_SIMILARITY
168
+ if similar and r.t_s - cur_last <= max_gap + 1e-9:
169
+ cur_last = r.t_s
170
+ continue
171
+ segments.append(Segment(start_s=cur_first, end_s=cur_last + 1.0 / fps, text=cur_text))
172
+ cur_text, cur_first, cur_last = r.text, r.t_s, r.t_s
173
+ segments.append(Segment(start_s=cur_first, end_s=cur_last + 1.0 / fps, text=cur_text))
174
+ for i in range(len(segments) - 1): # 防与下一段微重叠
175
+ if segments[i].end_s > segments[i + 1].start_s:
176
+ patched = segments[i]
177
+ segments[i] = Segment(patched.start_s, segments[i + 1].start_s, patched.text)
178
+ return segments
179
+
180
+
181
+ def probe_duration(video: Path) -> float:
182
+ """探测视频时长(秒):ffmpeg -i 读 stderr 的 Duration 行。
183
+
184
+ 项目无 ffprobe(imageio-ffmpeg 只带 ffmpeg),此为最省事的时长探测。
185
+ returncode 非 0 属预期(没有输出参数)。
186
+
187
+ Raises:
188
+ HardsubError: ffmpeg 缺失或执行失败。
189
+ """
190
+ exe = ffmpeg_exe()
191
+ if exe is None:
192
+ msg = "未找到 ffmpeg(系统 PATH 与 imageio-ffmpeg 内置均无;重装 earshot 依赖)"
193
+ raise HardsubError(msg)
194
+ cmd = [exe, "-hide_banner", "-i", str(video)]
195
+ proc = subprocess.run(cmd, capture_output=True, text=True, timeout=60) # noqa: S603
196
+ return parse_ffmpeg_duration(proc.stderr or "")
197
+
198
+
199
+ def extract_frames(video: Path, out_dir: Path, fps: float, region: str) -> list[tuple[float, Path]]:
200
+ """整段抽帧为 jpg 序列,返回 [(时间戳, 帧路径), ...]。
201
+
202
+ 一次 ffmpeg 跑完,时间戳由帧号精确推出(避免分批 -ss 的关键帧定位漂移,
203
+ 漂移会破坏 group_paragraphs 的 2.5s 间隔分段语义)。上限 MAX_FRAMES 截断。
204
+
205
+ Raises:
206
+ HardsubError: ffmpeg 缺失或执行失败。
207
+ """
208
+ exe = ffmpeg_exe()
209
+ if exe is None:
210
+ msg = "未找到 ffmpeg(系统 PATH 与 imageio-ffmpeg 内置均无;重装 earshot 依赖)"
211
+ raise HardsubError(msg)
212
+ out_dir.mkdir(parents=True, exist_ok=True)
213
+ cmd = [
214
+ exe,
215
+ "-hide_banner",
216
+ "-loglevel",
217
+ "error",
218
+ "-nostdin", # 不吞终端输入
219
+ "-y",
220
+ "-i",
221
+ str(video),
222
+ "-vf",
223
+ build_vf_chain(fps, region),
224
+ "-frames:v",
225
+ str(MAX_FRAMES),
226
+ "-q:v",
227
+ "3",
228
+ "-start_number",
229
+ "0",
230
+ str(out_dir / "f%06d.jpg"),
231
+ ]
232
+ proc = subprocess.run(cmd, capture_output=True, text=True, timeout=1800) # noqa: S603
233
+ if proc.returncode != 0:
234
+ msg = f"抽帧失败({proc.returncode}): {(proc.stderr or '').strip()[:500]}"
235
+ raise HardsubError(msg)
236
+ frames = sorted(out_dir.glob("f*.jpg"))
237
+ return [(i / fps, p) for i, p in enumerate(frames)]
238
+
239
+
240
+ def ocr_frames(
241
+ frames: list[tuple[float, Path]],
242
+ engine: OcrEngine,
243
+ min_score: float = DEFAULT_MIN_SCORE,
244
+ on_progress: ProgressFn | None = None,
245
+ on_frame: Callable[[FrameOcr], None] | None = None,
246
+ ) -> list[FrameOcr]:
247
+ """逐帧 OCR,过滤低分行,每帧处理完立即删(磁盘峰值≈单帧)。
248
+
249
+ Args:
250
+ frames: extract_frames 产物。
251
+ engine: OCR 引擎(注入,测试传闭包)。
252
+ min_score: 行级置信度阈值,低于则整行丢弃(噪声文本进笔记比漏一句更伤阅读)。
253
+ on_progress: 进度回调(每帧一次)。
254
+ on_frame: 每个非空识别结果的回调(实时字幕上屏用,listen 同款体验)。
255
+
256
+ Returns:
257
+ 非空文本的 FrameOcr 列表(按输入顺序)。
258
+ """
259
+ total = len(frames)
260
+ out: list[FrameOcr] = []
261
+ for done, (t_s, path) in enumerate(frames):
262
+ lines = [(t, s) for t, s in engine(path) if s >= min_score and t.strip()]
263
+ path.unlink(missing_ok=True) # 逐帧删除:兑现磁盘紧张约束
264
+ text = normalize_ocr_text("".join(t for t, _ in lines))
265
+ if text:
266
+ frame_ocr = FrameOcr(t_s=t_s, text=text, score=min((s for _, s in lines), default=0.0))
267
+ out.append(frame_ocr)
268
+ if on_frame:
269
+ on_frame(frame_ocr)
270
+ if on_progress:
271
+ on_progress(done + 1, total)
272
+ return out
273
+
274
+
275
+ def make_rapidocr_engine() -> OcrEngine:
276
+ """构造 RapidOCR 引擎闭包(模型只加载一次,全视频复用)。
277
+
278
+ Returns:
279
+ OcrEngine:帧路径 → [(文本, 置信度), ...]。
280
+
281
+ Raises:
282
+ HardsubError: [ocr] extra 未安装。
283
+ """
284
+ try:
285
+ from rapidocr import RapidOCR # noqa: PLC0415 延迟导入:不用 ocr 命令不加载
286
+ except ImportError as e:
287
+ msg = 'OCR 引擎未安装。安装:uv tool install "earshot-cli[ocr]"(或 pip install "earshot-cli[ocr]")'
288
+ raise HardsubError(msg) from e
289
+ import logging
290
+
291
+ # INFO/WARNING 会打断 \r 进度行;须在构造之后设——RapidOCR() 初始化时会重配自己的 logger
292
+ ocr = RapidOCR()
293
+ logging.getLogger("RapidOCR").setLevel(logging.ERROR)
294
+
295
+ def run(frame: Path) -> list[tuple[str, float]]:
296
+ return _parse_ocr_result(ocr(str(frame)))
297
+
298
+ return run
299
+
300
+
301
+ def download_video(url: str, dst_dir: Path, cookies_browser: str | None = None) -> DownloadedVideo:
302
+ """yt-dlp 下载视频到 dst_dir(合并为 mp4),返回路径与元信息。
303
+
304
+ Raises:
305
+ HardsubError: 下载失败。
306
+ """
307
+ import yt_dlp # noqa: PLC0415 延迟导入:不用 ocr 命令不加载
308
+
309
+ ts = datetime.now().strftime("%Y%m%d-%H%M%S")
310
+ opts: dict[str, Any] = {
311
+ "quiet": True,
312
+ "no_warnings": True,
313
+ "noplaylist": True,
314
+ # 无音轨视频(本场景触发源)自动落到单流分支,无需合并
315
+ "format": "bv*[ext=mp4]+ba[ext=m4a]/b[ext=mp4]/b",
316
+ "merge_output_format": "mp4",
317
+ "outtmpl": str(dst_dir / f"ocr-{ts}.%(ext)s"),
318
+ }
319
+ if exe := ffmpeg_exe():
320
+ opts["ffmpeg_location"] = exe # 系统无 PATH ffmpeg 时 yt-dlp 也能完成合并
321
+ if cookies_browser:
322
+ opts["cookiesfrombrowser"] = (cookies_browser,)
323
+ try:
324
+ info = yt_dlp.YoutubeDL(opts).extract_info(url, download=True)
325
+ except Exception as e: # yt_dlp 异常族庞大,统一收口
326
+ for part in dst_dir.glob(f"ocr-{ts}.*"): # 失败也清掉 .part 半成品
327
+ part.unlink(missing_ok=True)
328
+ msg = f"视频下载失败: {e}"
329
+ raise HardsubError(msg) from e
330
+ if not info:
331
+ msg = "yt-dlp 未返回视频信息"
332
+ raise HardsubError(msg)
333
+ files = sorted(dst_dir.glob(f"ocr-{ts}.*"))
334
+ videos = [f for f in files if f.suffix.lower() != ".part"]
335
+ if not videos:
336
+ msg = f"下载完成但未找到产物: {dst_dir}/ocr-{ts}.*"
337
+ raise HardsubError(msg)
338
+ return DownloadedVideo(
339
+ path=videos[0],
340
+ title=str(info.get("title") or url),
341
+ uploader=str(info.get("uploader") or info.get("channel") or "-"),
342
+ duration_s=float(info.get("duration") or 0),
343
+ )
344
+
345
+
346
+ def extract_hardsub(
347
+ video: Path,
348
+ tmp_root: Path,
349
+ fps: float = DEFAULT_FPS,
350
+ region: str = "bottom",
351
+ min_score: float = DEFAULT_MIN_SCORE,
352
+ engine: OcrEngine | None = None,
353
+ on_progress: ProgressFn | None = None,
354
+ on_frame: Callable[[FrameOcr], None] | None = None,
355
+ ) -> tuple[float, list[Segment]]:
356
+ """顶层编排:抽帧 → OCR → 合并,返回 (视频时长, Segment 列表)。
357
+
358
+ 帧目录在 finally 中删除;不删视频本体(URL/本地的删除策略差异留给 cmd 层)。
359
+ on_frame 透传给 ocr_frames(实时字幕上屏)。
360
+
361
+ Raises:
362
+ HardsubError: 引擎/ffmpeg 任一环节失败。
363
+ """
364
+ if engine is None:
365
+ engine = make_rapidocr_engine()
366
+ duration_s = probe_duration(video)
367
+ est = int(duration_s * fps) if duration_s else 0
368
+ if est:
369
+ print(f"→ 视频时长 {duration_s:.0f}s,采样 {fps}fps ≈ {min(est, MAX_FRAMES)} 帧")
370
+ frames_dir = tmp_root / f"ocr-frames-{datetime.now().strftime('%Y%m%d-%H%M%S')}"
371
+ try:
372
+ frames = extract_frames(video, frames_dir, fps, region)
373
+ if not frames:
374
+ msg = f"未抽出任何帧(视频损坏或时长为 0): {video}"
375
+ raise HardsubError(msg)
376
+ ocr_results = ocr_frames(frames, engine, min_score, on_progress, on_frame)
377
+ return duration_s, merge_frame_ocr(ocr_results, fps)
378
+ finally:
379
+ shutil.rmtree(frames_dir, ignore_errors=True)