dsh-zju-lecture-note 2.2.4 → 2.2.5
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.
- package/CHANGELOG.md +61 -1
- package/README.md +97 -150
- package/SECURITY.md +136 -44
- package/docs/technical.md +152 -44
- package/lib/client.js +14 -13
- package/lib/index.js +53 -19
- package/lib/tools.js +28 -3
- package/lib/tools.schema.json +28 -3
- package/mcp_server.py +285 -34
- package/package.json +6 -2
- package/skills/scholia-notes/references/prelude.typ +13 -0
- package/skills/scholia-notes.manifest.json +3 -3
- package/skills/zju-lecture-summarizer/SKILL.md +45 -12
- package/skills/zju-lecture-summarizer-help/SKILL.md +95 -0
- package/skills/zju-lecture-summarizer-help.manifest.json +14 -0
- package/skills/zju-lecture-summarizer-login/SKILL.md +40 -0
- package/skills/zju-lecture-summarizer-login.manifest.json +14 -0
- package/skills/zju-lecture-summarizer.manifest.json +4 -4
- package/zju_lecture/__init__.py +16 -0
- package/zju_lecture/browser_login.py +923 -0
- package/zju_lecture/cli.py +98 -3
- package/zju_lecture/client.py +91 -24
- package/zju_lecture/handout.py +51 -17
- package/zju_lecture/handout_prelude.typ +12 -0
- package/zju_lecture/note_lint.py +12 -0
- package/zju_lecture/prelude.typ +13 -0
- package/zju_lecture/study_notes.py +126 -10
package/zju_lecture/cli.py
CHANGED
|
@@ -8,8 +8,17 @@ import json
|
|
|
8
8
|
import os
|
|
9
9
|
import sys
|
|
10
10
|
|
|
11
|
+
from .browser_login import (
|
|
12
|
+
LoginError,
|
|
13
|
+
clear_session,
|
|
14
|
+
load_session_cookie,
|
|
15
|
+
login_available,
|
|
16
|
+
open_login_window,
|
|
17
|
+
session_summary,
|
|
18
|
+
)
|
|
11
19
|
from .client import (
|
|
12
20
|
BASE_URL,
|
|
21
|
+
TranscriptAuthError,
|
|
13
22
|
ZJUAPIError,
|
|
14
23
|
fetch_slides,
|
|
15
24
|
fetch_transcript,
|
|
@@ -37,7 +46,7 @@ def _read_cookie_file(path: str) -> str:
|
|
|
37
46
|
|
|
38
47
|
|
|
39
48
|
def _load_cookie(explicit: str = "", cookie_file: str = "") -> str:
|
|
40
|
-
"""Resolve a cookie: explicit
|
|
49
|
+
"""Resolve a cookie: explicit > file > ZJU_COOKIE > zju_login session > Edge."""
|
|
41
50
|
if explicit:
|
|
42
51
|
print(
|
|
43
52
|
"[zju-lecture] 警告: --cookie 会出现在进程列表中;建议改用 --cookie-file 或 ZJU_COOKIE。",
|
|
@@ -49,6 +58,9 @@ def _load_cookie(explicit: str = "", cookie_file: str = "") -> str:
|
|
|
49
58
|
env_cookie = os.environ.get("ZJU_COOKIE", "").strip()
|
|
50
59
|
if env_cookie:
|
|
51
60
|
return sanitize_cookie_header(env_cookie)
|
|
61
|
+
saved = load_session_cookie()
|
|
62
|
+
if saved:
|
|
63
|
+
return saved
|
|
52
64
|
return get_edge_cookie() or ""
|
|
53
65
|
|
|
54
66
|
|
|
@@ -84,8 +96,17 @@ def main():
|
|
|
84
96
|
p_parse.add_argument("url", help="回放 URL 或 sub_id")
|
|
85
97
|
|
|
86
98
|
# Command: fetch
|
|
87
|
-
p_fetch = subparsers.add_parser("fetch", help="
|
|
99
|
+
p_fetch = subparsers.add_parser("fetch", help="抓取课程语音识别字幕(可能需要登录态)")
|
|
88
100
|
p_fetch.add_argument("url", help="回放 URL 或 sub_id")
|
|
101
|
+
p_fetch.add_argument(
|
|
102
|
+
"--no-login",
|
|
103
|
+
action="store_true",
|
|
104
|
+
help="匿名请求被拒绝时不使用本机登录态(默认会自动读取本地登录态重试一次)",
|
|
105
|
+
)
|
|
106
|
+
p_fetch.add_argument(
|
|
107
|
+
"--cookie-file",
|
|
108
|
+
help="匿名请求被拒绝时,从指定本地文件读取登录态(不要传 Cookie 明文)",
|
|
109
|
+
)
|
|
89
110
|
p_fetch.add_argument(
|
|
90
111
|
"--format",
|
|
91
112
|
choices=["min", "seg", "chunk", "json"],
|
|
@@ -136,6 +157,29 @@ def main():
|
|
|
136
157
|
p_cw.add_argument("file", help="课件文件路径")
|
|
137
158
|
p_cw.add_argument("--max-chars", type=int, default=10000, help="最多提取字符数")
|
|
138
159
|
|
|
160
|
+
# Command: login
|
|
161
|
+
p_login = subparsers.add_parser(
|
|
162
|
+
"login",
|
|
163
|
+
help="打开独立登录窗口完成浙大登录,并安全保存本机登录态",
|
|
164
|
+
)
|
|
165
|
+
p_login.add_argument(
|
|
166
|
+
"url",
|
|
167
|
+
nargs="?",
|
|
168
|
+
default="",
|
|
169
|
+
help="登录后要打开的课堂链接(可选,仅接受 https 的 *.zju.edu.cn)",
|
|
170
|
+
)
|
|
171
|
+
p_login.add_argument(
|
|
172
|
+
"--timeout",
|
|
173
|
+
type=int,
|
|
174
|
+
default=300,
|
|
175
|
+
help="等待完成登录的秒数(默认 300,范围 30–540)",
|
|
176
|
+
)
|
|
177
|
+
p_login.add_argument(
|
|
178
|
+
"--clear",
|
|
179
|
+
action="store_true",
|
|
180
|
+
help="清除本机保存的登录态与独立登录窗口配置(不打开窗口)",
|
|
181
|
+
)
|
|
182
|
+
|
|
139
183
|
# Command: cookie
|
|
140
184
|
p_cookie = subparsers.add_parser("cookie", help="从本机 Edge 读取智云课堂 Cookie")
|
|
141
185
|
p_cookie.add_argument(
|
|
@@ -161,7 +205,24 @@ def main():
|
|
|
161
205
|
parsed = parse_lecture_url(args.url)
|
|
162
206
|
sub_id = parsed["sub_id"]
|
|
163
207
|
tenant = parsed.get("tenant_code", "112")
|
|
164
|
-
|
|
208
|
+
try:
|
|
209
|
+
segs = fetch_transcript(sub_id, tenant)
|
|
210
|
+
except TranscriptAuthError as exc:
|
|
211
|
+
if args.no_login:
|
|
212
|
+
raise ZJUAPIError(f"{exc}已按 --no-login 禁用本机登录态。") from exc
|
|
213
|
+
cookie = _load_cookie(cookie_file=args.cookie_file or os.environ.get("ZJU_COOKIE_FILE", ""))
|
|
214
|
+
if not cookie:
|
|
215
|
+
raise ZJUAPIError(
|
|
216
|
+
f"{exc}未读取到本机登录态;运行 `zju-lecture login` 打开独立登录窗口,"
|
|
217
|
+
"或使用 --cookie-file 指定本地 Cookie 文件(高级兜底)。"
|
|
218
|
+
) from exc
|
|
219
|
+
try:
|
|
220
|
+
segs = fetch_transcript(sub_id, tenant, cookie=cookie)
|
|
221
|
+
except TranscriptAuthError as auth_exc:
|
|
222
|
+
raise ZJUAPIError(
|
|
223
|
+
f"携带本地登录态后仍返回 HTTP {auth_exc.status},已停止重试;"
|
|
224
|
+
"请确认官网字幕权限并更新本机登录态。"
|
|
225
|
+
) from auth_exc
|
|
165
226
|
|
|
166
227
|
start_sec = args.start * 60 if args.start is not None else None
|
|
167
228
|
end_sec = (args.end * 60 + 59) if args.end is not None else None
|
|
@@ -262,10 +323,44 @@ def main():
|
|
|
262
323
|
sys.exit(1)
|
|
263
324
|
print(text)
|
|
264
325
|
|
|
326
|
+
elif args.command == "login":
|
|
327
|
+
if args.clear:
|
|
328
|
+
result = clear_session(delete_profile=True)
|
|
329
|
+
print(
|
|
330
|
+
"已清除本机登录态。"
|
|
331
|
+
if result.get("session_removed")
|
|
332
|
+
else "本机没有保存的登录态。"
|
|
333
|
+
)
|
|
334
|
+
if result.get("profile_removed"):
|
|
335
|
+
print("独立登录窗口的浏览器配置也已删除。")
|
|
336
|
+
if result.get("profile_error"):
|
|
337
|
+
print(
|
|
338
|
+
"独立登录窗口配置未能删除:"
|
|
339
|
+
f"{result['profile_error']}。请先关闭该窗口后重试。",
|
|
340
|
+
file=sys.stderr,
|
|
341
|
+
)
|
|
342
|
+
return
|
|
343
|
+
try:
|
|
344
|
+
result = open_login_window(args.url, args.timeout)
|
|
345
|
+
except LoginError as exc:
|
|
346
|
+
print(f"登录未完成({exc.reason}):{exc.message}", file=sys.stderr)
|
|
347
|
+
if exc.hint:
|
|
348
|
+
print(f"下一步:{exc.hint}", file=sys.stderr)
|
|
349
|
+
sys.exit(1)
|
|
350
|
+
print("登录成功,已读取本机登录态。")
|
|
351
|
+
print(f"- 浏览器: {result['browser']}")
|
|
352
|
+
print(f"- Cookie: {len(result['names'])} 条(含 _token,值不回显)")
|
|
353
|
+
if result.get("saved"):
|
|
354
|
+
print(f"- 保存: {result['saved_path']}(仅当前系统用户可解密)")
|
|
355
|
+
else:
|
|
356
|
+
print(f"- 保存失败: {result.get('save_error') or '未知原因'}(本次会话可用)")
|
|
357
|
+
print("现在可以运行 `zju-lecture fetch <url>`。")
|
|
358
|
+
|
|
265
359
|
elif args.command == "cookie":
|
|
266
360
|
c = get_edge_cookie()
|
|
267
361
|
if not c:
|
|
268
362
|
print("未能在本机 Edge 找到 classroom.zju.edu.cn 的 Cookie。")
|
|
363
|
+
print("推荐改用 `zju-lecture login`:它会打开独立登录窗口,不依赖 Edge 的 Cookie 解密。")
|
|
269
364
|
return
|
|
270
365
|
if args.reveal:
|
|
271
366
|
print("读取成功(明文回显;注意终端历史):")
|
package/zju_lecture/client.py
CHANGED
|
@@ -17,7 +17,7 @@ import urllib.parse
|
|
|
17
17
|
import urllib.request
|
|
18
18
|
from typing import Any, Dict, List, Optional
|
|
19
19
|
|
|
20
|
-
from .security import sanitize_cookie_header
|
|
20
|
+
from .security import REDACTOR, sanitize_cookie_header
|
|
21
21
|
|
|
22
22
|
BASE_URL = "https://classroom.zju.edu.cn"
|
|
23
23
|
BASE_HOST = (urllib.parse.urlparse(BASE_URL).hostname or "classroom.zju.edu.cn").lower()
|
|
@@ -109,18 +109,23 @@ def ssl_context_health() -> Dict[str, Any]:
|
|
|
109
109
|
return {"source": _CA_SOURCE, "path": _CA_PATH, "ca_certs": ca_count}
|
|
110
110
|
|
|
111
111
|
|
|
112
|
+
def _mask_proxy_credentials(value: str) -> str:
|
|
113
|
+
"""Hide ``user:password@`` in a proxy URL before it reaches an error message."""
|
|
114
|
+
return re.sub(r"(?i)([a-z][a-z0-9+.-]*://)[^/@\s]+@", r"\1[REDACTED]@", value)
|
|
115
|
+
|
|
116
|
+
|
|
112
117
|
def _proxy_env() -> str:
|
|
113
118
|
"""Describe the proxy environment, naming the variables to inspect.
|
|
114
119
|
|
|
115
120
|
"未设置" on its own does not tell the user which variable to look at, so the
|
|
116
121
|
unset case spells the names out. Returns a phrase without brackets: the
|
|
117
|
-
callers already wrap it in ().
|
|
122
|
+
callers already wrap it in (). Proxy userinfo is masked.
|
|
118
123
|
"""
|
|
119
124
|
found = []
|
|
120
125
|
for key in ("HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"):
|
|
121
126
|
value = os.environ.get(key)
|
|
122
127
|
if value:
|
|
123
|
-
found.append(f"{key}={value}")
|
|
128
|
+
found.append(f"{key}={_mask_proxy_credentials(value)}")
|
|
124
129
|
if found:
|
|
125
130
|
return ",".join(found)
|
|
126
131
|
return "HTTPS_PROXY / HTTP_PROXY 均未设置"
|
|
@@ -256,12 +261,13 @@ class _SameHostRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
|
256
261
|
"""
|
|
257
262
|
|
|
258
263
|
def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D401
|
|
259
|
-
|
|
260
|
-
|
|
264
|
+
parsed = urllib.parse.urlparse(newurl)
|
|
265
|
+
target = (parsed.hostname or "").lower()
|
|
266
|
+
if target != BASE_HOST or parsed.scheme != "https":
|
|
261
267
|
raise urllib.error.HTTPError(
|
|
262
268
|
req.full_url,
|
|
263
269
|
code,
|
|
264
|
-
f"
|
|
270
|
+
f"拒绝跨域或非 HTTPS 重定向到 {target or '(未知主机)'}(保护登录凭据)",
|
|
265
271
|
headers,
|
|
266
272
|
fp,
|
|
267
273
|
)
|
|
@@ -314,6 +320,12 @@ class ZJUAPIError(Exception):
|
|
|
314
320
|
pass
|
|
315
321
|
|
|
316
322
|
|
|
323
|
+
class TranscriptAuthError(ZJUAPIError):
|
|
324
|
+
def __init__(self, status: int):
|
|
325
|
+
self.status = status
|
|
326
|
+
super().__init__(f"字幕接口返回 HTTP {status},当前请求未获访问许可。")
|
|
327
|
+
|
|
328
|
+
|
|
317
329
|
def parse_lecture_url(url_or_sub_id: str) -> Dict[str, str]:
|
|
318
330
|
"""Extract course_id, sub_id, and tenant_code from a classroom URL or sub_id.
|
|
319
331
|
|
|
@@ -359,34 +371,69 @@ def parse_lecture_url(url_or_sub_id: str) -> Dict[str, str]:
|
|
|
359
371
|
}
|
|
360
372
|
|
|
361
373
|
|
|
374
|
+
_CLOCK_RE = re.compile(r"(\d{1,2}):(\d{2})(?::(\d{2}))?")
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _clock_seconds(value: Any) -> Optional[int]:
|
|
378
|
+
"""Parse ``HH:MM[:SS]`` (or a full datetime) into seconds of day."""
|
|
379
|
+
if value is None:
|
|
380
|
+
return None
|
|
381
|
+
text = str(value).strip()
|
|
382
|
+
if not text:
|
|
383
|
+
return None
|
|
384
|
+
if text.isdigit():
|
|
385
|
+
return int(text)
|
|
386
|
+
match = _CLOCK_RE.search(text)
|
|
387
|
+
if not match:
|
|
388
|
+
return None
|
|
389
|
+
hour, minute, second = match.group(1), match.group(2), match.group(3) or "0"
|
|
390
|
+
return int(hour) * 3600 + int(minute) * 60 + int(second)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _transcript_text(item: Dict[str, Any]) -> str:
|
|
394
|
+
for key in ("Text", "zhtext", "TransText", "entext"):
|
|
395
|
+
value = item.get(key)
|
|
396
|
+
if isinstance(value, str) and value.strip():
|
|
397
|
+
return value.strip()
|
|
398
|
+
return ""
|
|
399
|
+
|
|
400
|
+
|
|
362
401
|
def fetch_transcript(
|
|
363
402
|
sub_id: str,
|
|
364
403
|
tenant_code: str = "112",
|
|
365
|
-
timeout: int = 60
|
|
404
|
+
timeout: int = 60,
|
|
405
|
+
*,
|
|
406
|
+
cookie: Optional[str] = None,
|
|
366
407
|
) -> List[Dict[str, Any]]:
|
|
367
|
-
"""Fetch
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
Returns:
|
|
371
|
-
List of dicts: [{"begin_sec": int, "text": str}]
|
|
372
|
-
"""
|
|
373
|
-
url = (
|
|
374
|
-
f"{BASE_URL}/courseapi/v3/web-socket/search-trans-result"
|
|
375
|
-
f"?sub_id={sub_id}&tenant_code={tenant_code}"
|
|
376
|
-
)
|
|
408
|
+
"""Fetch transcript segments, optionally authenticating with a locally supplied session."""
|
|
409
|
+
query = urllib.parse.urlencode({"sub_id": sub_id, "tenant_code": tenant_code, "format": "json"})
|
|
410
|
+
url = f"{BASE_URL}/courseapi/v3/web-socket/search-trans-result?{query}"
|
|
377
411
|
req_headers = {"User-Agent": USER_AGENT}
|
|
412
|
+
if cookie is not None:
|
|
413
|
+
cookie = sanitize_cookie_header(cookie)
|
|
414
|
+
REDACTOR.add_cookie(cookie)
|
|
415
|
+
token = extract_classroom_token(cookie)
|
|
416
|
+
if not token:
|
|
417
|
+
raise ZJUAPIError(
|
|
418
|
+
"本地登录态缺少可用的 _token,无法进行字幕鉴权;请重新登录智云课堂并更新本机登录态。"
|
|
419
|
+
)
|
|
420
|
+
REDACTOR.add(token)
|
|
421
|
+
req_headers["Authorization"] = f"Bearer {token}"
|
|
378
422
|
try:
|
|
379
423
|
data = json.loads(_fetch_bytes(url, req_headers, timeout).decode("utf-8"))
|
|
380
424
|
except urllib.error.HTTPError as e:
|
|
381
|
-
|
|
425
|
+
e.close()
|
|
426
|
+
if e.code in (401, 403):
|
|
427
|
+
raise TranscriptAuthError(e.code) from e
|
|
428
|
+
raise ZJUAPIError(f"字幕接口返回 HTTP {e.code}。") from e
|
|
382
429
|
except Exception as e:
|
|
383
430
|
raise ZJUAPIError(
|
|
384
|
-
|
|
431
|
+
"请求字幕接口失败。\n" + REDACTOR.redact(describe_network_error(e))
|
|
385
432
|
) from e
|
|
386
433
|
|
|
387
434
|
code = data.get("code")
|
|
388
435
|
if code != 0:
|
|
389
|
-
msg = data.get("msg") or f"未知错误 (code={code})"
|
|
436
|
+
msg = REDACTOR.redact(data.get("msg") or f"未知错误 (code={code})")
|
|
390
437
|
raise ZJUAPIError(f"字幕接口返回非零状态码: {msg}")
|
|
391
438
|
|
|
392
439
|
items = data.get("list") or []
|
|
@@ -394,12 +441,32 @@ def fetch_transcript(
|
|
|
394
441
|
raise ZJUAPIError("字幕数据列表为空,可能课程刚结束尚未生成字幕或该课程未开启录制转写")
|
|
395
442
|
|
|
396
443
|
raw_segments = items[0].get("all_content") or []
|
|
444
|
+
# 老课程(trans_type="ai")只有 time/zhtext/entext,没有 BeginSec;
|
|
445
|
+
# 用第一条时间戳作为相对零点,至少保证顺序与间隔正确。
|
|
446
|
+
uses_clock = not any(item.get("BeginSec") not in (None, "") for item in raw_segments)
|
|
447
|
+
clock_base: Optional[int] = None
|
|
448
|
+
if uses_clock:
|
|
449
|
+
clock_base = next(
|
|
450
|
+
(clock for clock in (_clock_seconds(item.get("time")) for item in raw_segments) if clock is not None),
|
|
451
|
+
None,
|
|
452
|
+
)
|
|
453
|
+
|
|
397
454
|
segments: List[Dict[str, Any]] = []
|
|
398
455
|
for item in raw_segments:
|
|
399
|
-
text = (item
|
|
400
|
-
if text:
|
|
401
|
-
|
|
402
|
-
|
|
456
|
+
text = _transcript_text(item)
|
|
457
|
+
if not text:
|
|
458
|
+
continue
|
|
459
|
+
if uses_clock:
|
|
460
|
+
clock = _clock_seconds(item.get("time"))
|
|
461
|
+
if clock is None or clock_base is None:
|
|
462
|
+
continue
|
|
463
|
+
sec = max(0, clock - clock_base)
|
|
464
|
+
else:
|
|
465
|
+
try:
|
|
466
|
+
sec = int(item.get("BeginSec"))
|
|
467
|
+
except (TypeError, ValueError):
|
|
468
|
+
continue
|
|
469
|
+
segments.append({"begin_sec": sec, "text": text})
|
|
403
470
|
|
|
404
471
|
segments.sort(key=lambda x: x["begin_sec"])
|
|
405
472
|
if not segments:
|
package/zju_lecture/handout.py
CHANGED
|
@@ -41,6 +41,8 @@ from .study_notes import (
|
|
|
41
41
|
StudyNotesError,
|
|
42
42
|
_run_typst,
|
|
43
43
|
_SUMMARY_LINE_RE,
|
|
44
|
+
_UNKNOWN_MARKER_RE,
|
|
45
|
+
block_boundary,
|
|
44
46
|
find_typst,
|
|
45
47
|
latex_to_typst,
|
|
46
48
|
pad_inline_math,
|
|
@@ -98,11 +100,8 @@ _TABLE_SEP_RE = re.compile(
|
|
|
98
100
|
)
|
|
99
101
|
_IMAGE_RE = re.compile(r'^!\[([^\]]*)\]\(\s*([^)\s]+)(?:\s+"[^"]*")?\s*\)$')
|
|
100
102
|
_HR_RE = re.compile(r"^\s*([-*_])(?:\s*\1){2,}\s*$")
|
|
101
|
-
#:
|
|
102
|
-
|
|
103
|
-
_PSEUDO_HEADING_RE = re.compile(
|
|
104
|
-
r"^\*\*[^*\n]{1,40}\*\*(?:\s*`?\[\d{1,2}:\d{2}(?::\d{2})?\]`?)?\s*$"
|
|
105
|
-
)
|
|
103
|
+
#: 只剩破折号的「正文」:`[例] 标题 ——` 拆出来的残渣。
|
|
104
|
+
_DASH_ONLY_RE = re.compile(r"^[—–-]+$")
|
|
106
105
|
_LINK_RE = re.compile(r"\[([^\]]*)\]\(\s*([^)\s]+)(?:\s+\"[^\"]*\")?\s*\)")
|
|
107
106
|
_DETAILS_OPEN_RE = re.compile(r"<details[^>]*>", re.IGNORECASE)
|
|
108
107
|
_DETAILS_CLOSE_RE = re.compile(r"</details\s*>", re.IGNORECASE)
|
|
@@ -331,12 +330,20 @@ def _extract_label(text: str) -> Tuple[str, str]:
|
|
|
331
330
|
|
|
332
331
|
|
|
333
332
|
def _split_knot_title(body: str) -> Tuple[str, str]:
|
|
334
|
-
"""按 ``标题 —— 正文`` 拆开 knot 的内容。
|
|
333
|
+
"""按 ``标题 —— 正文`` 拆开 knot 的内容。
|
|
334
|
+
|
|
335
|
+
标题单独占一行、以 ``——`` 收尾时(正文从下一行开始),残留的破折号不是
|
|
336
|
+
正文的一部分 —— 否则 ``[例] 例 1:… ——`` 会在框里多排一个「—」。
|
|
337
|
+
"""
|
|
335
338
|
for separator in ("——", "—", " – ", " - "):
|
|
336
339
|
if separator in body:
|
|
337
340
|
head, rest = body.split(separator, 1)
|
|
338
|
-
if head.strip()
|
|
339
|
-
|
|
341
|
+
if not head.strip():
|
|
342
|
+
continue
|
|
343
|
+
rest = rest.strip()
|
|
344
|
+
if not rest or _DASH_ONLY_RE.match(rest):
|
|
345
|
+
return head.strip(), ""
|
|
346
|
+
return head.strip(), rest
|
|
340
347
|
return "", body.strip()
|
|
341
348
|
|
|
342
349
|
|
|
@@ -665,6 +672,10 @@ def _quote_block(
|
|
|
665
672
|
"NOTE": ("说明", "def"),
|
|
666
673
|
"TIP": ("提示", "def"),
|
|
667
674
|
}.get(kind, ("", "thm"))
|
|
675
|
+
if kind == "IMPORTANT":
|
|
676
|
+
# 「重点」不再套方框:走 prelude 的 keypoint —— 规范蓝色的文字段落,
|
|
677
|
+
# 只保留首行缩进与段距,没有底色 / 左侧竖线。
|
|
678
|
+
return "#keypoint[*" + label + "* " + body + "]"
|
|
668
679
|
if kind:
|
|
669
680
|
accent = _PALETTE[tone]
|
|
670
681
|
return (
|
|
@@ -787,12 +798,14 @@ def _collect_marker_body(
|
|
|
787
798
|
index: int,
|
|
788
799
|
first: str,
|
|
789
800
|
absorb: bool,
|
|
801
|
+
proof: bool = False,
|
|
790
802
|
) -> Tuple[List[str], int]:
|
|
791
803
|
"""收集标记行之后的正文行,返回 ``(行列表, 下一个待处理下标)``。
|
|
792
804
|
|
|
793
805
|
``absorb=False`` 沿用旧规则:遇到空行、标题、公式、列表、表格、代码块
|
|
794
|
-
或下一个标记就停。``absorb=True``
|
|
795
|
-
|
|
806
|
+
或下一个标记就停。``absorb=True`` 一直收到下一个标题 / 标记 / 新话题,
|
|
807
|
+
空行保留为段落分隔;``proof=True`` 时不把「短引导词 + 时间码」当边界,
|
|
808
|
+
免得证明被从中间截断。
|
|
796
809
|
"""
|
|
797
810
|
body: List[str] = [first] if first else []
|
|
798
811
|
total = len(lines)
|
|
@@ -800,11 +813,7 @@ def _collect_marker_body(
|
|
|
800
813
|
while index < total:
|
|
801
814
|
raw = lines[index]
|
|
802
815
|
stripped = raw.strip()
|
|
803
|
-
if (
|
|
804
|
-
_HEADING_RE.match(stripped)
|
|
805
|
-
or _is_marker_start(stripped)
|
|
806
|
-
or _PSEUDO_HEADING_RE.match(stripped)
|
|
807
|
-
):
|
|
816
|
+
if block_boundary(stripped, proof=proof):
|
|
808
817
|
break
|
|
809
818
|
body.append(raw)
|
|
810
819
|
index += 1
|
|
@@ -1047,6 +1056,7 @@ def _is_block_start(line: str) -> bool:
|
|
|
1047
1056
|
or (stripped.startswith("|") and stripped.endswith("|"))
|
|
1048
1057
|
or _IMAGE_RE.match(stripped)
|
|
1049
1058
|
or _is_marker_start(stripped)
|
|
1059
|
+
or _UNKNOWN_MARKER_RE.match(stripped)
|
|
1050
1060
|
or stripped.lower().startswith("<details")
|
|
1051
1061
|
or stripped.lower().startswith("</details")
|
|
1052
1062
|
)
|
|
@@ -1101,7 +1111,7 @@ def _collect_refs(lines: Sequence[str]) -> Dict[str, str]:
|
|
|
1101
1111
|
# 与 _render_body 用同一个收集器:框可以跨段,<label> 也可能写在
|
|
1102
1112
|
# 最后一段末尾;两处必须同进同退,编号才不会漂。
|
|
1103
1113
|
body_lines, index = _collect_marker_body(
|
|
1104
|
-
lines, index, marker.group(2), _absorbs_blocks(name)
|
|
1114
|
+
lines, index, marker.group(2), _absorbs_blocks(name), name == "证明"
|
|
1105
1115
|
)
|
|
1106
1116
|
counts["knot"] = counts.get("knot", 0) + 1
|
|
1107
1117
|
number = (str(section) + "." if section else "") + str(counts["knot"])
|
|
@@ -1173,7 +1183,7 @@ def _render_body(
|
|
|
1173
1183
|
if marker and marker.group(1) in MARKERS:
|
|
1174
1184
|
name = marker.group(1)
|
|
1175
1185
|
body_lines, index = _collect_marker_body(
|
|
1176
|
-
lines, index + 1, marker.group(2), _absorbs_blocks(name)
|
|
1186
|
+
lines, index + 1, marker.group(2), _absorbs_blocks(name), name == "证明"
|
|
1177
1187
|
)
|
|
1178
1188
|
call, _shape = MARKERS[name]
|
|
1179
1189
|
number = ""
|
|
@@ -1192,6 +1202,30 @@ def _render_body(
|
|
|
1192
1202
|
count(call or name)
|
|
1193
1203
|
continue
|
|
1194
1204
|
|
|
1205
|
+
# 未知的中文标记(`[推导] …`):推导按旧规范的 Proof 排(斜体 Proof. +
|
|
1206
|
+
# 块末 qed,跨段、不套框);其余未知标记按加粗小标题兜底。
|
|
1207
|
+
unknown = _UNKNOWN_MARKER_RE.match(stripped)
|
|
1208
|
+
if unknown:
|
|
1209
|
+
if unknown.group(1) == "推导":
|
|
1210
|
+
body_lines, index = _collect_marker_body(
|
|
1211
|
+
lines, index + 1, unknown.group(2), True, True
|
|
1212
|
+
)
|
|
1213
|
+
fragment, inner_paragraphs = _render_marker_block(
|
|
1214
|
+
"证明", body_lines, "", warnings, image_resolver, refs
|
|
1215
|
+
)
|
|
1216
|
+
out.append(fragment)
|
|
1217
|
+
if inner_paragraphs:
|
|
1218
|
+
count("paragraph", inner_paragraphs)
|
|
1219
|
+
count("proof")
|
|
1220
|
+
continue
|
|
1221
|
+
lead = "**" + unknown.group(1) + "**"
|
|
1222
|
+
if unknown.group(2):
|
|
1223
|
+
lead += " " + unknown.group(2)
|
|
1224
|
+
out.append(_paragraph(lead, warnings, image_resolver, refs))
|
|
1225
|
+
count("paragraph")
|
|
1226
|
+
index += 1
|
|
1227
|
+
continue
|
|
1228
|
+
|
|
1195
1229
|
# 自测题的答案块:`<details><summary>答案</summary>…</details>`。
|
|
1196
1230
|
# 题干已在上面的段落分支里套成 `#selftest` 琥珀框;答案排在框外,
|
|
1197
1231
|
# 用 `#answer`(左侧淡灰细线 + 标签)与题目分开。
|
|
@@ -298,6 +298,18 @@
|
|
|
298
298
|
#let accent(body) = text(weight: "bold", fill: palette.thm)[#body]
|
|
299
299
|
#let warn(body) = text(weight: "bold", fill: palette.warn)[#body]
|
|
300
300
|
#let aside(body) = text(size: 0.9em, fill: palette.muted)[#body]
|
|
301
|
+
// 重点:蓝色文字段落(不是方框)。用于 `> [!IMPORTANT]`:块级容器只提供
|
|
302
|
+
// 段距与首行缩进,没有底色 / 竖线,读起来仍是正文。
|
|
303
|
+
#let keypoint(body) = block(
|
|
304
|
+
width: 100%,
|
|
305
|
+
above: 6pt,
|
|
306
|
+
below: 6pt,
|
|
307
|
+
{
|
|
308
|
+
set text(fill: palette.thm)
|
|
309
|
+
h(2em)
|
|
310
|
+
body
|
|
311
|
+
},
|
|
312
|
+
)
|
|
301
313
|
#let gap(hint) = text(font: fonts.sans, size: 0.92em, fill: palette.eg)[[ fill in: #hint ]]
|
|
302
314
|
#let fillin(width: 2.2cm) = box(
|
|
303
315
|
width: width,
|
package/zju_lecture/note_lint.py
CHANGED
|
@@ -20,6 +20,8 @@ import tempfile
|
|
|
20
20
|
import time
|
|
21
21
|
from typing import List, NamedTuple
|
|
22
22
|
|
|
23
|
+
from .study_notes import MARKERS, _UNKNOWN_MARKER_RE
|
|
24
|
+
|
|
23
25
|
ERROR = "error"
|
|
24
26
|
WARN = "warn"
|
|
25
27
|
|
|
@@ -206,6 +208,16 @@ def check_markdown(text: str) -> List[Issue]:
|
|
|
206
208
|
_excerpt(stripped),
|
|
207
209
|
))
|
|
208
210
|
|
|
211
|
+
unknown = _UNKNOWN_MARKER_RE.match(probe.strip())
|
|
212
|
+
if unknown and unknown.group(1) not in MARKERS:
|
|
213
|
+
issues.append(Issue(
|
|
214
|
+
idx, WARN, "unknown_marker",
|
|
215
|
+
f"未知标记 `[{unknown.group(1)}]`,PDF 里只会排成加粗小标题",
|
|
216
|
+
"换成已支持的标记(`[定义]` / `[定理]` / `[证明]` / `[例]` / `[直觉]` / "
|
|
217
|
+
"`[强调]` / `[弱注]` 等),或去掉方括号写成普通段落。",
|
|
218
|
+
_excerpt(stripped),
|
|
219
|
+
))
|
|
220
|
+
|
|
209
221
|
|
|
210
222
|
# Per-formula checks.
|
|
211
223
|
for offset, body in _iter_inline_math(probe):
|
package/zju_lecture/prelude.typ
CHANGED
|
@@ -62,6 +62,19 @@
|
|
|
62
62
|
// 易错点:粗体 + 紫。刻意不做成方框,避免多一个色块。
|
|
63
63
|
#let warn(body) = accent(body, tone: "warn", strong: true)
|
|
64
64
|
|
|
65
|
+
// 重点:蓝色文字段落(不是方框)。用于 `> [!IMPORTANT]`:块级容器只提供
|
|
66
|
+
// 段距与首行缩进,没有底色 / 竖线,读起来仍是正文。
|
|
67
|
+
#let keypoint(body) = context block(
|
|
68
|
+
width: 100%,
|
|
69
|
+
above: 6pt,
|
|
70
|
+
below: 6pt,
|
|
71
|
+
{
|
|
72
|
+
set text(fill: active.get().thm)
|
|
73
|
+
h(2em)
|
|
74
|
+
body
|
|
75
|
+
},
|
|
76
|
+
)
|
|
77
|
+
|
|
65
78
|
// ── 3. 细分隔线:比方框轻得多的段落切分 ──
|
|
66
79
|
#let divider = context block(width: 100%, above: 0.6em, below: 0.6em)[
|
|
67
80
|
#line(length: 100%, stroke: 0.4pt + active.get().hairline)
|