earshot-cli 0.5.0__tar.gz → 0.7.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.
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/PKG-INFO +12 -2
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/README.md +9 -1
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/pyproject.toml +6 -2
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/src/earshot/cli.py +119 -4
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/src/earshot/compose.py +22 -1
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/src/earshot/deliver.py +132 -39
- earshot_cli-0.7.0/src/earshot/hardsub.py +379 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/src/earshot/subtitle.py +4 -1
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/tests/test_compose.py +24 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/tests/test_deliver.py +21 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/tests/test_deliver_api.py +103 -2
- earshot_cli-0.7.0/tests/test_hardsub.py +221 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/tests/test_wizard.py +16 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/uv.lock +465 -1
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/.github/workflows/ci.yml +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/.github/workflows/publish.yml +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/.gitignore +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/LICENSE +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/scripts/download_models.sh +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/src/earshot/__init__.py +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/src/earshot/auth.py +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/src/earshot/capture.py +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/src/earshot/config.py +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/src/earshot/extract.py +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/src/earshot/live.py +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/src/earshot/models.py +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/src/earshot/transcribe.py +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/src/earshot/transcribe_cloud.py +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/tests/conftest.py +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/tests/test_auth.py +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/tests/test_config.py +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/tests/test_credential_lifecycle.py +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/tests/test_do_deliver.py +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/tests/test_extract.py +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/tests/test_live.py +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/tests/test_me.py +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.0}/tests/test_subtitle.py +0 -0
- {earshot_cli-0.5.0 → earshot_cli-0.7.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.
|
|
3
|
+
Version: 0.7.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
|
|
@@ -160,10 +162,13 @@ uv tool upgrade earshot-cli
|
|
|
160
162
|
源码安装请**锁版本 tag**,不要引滚动的 `main`(消费方 `uv sync`/`pip install` 会隐性升级到未审阅代码;升级应当是显式改版本号的决策):
|
|
161
163
|
|
|
162
164
|
```bash
|
|
163
|
-
uv tool install "earshot-cli @ https://github.com/helloworldtang/earshot/archive/refs/tags/v0.
|
|
165
|
+
uv tool install "earshot-cli @ https://github.com/helloworldtang/earshot/archive/refs/tags/v0.7.0.tar.gz"
|
|
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
|
|
|
@@ -127,10 +127,13 @@ uv tool upgrade earshot-cli
|
|
|
127
127
|
源码安装请**锁版本 tag**,不要引滚动的 `main`(消费方 `uv sync`/`pip install` 会隐性升级到未审阅代码;升级应当是显式改版本号的决策):
|
|
128
128
|
|
|
129
129
|
```bash
|
|
130
|
-
uv tool install "earshot-cli @ https://github.com/helloworldtang/earshot/archive/refs/tags/v0.
|
|
130
|
+
uv tool install "earshot-cli @ https://github.com/helloworldtang/earshot/archive/refs/tags/v0.7.0.tar.gz"
|
|
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.
|
|
3
|
+
version = "0.7.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
|
|
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)
|
|
@@ -20,6 +20,9 @@ EXOMIND_PENDING_EXIT_CODE = 3 # exomind CLI 契约:3 = 已提交、后台仍在
|
|
|
20
20
|
DELIVER_TIMEOUT_S = 600.0
|
|
21
21
|
INGEST_POLL_INTERVAL_S = 2.0
|
|
22
22
|
INGEST_POLL_BUDGET_S = 120.0
|
|
23
|
+
# 服务端 IngestRequest 上限 MAX_INGEST_CONTENT=30000 字符,超限 422「请拆成几次存入」;
|
|
24
|
+
# 客户端留 2K 余量按段落边界预分片,避免整篇转写被一次性拒收(2026-11-15,45K 录播课转写实证)。
|
|
25
|
+
INGEST_MAX_CONTENT_CHARS = 28000
|
|
23
26
|
|
|
24
27
|
|
|
25
28
|
@dataclass(frozen=True, slots=True)
|
|
@@ -85,6 +88,27 @@ def deliver_exomind(
|
|
|
85
88
|
return DeliveryResult("failed", detail)
|
|
86
89
|
|
|
87
90
|
|
|
91
|
+
def _raise_with_server_detail(resp: httpx.Response) -> None:
|
|
92
|
+
"""is_error 响应抛 RuntimeError 并带上服务端 detail(失败信息与失败事实同源)。
|
|
93
|
+
|
|
94
|
+
裸状态码(如「422」)用户无从下手;拒收原因(内容太长/标题超限等)只在
|
|
95
|
+
响应体里。JSON 取 detail 字段,解析不了退回响应体前 200 字符。
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
resp: 已完成的 httpx 响应。
|
|
99
|
+
|
|
100
|
+
Raises:
|
|
101
|
+
RuntimeError: 携带 ``HTTP {status_code}: {detail}`` 格式的错误。
|
|
102
|
+
"""
|
|
103
|
+
try:
|
|
104
|
+
body: Any = resp.json()
|
|
105
|
+
detail = body.get("detail") if isinstance(body, dict) else body
|
|
106
|
+
msg = str(detail) if detail else resp.text[:200]
|
|
107
|
+
except ValueError:
|
|
108
|
+
msg = resp.text[:200]
|
|
109
|
+
raise RuntimeError(f"HTTP {resp.status_code}: {msg}") from None
|
|
110
|
+
|
|
111
|
+
|
|
88
112
|
def deliver_webhook(
|
|
89
113
|
url: str,
|
|
90
114
|
title: str,
|
|
@@ -109,7 +133,8 @@ def deliver_webhook(
|
|
|
109
133
|
|
|
110
134
|
def _post(target: str, payload: dict[str, str | list[str]]) -> None:
|
|
111
135
|
resp = httpx.post(target, json=payload, timeout=30.0)
|
|
112
|
-
resp.
|
|
136
|
+
if resp.is_error:
|
|
137
|
+
_raise_with_server_detail(resp)
|
|
113
138
|
|
|
114
139
|
send = poster or _post
|
|
115
140
|
payload: dict[str, str | list[str]] = {"origin": origin, "title": title, "content": content_md, "tags": tags}
|
|
@@ -134,6 +159,42 @@ def _as_count(value: Any) -> int:
|
|
|
134
159
|
return 0
|
|
135
160
|
|
|
136
161
|
|
|
162
|
+
def split_for_ingest(content: str, limit: int = INGEST_MAX_CONTENT_CHARS) -> list[str]:
|
|
163
|
+
"""按段落边界贪心分片,单段超限时再按字符硬切。
|
|
164
|
+
|
|
165
|
+
服务端对 content 有 30000 字符硬上限(超限 422 拒收并提示拆分),
|
|
166
|
+
长转写(1h 录播课 ~45K 字符)必须客户端预分片。
|
|
167
|
+
|
|
168
|
+
Args:
|
|
169
|
+
content: 完整正文。
|
|
170
|
+
limit: 单片字符上限。
|
|
171
|
+
|
|
172
|
+
Returns:
|
|
173
|
+
分片列表;不超过 limit 时原样单元素返回。各片拼接内容与原文一致
|
|
174
|
+
(硬切场景仅多出切点处的字符分裂,不丢字)。
|
|
175
|
+
"""
|
|
176
|
+
if len(content) <= limit:
|
|
177
|
+
return [content]
|
|
178
|
+
chunks: list[str] = []
|
|
179
|
+
buf = ""
|
|
180
|
+
for para in content.split("\n\n"):
|
|
181
|
+
while len(para) > limit:
|
|
182
|
+
if buf:
|
|
183
|
+
chunks.append(buf)
|
|
184
|
+
buf = ""
|
|
185
|
+
chunks.append(para[:limit])
|
|
186
|
+
para = para[limit:]
|
|
187
|
+
cand = f"{buf}\n\n{para}" if buf else para
|
|
188
|
+
if len(cand) > limit:
|
|
189
|
+
chunks.append(buf)
|
|
190
|
+
buf = para
|
|
191
|
+
else:
|
|
192
|
+
buf = cand
|
|
193
|
+
if buf:
|
|
194
|
+
chunks.append(buf)
|
|
195
|
+
return chunks
|
|
196
|
+
|
|
197
|
+
|
|
137
198
|
def deliver_exomind_api(
|
|
138
199
|
md_path: Path,
|
|
139
200
|
title: str,
|
|
@@ -149,6 +210,9 @@ def deliver_exomind_api(
|
|
|
149
210
|
|
|
150
211
|
走 POST /ingest/async + GET /ingest/status,与 CLI 同契约:
|
|
151
212
|
秒回 job_id → 轮询至 done/failed;超预算视为 pending(内容已入库,抽取仍在跑)。
|
|
213
|
+
正文超 INGEST_MAX_CONTENT_CHARS 时按段落边界自动分片逐片投递
|
|
214
|
+
(标题加「(i/n)」后缀,各片独立 client_key);任一片失败即 failed,
|
|
215
|
+
detail 注明已成功的片,未投的片不再发。
|
|
152
216
|
|
|
153
217
|
Args:
|
|
154
218
|
md_path: 笔记文件。
|
|
@@ -157,7 +221,7 @@ def deliver_exomind_api(
|
|
|
157
221
|
settings: 含 base_url / api_key 的配置。
|
|
158
222
|
poster: ``(url, payload, headers) -> 响应 dict``(测试注入)。
|
|
159
223
|
getter: ``(url, params, headers) -> 响应 dict``(测试注入)。
|
|
160
|
-
poll_interval_s / poll_budget_s:
|
|
224
|
+
poll_interval_s / poll_budget_s: 轮询节奏与总预算(单片)。
|
|
161
225
|
source_url: 原文链接(video 路线);content+url 并存时服务端仅作出处留痕,不抓取。
|
|
162
226
|
|
|
163
227
|
Returns:
|
|
@@ -168,7 +232,8 @@ def deliver_exomind_api(
|
|
|
168
232
|
|
|
169
233
|
def _post(url: str, payload: dict[str, Any], headers: dict[str, str]) -> dict[str, Any]:
|
|
170
234
|
resp = httpx.post(url, json=payload, headers=headers, timeout=60.0)
|
|
171
|
-
resp.
|
|
235
|
+
if resp.is_error:
|
|
236
|
+
_raise_with_server_detail(resp)
|
|
172
237
|
return dict(resp.json())
|
|
173
238
|
|
|
174
239
|
def _get(url: str, params: dict[str, str], headers: dict[str, str]) -> dict[str, Any]:
|
|
@@ -182,39 +247,67 @@ def deliver_exomind_api(
|
|
|
182
247
|
headers = ua_headers(Authorization=f"Bearer {settings.exomind_api_key}")
|
|
183
248
|
|
|
184
249
|
content = md_path.read_text(encoding="utf-8")
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
250
|
+
chunks = split_for_ingest(content)
|
|
251
|
+
total = len(chunks)
|
|
252
|
+
|
|
253
|
+
def _deliver_chunk(idx: int, chunk: str) -> DeliveryResult:
|
|
254
|
+
"""投递单片:提交 → 轮询回执,与未分片路径完全同构。"""
|
|
255
|
+
chunk_title = title
|
|
256
|
+
if total > 1 and title:
|
|
257
|
+
# 服务端标题上限 200 字符,后缀前先截,拒收在客户端就挡住
|
|
258
|
+
chunk_title = f"{title[:190]}({idx}/{total})"
|
|
259
|
+
payload: dict[str, Any] = {"content": chunk, "origin": EXOMIND_ORIGIN, "client_key": client_key_for(chunk)}
|
|
260
|
+
if chunk_title:
|
|
261
|
+
payload["title"] = chunk_title
|
|
262
|
+
if tags:
|
|
263
|
+
payload["tags"] = tags
|
|
264
|
+
if source_url:
|
|
265
|
+
payload["url"] = source_url
|
|
266
|
+
try:
|
|
267
|
+
resp = post(f"{base}/ingest/async", payload, headers)
|
|
268
|
+
except Exception as e:
|
|
269
|
+
return DeliveryResult("failed", f"提交 ingest 失败: {e}")
|
|
270
|
+
job_id = resp.get("job_id")
|
|
271
|
+
if not job_id:
|
|
272
|
+
return DeliveryResult("failed", f"响应缺 job_id: {str(resp)[:200]}")
|
|
273
|
+
|
|
274
|
+
deadline = time.monotonic() + poll_budget_s
|
|
275
|
+
try:
|
|
276
|
+
while time.monotonic() < deadline:
|
|
277
|
+
try:
|
|
278
|
+
st = get(f"{base}/ingest/status", {"job_id": str(job_id)}, headers)
|
|
279
|
+
except Exception as e:
|
|
280
|
+
return DeliveryResult("failed", f"查询回执失败(job_id={job_id}): {e}")
|
|
281
|
+
status = st.get("status")
|
|
282
|
+
if status == "done":
|
|
283
|
+
n_entities = _as_count(st.get("entities"))
|
|
284
|
+
n_pages = _as_count(st.get("created_pages"))
|
|
285
|
+
n_updated = _as_count(st.get("updated_pages"))
|
|
286
|
+
detail = f"已入库:实体 {n_entities} 个,页面 +{n_pages}/更{n_updated}(job_id={job_id})"
|
|
287
|
+
return DeliveryResult("delivered", detail)
|
|
288
|
+
if status == "failed":
|
|
289
|
+
return DeliveryResult("failed", f"服务端抽取失败: {st.get('error', '未知')}(job_id={job_id})")
|
|
290
|
+
time.sleep(poll_interval_s)
|
|
291
|
+
except KeyboardInterrupt:
|
|
292
|
+
# Ctrl-C = 不等回执了;内容已提交,服务端 job 会继续跑完
|
|
293
|
+
return DeliveryResult("pending", f"已提交,不再等待回执(job_id={job_id})")
|
|
294
|
+
return DeliveryResult("pending", f"已提交,后台抽取中(job_id={job_id})")
|
|
295
|
+
|
|
296
|
+
results = [_deliver_chunk(i + 1, chunk) for i, chunk in enumerate(chunks)]
|
|
297
|
+
if total == 1:
|
|
298
|
+
return results[0]
|
|
299
|
+
prefix = f"分 {total} 片投递:"
|
|
300
|
+
statuses = {r.status for r in results}
|
|
301
|
+
if statuses == {"delivered"}:
|
|
302
|
+
summary = ";".join(f"片{i + 1} {r.detail}" for i, r in enumerate(results))
|
|
303
|
+
return DeliveryResult("delivered", f"{prefix}全部入库。{summary}")
|
|
304
|
+
if "failed" in statuses:
|
|
305
|
+
ok = sum(1 for r in results if r.status == "delivered")
|
|
306
|
+
failed_idx = next(i + 1 for i, r in enumerate(results) if r.status == "failed")
|
|
307
|
+
return DeliveryResult(
|
|
308
|
+
"failed",
|
|
309
|
+
f"{prefix}第 {failed_idx} 片失败({results[failed_idx - 1].detail}),已成功 {ok}/{total} 片;"
|
|
310
|
+
"已入库片重跑时会按 client_key 幂等去重",
|
|
311
|
+
)
|
|
312
|
+
summary = ";".join(f"片{i + 1} {r.status}:{r.detail}" for i, r in enumerate(results))
|
|
313
|
+
return DeliveryResult("pending", f"{prefix}部分片仍在抽取。{summary}")
|