slide-anki-mcp 0.2.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.
- slide_anki_mcp-0.2.0/.github/workflows/test.yml +25 -0
- slide_anki_mcp-0.2.0/.gitignore +6 -0
- slide_anki_mcp-0.2.0/CONTRIBUTING.md +35 -0
- slide_anki_mcp-0.2.0/LICENSE +21 -0
- slide_anki_mcp-0.2.0/PKG-INFO +144 -0
- slide_anki_mcp-0.2.0/README.md +126 -0
- slide_anki_mcp-0.2.0/docs/issues.md +66 -0
- slide_anki_mcp-0.2.0/pyproject.toml +25 -0
- slide_anki_mcp-0.2.0/src/slide_anki_mcp/__init__.py +1 -0
- slide_anki_mcp-0.2.0/src/slide_anki_mcp/core.py +161 -0
- slide_anki_mcp-0.2.0/src/slide_anki_mcp/server.py +78 -0
- slide_anki_mcp-0.2.0/tests/e2e_stdio.py +54 -0
- slide_anki_mcp-0.2.0/tests/test_core.py +267 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
name: test
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
pull_request:
|
|
6
|
+
|
|
7
|
+
jobs:
|
|
8
|
+
test:
|
|
9
|
+
strategy:
|
|
10
|
+
fail-fast: false
|
|
11
|
+
matrix:
|
|
12
|
+
os: [ubuntu-latest, windows-latest]
|
|
13
|
+
python: ["3.10", "3.12"]
|
|
14
|
+
runs-on: ${{ matrix.os }}
|
|
15
|
+
steps:
|
|
16
|
+
- uses: actions/checkout@v4
|
|
17
|
+
- uses: actions/setup-python@v5
|
|
18
|
+
with:
|
|
19
|
+
python-version: ${{ matrix.python }}
|
|
20
|
+
# The Arabic test needs a font with Arabic letters; Windows has Arial.
|
|
21
|
+
- if: runner.os == 'Linux'
|
|
22
|
+
run: sudo apt-get update && sudo apt-get install -y fonts-dejavu-core
|
|
23
|
+
- run: pip install ".[test]"
|
|
24
|
+
- run: pytest -q -rs
|
|
25
|
+
- run: python tests/e2e_stdio.py
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Contributing
|
|
2
|
+
|
|
3
|
+
Thank you for helping. This is a small project and I want to keep it small: it reads slide text, checks cards against it, and writes an Anki file. Changes that keep it simple are the easiest to accept.
|
|
4
|
+
|
|
5
|
+
## Run the tests
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install -e ".[test]"
|
|
9
|
+
pytest
|
|
10
|
+
python tests/e2e_stdio.py
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
`pytest` runs the unit tests in `tests/test_core.py`. The test PDFs are made by the tests with `reportlab`, so you do not need any lecture files. The Arabic test needs a font with Arabic letters (Arial or Tahoma on Windows, DejaVu Sans on Linux). If none is found, it is skipped.
|
|
14
|
+
|
|
15
|
+
`tests/e2e_stdio.py` starts the server the way Claude does (over stdio) and calls `export_anki` three times: with a good card, with a bad card (nothing may be written), and with a path that already exists (it must be refused).
|
|
16
|
+
|
|
17
|
+
GitHub Actions runs both on Python 3.10 and 3.12, on Ubuntu and Windows.
|
|
18
|
+
|
|
19
|
+
## Where things are
|
|
20
|
+
|
|
21
|
+
- `src/slide_anki_mcp/core.py`: reading the PDF, checking a card, writing the `.tsv`. No MCP code here.
|
|
22
|
+
- `src/slide_anki_mcp/server.py`: the four MCP tools. Each one is a thin wrapper around `core.py`.
|
|
23
|
+
|
|
24
|
+
## Adding a check
|
|
25
|
+
|
|
26
|
+
1. Write a test in `tests/test_core.py` that builds a small PDF with `make_pdf`, makes a card that should fail (or pass), and asserts the result of `core.check_card`.
|
|
27
|
+
2. Run `pytest` and see the new test fail.
|
|
28
|
+
3. Change `check_card` in `core.py`. A failing card should set `ok` to `False` and add a short, readable reason or the failing text to `unsupported`.
|
|
29
|
+
4. Run all the tests again. Existing tests should keep passing unless the change is on purpose; if so, say why in the pull request.
|
|
30
|
+
|
|
31
|
+
## Please keep in mind
|
|
32
|
+
|
|
33
|
+
- Do not add real lecture PDFs to the repository. They belong to the lecturer.
|
|
34
|
+
- Add a new dependency only if the change really needs it.
|
|
35
|
+
- Keep the README honest: only describe what the code does and what you have tested.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 slide-anki-mcp contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: slide-anki-mcp
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: MCP server that turns lecture PDFs into Anki cards, rejecting any answer the cited slide does not support.
|
|
5
|
+
Project-URL: Homepage, https://github.com/2Mesh/slide-anki-mcp
|
|
6
|
+
Project-URL: Issues, https://github.com/2Mesh/slide-anki-mcp/issues
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Requires-Dist: mcp<2,>=1.2
|
|
11
|
+
Requires-Dist: pypdf>=4
|
|
12
|
+
Provides-Extra: test
|
|
13
|
+
Requires-Dist: arabic-reshaper; extra == 'test'
|
|
14
|
+
Requires-Dist: pytest; extra == 'test'
|
|
15
|
+
Requires-Dist: python-bidi; extra == 'test'
|
|
16
|
+
Requires-Dist: reportlab; extra == 'test'
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# slide-anki-mcp
|
|
20
|
+
|
|
21
|
+
[](https://github.com/2Mesh/slide-anki-mcp/actions/workflows/test.yml)
|
|
22
|
+
|
|
23
|
+
An MCP server for students who study from lecture slides. It makes Claude (or any MCP client) quote the slide for every Anki card, and it rejects a card when the quote is not really on that slide.
|
|
24
|
+
|
|
25
|
+
Study tools often write cards from the model's own knowledge. If your exam is graded against your lecturer's slides, that is a risk. Here every card carries a quote from the slide, the server checks the quote letter by letter, and the quote is written into the card so you can read it next to the answer.
|
|
26
|
+
|
|
27
|
+
**What it proves:** the quote is on the slide, and the answer is inside the quote.
|
|
28
|
+
**What it does not prove:** that the card is correct. You still need to read your cards.
|
|
29
|
+
|
|
30
|
+
## Quick start
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install git+https://github.com/2Mesh/slide-anki-mcp
|
|
34
|
+
claude mcp add slide-anki -- slide-anki-mcp
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Then ask Claude: "Read C:\lectures\renal.pdf with slide-anki. Make cards from slides 3 to 10, quote each slide in the evidence field, and export to C:\lectures\renal.tsv." Give the full path to the PDF. Import the `.tsv` in Anki with File → Import.
|
|
38
|
+
|
|
39
|
+
Needs Python 3.10 or newer. It is not on PyPI yet, so install from GitHub as above.
|
|
40
|
+
|
|
41
|
+
## Tools
|
|
42
|
+
|
|
43
|
+
| Tool | What it does |
|
|
44
|
+
|---|---|
|
|
45
|
+
| `list_slides(pdf_path)` | Slide numbers with first line and length. Warns about slides with little or no text |
|
|
46
|
+
| `get_slide(pdf_path, slide)` | Exact text of one slide, to copy quotes from |
|
|
47
|
+
| `check_cards(pdf_path, cards)` | Checks each card. A failing card comes back with the slide text so the quote can be fixed |
|
|
48
|
+
| `export_anki(pdf_path, cards, out_path)` | Writes a new `.tsv` only if every card passes. Each card is tagged `Slide_N`. Exact duplicates are written once |
|
|
49
|
+
|
|
50
|
+
A card is:
|
|
51
|
+
|
|
52
|
+
```json
|
|
53
|
+
{"front": "Where is ADH produced?", "back": "the hypothalamus",
|
|
54
|
+
"evidence": "ADH is produced in the hypothalamus", "slide": 1}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
A card passes only if all of these are true:
|
|
58
|
+
|
|
59
|
+
1. The slide has text. A slide with none is rejected with "slide has no text, cannot verify".
|
|
60
|
+
2. `evidence` is at least 4 words and is on the cited slide exactly as quoted. Case, extra spaces, a word split by a hyphen at a line break, and dash or quote style are ignored. Everything else must match, including `<`, `>`, `+`, `-` and numbers. Superscripts are kept: `10⁵` is not `105`.
|
|
61
|
+
3. `back` is inside `evidence`, and is not cut from a longer token: `1500 ml` is not found in `1000-1500 ml`, and `70 mV` is not found in `-70 mV`.
|
|
62
|
+
|
|
63
|
+
`export_anki` also refuses an `out_path` that does not end with `.tsv`, that already exists, or whose folder does not exist. It never overwrites a file.
|
|
64
|
+
|
|
65
|
+
## Example
|
|
66
|
+
|
|
67
|
+
Made with a small two-slide test PDF. Slide 1 says "ADH is produced in the hypothalamus", slide 2 says "Normal plasma sodium is 135-145 mmol/L". `check_cards` with one wrong card and one right card:
|
|
68
|
+
|
|
69
|
+
```json
|
|
70
|
+
[
|
|
71
|
+
{"slide": 1, "ok": false, "unsupported": ["evidence is not on this slide exactly as quoted"]},
|
|
72
|
+
{"slide": 2, "ok": true, "unsupported": []}
|
|
73
|
+
]
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
(The failing card also comes back with `slide_text`, left out here.) After fixing the first card and sending the sodium card twice by mistake, `export_anki` returns:
|
|
77
|
+
|
|
78
|
+
```json
|
|
79
|
+
{"written": "/path/to/cards.tsv", "count": 2, "duplicates_skipped": [2]}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
and the file contains:
|
|
83
|
+
|
|
84
|
+
```
|
|
85
|
+
#separator:tab
|
|
86
|
+
#html:false
|
|
87
|
+
#tags column:3
|
|
88
|
+
"Where is ADH produced?" "the hypothalamus | Source (slide 1): ADH is produced in the hypothalamus" "slides Slide_1"
|
|
89
|
+
"Normal plasma sodium?" "135-145 mmol/L | Source (slide 2): Normal plasma sodium is 135-145 mmol/L" "slides Slide_2"
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
The header lines are read by Anki 2.1.54 and newer. Older versions need the field separator set to Tab by hand. Every field is quoted so a front that starts with `#` is not read as a header line. I have not tried the import in Anki yet.
|
|
93
|
+
|
|
94
|
+
## Install for Claude Desktop
|
|
95
|
+
|
|
96
|
+
Open `claude_desktop_config.json` (Windows: `%APPDATA%\Claude\claude_desktop_config.json`, macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`), add the server, then restart Claude Desktop:
|
|
97
|
+
|
|
98
|
+
```json
|
|
99
|
+
{
|
|
100
|
+
"mcpServers": {
|
|
101
|
+
"slide-anki": {
|
|
102
|
+
"command": "slide-anki-mcp"
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
If Claude cannot find the command, put its full path in `"command"`. Get the path with `where slide-anki-mcp` on Windows or `which slide-anki-mcp` on macOS and Linux. If you installed inside a virtual environment, you need that full path for Claude Code as well.
|
|
109
|
+
|
|
110
|
+
## What it cannot catch
|
|
111
|
+
|
|
112
|
+
- **Meaning.** It checks that words are on the slide, not what they mean. If the slide says "Mitral valve does not have three cusps", a card with the back "three cusps" and that full sentence as evidence passes. The "does not" is in the exported card, so you can see it, but the server does not detect it.
|
|
113
|
+
- **The front.** The question is never checked. A true sentence under the wrong question passes.
|
|
114
|
+
- **Units that differ only in case.** Case is ignored, so `mM` and `mm`, or `Mg` and `mg`, count as the same.
|
|
115
|
+
- **Quotes that start right after a dash or sign.** If a slide line reads `Beverages -1000-1500 ml`, the quote has to include the dash. A quote that cuts a number, unit or range in the middle (`135` from `135-145 mmol/L`, `140 mmol` from `140 mmol/L`) is rejected.
|
|
116
|
+
- **Paraphrases.** A correct answer in other words is rejected. Copy the slide's wording. Small differences such as "200mL" on the slide and "200 mL" in the card are also rejected.
|
|
117
|
+
- **Images.** Text inside pictures, scanned pages and diagrams is not read, and cards that cite those slides are rejected. On one real 40-slide lecture, 4 slides had no text at all and 7 more had under 40 characters, mostly section titles.
|
|
118
|
+
- **Bad text extraction.** If the PDF stores text in an odd way, the extracted words can be split or out of order, and correct cards will fail.
|
|
119
|
+
|
|
120
|
+
For the numbers: an earlier version of this tool matched the answer against the slide with symbols removed. On a real 40-slide lecture it accepted 8 of 30 cards that were made wrong on purpose, for example a changed number or a dropped "No". This version keeps symbols and requires a quote. On a new set of 30 correct and 29 wrong cards from the same lecture (written by a reviewer, so a small and friendly sample), it accepted 26 of the 30 correct cards and 0 of the 29 wrong ones. The 4 rejected correct cards were quotes shorter than 4 words, a quote with `and` where the slide has `&`, and a quote that left out a leading dash. The wrong cards did not include a dropped "not", because that lecture has no usable place for one, so that case is untested on real slides.
|
|
121
|
+
|
|
122
|
+
### Arabic
|
|
123
|
+
|
|
124
|
+
Arabic works on a generated test PDF (Arial or DejaVu font, letters shaped and stored in right-to-left display order with `arabic-reshaper` and `python-bidi`): exact Arabic quotes pass, wrong ones fail, and short vowel marks are ignored. It is not tested on a real Arabic lecture. If a PDF stores Arabic in another order, the extracted text comes out reversed and Arabic cards will not match.
|
|
125
|
+
|
|
126
|
+
## Roadmap
|
|
127
|
+
|
|
128
|
+
These are real gaps, not promises:
|
|
129
|
+
|
|
130
|
+
- **OCR for image slides**, so text in pictures and scanned decks can be checked.
|
|
131
|
+
- **Meaning-aware checking**, so a correct paraphrase can pass and a phrase taken out of context can be caught.
|
|
132
|
+
- **Testing on real Arabic lectures and a real Anki import.**
|
|
133
|
+
|
|
134
|
+
## Develop
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
pip install -e ".[test]"
|
|
138
|
+
pytest
|
|
139
|
+
python tests/e2e_stdio.py
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
143
|
+
|
|
144
|
+
MIT licensed.
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# slide-anki-mcp
|
|
2
|
+
|
|
3
|
+
[](https://github.com/2Mesh/slide-anki-mcp/actions/workflows/test.yml)
|
|
4
|
+
|
|
5
|
+
An MCP server for students who study from lecture slides. It makes Claude (or any MCP client) quote the slide for every Anki card, and it rejects a card when the quote is not really on that slide.
|
|
6
|
+
|
|
7
|
+
Study tools often write cards from the model's own knowledge. If your exam is graded against your lecturer's slides, that is a risk. Here every card carries a quote from the slide, the server checks the quote letter by letter, and the quote is written into the card so you can read it next to the answer.
|
|
8
|
+
|
|
9
|
+
**What it proves:** the quote is on the slide, and the answer is inside the quote.
|
|
10
|
+
**What it does not prove:** that the card is correct. You still need to read your cards.
|
|
11
|
+
|
|
12
|
+
## Quick start
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pip install git+https://github.com/2Mesh/slide-anki-mcp
|
|
16
|
+
claude mcp add slide-anki -- slide-anki-mcp
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Then ask Claude: "Read C:\lectures\renal.pdf with slide-anki. Make cards from slides 3 to 10, quote each slide in the evidence field, and export to C:\lectures\renal.tsv." Give the full path to the PDF. Import the `.tsv` in Anki with File → Import.
|
|
20
|
+
|
|
21
|
+
Needs Python 3.10 or newer. It is not on PyPI yet, so install from GitHub as above.
|
|
22
|
+
|
|
23
|
+
## Tools
|
|
24
|
+
|
|
25
|
+
| Tool | What it does |
|
|
26
|
+
|---|---|
|
|
27
|
+
| `list_slides(pdf_path)` | Slide numbers with first line and length. Warns about slides with little or no text |
|
|
28
|
+
| `get_slide(pdf_path, slide)` | Exact text of one slide, to copy quotes from |
|
|
29
|
+
| `check_cards(pdf_path, cards)` | Checks each card. A failing card comes back with the slide text so the quote can be fixed |
|
|
30
|
+
| `export_anki(pdf_path, cards, out_path)` | Writes a new `.tsv` only if every card passes. Each card is tagged `Slide_N`. Exact duplicates are written once |
|
|
31
|
+
|
|
32
|
+
A card is:
|
|
33
|
+
|
|
34
|
+
```json
|
|
35
|
+
{"front": "Where is ADH produced?", "back": "the hypothalamus",
|
|
36
|
+
"evidence": "ADH is produced in the hypothalamus", "slide": 1}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
A card passes only if all of these are true:
|
|
40
|
+
|
|
41
|
+
1. The slide has text. A slide with none is rejected with "slide has no text, cannot verify".
|
|
42
|
+
2. `evidence` is at least 4 words and is on the cited slide exactly as quoted. Case, extra spaces, a word split by a hyphen at a line break, and dash or quote style are ignored. Everything else must match, including `<`, `>`, `+`, `-` and numbers. Superscripts are kept: `10⁵` is not `105`.
|
|
43
|
+
3. `back` is inside `evidence`, and is not cut from a longer token: `1500 ml` is not found in `1000-1500 ml`, and `70 mV` is not found in `-70 mV`.
|
|
44
|
+
|
|
45
|
+
`export_anki` also refuses an `out_path` that does not end with `.tsv`, that already exists, or whose folder does not exist. It never overwrites a file.
|
|
46
|
+
|
|
47
|
+
## Example
|
|
48
|
+
|
|
49
|
+
Made with a small two-slide test PDF. Slide 1 says "ADH is produced in the hypothalamus", slide 2 says "Normal plasma sodium is 135-145 mmol/L". `check_cards` with one wrong card and one right card:
|
|
50
|
+
|
|
51
|
+
```json
|
|
52
|
+
[
|
|
53
|
+
{"slide": 1, "ok": false, "unsupported": ["evidence is not on this slide exactly as quoted"]},
|
|
54
|
+
{"slide": 2, "ok": true, "unsupported": []}
|
|
55
|
+
]
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
(The failing card also comes back with `slide_text`, left out here.) After fixing the first card and sending the sodium card twice by mistake, `export_anki` returns:
|
|
59
|
+
|
|
60
|
+
```json
|
|
61
|
+
{"written": "/path/to/cards.tsv", "count": 2, "duplicates_skipped": [2]}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
and the file contains:
|
|
65
|
+
|
|
66
|
+
```
|
|
67
|
+
#separator:tab
|
|
68
|
+
#html:false
|
|
69
|
+
#tags column:3
|
|
70
|
+
"Where is ADH produced?" "the hypothalamus | Source (slide 1): ADH is produced in the hypothalamus" "slides Slide_1"
|
|
71
|
+
"Normal plasma sodium?" "135-145 mmol/L | Source (slide 2): Normal plasma sodium is 135-145 mmol/L" "slides Slide_2"
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
The header lines are read by Anki 2.1.54 and newer. Older versions need the field separator set to Tab by hand. Every field is quoted so a front that starts with `#` is not read as a header line. I have not tried the import in Anki yet.
|
|
75
|
+
|
|
76
|
+
## Install for Claude Desktop
|
|
77
|
+
|
|
78
|
+
Open `claude_desktop_config.json` (Windows: `%APPDATA%\Claude\claude_desktop_config.json`, macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`), add the server, then restart Claude Desktop:
|
|
79
|
+
|
|
80
|
+
```json
|
|
81
|
+
{
|
|
82
|
+
"mcpServers": {
|
|
83
|
+
"slide-anki": {
|
|
84
|
+
"command": "slide-anki-mcp"
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
If Claude cannot find the command, put its full path in `"command"`. Get the path with `where slide-anki-mcp` on Windows or `which slide-anki-mcp` on macOS and Linux. If you installed inside a virtual environment, you need that full path for Claude Code as well.
|
|
91
|
+
|
|
92
|
+
## What it cannot catch
|
|
93
|
+
|
|
94
|
+
- **Meaning.** It checks that words are on the slide, not what they mean. If the slide says "Mitral valve does not have three cusps", a card with the back "three cusps" and that full sentence as evidence passes. The "does not" is in the exported card, so you can see it, but the server does not detect it.
|
|
95
|
+
- **The front.** The question is never checked. A true sentence under the wrong question passes.
|
|
96
|
+
- **Units that differ only in case.** Case is ignored, so `mM` and `mm`, or `Mg` and `mg`, count as the same.
|
|
97
|
+
- **Quotes that start right after a dash or sign.** If a slide line reads `Beverages -1000-1500 ml`, the quote has to include the dash. A quote that cuts a number, unit or range in the middle (`135` from `135-145 mmol/L`, `140 mmol` from `140 mmol/L`) is rejected.
|
|
98
|
+
- **Paraphrases.** A correct answer in other words is rejected. Copy the slide's wording. Small differences such as "200mL" on the slide and "200 mL" in the card are also rejected.
|
|
99
|
+
- **Images.** Text inside pictures, scanned pages and diagrams is not read, and cards that cite those slides are rejected. On one real 40-slide lecture, 4 slides had no text at all and 7 more had under 40 characters, mostly section titles.
|
|
100
|
+
- **Bad text extraction.** If the PDF stores text in an odd way, the extracted words can be split or out of order, and correct cards will fail.
|
|
101
|
+
|
|
102
|
+
For the numbers: an earlier version of this tool matched the answer against the slide with symbols removed. On a real 40-slide lecture it accepted 8 of 30 cards that were made wrong on purpose, for example a changed number or a dropped "No". This version keeps symbols and requires a quote. On a new set of 30 correct and 29 wrong cards from the same lecture (written by a reviewer, so a small and friendly sample), it accepted 26 of the 30 correct cards and 0 of the 29 wrong ones. The 4 rejected correct cards were quotes shorter than 4 words, a quote with `and` where the slide has `&`, and a quote that left out a leading dash. The wrong cards did not include a dropped "not", because that lecture has no usable place for one, so that case is untested on real slides.
|
|
103
|
+
|
|
104
|
+
### Arabic
|
|
105
|
+
|
|
106
|
+
Arabic works on a generated test PDF (Arial or DejaVu font, letters shaped and stored in right-to-left display order with `arabic-reshaper` and `python-bidi`): exact Arabic quotes pass, wrong ones fail, and short vowel marks are ignored. It is not tested on a real Arabic lecture. If a PDF stores Arabic in another order, the extracted text comes out reversed and Arabic cards will not match.
|
|
107
|
+
|
|
108
|
+
## Roadmap
|
|
109
|
+
|
|
110
|
+
These are real gaps, not promises:
|
|
111
|
+
|
|
112
|
+
- **OCR for image slides**, so text in pictures and scanned decks can be checked.
|
|
113
|
+
- **Meaning-aware checking**, so a correct paraphrase can pass and a phrase taken out of context can be caught.
|
|
114
|
+
- **Testing on real Arabic lectures and a real Anki import.**
|
|
115
|
+
|
|
116
|
+
## Develop
|
|
117
|
+
|
|
118
|
+
```bash
|
|
119
|
+
pip install -e ".[test]"
|
|
120
|
+
pytest
|
|
121
|
+
python tests/e2e_stdio.py
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
125
|
+
|
|
126
|
+
MIT licensed.
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# Issues to open
|
|
2
|
+
|
|
3
|
+
Three issue texts, ready to paste into GitHub. Not filed yet.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Read text from image slides (OCR)
|
|
8
|
+
|
|
9
|
+
**Problem**
|
|
10
|
+
|
|
11
|
+
Many lecture slides are pictures: diagrams, screenshots, scanned pages. `pypdf` only reads real text, so these slides come out empty. On one real 40-slide lecture, 4 slides had no text at all and 7 more had under 40 characters. `list_slides` warns about them, and cards that cite a slide with no text are rejected with "slide has no text, cannot verify".
|
|
12
|
+
|
|
13
|
+
**What would help**
|
|
14
|
+
|
|
15
|
+
An optional OCR step for slides with little or no text, so their words can be used in the check.
|
|
16
|
+
|
|
17
|
+
**Things to decide**
|
|
18
|
+
|
|
19
|
+
- Which OCR tool. It should run offline and install without too much trouble on Windows.
|
|
20
|
+
- OCR makes mistakes. A card should not fail only because OCR misread a letter, and it should not pass because of an OCR error either. The result could say which text came from OCR.
|
|
21
|
+
- It should stay optional, so the basic install stays small.
|
|
22
|
+
|
|
23
|
+
**Done when**
|
|
24
|
+
|
|
25
|
+
A test PDF with text drawn as an image gives that text through `get_slide`, and a card that quotes it passes `check_cards`.
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## 2. Accept correct paraphrases (meaning-aware matching)
|
|
30
|
+
|
|
31
|
+
**Problem**
|
|
32
|
+
|
|
33
|
+
The check needs the model to quote the slide: an `evidence` quote must be on the slide exactly (symbols and numbers kept) and the answer must be inside it. A correct answer in different words is rejected, so the model has to copy the slide's wording. The check also cannot see meaning: if the slide says "Furosemide does not cause hyperkalemia", the back "cause hyperkalemia" with that full sentence as evidence passes, and only a person reading the exported evidence can see the "does not".
|
|
34
|
+
|
|
35
|
+
**What would help**
|
|
36
|
+
|
|
37
|
+
A way to accept answers that mean the same as the slide, and to catch answers that take slide words out of context.
|
|
38
|
+
|
|
39
|
+
**Things to decide**
|
|
40
|
+
|
|
41
|
+
- How to do it without letting invented facts back in, which is the reason this project exists. Any looser match should still show which slide text supports the answer.
|
|
42
|
+
- Whether this needs a model, and if so, whether it can run locally.
|
|
43
|
+
- Keep the strict check as the default, with the looser one as an option.
|
|
44
|
+
|
|
45
|
+
**Done when**
|
|
46
|
+
|
|
47
|
+
There are tests for: a correct paraphrase that passes, a wrong answer with similar words that fails, and the furosemide example above that fails.
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
## 3. Test with real Arabic slides
|
|
52
|
+
|
|
53
|
+
**Problem**
|
|
54
|
+
|
|
55
|
+
Arabic matching works on a test PDF made with `reportlab`, `arabic-reshaper` and `python-bidi`. It has not been tried on a real Arabic lecture exported from PowerPoint, Word or Google Slides. Those programs may store Arabic text differently. If the text comes out in reversed order, correct Arabic cards will fail.
|
|
56
|
+
|
|
57
|
+
**What would help**
|
|
58
|
+
|
|
59
|
+
- Try a few real Arabic or mixed Arabic/English lecture PDFs and note whether `get_slide` returns the Arabic in the right order.
|
|
60
|
+
- If some programs give reversed text, find a way to detect and fix it, with a test.
|
|
61
|
+
|
|
62
|
+
**Please do not** attach lecture PDFs you do not have the right to share. A small PDF you made yourself, exported from the same program, is enough.
|
|
63
|
+
|
|
64
|
+
**Done when**
|
|
65
|
+
|
|
66
|
+
The README says which PDF sources were tested with Arabic, and there is a test for each case that needed a fix.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "slide-anki-mcp"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "MCP server that turns lecture PDFs into Anki cards, rejecting any answer the cited slide does not support."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = ["mcp>=1.2,<2", "pypdf>=4"]
|
|
13
|
+
|
|
14
|
+
[project.urls]
|
|
15
|
+
Homepage = "https://github.com/2Mesh/slide-anki-mcp"
|
|
16
|
+
Issues = "https://github.com/2Mesh/slide-anki-mcp/issues"
|
|
17
|
+
|
|
18
|
+
[project.optional-dependencies]
|
|
19
|
+
test = ["pytest", "reportlab", "arabic-reshaper", "python-bidi"]
|
|
20
|
+
|
|
21
|
+
[project.scripts]
|
|
22
|
+
slide-anki-mcp = "slide_anki_mcp.server:main"
|
|
23
|
+
|
|
24
|
+
[tool.hatch.build.targets.wheel]
|
|
25
|
+
packages = ["src/slide_anki_mcp"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.2.0"
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Pure logic: read slides from a PDF, check cards against them, write Anki TSV.
|
|
2
|
+
|
|
3
|
+
The check is an evidence check. Every card must carry ``evidence``: a quote
|
|
4
|
+
copied from the cited slide. The server confirms the quote is really on that
|
|
5
|
+
slide (symbols, signs and numbers kept exactly) and that the answer sits inside
|
|
6
|
+
the quote. It cannot tell whether the card means what the slide means: the
|
|
7
|
+
quote is written into the exported card so the student can read it.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import csv
|
|
13
|
+
import re
|
|
14
|
+
import unicodedata
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from pypdf import PdfReader
|
|
18
|
+
|
|
19
|
+
MIN_TEXT_CHARS = 40 # list_slides warns below this
|
|
20
|
+
MIN_WORD_CHARS = 5 # fewer word characters than this = "no text"
|
|
21
|
+
MIN_EVIDENCE_WORDS = 4
|
|
22
|
+
|
|
23
|
+
_SUPER = str.maketrans({
|
|
24
|
+
"⁰": "^0", "¹": "^1", "²": "^2", "³": "^3", "⁴": "^4", "⁵": "^5", "⁶": "^6",
|
|
25
|
+
"⁷": "^7", "⁸": "^8", "⁹": "^9", "⁺": "^+", "⁻": "^-",
|
|
26
|
+
"₀": "_0", "₁": "_1", "₂": "_2", "₃": "_3", "₄": "_4", "₅": "_5", "₆": "_6",
|
|
27
|
+
"₇": "_7", "₈": "_8", "₉": "_9",
|
|
28
|
+
"–": "-", "—": "-", "−": "-", "‘": "'", "’": "'", "“": '"', "”": '"',
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _text(s: str, join_hyphen: bool = True) -> str:
|
|
33
|
+
"""Make text comparable without losing symbols, signs or digits.
|
|
34
|
+
|
|
35
|
+
Only layout is ignored: case, runs of whitespace, a word split by a hyphen
|
|
36
|
+
at a line break, dash and quote styles. Superscripts become ^n so that
|
|
37
|
+
"10⁵" never turns into "105". NFKC turns Arabic presentation forms (which
|
|
38
|
+
PDFs may store) back into normal letters; Arabic short vowels are dropped.
|
|
39
|
+
"""
|
|
40
|
+
s = s.translate(_SUPER)
|
|
41
|
+
s = unicodedata.normalize("NFKC", s)
|
|
42
|
+
s = "".join(ch for ch in s if unicodedata.category(ch) not in ("Mn", "Cf"))
|
|
43
|
+
s = re.sub(r"(?<=[^\W\d_])-[ \t]*\r?\n[ \t]*(?=[^\W\d_])", "" if join_hyphen else "-", s)
|
|
44
|
+
return re.sub(r"\s+", " ", s).strip().casefold().strip(" .;:,")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _contains(haystack: str, needle: str) -> bool:
|
|
48
|
+
"""True if needle is in haystack as whole words, not cut from a longer token.
|
|
49
|
+
|
|
50
|
+
"1500 ml" is not found in "1000-1500 ml", and "70 mv" is not found in "-70 mv".
|
|
51
|
+
"""
|
|
52
|
+
if not needle:
|
|
53
|
+
return False
|
|
54
|
+
pattern = r"(?<![\w.+\-<>^])" + re.escape(needle) + r"(?![\w^+\-/%]|[.,]\d)"
|
|
55
|
+
return re.search(pattern, haystack) is not None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def read_slides(pdf_path: str) -> list[str]:
|
|
59
|
+
"""Return the text of each page (slide), index 0 = slide 1."""
|
|
60
|
+
try:
|
|
61
|
+
reader = PdfReader(pdf_path)
|
|
62
|
+
pages = list(reader.pages)
|
|
63
|
+
except FileNotFoundError:
|
|
64
|
+
raise ValueError(f"file not found: {pdf_path}") from None
|
|
65
|
+
except Exception as exc: # pypdf raises several error types for bad files
|
|
66
|
+
raise ValueError(f"cannot read {pdf_path} as a PDF: {exc}") from None
|
|
67
|
+
if not pages:
|
|
68
|
+
raise ValueError("PDF has no pages")
|
|
69
|
+
return [(page.extract_text() or "").replace("�", "-").strip() for page in pages]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _has_text(slide: str) -> bool:
|
|
73
|
+
return len(re.findall(r"\w", slide)) >= MIN_WORD_CHARS
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def slide_overview(slides: list[str]) -> list[dict]:
|
|
77
|
+
out = []
|
|
78
|
+
for i, text in enumerate(slides, start=1):
|
|
79
|
+
first = next((ln.strip() for ln in text.splitlines() if ln.strip()), "")
|
|
80
|
+
warning = None
|
|
81
|
+
if not _has_text(text):
|
|
82
|
+
warning = "slide has no text, cannot verify cards against it"
|
|
83
|
+
elif len(text) < MIN_TEXT_CHARS:
|
|
84
|
+
warning = "under 40 characters of text: may be an image or title slide"
|
|
85
|
+
out.append({"slide": i, "title": first[:80], "chars": len(text), "warning": warning})
|
|
86
|
+
return out
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _fail(result: dict, *problems: str) -> dict:
|
|
90
|
+
result["ok"] = False
|
|
91
|
+
result["unsupported"].extend(problems)
|
|
92
|
+
return result
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def check_card(card: dict, slides: list[str]) -> dict:
|
|
96
|
+
"""Check one card {front, back, slide, evidence}. Never raises on bad input.
|
|
97
|
+
|
|
98
|
+
Passes only if: the slide has text; the evidence is a quote of at least
|
|
99
|
+
4 words that is literally on the cited slide; and the back is inside the
|
|
100
|
+
evidence. Returns ``ok`` and ``unsupported`` (the reasons). When a card
|
|
101
|
+
fails, the slide text is returned too so the model can quote it correctly.
|
|
102
|
+
"""
|
|
103
|
+
result = {"slide": None, "ok": True, "unsupported": []}
|
|
104
|
+
if not isinstance(card, dict):
|
|
105
|
+
return _fail(result, "card must be an object with front, back, slide, evidence")
|
|
106
|
+
page = card.get("slide")
|
|
107
|
+
result["slide"] = page
|
|
108
|
+
if isinstance(page, bool) or not isinstance(page, int) or not 1 <= page <= len(slides):
|
|
109
|
+
return _fail(result, "slide number missing or out of range")
|
|
110
|
+
slide = slides[page - 1]
|
|
111
|
+
front, back, evidence = card.get("front"), card.get("back"), card.get("evidence")
|
|
112
|
+
for name, value in (("front", front), ("back", back), ("evidence", evidence)):
|
|
113
|
+
if not isinstance(value, str) or not _text(value):
|
|
114
|
+
_fail(result, f"{name} must be non-empty text")
|
|
115
|
+
if result["unsupported"]:
|
|
116
|
+
return result
|
|
117
|
+
if not _has_text(slide):
|
|
118
|
+
return _fail(result, "slide has no text, cannot verify")
|
|
119
|
+
slide_t, ev_t, back_t = _text(slide), _text(evidence), _text(back)
|
|
120
|
+
if len(ev_t.split()) < MIN_EVIDENCE_WORDS:
|
|
121
|
+
_fail(result, f"evidence too short: quote a full sentence or line (at least {MIN_EVIDENCE_WORDS} words)")
|
|
122
|
+
elif not (_contains(slide_t, ev_t) or _contains(_text(slide, join_hyphen=False), ev_t)):
|
|
123
|
+
_fail(result, "evidence is not on this slide exactly as quoted")
|
|
124
|
+
elif not _contains(ev_t, back_t):
|
|
125
|
+
_fail(result, "the back is not inside the evidence quote")
|
|
126
|
+
if not result["ok"]:
|
|
127
|
+
result["slide_text"] = slide[:3000]
|
|
128
|
+
return result
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def card_key(card: dict) -> tuple[str, str]:
|
|
132
|
+
return _text(card["front"]), _text(card["back"])
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def write_anki_tsv(cards: list[dict], out_path: str, deck_tag: str = "slides") -> str:
|
|
136
|
+
"""Write an Anki-importable tab-separated file: Front, Back, Tags.
|
|
137
|
+
|
|
138
|
+
The back ends with the slide number and the evidence quote, so the student
|
|
139
|
+
sees the source beside every answer. Every field is quoted, so a front that
|
|
140
|
+
starts with '#' is not read as a header line. The header lines tell Anki
|
|
141
|
+
2.1.54+ the separator, plain text and tags column. Refuses any path that is
|
|
142
|
+
not a new ``.tsv`` file in an existing folder.
|
|
143
|
+
"""
|
|
144
|
+
path = Path(out_path)
|
|
145
|
+
if path.suffix.lower() != ".tsv":
|
|
146
|
+
raise ValueError("out_path must end with .tsv")
|
|
147
|
+
if not path.parent.is_dir():
|
|
148
|
+
raise ValueError(f"folder does not exist: {path.parent}")
|
|
149
|
+
try:
|
|
150
|
+
fh = path.open("x", newline="", encoding="utf-8")
|
|
151
|
+
except FileExistsError:
|
|
152
|
+
raise ValueError(f"file already exists, choose a new name: {path}") from None
|
|
153
|
+
except OSError as exc: # for example a folder with that name, or no permission
|
|
154
|
+
raise ValueError(f"cannot create {path}: {exc.strerror or exc}") from None
|
|
155
|
+
with fh:
|
|
156
|
+
fh.write("#separator:tab\n#html:false\n#tags column:3\n")
|
|
157
|
+
writer = csv.writer(fh, delimiter="\t", lineterminator="\n", quoting=csv.QUOTE_ALL)
|
|
158
|
+
for card in cards:
|
|
159
|
+
back = f"{card['back']} | Source (slide {card['slide']}): {card['evidence']}"
|
|
160
|
+
writer.writerow([card["front"], back, f"{deck_tag} Slide_{card['slide']}"])
|
|
161
|
+
return str(path.resolve())
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""MCP server exposing slide reading, card checking and Anki export."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from mcp.server.fastmcp import FastMCP
|
|
6
|
+
|
|
7
|
+
from . import core
|
|
8
|
+
|
|
9
|
+
mcp = FastMCP("slide-anki")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@mcp.tool()
|
|
13
|
+
def list_slides(pdf_path: str) -> list[dict]:
|
|
14
|
+
"""List every slide in a lecture PDF (full path) with its first line and text length.
|
|
15
|
+
|
|
16
|
+
A slide with a 'warning' has little or no text. Cards cannot be checked against it.
|
|
17
|
+
"""
|
|
18
|
+
return core.slide_overview(core.read_slides(pdf_path))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@mcp.tool()
|
|
22
|
+
def get_slide(pdf_path: str, slide: int) -> str:
|
|
23
|
+
"""Return the exact text of one slide (1-based). Copy evidence quotes from this text."""
|
|
24
|
+
slides = core.read_slides(pdf_path)
|
|
25
|
+
if not 1 <= slide <= len(slides):
|
|
26
|
+
raise ValueError(f"slide must be between 1 and {len(slides)}")
|
|
27
|
+
return slides[slide - 1]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@mcp.tool()
|
|
31
|
+
def check_cards(pdf_path: str, cards: list[dict]) -> list[dict]:
|
|
32
|
+
"""Check each card {front, back, slide, evidence} against the text of its slide.
|
|
33
|
+
|
|
34
|
+
'evidence' must be a quote of at least 4 words copied exactly from the cited
|
|
35
|
+
slide, and 'back' must be inside that quote. Symbols, signs and numbers must
|
|
36
|
+
match exactly. A passing card means the quote is on the slide. It does not
|
|
37
|
+
mean the card is correct: read the evidence next to the answer. A failing
|
|
38
|
+
card comes back with the slide text so the quote can be fixed.
|
|
39
|
+
"""
|
|
40
|
+
slides = core.read_slides(pdf_path)
|
|
41
|
+
return [core.check_card(c, slides) for c in cards]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@mcp.tool()
|
|
45
|
+
def export_anki(pdf_path: str, cards: list[dict], out_path: str) -> dict:
|
|
46
|
+
"""Write cards to a new Anki-importable .tsv, only if every card passes check_cards.
|
|
47
|
+
|
|
48
|
+
out_path must end with .tsv, be in an existing folder, and must not exist yet.
|
|
49
|
+
The evidence quote and slide number are written at the end of each answer.
|
|
50
|
+
Exact duplicates (same front and back) are written once; the indexes of the
|
|
51
|
+
skipped copies are listed in 'duplicates_skipped'.
|
|
52
|
+
"""
|
|
53
|
+
path = Path(out_path)
|
|
54
|
+
if path.suffix.lower() != ".tsv":
|
|
55
|
+
raise ValueError("out_path must end with .tsv")
|
|
56
|
+
slides = core.read_slides(pdf_path)
|
|
57
|
+
checks = [core.check_card(c, slides) for c in cards]
|
|
58
|
+
bad = [i for i, c in enumerate(checks) if not c["ok"]]
|
|
59
|
+
if bad:
|
|
60
|
+
return {"written": None, "rejected_card_indexes": bad, "details": [checks[i] for i in bad]}
|
|
61
|
+
seen, unique, dupes = set(), [], []
|
|
62
|
+
for i, c in enumerate(cards):
|
|
63
|
+
key = core.card_key(c)
|
|
64
|
+
if key in seen:
|
|
65
|
+
dupes.append(i)
|
|
66
|
+
else:
|
|
67
|
+
seen.add(key)
|
|
68
|
+
unique.append(c)
|
|
69
|
+
return {"written": core.write_anki_tsv(unique, out_path), "count": len(unique),
|
|
70
|
+
"duplicates_skipped": dupes}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def main() -> None:
|
|
74
|
+
mcp.run()
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
if __name__ == "__main__":
|
|
78
|
+
main()
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""End-to-end: spawn the server over stdio and call the tools like Claude would."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import csv
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
import tempfile
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from mcp import ClientSession, StdioServerParameters
|
|
11
|
+
from mcp.client.stdio import stdio_client
|
|
12
|
+
from reportlab.pdfgen import canvas
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
async def main():
|
|
16
|
+
d = Path(tempfile.mkdtemp())
|
|
17
|
+
pdf = d / "lec.pdf"
|
|
18
|
+
c = canvas.Canvas(str(pdf))
|
|
19
|
+
c.drawString(72, 800, "Mitral valve")
|
|
20
|
+
c.drawString(72, 780, "The mitral valve has two cusps")
|
|
21
|
+
c.showPage()
|
|
22
|
+
c.save()
|
|
23
|
+
params = StdioServerParameters(command=sys.executable, args=["-m", "slide_anki_mcp.server"],
|
|
24
|
+
env={**os.environ})
|
|
25
|
+
async with stdio_client(params) as (r, w):
|
|
26
|
+
async with ClientSession(r, w) as s:
|
|
27
|
+
await s.initialize()
|
|
28
|
+
tools = sorted(t.name for t in (await s.list_tools()).tools)
|
|
29
|
+
assert tools == ["check_cards", "export_anki", "get_slide", "list_slides"], tools
|
|
30
|
+
ev = "The mitral valve has two cusps"
|
|
31
|
+
good = [{"front": "How many cusps?", "back": "two cusps", "evidence": ev, "slide": 1}]
|
|
32
|
+
bad = [{"front": "How many cusps?", "back": "three big cusps",
|
|
33
|
+
"evidence": "The mitral valve has three big cusps", "slide": 1}]
|
|
34
|
+
|
|
35
|
+
async def export(cards, name):
|
|
36
|
+
res = await s.call_tool("export_anki", {"pdf_path": str(pdf), "cards": cards,
|
|
37
|
+
"out_path": str(d / name)})
|
|
38
|
+
return res
|
|
39
|
+
|
|
40
|
+
ok = json.loads((await export(good, "o.tsv")).content[0].text)
|
|
41
|
+
no = json.loads((await export(bad, "p.tsv")).content[0].text)
|
|
42
|
+
again = await export(good, "o.tsv")
|
|
43
|
+
print("GOOD :", ok["count"], "card written")
|
|
44
|
+
print("BAD :", no["rejected_card_indexes"], no["details"][0]["unsupported"])
|
|
45
|
+
print("AGAIN:", again.isError, again.content[0].text[:80])
|
|
46
|
+
assert (d / "o.tsv").exists() and not (d / "p.tsv").exists()
|
|
47
|
+
assert again.isError # an existing file is never overwritten
|
|
48
|
+
body = [ln for ln in (d / "o.tsv").read_text(encoding="utf-8").splitlines() if not ln.startswith("#")]
|
|
49
|
+
row = next(csv.reader(body, delimiter="\t"))
|
|
50
|
+
assert row[0] == "How many cusps?" and ev in row[1] and row[2] == "slides Slide_1", row
|
|
51
|
+
print("E2E OK")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
asyncio.run(main())
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
from reportlab.pdfgen import canvas
|
|
6
|
+
|
|
7
|
+
from slide_anki_mcp import core, server
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def make_pdf(path, pages):
|
|
11
|
+
c = canvas.Canvas(str(path))
|
|
12
|
+
for lines in pages:
|
|
13
|
+
y = 800
|
|
14
|
+
for line in lines:
|
|
15
|
+
c.drawString(72, y, line)
|
|
16
|
+
y -= 20
|
|
17
|
+
c.showPage()
|
|
18
|
+
c.save()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def card(back, evidence, slide=1, front="q"):
|
|
22
|
+
return {"front": front, "back": back, "evidence": evidence, "slide": slide}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def check(slide_text, *args, **kw):
|
|
26
|
+
return core.check_card(card(*args, **kw), [slide_text])
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def reasons(res):
|
|
30
|
+
return " ".join(res["unsupported"])
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# ---- reading and overview -------------------------------------------------
|
|
34
|
+
|
|
35
|
+
def test_read_and_overview(tmp_path):
|
|
36
|
+
pdf = tmp_path / "lec.pdf"
|
|
37
|
+
make_pdf(pdf, [["Cardiac cycle", "Systole is ventricular contraction"], ["Valves", "Mitral valve has two cusps"]])
|
|
38
|
+
slides = core.read_slides(str(pdf))
|
|
39
|
+
assert len(slides) == 2
|
|
40
|
+
assert core.slide_overview(slides)[0]["title"] == "Cardiac cycle"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_overview_warns_on_empty_and_short_slides(tmp_path):
|
|
44
|
+
pdf = tmp_path / "lec.pdf"
|
|
45
|
+
make_pdf(pdf, [["Mitral valve has two cusps and a long enough line"], ["Valves"], []])
|
|
46
|
+
ov = core.slide_overview(core.read_slides(str(pdf)))
|
|
47
|
+
assert ov[0]["warning"] is None
|
|
48
|
+
assert "under 40" in ov[1]["warning"]
|
|
49
|
+
assert "no text" in ov[2]["warning"]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_pdf_with_no_pages_raises(tmp_path):
|
|
53
|
+
from pypdf import PdfWriter
|
|
54
|
+
pdf = tmp_path / "zero.pdf"
|
|
55
|
+
PdfWriter().write(str(pdf))
|
|
56
|
+
with pytest.raises(ValueError):
|
|
57
|
+
core.read_slides(str(pdf))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_missing_and_non_pdf_files_give_clear_errors(tmp_path):
|
|
61
|
+
with pytest.raises(ValueError, match="not found"):
|
|
62
|
+
core.read_slides(str(tmp_path / "nope.pdf"))
|
|
63
|
+
junk = tmp_path / "junk.pdf"
|
|
64
|
+
junk.write_text("this is not a pdf")
|
|
65
|
+
with pytest.raises(ValueError, match="cannot read"):
|
|
66
|
+
core.read_slides(str(junk))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# ---- the evidence check ---------------------------------------------------
|
|
70
|
+
|
|
71
|
+
SLIDE = "Mitral valve\nThe mitral valve has two cusps"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_supported_card_passes_and_wrong_answer_fails():
|
|
75
|
+
ok = check(SLIDE, "two cusps", "The mitral valve has two cusps")
|
|
76
|
+
bad = check(SLIDE, "three large cusps", "The mitral valve has three large cusps")
|
|
77
|
+
assert ok["ok"] and not bad["ok"]
|
|
78
|
+
assert "not on this slide" in reasons(bad)
|
|
79
|
+
assert "The mitral valve has two cusps" in bad["slide_text"]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def test_short_wrong_answer_is_rejected():
|
|
83
|
+
slide = "ADH is produced in Hypothalamus\nDaily intake is 100 meq"
|
|
84
|
+
assert check(slide, "Hypothalamus", "ADH is produced in Hypothalamus")["ok"]
|
|
85
|
+
assert not check(slide, "Anterior pituitary", "ADH is produced in Anterior pituitary")["ok"]
|
|
86
|
+
assert not check(slide, "200 meq", "Daily intake is 200 meq")["ok"]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_comparison_and_sign_symbols_are_kept():
|
|
90
|
+
slide = "Normal K is > 3.5 mmol/L. Resting potential is -70 mV"
|
|
91
|
+
assert check(slide, "> 3.5 mmol/L", "Normal K is > 3.5 mmol/L")["ok"]
|
|
92
|
+
assert not check(slide, "< 3.5 mmol/L", "Normal K is < 3.5 mmol/L")["ok"]
|
|
93
|
+
assert check(slide, "-70 mV", "Resting potential is -70 mV")["ok"]
|
|
94
|
+
assert not check(slide, "+70 mV", "Resting potential is +70 mV")["ok"]
|
|
95
|
+
# the back cannot drop the sign that the evidence keeps
|
|
96
|
+
assert not check(slide, "70 mV", "Resting potential is -70 mV")["ok"]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def test_superscripts_do_not_become_plain_digits():
|
|
100
|
+
slide = "Count is 10\u2075 cells per mL in blood"
|
|
101
|
+
assert check(slide, "10\u2075 cells", "Count is 10\u2075 cells per mL")["ok"]
|
|
102
|
+
assert not check(slide, "105 cells", "Count is 105 cells per mL")["ok"]
|
|
103
|
+
assert core._text("10\u2075") != core._text("105")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def test_a_cut_range_is_rejected():
|
|
107
|
+
slide = "Daily intake is 1000-1500 ml of water"
|
|
108
|
+
assert check(slide, "1000-1500 ml", "Daily intake is 1000-1500 ml")["ok"]
|
|
109
|
+
assert not check(slide, "1500 ml", "Daily intake is 1000-1500 ml")["ok"]
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def test_negation_is_visible_in_the_evidence_not_detected():
|
|
113
|
+
"""Known limit: the check cannot judge meaning. The quote is exported so a
|
|
114
|
+
human can see 'does not have' next to the answer."""
|
|
115
|
+
slide = "Mitral valve does not have three cusps"
|
|
116
|
+
res = check(slide, "three cusps", "Mitral valve does not have three cusps")
|
|
117
|
+
assert res["ok"]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def test_evidence_must_be_long_enough_and_exactly_on_the_slide():
|
|
121
|
+
assert "too short" in reasons(check(SLIDE, "two cusps", "two cusps"))
|
|
122
|
+
assert "not on this slide" in reasons(check(SLIDE, "two cusps", "The itral valve has two cusps"))
|
|
123
|
+
assert "not on this slide" in reasons(check(SLIDE, "two cusps", "The mitral valve has tw"))
|
|
124
|
+
assert "not on this slide" in reasons(check(SLIDE, "two cusps", "The mitral valve has two large cusps"))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def test_back_must_be_inside_the_evidence():
|
|
128
|
+
res = check(SLIDE, "two cusps and a flap", "The mitral valve has two cusps")
|
|
129
|
+
assert "back is not inside" in reasons(res)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def test_word_hyphenated_at_a_line_break_still_matches():
|
|
133
|
+
slide = "Muscle contrac-\ntion needs calcium ions"
|
|
134
|
+
assert check(slide, "Muscle contraction", "Muscle contraction needs calcium ions")["ok"]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def test_slide_without_text_is_rejected_loudly():
|
|
138
|
+
for empty in ("", " ", "\u25cf"):
|
|
139
|
+
res = check(empty, "two cusps", "The mitral valve has two cusps")
|
|
140
|
+
assert not res["ok"] and "cannot verify" in reasons(res)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def test_bad_card_fields_are_rejected_not_crashing():
|
|
144
|
+
slides = [SLIDE]
|
|
145
|
+
good = card("two cusps", "The mitral valve has two cusps")
|
|
146
|
+
bads = [{k: v for k, v in good.items() if k != "evidence"}, {k: v for k, v in good.items() if k != "front"},
|
|
147
|
+
{**good, "back": ""}, {**good, "back": None}, {**good, "back": 5}, {**good, "evidence": 7},
|
|
148
|
+
{**good, "slide": True}, {**good, "slide": 0}, {**good, "slide": 9}, "a string", None, 5]
|
|
149
|
+
for bad in bads:
|
|
150
|
+
assert not core.check_card(bad, slides)["ok"], bad
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
# ---- exporting ------------------------------------------------------------
|
|
154
|
+
|
|
155
|
+
def rows(path):
|
|
156
|
+
with open(path, encoding="utf-8", newline="") as fh:
|
|
157
|
+
text = [ln for ln in fh.read().splitlines(keepends=True)]
|
|
158
|
+
header = [ln.rstrip("\n") for ln in text if ln.startswith("#") and not ln.startswith('"#')]
|
|
159
|
+
body = [ln for ln in text if ln not in [h + "\n" for h in header]]
|
|
160
|
+
return header, list(csv.reader(body, delimiter="\t"))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def test_tsv_has_header_quotes_everything_and_shows_the_evidence(tmp_path):
|
|
164
|
+
cards = [{"front": "#1 valve?", "back": "two cusps", "slide": 4,
|
|
165
|
+
"evidence": "The mitral valve has two cusps"}]
|
|
166
|
+
out = core.write_anki_tsv(cards, str(tmp_path / "o.tsv"))
|
|
167
|
+
header, body = rows(out)
|
|
168
|
+
assert header == ["#separator:tab", "#html:false", "#tags column:3"]
|
|
169
|
+
assert body == [["#1 valve?", "two cusps | Source (slide 4): The mitral valve has two cusps",
|
|
170
|
+
"slides Slide_4"]]
|
|
171
|
+
assert open(out, encoding="utf-8").read().splitlines()[3].startswith('"#1 valve?"')
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def test_export_refuses_wrong_extension_existing_file_and_missing_folder(tmp_path):
|
|
175
|
+
cards = [{"front": "q", "back": "A", "slide": 1, "evidence": "The mitral valve has two cusps"}]
|
|
176
|
+
victim = tmp_path / "victim.cfg"
|
|
177
|
+
victim.write_text("keep me")
|
|
178
|
+
with pytest.raises(ValueError, match=".tsv"):
|
|
179
|
+
core.write_anki_tsv(cards, str(victim))
|
|
180
|
+
assert victim.read_text() == "keep me"
|
|
181
|
+
existing = tmp_path / "taken.tsv"
|
|
182
|
+
existing.write_text("keep me too")
|
|
183
|
+
with pytest.raises(ValueError, match="already exists"):
|
|
184
|
+
core.write_anki_tsv(cards, str(existing))
|
|
185
|
+
assert existing.read_text() == "keep me too"
|
|
186
|
+
with pytest.raises(ValueError, match="folder"):
|
|
187
|
+
core.write_anki_tsv(cards, str(tmp_path / "no_such" / "x.tsv"))
|
|
188
|
+
assert not (tmp_path / "no_such").exists()
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def test_server_export_checks_before_writing(tmp_path):
|
|
192
|
+
pdf = tmp_path / "lec.pdf"
|
|
193
|
+
make_pdf(pdf, [["Mitral valve has two cusps"]])
|
|
194
|
+
good = card("two cusps", "Mitral valve has two cusps", front="Cusps?")
|
|
195
|
+
bad = card("three cusps", "Mitral valve has three cusps", front="Cusps?")
|
|
196
|
+
res = server.export_anki(str(pdf), [good, bad], str(tmp_path / "o.tsv"))
|
|
197
|
+
assert res["written"] is None and res["rejected_card_indexes"] == [1]
|
|
198
|
+
assert not (tmp_path / "o.tsv").exists()
|
|
199
|
+
with pytest.raises(ValueError, match=".tsv"):
|
|
200
|
+
server.export_anki(str(pdf), [good], str(tmp_path / "victim.cfg"))
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def test_export_skips_duplicates_ignoring_case_and_spaces(tmp_path):
|
|
204
|
+
pdf = tmp_path / "lec.pdf"
|
|
205
|
+
make_pdf(pdf, [["Mitral valve has two cusps"]])
|
|
206
|
+
one = card("two cusps", "Mitral valve has two cusps", front="Cusps?")
|
|
207
|
+
same = {**one, "front": "Cusps? ", "back": "Two cusps"}
|
|
208
|
+
other = {**one, "front": "Mitral cusps?"}
|
|
209
|
+
res = server.export_anki(str(pdf), [one, other, same], str(tmp_path / "o.tsv"))
|
|
210
|
+
assert res["count"] == 2 and res["duplicates_skipped"] == [2]
|
|
211
|
+
assert len(rows(res["written"])[1]) == 2
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
# ---- Arabic ---------------------------------------------------------------
|
|
215
|
+
|
|
216
|
+
ARABIC_FONTS = ["C:/Windows/Fonts/arial.ttf", "C:/Windows/Fonts/tahoma.ttf",
|
|
217
|
+
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"]
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def test_arabic_slide_matches(tmp_path):
|
|
221
|
+
"""Store Arabic as shaped letters in display (right-to-left) order, as a PDF may."""
|
|
222
|
+
arabic_reshaper = pytest.importorskip("arabic_reshaper")
|
|
223
|
+
bidi = pytest.importorskip("bidi.algorithm")
|
|
224
|
+
from reportlab.pdfbase import pdfmetrics
|
|
225
|
+
from reportlab.pdfbase.ttfonts import TTFont
|
|
226
|
+
font = next((f for f in ARABIC_FONTS if os.path.exists(f)), None)
|
|
227
|
+
if font is None:
|
|
228
|
+
pytest.skip("no Arabic-capable font found")
|
|
229
|
+
pdfmetrics.registerFont(TTFont("ArabicTest", font))
|
|
230
|
+
pdf = tmp_path / "ar.pdf"
|
|
231
|
+
c = canvas.Canvas(str(pdf))
|
|
232
|
+
c.setFont("ArabicTest", 16)
|
|
233
|
+
c.drawString(72, 800, bidi.get_display(arabic_reshaper.reshape("الكلية تنظم توازن الماء")))
|
|
234
|
+
c.showPage()
|
|
235
|
+
c.save()
|
|
236
|
+
slides = core.read_slides(str(pdf))
|
|
237
|
+
full = "الكلية تنظم توازن الماء"
|
|
238
|
+
assert core.check_card(card(full, full), slides)["ok"]
|
|
239
|
+
assert core.check_card(card("تُنظّم توازن", full), slides)["ok"]
|
|
240
|
+
assert not core.check_card(card("القلب ينظم توازن الماء", "القلب ينظم توازن الماء"), slides)["ok"]
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
# ---- review round 2: cuts inside a token, invisible characters ------------
|
|
244
|
+
|
|
245
|
+
def test_quote_or_back_cut_inside_a_number_or_unit_is_rejected():
|
|
246
|
+
slide = "Normal sodium is 135-145 mmol/L\nPump moves Na+ out\nCount is 14.5 per mL"
|
|
247
|
+
assert not check(slide, "135", "Normal sodium is 135")["ok"]
|
|
248
|
+
assert not check("Dose 140 mmol/L daily", "140 mmol", "Dose 140 mmol")["ok"]
|
|
249
|
+
assert not check(slide, "14", "Count is 14")["ok"]
|
|
250
|
+
assert not check(slide, "Na", "Pump moves Na")["ok"]
|
|
251
|
+
assert check(slide, "135-145 mmol/L", "Normal sodium is 135-145 mmol/L")["ok"]
|
|
252
|
+
assert check(slide, "Na+", "Pump moves Na+ out")["ok"]
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def test_invisible_characters_and_kept_hyphens_in_pdf_text():
|
|
256
|
+
soft = "contraction needs calcium ions"
|
|
257
|
+
assert check(soft, "contraction", "contraction needs calcium ions")["ok"]
|
|
258
|
+
wrapped = "Water-\nsoluble vitamins are stored briefly"
|
|
259
|
+
assert check(wrapped, "Water-soluble vitamins", "Water-soluble vitamins are stored briefly")["ok"]
|
|
260
|
+
assert check(wrapped, "Watersoluble vitamins", "Watersoluble vitamins are stored briefly")["ok"]
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def test_directory_named_like_the_output_file_is_a_clear_error(tmp_path):
|
|
264
|
+
(tmp_path / "x.tsv").mkdir()
|
|
265
|
+
cards = [{"front": "q", "back": "A", "slide": 1, "evidence": "The mitral valve has two cusps"}]
|
|
266
|
+
with pytest.raises(ValueError):
|
|
267
|
+
core.write_anki_tsv(cards, str(tmp_path / "x.tsv"))
|