socratic-sidecar 0.3.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 (83) hide show
  1. socratic_sidecar-0.3.0/PKG-INFO +174 -0
  2. socratic_sidecar-0.3.0/README.md +146 -0
  3. socratic_sidecar-0.3.0/app/__init__.py +0 -0
  4. socratic_sidecar-0.3.0/app/__main__.py +115 -0
  5. socratic_sidecar-0.3.0/app/adapters/__init__.py +39 -0
  6. socratic_sidecar-0.3.0/app/adapters/base.py +50 -0
  7. socratic_sidecar-0.3.0/app/adapters/cts.py +190 -0
  8. socratic_sidecar-0.3.0/app/adapters/http.py +71 -0
  9. socratic_sidecar-0.3.0/app/adapters/wikisource.py +260 -0
  10. socratic_sidecar-0.3.0/app/catalog.py +127 -0
  11. socratic_sidecar-0.3.0/app/citation_policy.py +807 -0
  12. socratic_sidecar-0.3.0/app/citations.py +81 -0
  13. socratic_sidecar-0.3.0/app/classifier.py +36 -0
  14. socratic_sidecar-0.3.0/app/compute.py +45 -0
  15. socratic_sidecar-0.3.0/app/config.py +270 -0
  16. socratic_sidecar-0.3.0/app/critic.py +127 -0
  17. socratic_sidecar-0.3.0/app/curriculum.py +159 -0
  18. socratic_sidecar-0.3.0/app/editions.py +107 -0
  19. socratic_sidecar-0.3.0/app/evaluations.py +75 -0
  20. socratic_sidecar-0.3.0/app/evaluator.py +140 -0
  21. socratic_sidecar-0.3.0/app/federated.py +236 -0
  22. socratic_sidecar-0.3.0/app/glossary.json +1066 -0
  23. socratic_sidecar-0.3.0/app/ingest.py +98 -0
  24. socratic_sidecar-0.3.0/app/learner.py +196 -0
  25. socratic_sidecar-0.3.0/app/lexical.py +523 -0
  26. socratic_sidecar-0.3.0/app/lexicon.py +201 -0
  27. socratic_sidecar-0.3.0/app/llm.py +144 -0
  28. socratic_sidecar-0.3.0/app/locators.py +163 -0
  29. socratic_sidecar-0.3.0/app/main.py +781 -0
  30. socratic_sidecar-0.3.0/app/pages.py +200 -0
  31. socratic_sidecar-0.3.0/app/policy.py +59 -0
  32. socratic_sidecar-0.3.0/app/review.py +339 -0
  33. socratic_sidecar-0.3.0/app/schema.py +205 -0
  34. socratic_sidecar-0.3.0/app/search.py +1112 -0
  35. socratic_sidecar-0.3.0/app/state_machine.py +230 -0
  36. socratic_sidecar-0.3.0/app/state_store.py +132 -0
  37. socratic_sidecar-0.3.0/app/textutil.py +117 -0
  38. socratic_sidecar-0.3.0/app/toc.py +77 -0
  39. socratic_sidecar-0.3.0/app/translate.py +307 -0
  40. socratic_sidecar-0.3.0/pyproject.toml +51 -0
  41. socratic_sidecar-0.3.0/setup.cfg +4 -0
  42. socratic_sidecar-0.3.0/socratic_sidecar.egg-info/PKG-INFO +174 -0
  43. socratic_sidecar-0.3.0/socratic_sidecar.egg-info/SOURCES.txt +81 -0
  44. socratic_sidecar-0.3.0/socratic_sidecar.egg-info/dependency_links.txt +1 -0
  45. socratic_sidecar-0.3.0/socratic_sidecar.egg-info/entry_points.txt +2 -0
  46. socratic_sidecar-0.3.0/socratic_sidecar.egg-info/requires.txt +20 -0
  47. socratic_sidecar-0.3.0/socratic_sidecar.egg-info/top_level.txt +1 -0
  48. socratic_sidecar-0.3.0/tests/test_auth.py +36 -0
  49. socratic_sidecar-0.3.0/tests/test_cache.py +47 -0
  50. socratic_sidecar-0.3.0/tests/test_chapter_scope.py +77 -0
  51. socratic_sidecar-0.3.0/tests/test_citation_policy.py +775 -0
  52. socratic_sidecar-0.3.0/tests/test_citations_store.py +110 -0
  53. socratic_sidecar-0.3.0/tests/test_classifier.py +36 -0
  54. socratic_sidecar-0.3.0/tests/test_compute.py +137 -0
  55. socratic_sidecar-0.3.0/tests/test_cts_adapter.py +111 -0
  56. socratic_sidecar-0.3.0/tests/test_curriculum.py +107 -0
  57. socratic_sidecar-0.3.0/tests/test_embed_public.py +155 -0
  58. socratic_sidecar-0.3.0/tests/test_evaluator.py +132 -0
  59. socratic_sidecar-0.3.0/tests/test_federated.py +103 -0
  60. socratic_sidecar-0.3.0/tests/test_ingest_public.py +154 -0
  61. socratic_sidecar-0.3.0/tests/test_learner.py +80 -0
  62. socratic_sidecar-0.3.0/tests/test_lexical.py +190 -0
  63. socratic_sidecar-0.3.0/tests/test_lexicon.py +177 -0
  64. socratic_sidecar-0.3.0/tests/test_llm.py +160 -0
  65. socratic_sidecar-0.3.0/tests/test_no_index.py +111 -0
  66. socratic_sidecar-0.3.0/tests/test_pages.py +109 -0
  67. socratic_sidecar-0.3.0/tests/test_policy.py +95 -0
  68. socratic_sidecar-0.3.0/tests/test_render_switch.py +110 -0
  69. socratic_sidecar-0.3.0/tests/test_review.py +134 -0
  70. socratic_sidecar-0.3.0/tests/test_schema_v2.py +162 -0
  71. socratic_sidecar-0.3.0/tests/test_state_machine.py +126 -0
  72. socratic_sidecar-0.3.0/tests/test_state_store.py +53 -0
  73. socratic_sidecar-0.3.0/tests/test_toc.py +69 -0
  74. socratic_sidecar-0.3.0/tests/test_toc_bind.py +56 -0
  75. socratic_sidecar-0.3.0/tests/test_toc_clean.py +23 -0
  76. socratic_sidecar-0.3.0/tests/test_toc_find.py +42 -0
  77. socratic_sidecar-0.3.0/tests/test_toc_pian.py +54 -0
  78. socratic_sidecar-0.3.0/tests/test_translate.py +129 -0
  79. socratic_sidecar-0.3.0/tests/test_v2_lexical_fusion.py +108 -0
  80. socratic_sidecar-0.3.0/tests/test_v2_search.py +233 -0
  81. socratic_sidecar-0.3.0/tests/test_v2_translation.py +97 -0
  82. socratic_sidecar-0.3.0/tests/test_v2_vectors.py +178 -0
  83. socratic_sidecar-0.3.0/tests/test_wikisource_adapter.py +97 -0
@@ -0,0 +1,174 @@
1
+ Metadata-Version: 2.4
2
+ Name: socratic-sidecar
3
+ Version: 0.3.0
4
+ Summary: Minimal Socratic tutor sidecar: search, pages, compute
5
+ License: MIT
6
+ Project-URL: Homepage, https://github.com/Icefox12138/socratic-tutor/tree/main/sidecar
7
+ Project-URL: Repository, https://github.com/Icefox12138/socratic-tutor
8
+ Project-URL: Issues, https://github.com/Icefox12138/socratic-tutor/issues
9
+ Requires-Python: >=3.12
10
+ Description-Content-Type: text/markdown
11
+ Requires-Dist: calcbox<0.5,>=0.3
12
+ Requires-Dist: fastapi>=0.110
13
+ Requires-Dist: uvicorn>=0.29
14
+ Requires-Dist: pypdfium2>=4.30
15
+ Requires-Dist: pillow>=10.0
16
+ Requires-Dist: sympy>=1.13
17
+ Requires-Dist: scipy>=1.11
18
+ Requires-Dist: PyYAML>=6.0
19
+ Requires-Dist: classics-index>=0.1
20
+ Provides-Extra: test
21
+ Requires-Dist: requests; extra == "test"
22
+ Requires-Dist: httpx2; extra == "test"
23
+ Provides-Extra: compute
24
+ Requires-Dist: pint>=0.23; extra == "compute"
25
+ Requires-Dist: control>=0.10; extra == "compute"
26
+ Provides-Extra: lemma
27
+ Requires-Dist: simplemma>=2.0; extra == "lemma"
28
+
29
+ # sidecar(最小服务,v0.2.1)
30
+
31
+ 只做四件事:`/health`、`/v1/search`、`/v1/pages`、`/v1/compute`。
32
+
33
+ 检索默认走 **FTS bigram + BGE-M3 + bge-reranker**;模型不可用时自动退回 FTS。
34
+
35
+ 浏览器教学台:**http://127.0.0.1:8765/ui**(引用卡、提示级别、页图回看、掌握度)。
36
+
37
+ ## Docker(配套服务)
38
+
39
+ ```bash
40
+ # 在仓库根目录
41
+ docker compose up --build
42
+ # 或
43
+ docker build -t socratic-sidecar:0.2.1 .
44
+ docker run -p 8765:8765 -v "$PWD/data:/data" -v "$PWD/samples/PDF:/books:ro" \
45
+ socratic-sidecar:0.2.1
46
+ ```
47
+
48
+ 镜像不带书、不带 BGE 权重;默认 `SOCRATIC_BGE=0`,需要 BGE 时挂载模型并设
49
+ `SOCRATIC_BGE=1`。`/data` 必须可写(SQLite journal、state.db、页图缓存)。
50
+
51
+ ## 运行
52
+
53
+ ```powershell
54
+ cd D:\Guo-Code\socratic-tutor\sidecar
55
+ python -m uvicorn app.main:app --host 127.0.0.1 --port 8765 --timeout-keep-alive 75
56
+ ```
57
+
58
+ 若要用 BGE/rerank,必须用带 torch 的 `.venv-bge`:
59
+
60
+ ```powershell
61
+ & 'D:\Guo-Code\socratic-tutor\.venv-bge\Scripts\python.exe' -m uvicorn app.main:app --host 127.0.0.1 --port 8765 --timeout-keep-alive 75
62
+ ```
63
+
64
+ `--timeout-keep-alive 75` 不是可有可无的:uvicorn 默认 5 秒就关闭空闲连接,而插件的内置教学台每 15 秒轮询一次(`plugin-socratic/client.js`),Keep-Alive 短于轮询间隔时,浏览器复用连接恰好撞上服务端关闭,会偶发 `net::ERR_EMPTY_RESPONSE`,面板上显示为 `sidecar: Failed to fetch`。给到 75 秒即可消除这类瞬断。
65
+
66
+ 可选环境变量:
67
+
68
+ | 变量 | 默认 | 说明 |
69
+ |---|---|---|
70
+ | `SOCRATIC_DB` | `eval/p1/ingest/search.db` | chunks 索引 |
71
+ | `SOCRATIC_ROOT` | `D:\Guo-Code` | PDF 根 |
72
+ | `SOCRATIC_CACHE` | `sidecar/cache/pages` | 页图缓存 |
73
+ | `SOCRATIC_TOKEN` | 空 | 非空时要求 `X-Sidecar-Token` |
74
+ | `SOCRATIC_REQUIRE_AUTH` | `0` | `1` 时无 token 配置直接 503 |
75
+ | `SOCRATIC_CORS_ORIGIN_REGEX` | `(http://(127\.0\.0\.1\|localhost)(:\d+)?\|dsh-app://[^/]+)` | 允许调用 sidecar 的浏览器源。DSH 桌面应用用自定义协议 `dsh-app://` 渲染界面,内置教学台就是从该源发请求的;不含此项会被浏览器判 `Failed to fetch` |
76
+ | `SOCRATIC_PRELOAD` | `0` | `1` 时启动后后台加载 BGE/reranker |
77
+ | `SOCRATIC_BGE` | `1` | `0` 时强制 FTS |
78
+ | `SOCRATIC_RERANK_TOPK` | `50` | 送入 reranker 的候选数 |
79
+ | `SOCRATIC_BGE_MODEL` | `models/bge-m3` | 嵌入模型 |
80
+ | `SOCRATIC_RERANK_MODEL` | `models/bge-reranker-v2-m3` | 重排模型 |
81
+ | `SOCRATIC_IMAGE_ONLY_LANGS` | `greek,grc` | 只回页图、不回文本的语言(见 §页图策略) |
82
+
83
+ ## 章回索引 / 页图浏览(P3-2)
84
+
85
+ 竖排扫描件没有文本层,索引从**版心**(页边书眉)的 OCR 里建:裁右侧竖条 → 取最上方短「卷」行 → 连续 ≥5 页才算一章。C1《史记》358 页得出 7 卷 + 卷首/卷末,覆盖 358/358 页。
86
+
87
+ - 建索引:`vertical_title_ocr.py` 扫整本右栏(卷眉 + 篇名)→ `build_index.py` 一次得到卷与篇(也支持 `--headers` 用单独的卷眉 pass);结果写 `toc` 表,`level=1` 卷、`level=2` 篇;
88
+ - 浏览:`/browse`,章回列表 + ←/→ 翻页 + 150/200 dpi;
89
+ - 详见 `docs/P3-2-vertical-index.md`。
90
+
91
+ ## 页图策略(K5)
92
+
93
+ 希腊文命中**不返回文本**:`text` 置空,带 `image_only: true` 与 `citation.page_image`;`/v1/chunks/{id}` 同样处理,`citations` 表的 `snippet` 写空串。检索本身仍用存储文本(FTS/BGE/rerank),所以召回不受影响。
94
+
95
+ 原因:本地 OCR 在 K5 上 CER 70.9–94.0%,且文本层是"希腊文 + 英文注释"混合,直接引用会造出页图不支持的引文。策略在 `app/policy.py`,可用 `SOCRATIC_IMAGE_ONLY_LANGS` 覆盖或清空回退。详见 `docs/P1-3c-K5-pageimage.md`。
96
+
97
+ ## 检索性能(4060 8 GB)
98
+
99
+ | 项 | 实测 |
100
+ |---|---:|
101
+ | 首次查询(加载模型) | ~8.6 s |
102
+ | 预热后 p50 | ~700 ms |
103
+ | 预热后 p95 | ~830 ms |
104
+ | **缓存命中** | **~10 ms** |
105
+ | 100 问句 page recall@10 | **0.80–0.82**(选择性翻译;默认关闭) |
106
+ | 中文 / 拉丁 / 希腊 / 英文 | 93% / 70% / 42–58% / 70% |
107
+
108
+ 缓存:`/v1/search` 按 `(query,view,limit,source,lang,BGE)` 缓存,TTL 300 s、LRU 256;命中仍会写 `citations`。管理端点 `/v1/cache`、`POST /v1/cache/clear`,健康检查含 `cache` 统计。
109
+
110
+ 说明:0.80–0.82 需要 `SOCRATIC_V1_RETRIEVAL=1` + LLM key;默认路径仍约 0.76。
111
+ v2 公开语料 130 人工题的 R@5 为 0.977(见 `eval/public/RESULTS-project.md`)。
112
+
113
+ ## 端点
114
+
115
+ | 方法 | 路径 | 参数 |
116
+ |---|---|---|
117
+ | GET | `/health` | — |
118
+ | GET | `/v1/search` | `q`, `view=student\|tutor`, `limit`, `source?`, `lang?`, `book?`, `chapter?` |
119
+ | GET | `/v1/chunks/{id}` | `view` |
120
+ | POST | `/v1/review` | `{session_id, state?, answers?, record?}` → 复盘报告(P3) |
121
+ | GET | `/v1/books` | 有章回索引的书 |
122
+ | GET | `/v1/toc` | `source`, `book` → 章回索引 + 总页数(P3-2) |
123
+ | GET | `/v1/chapter` | `book`, `q` 或 `page` → 章回 + 页码范围 + 页图(P3-6) |
124
+ | GET | `/browse` | 页图浏览页(章回列表 + 翻页) |
125
+ | GET | `/v1/pages` | `source`, `book`, `page`, `dpi`, `bbox?` |
126
+ | POST | `/v1/compute` | `{expression, operation, variable, point}` |
127
+ | POST | `/v1/state/init` | `{session_id, goal, concept, lang}` |
128
+ | POST | `/v1/state/step` | `{session_id, event, result?}` |
129
+ | GET | `/v1/state/{id}` | 状态 + 摘要 |
130
+ | GET | `/v1/state/{id}/events` | 事件日志 |
131
+ | POST | `/v1/state/{id}/replay` | 从事件重建状态 |
132
+ | POST | `/v1/classify` | `{text}` → 提问类型/是否多问 |
133
+ | POST | `/v1/evaluate` | `{question, answer, rubric?, expected?, use_llm}` |
134
+ | POST | `/v1/critic` | `{text, hint_level, has_citation}` |
135
+ | POST | `/v1/critic/rewrite` | `{text}` → 只保留第一个问句 |
136
+ | POST | `/v1/critic/citation` | `{text, mode}` → soften/mark/off |
137
+ | GET | `/v1/evaluations/{session_id}` | 判定历史 |
138
+ | GET | `/v1/citations/{session_id}` | 最近引用;`?turn=N` 按回合 |
139
+ | GET | `/v1/cache` | 命中/miss/容量/TTL |
140
+ | POST | `/v1/cache/clear` | 清空查询缓存 |
141
+ | GET | `/v1/mastery/{concept}` | BKT 掌握度 |
142
+ | GET | `/v1/mastery` | 全部概念 |
143
+ | POST | `/v1/cards` | 添加 FSRS 卡 |
144
+ | POST | `/v1/cards/{id}/review` | `{rating: again\|hard\|good\|easy}` |
145
+ | GET | `/v1/cards/due` | 到期卡 |
146
+
147
+ `view=answer_key` **不接受**;`search` 在 SQL 层过滤 `visibility`。
148
+
149
+ ## 示例
150
+
151
+ ```bash
152
+ curl "http://127.0.0.1:8765/health"
153
+ curl "http://127.0.0.1:8765/v1/search?q=%E5%BE%AE%E5%88%86&view=student&limit=3"
154
+ curl -X POST http://127.0.0.1:8765/v1/compute \
155
+ -H "Content-Type: application/json" \
156
+ -d '{"expression":"x^2","operation":"diff"}'
157
+ ```
158
+
159
+ ## 冒烟
160
+
161
+ ```powershell
162
+ # 终端 1
163
+ python -m uvicorn app.main:app --port 8765 --timeout-keep-alive 75
164
+ # 终端 2
165
+ python tests/smoke.py
166
+ ```
167
+
168
+ ## 边界
169
+
170
+ - 计算只接受 SymPy 表达式与白名单操作,**不执行任意 Python**;
171
+ - 页图 `book` 路径做根目录校验,防路径穿越;
172
+ - 无鉴权时只绑 `127.0.0.1`;暴露端口必须设 `SOCRATIC_TOKEN`;
173
+ - CORS 只允许 `http://127.0.0.1:*` / `http://localhost:*`(供 DSH 内嵌 UI 调用)。
174
+ - 未接 BGE/reranker;`tier` 暂为 `unknown`。
@@ -0,0 +1,146 @@
1
+ # sidecar(最小服务,v0.2.1)
2
+
3
+ 只做四件事:`/health`、`/v1/search`、`/v1/pages`、`/v1/compute`。
4
+
5
+ 检索默认走 **FTS bigram + BGE-M3 + bge-reranker**;模型不可用时自动退回 FTS。
6
+
7
+ 浏览器教学台:**http://127.0.0.1:8765/ui**(引用卡、提示级别、页图回看、掌握度)。
8
+
9
+ ## Docker(配套服务)
10
+
11
+ ```bash
12
+ # 在仓库根目录
13
+ docker compose up --build
14
+ # 或
15
+ docker build -t socratic-sidecar:0.2.1 .
16
+ docker run -p 8765:8765 -v "$PWD/data:/data" -v "$PWD/samples/PDF:/books:ro" \
17
+ socratic-sidecar:0.2.1
18
+ ```
19
+
20
+ 镜像不带书、不带 BGE 权重;默认 `SOCRATIC_BGE=0`,需要 BGE 时挂载模型并设
21
+ `SOCRATIC_BGE=1`。`/data` 必须可写(SQLite journal、state.db、页图缓存)。
22
+
23
+ ## 运行
24
+
25
+ ```powershell
26
+ cd D:\Guo-Code\socratic-tutor\sidecar
27
+ python -m uvicorn app.main:app --host 127.0.0.1 --port 8765 --timeout-keep-alive 75
28
+ ```
29
+
30
+ 若要用 BGE/rerank,必须用带 torch 的 `.venv-bge`:
31
+
32
+ ```powershell
33
+ & 'D:\Guo-Code\socratic-tutor\.venv-bge\Scripts\python.exe' -m uvicorn app.main:app --host 127.0.0.1 --port 8765 --timeout-keep-alive 75
34
+ ```
35
+
36
+ `--timeout-keep-alive 75` 不是可有可无的:uvicorn 默认 5 秒就关闭空闲连接,而插件的内置教学台每 15 秒轮询一次(`plugin-socratic/client.js`),Keep-Alive 短于轮询间隔时,浏览器复用连接恰好撞上服务端关闭,会偶发 `net::ERR_EMPTY_RESPONSE`,面板上显示为 `sidecar: Failed to fetch`。给到 75 秒即可消除这类瞬断。
37
+
38
+ 可选环境变量:
39
+
40
+ | 变量 | 默认 | 说明 |
41
+ |---|---|---|
42
+ | `SOCRATIC_DB` | `eval/p1/ingest/search.db` | chunks 索引 |
43
+ | `SOCRATIC_ROOT` | `D:\Guo-Code` | PDF 根 |
44
+ | `SOCRATIC_CACHE` | `sidecar/cache/pages` | 页图缓存 |
45
+ | `SOCRATIC_TOKEN` | 空 | 非空时要求 `X-Sidecar-Token` |
46
+ | `SOCRATIC_REQUIRE_AUTH` | `0` | `1` 时无 token 配置直接 503 |
47
+ | `SOCRATIC_CORS_ORIGIN_REGEX` | `(http://(127\.0\.0\.1\|localhost)(:\d+)?\|dsh-app://[^/]+)` | 允许调用 sidecar 的浏览器源。DSH 桌面应用用自定义协议 `dsh-app://` 渲染界面,内置教学台就是从该源发请求的;不含此项会被浏览器判 `Failed to fetch` |
48
+ | `SOCRATIC_PRELOAD` | `0` | `1` 时启动后后台加载 BGE/reranker |
49
+ | `SOCRATIC_BGE` | `1` | `0` 时强制 FTS |
50
+ | `SOCRATIC_RERANK_TOPK` | `50` | 送入 reranker 的候选数 |
51
+ | `SOCRATIC_BGE_MODEL` | `models/bge-m3` | 嵌入模型 |
52
+ | `SOCRATIC_RERANK_MODEL` | `models/bge-reranker-v2-m3` | 重排模型 |
53
+ | `SOCRATIC_IMAGE_ONLY_LANGS` | `greek,grc` | 只回页图、不回文本的语言(见 §页图策略) |
54
+
55
+ ## 章回索引 / 页图浏览(P3-2)
56
+
57
+ 竖排扫描件没有文本层,索引从**版心**(页边书眉)的 OCR 里建:裁右侧竖条 → 取最上方短「卷」行 → 连续 ≥5 页才算一章。C1《史记》358 页得出 7 卷 + 卷首/卷末,覆盖 358/358 页。
58
+
59
+ - 建索引:`vertical_title_ocr.py` 扫整本右栏(卷眉 + 篇名)→ `build_index.py` 一次得到卷与篇(也支持 `--headers` 用单独的卷眉 pass);结果写 `toc` 表,`level=1` 卷、`level=2` 篇;
60
+ - 浏览:`/browse`,章回列表 + ←/→ 翻页 + 150/200 dpi;
61
+ - 详见 `docs/P3-2-vertical-index.md`。
62
+
63
+ ## 页图策略(K5)
64
+
65
+ 希腊文命中**不返回文本**:`text` 置空,带 `image_only: true` 与 `citation.page_image`;`/v1/chunks/{id}` 同样处理,`citations` 表的 `snippet` 写空串。检索本身仍用存储文本(FTS/BGE/rerank),所以召回不受影响。
66
+
67
+ 原因:本地 OCR 在 K5 上 CER 70.9–94.0%,且文本层是"希腊文 + 英文注释"混合,直接引用会造出页图不支持的引文。策略在 `app/policy.py`,可用 `SOCRATIC_IMAGE_ONLY_LANGS` 覆盖或清空回退。详见 `docs/P1-3c-K5-pageimage.md`。
68
+
69
+ ## 检索性能(4060 8 GB)
70
+
71
+ | 项 | 实测 |
72
+ |---|---:|
73
+ | 首次查询(加载模型) | ~8.6 s |
74
+ | 预热后 p50 | ~700 ms |
75
+ | 预热后 p95 | ~830 ms |
76
+ | **缓存命中** | **~10 ms** |
77
+ | 100 问句 page recall@10 | **0.80–0.82**(选择性翻译;默认关闭) |
78
+ | 中文 / 拉丁 / 希腊 / 英文 | 93% / 70% / 42–58% / 70% |
79
+
80
+ 缓存:`/v1/search` 按 `(query,view,limit,source,lang,BGE)` 缓存,TTL 300 s、LRU 256;命中仍会写 `citations`。管理端点 `/v1/cache`、`POST /v1/cache/clear`,健康检查含 `cache` 统计。
81
+
82
+ 说明:0.80–0.82 需要 `SOCRATIC_V1_RETRIEVAL=1` + LLM key;默认路径仍约 0.76。
83
+ v2 公开语料 130 人工题的 R@5 为 0.977(见 `eval/public/RESULTS-project.md`)。
84
+
85
+ ## 端点
86
+
87
+ | 方法 | 路径 | 参数 |
88
+ |---|---|---|
89
+ | GET | `/health` | — |
90
+ | GET | `/v1/search` | `q`, `view=student\|tutor`, `limit`, `source?`, `lang?`, `book?`, `chapter?` |
91
+ | GET | `/v1/chunks/{id}` | `view` |
92
+ | POST | `/v1/review` | `{session_id, state?, answers?, record?}` → 复盘报告(P3) |
93
+ | GET | `/v1/books` | 有章回索引的书 |
94
+ | GET | `/v1/toc` | `source`, `book` → 章回索引 + 总页数(P3-2) |
95
+ | GET | `/v1/chapter` | `book`, `q` 或 `page` → 章回 + 页码范围 + 页图(P3-6) |
96
+ | GET | `/browse` | 页图浏览页(章回列表 + 翻页) |
97
+ | GET | `/v1/pages` | `source`, `book`, `page`, `dpi`, `bbox?` |
98
+ | POST | `/v1/compute` | `{expression, operation, variable, point}` |
99
+ | POST | `/v1/state/init` | `{session_id, goal, concept, lang}` |
100
+ | POST | `/v1/state/step` | `{session_id, event, result?}` |
101
+ | GET | `/v1/state/{id}` | 状态 + 摘要 |
102
+ | GET | `/v1/state/{id}/events` | 事件日志 |
103
+ | POST | `/v1/state/{id}/replay` | 从事件重建状态 |
104
+ | POST | `/v1/classify` | `{text}` → 提问类型/是否多问 |
105
+ | POST | `/v1/evaluate` | `{question, answer, rubric?, expected?, use_llm}` |
106
+ | POST | `/v1/critic` | `{text, hint_level, has_citation}` |
107
+ | POST | `/v1/critic/rewrite` | `{text}` → 只保留第一个问句 |
108
+ | POST | `/v1/critic/citation` | `{text, mode}` → soften/mark/off |
109
+ | GET | `/v1/evaluations/{session_id}` | 判定历史 |
110
+ | GET | `/v1/citations/{session_id}` | 最近引用;`?turn=N` 按回合 |
111
+ | GET | `/v1/cache` | 命中/miss/容量/TTL |
112
+ | POST | `/v1/cache/clear` | 清空查询缓存 |
113
+ | GET | `/v1/mastery/{concept}` | BKT 掌握度 |
114
+ | GET | `/v1/mastery` | 全部概念 |
115
+ | POST | `/v1/cards` | 添加 FSRS 卡 |
116
+ | POST | `/v1/cards/{id}/review` | `{rating: again\|hard\|good\|easy}` |
117
+ | GET | `/v1/cards/due` | 到期卡 |
118
+
119
+ `view=answer_key` **不接受**;`search` 在 SQL 层过滤 `visibility`。
120
+
121
+ ## 示例
122
+
123
+ ```bash
124
+ curl "http://127.0.0.1:8765/health"
125
+ curl "http://127.0.0.1:8765/v1/search?q=%E5%BE%AE%E5%88%86&view=student&limit=3"
126
+ curl -X POST http://127.0.0.1:8765/v1/compute \
127
+ -H "Content-Type: application/json" \
128
+ -d '{"expression":"x^2","operation":"diff"}'
129
+ ```
130
+
131
+ ## 冒烟
132
+
133
+ ```powershell
134
+ # 终端 1
135
+ python -m uvicorn app.main:app --port 8765 --timeout-keep-alive 75
136
+ # 终端 2
137
+ python tests/smoke.py
138
+ ```
139
+
140
+ ## 边界
141
+
142
+ - 计算只接受 SymPy 表达式与白名单操作,**不执行任意 Python**;
143
+ - 页图 `book` 路径做根目录校验,防路径穿越;
144
+ - 无鉴权时只绑 `127.0.0.1`;暴露端口必须设 `SOCRATIC_TOKEN`;
145
+ - CORS 只允许 `http://127.0.0.1:*` / `http://localhost:*`(供 DSH 内嵌 UI 调用)。
146
+ - 未接 BGE/reranker;`tier` 暂为 `unknown`。
File without changes
@@ -0,0 +1,115 @@
1
+ """Command-line entry point for the socratic sidecar.
2
+
3
+ python -m app --port 8765
4
+ socratic-sidecar --data /srv/socratic --port 8765
5
+
6
+ `app.config` reads every setting from the environment *at import time*, so this
7
+ module translates the flags into SOCRATIC_* variables before it imports app or
8
+ uvicorn. That also makes the two invocation styles above exactly equivalent:
9
+ with no arguments, `python -m app` is the same as the console script.
10
+
11
+ The flags mirror the environment variables; explicit flags win over an
12
+ already-exported SOCRATIC_* value because they are applied afterwards.
13
+ """
14
+ import argparse
15
+ import os
16
+ import sys
17
+
18
+ DEFAULT_HOST = "127.0.0.1"
19
+ DEFAULT_PORT = 8765
20
+
21
+ #: flag -> environment variable, for the plain string-valued options. Paths are
22
+ #: made absolute so the service keeps resolving them if a later component
23
+ #: changes the working directory.
24
+ _ENV_FLAGS = {
25
+ "data": "SOCRATIC_DATA",
26
+ "db": "SOCRATIC_DB",
27
+ "lexicon_db": "SOCRATIC_LEXICON_DB",
28
+ "root": "SOCRATIC_ROOT",
29
+ "curriculum": "SOCRATIC_CURRICULUM",
30
+ "cache": "SOCRATIC_CACHE",
31
+ "state_db": "SOCRATIC_STATE_DB",
32
+ }
33
+ _PATH_FLAGS = set(_ENV_FLAGS)
34
+
35
+
36
+ def build_parser():
37
+ parser = argparse.ArgumentParser(
38
+ prog="socratic-sidecar",
39
+ description="Minimal Socratic tutor sidecar: search, pages, compute.",
40
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
41
+ epilog=(
42
+ "Every option maps to a SOCRATIC_* environment variable and is "
43
+ "applied before the application is imported, so e.g. "
44
+ "`--data DIR` is the same as exporting SOCRATIC_DATA=DIR. "
45
+ "With no arguments this is equivalent to `python -m app`."
46
+ ),
47
+ )
48
+ parser.add_argument("--host", default=DEFAULT_HOST,
49
+ help="interface to bind")
50
+ parser.add_argument("--port", type=int, default=DEFAULT_PORT,
51
+ help="TCP port to listen on")
52
+ parser.add_argument("--data", metavar="DIR",
53
+ help="derived data root (indexes, vectors, caches)")
54
+ parser.add_argument("--db", metavar="FILE",
55
+ help="RAG database holding the chunks index")
56
+ parser.add_argument("--lexicon-db", metavar="FILE",
57
+ help="dictionary / grammar database")
58
+ parser.add_argument("--root", metavar="DIR",
59
+ help="directory containing the book library")
60
+ parser.add_argument("--curriculum", metavar="DIR",
61
+ help="directory of curriculum lesson packs")
62
+ parser.add_argument("--cache", metavar="DIR",
63
+ help="page-image cache directory")
64
+ parser.add_argument("--state-db", metavar="FILE",
65
+ help="SQLite file for learner state and the chapter index")
66
+ parser.add_argument("--token", metavar="TOKEN",
67
+ help="shared token required by /v1/* (empty means no auth)")
68
+ parser.add_argument("--bge", action=argparse.BooleanOptionalAction,
69
+ default=None,
70
+ help="enable/disable BGE embeddings; default follows SOCRATIC_BGE")
71
+ parser.add_argument("--version", action="version",
72
+ version="%(prog)s " + _version())
73
+ return parser
74
+
75
+
76
+ def _version():
77
+ try:
78
+ from importlib.metadata import version
79
+ return version("socratic-sidecar")
80
+ except Exception:
81
+ try:
82
+ from . import config
83
+ return config.VERSION
84
+ except Exception:
85
+ return "unknown"
86
+
87
+
88
+ def configure_environment(args):
89
+ """Apply parsed flags to the process environment (before importing app)."""
90
+ for flag, env_name in _ENV_FLAGS.items():
91
+ value = getattr(args, flag)
92
+ if value:
93
+ if flag in _PATH_FLAGS:
94
+ value = os.path.abspath(os.path.expanduser(value))
95
+ os.environ[env_name] = value
96
+ if args.token is not None:
97
+ os.environ["SOCRATIC_TOKEN"] = args.token
98
+ if args.bge is not None:
99
+ os.environ["SOCRATIC_BGE"] = "1" if args.bge else "0"
100
+
101
+
102
+ def main(argv=None):
103
+ args = build_parser().parse_args(argv)
104
+ configure_environment(args)
105
+
106
+ # Import only after the environment is final: config.py snapshots it.
107
+ import uvicorn
108
+
109
+ uvicorn.run("app.main:app", host=args.host, port=args.port,
110
+ timeout_keep_alive=75)
111
+ return 0
112
+
113
+
114
+ if __name__ == "__main__":
115
+ sys.exit(main())
@@ -0,0 +1,39 @@
1
+ """Adapter registry.
2
+
3
+ Adapters are constructed from a source id plus keyword arguments; the registry
4
+ keeps the CLI and the ingest tests from hard-coding classes. Add a new corpus by
5
+ implementing ``fetch()`` and registering it here — the schema does not change.
6
+ """
7
+ from .base import Document, FetchError, Section, SourceSpec
8
+ from .cts import CtsAdapter, passage, work_urn
9
+ from .wikisource import MediaWikiClient, WikisourceAdapter, extract_sections
10
+
11
+ __all__ = [
12
+ "Document", "FetchError", "Section", "SourceSpec",
13
+ "CtsAdapter", "MediaWikiClient", "WikisourceAdapter",
14
+ "extract_sections", "passage", "work_urn",
15
+ "get", "register", "names",
16
+ ]
17
+
18
+ _REGISTRY = {
19
+ "wikisource": WikisourceAdapter,
20
+ "mediawiki": WikisourceAdapter,
21
+ "perseus": CtsAdapter,
22
+ "cts": CtsAdapter,
23
+ }
24
+
25
+
26
+ def register(name, cls):
27
+ _REGISTRY[name] = cls
28
+
29
+
30
+ def names():
31
+ return sorted(_REGISTRY)
32
+
33
+
34
+ def get(name, **kwargs):
35
+ try:
36
+ cls = _REGISTRY[name.lower()]
37
+ except KeyError:
38
+ raise KeyError("unknown adapter %r (known: %s)" % (name, ", ".join(names())))
39
+ return cls(**kwargs)
@@ -0,0 +1,50 @@
1
+ """Shared shapes for public-corpus adapters.
2
+
3
+ An adapter turns one external reference (a Wikisource title, a CTS URN, …) into
4
+ a :class:`Document` whose sections already carry a typed locator. Nothing in
5
+ this package writes to the database; ingestion is a separate step so fetching
6
+ and storing can be retried independently.
7
+ """
8
+ from dataclasses import dataclass, field
9
+
10
+
11
+ class FetchError(RuntimeError):
12
+ """The source refused, or returned something the adapter cannot parse."""
13
+
14
+
15
+ @dataclass
16
+ class Section:
17
+ title: str
18
+ text: str
19
+ locator: dict
20
+ ordinal: int = 0
21
+ quality: str | None = None
22
+
23
+
24
+ @dataclass
25
+ class Document:
26
+ document_id: str
27
+ source_id: str
28
+ title: str
29
+ sections: list[Section]
30
+ lang: str = "zh"
31
+ author: str | None = None
32
+ edition: str | None = None
33
+ script: str | None = None
34
+ license: str = "unknown"
35
+ provenance: str = ""
36
+ canonical_url: str = ""
37
+ metadata: dict = field(default_factory=dict)
38
+ source_version: str = ""
39
+
40
+
41
+ @dataclass
42
+ class SourceSpec:
43
+ source_id: str
44
+ adapter: str
45
+ base_url: str
46
+ license: str = "unknown"
47
+ redistribution: str = "unknown"
48
+ rate_limit: float | None = 1.0
49
+ auth_env: str | None = None
50
+ config: dict = field(default_factory=dict)