code-mode-for-zotero 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,139 @@
1
+ Metadata-Version: 2.5
2
+ Name: code-mode-for-zotero
3
+ Version: 0.1.0
4
+ Summary: A local MCP server that lets an AI assistant read your Zotero library by writing short Python scripts, run in a sandbox, with page-level passage search.
5
+ Project-URL: Homepage, https://github.com/ltalignani/code-mode-for-zotero
6
+ Project-URL: Issues, https://github.com/ltalignani/code-mode-for-zotero/issues
7
+ Project-URL: Changelog, https://github.com/ltalignani/code-mode-for-zotero/blob/main/CHANGELOG.md
8
+ Author: Loïc Talignani, Thierry Valéro
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ License-File: NOTICE
12
+ Keywords: bibliography,claude,code mode,mcp,model context protocol,rag,zotero
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Operating System :: MacOS
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Topic :: Scientific/Engineering
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: fastmcp<5,>=3
21
+ Requires-Dist: httpx>=0.27
22
+ Requires-Dist: markdownify>=1.2
23
+ Requires-Dist: pdf-inspector==0.2.6
24
+ Requires-Dist: snowballstemmer>=2.2
25
+ Requires-Dist: unidecode>=1.3
26
+ Provides-Extra: dev
27
+ Requires-Dist: numpy>=1.26; extra == 'dev'
28
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
29
+ Requires-Dist: pytest>=8; extra == 'dev'
30
+ Requires-Dist: ruff>=0.6; extra == 'dev'
31
+ Provides-Extra: embeddings
32
+ Requires-Dist: numpy>=1.26; extra == 'embeddings'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # Code Mode for Zotero
36
+
37
+ Read your Zotero library from Claude, ChatGPT or any MCP client, by letting the model write short Python scripts instead of calling dozens of tools. The scripts run in a sandbox on your computer, read the local `zotero.sqlite`, and only what they print goes back to the model. Passages can be searched by meaning, in French or English, and every hit comes with its page, so answers can be cited as `citekey, p. 12`.
38
+
39
+ > Not affiliated with Zotero or the Corporation for Digital Scholarship. Zotero is their project; this is an independent tool that reads the files Zotero keeps on your disk.
40
+
41
+ Status: alpha (0.1). macOS and Linux. Windows is not supported yet, because scripts cannot be isolated there.
42
+
43
+ ## Why code mode
44
+
45
+ A classic Zotero MCP server exposes one tool per operation, which puts thousands of tokens of tool definitions in every conversation and sends every intermediate result through the model. This server has two tools:
46
+
47
+ | Tool | What it does |
48
+ |---|---|
49
+ | `search_api(query="")` | Lists the `zotero.*` functions a script can call, with their documentation. |
50
+ | `execute(code, timeout_seconds=30)` | Runs a script and returns what it printed. |
51
+
52
+ The two definitions take about 230 tokens. A search over 200 items, a filter and a sort happen inside the script, and only the five lines the script prints reach the model.
53
+
54
+ ## What a script can call
55
+
56
+ All read-only. Records are small flat dicts (key, title, creators, year, DOI, tags, `citationKey`, library).
57
+
58
+ | Function | Returns |
59
+ |---|---|
60
+ | `zotero.search(query, ...)` | Items matching a query, at most 200 |
61
+ | `zotero.get_item(ref, detail)` | One item, by Zotero key, citation key or Better BibTeX key |
62
+ | `zotero.fulltext(ref, first, last)` | The text of an item's PDF, one entry per page |
63
+ | `zotero.find(ref, query)` | Paragraphs of one document that contain every word, with page numbers |
64
+ | `zotero.passages(query, limit, keys)` | The most relevant passages across the library, with page numbers |
65
+ | `zotero.rag_index(...)`, `zotero.rag_status()` | Build and inspect the passage index |
66
+
67
+ Every library in the database is searched (personal and groups) unless `ZOTERO_MCP_LIBRARY` says otherwise (`0` for the personal library, or a group id).
68
+
69
+ ## Install
70
+
71
+ Requires Python 3.10 or later and Zotero installed on the same computer (it does not need to be running).
72
+
73
+ ```bash
74
+ uv tool install 'code-mode-for-zotero[embeddings]' # or: pipx install ..., pip install ...
75
+ code-mode-zotero --check-sandbox # what scripts can and cannot do here
76
+ ```
77
+
78
+ Claude Desktop, in `claude_desktop_config.json`:
79
+
80
+ ```json
81
+ {
82
+ "mcpServers": {
83
+ "zotero": {
84
+ "command": "code-mode-zotero",
85
+ "env": {
86
+ "ZOTERO_RAG_EMBED_URL": "http://localhost:1234/v1",
87
+ "ZOTERO_RAG_EMBED_MODEL": "text-embedding-bge-m3"
88
+ }
89
+ }
90
+ }
91
+ }
92
+ ```
93
+
94
+ The `env` block is optional; without it, passage search works on keywords only. Claude Desktop does not read your shell profile, so variables go in this block.
95
+
96
+ ## Passage search
97
+
98
+ ```bash
99
+ code-mode-zotero --check-embeddings # one call to your embeddings server, with a sanity check
100
+ code-mode-zotero --index # build or refresh the index; resumable
101
+ code-mode-zotero --index --force # rebuild everything, e.g. after changing the model
102
+ ```
103
+
104
+ Passages are cut from each PDF without crossing a page, cleaned of reference lists, tables and line numbers, and stored in one SQLite file. Keyword search uses French and English word stems, so "pyréthrinoïde" finds "pyréthrinoïdes". When an embeddings endpoint is configured (LM Studio, Ollama, vLLM or any OpenAI-compatible `/v1/embeddings`), passages are also ranked by meaning and the two rankings are merged. If the endpoint is unreachable, search falls back to keywords and says so in each result.
105
+
106
+ ## What it runs, reads, writes and sends
107
+
108
+ This section is complete; if the code does something not listed here, it is a bug.
109
+
110
+ - **Runs**: the MCP server, and for each `execute` call a child Python process with the script. On macOS the child runs under `sandbox-exec` with no network, no file writes, no new processes and no access to your home folder; on Linux it runs in an empty network namespace (files and processes are not blocked there, so scripts only run with `ZOTERO_MCP_SANDBOX=relaxed`). CPU time, output size and run time are limited everywhere, memory on Linux.
111
+ - **Reads**: `zotero.sqlite`, read-only (it may be copied to a temporary folder so it can be read while Zotero is writing), `better-bibtex.sqlite` if present, and attachment files in Zotero's storage folder.
112
+ - **Writes**: the passage index (`~/.local/share/code-mode-for-zotero/rag.sqlite`, or `ZOTERO_RAG_DB`) and a cache of extracted text (`~/.cache/code-mode-for-zotero/fulltext/`). It never writes to your Zotero library.
113
+ - **Sends**: passage text and search queries to the embeddings endpoint you configure, and nowhere else. With no endpoint configured, the server makes no network call. There is no telemetry.
114
+
115
+ See [PRIVACY.md](PRIVACY.md) and [SECURITY.md](SECURITY.md).
116
+
117
+ ## Settings
118
+
119
+ | Variable | Default | Meaning |
120
+ |---|---|---|
121
+ | `ZOTERO_DB_PATH` | found automatically | Path to `zotero.sqlite` |
122
+ | `ZOTERO_BBT_DB` | next to `zotero.sqlite` | Path to `better-bibtex.sqlite` |
123
+ | `ZOTERO_MCP_LIBRARY` | `all` | `all`, `0` (personal) or a group id |
124
+ | `ZOTERO_MCP_SANDBOX` | `strict` | `relaxed` runs scripts without full isolation |
125
+ | `ZOTERO_RAG_DB` | `~/.local/share/code-mode-for-zotero/rag.sqlite` | Passage index |
126
+ | `ZOTERO_RAG_EMBED_URL` | none | OpenAI-compatible endpoint, e.g. `http://localhost:1234/v1` |
127
+ | `ZOTERO_RAG_EMBED_MODEL` | `nomic-embed-text` | Embedding model name |
128
+ | `ZOTERO_RAG_EMBED_KEY` | none | Bearer token, if the endpoint needs one |
129
+
130
+ ## Limits
131
+
132
+ - Read-only: no adding, tagging or annotating items.
133
+ - A timeout stops a script but not a database call already running.
134
+ - Scanned PDFs without a text layer are reported (`needsOcr`) and not indexed.
135
+ - An index built with one embedding model cannot be queried with another.
136
+
137
+ ## Authors and origin
138
+
139
+ Loïc Talignani and Thierry Valéro. The data-access layer comes from [Zotero MCP](https://github.com/54yyyu/zotero-mcp) (MIT); see [NOTICE](NOTICE). MIT License.
@@ -0,0 +1,24 @@
1
+ code_mode_zotero/__init__.py,sha256=zzvBQJRkc5ceGaRkdKTL728UcoZNXNFRkEKIg0a0rmE,161
2
+ code_mode_zotero/__main__.py,sha256=eXeapLl0Z_NGF07njwHmC1hCz6ocYqR1RHwGCm6-gBs,80
3
+ code_mode_zotero/_sandbox_child.py,sha256=wxeLAYLODi2Jb5TM855DZ59jZEZ246DOTOUuBU_gIk8,6404
4
+ code_mode_zotero/bbt_keys.py,sha256=xNg3WpbroRYUpthnXaxFZ0hJdeWwvNFolydHmZaJx7k,4657
5
+ code_mode_zotero/codemode_api.py,sha256=fTnPq0IAAzDvpVjxrSaM5Vo1Vw4S1OODaKIBVT-K48g,22527
6
+ code_mode_zotero/codemode_server.py,sha256=CE8JrtvkNSSN4Dwdb6EpWYXEYi1drWfByqiUUiuNxqQ,10283
7
+ code_mode_zotero/collections_scope.py,sha256=FuFrWETtEKN9GNhjyfqwt6XCPH6Q3O-wGn3NkixGiXg,3545
8
+ code_mode_zotero/extract.py,sha256=ygmoqSZStOyoN6Vfj2Qle6jrvKzfPh3MKIJs2NWiRd8,32780
9
+ code_mode_zotero/fulltext_cache.py,sha256=LXYgT3fL8Of2ajivVpQQhMQvXHHCno1qqRYqVbLebUQ,9707
10
+ code_mode_zotero/library.py,sha256=Om-_TphXHMAzXieVQjGptBk_K7vIgP3YTBy0Mzdciss,14603
11
+ code_mode_zotero/local_db.py,sha256=3oay8RTvGyffXgXbR44XYlV7qvAwBESvQGkVjV6qkY4,164783
12
+ code_mode_zotero/rag.py,sha256=zzgQJ4kLf01lIEvAJDn7UqXucpiu_vL5S_SIK-6hhic,20738
13
+ code_mode_zotero/sandbox.py,sha256=F0I9QOgi4zwHybnQFSyh2ILZi7Aar9vr39rsWax7eb8,15450
14
+ code_mode_zotero/schema.py,sha256=ByUE3wck6wd4wRteBWpawKQ0xUD8oLUA7ijDmFRVzOk,6821
15
+ code_mode_zotero/search_semantics.py,sha256=QzpUbBwXCyZXaNNRG1pfbT1rTwS87gFt1RSoZul3Ncg,10105
16
+ code_mode_zotero/strict_sqlite.py,sha256=fKby8uU1Xf0m1jwiuSJ6HI17n6KBa2-Lj0_IH8WB0DI,7896
17
+ code_mode_zotero/utils.py,sha256=KHmJKaU0_oFFrT5MSoz1uSeAb5Jwa4gF-rcDH0aLiyc,33381
18
+ code_mode_zotero/data/zotero_basefields.json,sha256=UHYzCFantG7Dn6kpgxCn-4jp6THQMtbeK-Wq7JffWZE,30058
19
+ code_mode_for_zotero-0.1.0.dist-info/METADATA,sha256=xgipYRCIowHP_aSns2Db3v_EfF-BmRI93CJZ81xtcio,7700
20
+ code_mode_for_zotero-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
21
+ code_mode_for_zotero-0.1.0.dist-info/entry_points.txt,sha256=VyelqjVnp6cuWHce6QekXLhtiWm6zB2TaEqNjWyGjbg,75
22
+ code_mode_for_zotero-0.1.0.dist-info/licenses/LICENSE,sha256=TWr0Gu2AVZBgic5e3RIltZwBhWu8wT9UQLsOI_nlirc,1135
23
+ code_mode_for_zotero-0.1.0.dist-info/licenses/NOTICE,sha256=3N4b5rKJF8o8U_eojOpVo9PPbnlQ-eUtVHQQc4ODrGc,730
24
+ code_mode_for_zotero-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ code-mode-zotero = code_mode_zotero.codemode_server:main
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Loïc Talignani and Thierry Valéro
4
+ Copyright (c) 2025 Zotero MCP Contributors
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,14 @@
1
+ Code Mode for Zotero
2
+ Copyright (c) 2026 Loïc Talignani and Thierry Valéro
3
+
4
+ This project started from Zotero MCP (https://github.com/54yyyu/zotero-mcp),
5
+ MIT License, Copyright (c) 2025 Zotero MCP Contributors, at commit 0e6ff62
6
+ (release 0.17.4). The modules local_db, library, extract, utils, schema,
7
+ strict_sqlite, fulltext_cache, search_semantics and collections_scope, the
8
+ vendored data/zotero_basefields.json, and part of the test suite come from
9
+ that project, adapted. The Zotero browser-plugin part of Zotero MCP, which is
10
+ under the AGPL, is not included.
11
+
12
+ Zotero is a project of the Corporation for Digital Scholarship.
13
+ This project is not affiliated with or endorsed by Zotero or the Corporation
14
+ for Digital Scholarship.
@@ -0,0 +1,4 @@
1
+ """Code Mode for Zotero: a local MCP server that lets a model read a Zotero
2
+ library by writing short Python scripts, run in a sandbox."""
3
+
4
+ __version__ = "0.1.0"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from code_mode_zotero.codemode_server import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,182 @@
1
+ """Child process that runs model-written code. Standard library only.
2
+
3
+ This file is run as a script (``python -I -B _sandbox_child.py IN OUT``) and
4
+ must not import anything from ``code_mode_zotero``: the child has no access to the
5
+ Zotero database, the library, or the network. Everything it can learn about
6
+ the library comes through the ``zotero`` object, whose methods forward each
7
+ call to the parent over a pipe and return the parent's JSON answer. The
8
+ parent decides which methods exist and checks every call.
9
+
10
+ Protocol, one JSON object per line:
11
+
12
+ parent -> child ``{"init": {"code", "methods", "timeout", "max_output"}}``
13
+ child -> parent ``{"id", "method", "args", "kwargs"}`` a call
14
+ parent -> child ``{"id", "result"}`` or ``{"id", "error"}`` its answer
15
+ child -> parent ``{"done": true, "stdout", "error", "truncated"}``
16
+
17
+ Nothing here is a security boundary on its own. The boundary is the operating
18
+ system sandbox the parent wraps this process in; the limits below only keep a
19
+ runaway script from hurting the machine when that sandbox is partial.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import ast
25
+ import contextlib
26
+ import json
27
+ import linecache
28
+ import os
29
+ import sys
30
+ import traceback
31
+
32
+ _FILENAME = "<script>"
33
+
34
+
35
+ class ZoteroCallError(Exception):
36
+ """The parent refused or failed a call made through ``zotero``."""
37
+
38
+
39
+ class _Bounded:
40
+ """A text sink that keeps the first ``limit`` characters and counts the rest."""
41
+
42
+ def __init__(self, limit: int) -> None:
43
+ self.limit = limit
44
+ self.parts: list[str] = []
45
+ self.size = 0
46
+ self.truncated = False
47
+
48
+ def write(self, text: str) -> int:
49
+ room = self.limit - self.size
50
+ if room > 0:
51
+ self.parts.append(text[:room])
52
+ self.size += min(len(text), room)
53
+ if len(text) > room:
54
+ self.truncated = True
55
+ return len(text)
56
+
57
+ def flush(self) -> None:
58
+ pass
59
+
60
+ def getvalue(self) -> str:
61
+ return "".join(self.parts)
62
+
63
+
64
+ def _apply_limits(cpu_seconds: int) -> None:
65
+ try:
66
+ import resource
67
+ except ImportError: # not POSIX
68
+ return
69
+ for name, value in (
70
+ ("RLIMIT_CPU", cpu_seconds),
71
+ ("RLIMIT_FSIZE", 0), # no file can grow: writes fail with EFBIG
72
+ ("RLIMIT_CORE", 0),
73
+ ("RLIMIT_AS", 2 * 1024**3), # enforced on Linux, ignored on macOS
74
+ ):
75
+ try:
76
+ limit = getattr(resource, name)
77
+ resource.setrlimit(limit, (value, value))
78
+ except (ValueError, OSError):
79
+ pass
80
+
81
+
82
+ class _Channel:
83
+ def __init__(self, read_fd: int, write_fd: int) -> None:
84
+ self._in = os.fdopen(read_fd, "r", encoding="utf-8", newline="\n")
85
+ self._out = os.fdopen(write_fd, "w", encoding="utf-8", newline="\n")
86
+ self._next = 0
87
+
88
+ def send(self, message: dict) -> None:
89
+ self._out.write(json.dumps(message, ensure_ascii=False) + "\n")
90
+ self._out.flush()
91
+
92
+ def receive(self) -> dict:
93
+ line = self._in.readline()
94
+ if not line:
95
+ raise SystemExit(0) # the parent went away
96
+ return json.loads(line)
97
+
98
+ def call(self, method: str, args: tuple, kwargs: dict):
99
+ self._next += 1
100
+ call_id = self._next
101
+ self.send({"id": call_id, "method": method, "args": list(args), "kwargs": kwargs})
102
+ while True:
103
+ reply = self.receive()
104
+ if reply.get("id") == call_id:
105
+ break
106
+ if "error" in reply:
107
+ raise ZoteroCallError(reply["error"])
108
+ return reply["result"]
109
+
110
+
111
+ class _Zotero:
112
+ """Forwards method calls to the parent. Only listed methods exist."""
113
+
114
+ def __init__(self, channel: _Channel, methods: list[str]) -> None:
115
+ self._channel = channel
116
+ self._methods = frozenset(methods)
117
+
118
+ def __getattr__(self, name: str):
119
+ if name.startswith("_") or name not in self._methods:
120
+ raise AttributeError(f"zotero has no method {name!r}; available: {sorted(self._methods)}")
121
+
122
+ def call(*args, **kwargs):
123
+ return self._channel.call(name, args, kwargs)
124
+
125
+ call.__name__ = name
126
+ return call
127
+
128
+ def __dir__(self):
129
+ return sorted(self._methods)
130
+
131
+ def __repr__(self) -> str:
132
+ return f"<zotero: {', '.join(sorted(self._methods))}>"
133
+
134
+
135
+ def _run(code: str, namespace: dict) -> None:
136
+ """Run ``code`` like a notebook cell: a final bare expression is printed."""
137
+ lines = code.splitlines(keepends=True)
138
+ linecache.cache[_FILENAME] = (len(code), None, lines, _FILENAME) # so errors can show the line
139
+ tree = ast.parse(code, _FILENAME, "exec")
140
+ last = None
141
+ if tree.body and isinstance(tree.body[-1], ast.Expr):
142
+ last = ast.Expression(tree.body.pop().value)
143
+ exec(compile(tree, _FILENAME, "exec"), namespace)
144
+ if last is not None:
145
+ value = eval(compile(last, _FILENAME, "eval"), namespace)
146
+ if value is not None:
147
+ print(repr(value))
148
+
149
+
150
+ def _format_error(exc: BaseException) -> str:
151
+ """The error as the script's author needs it: their own frames only."""
152
+ if isinstance(exc, SyntaxError):
153
+ where = f"line {exc.lineno}" if exc.lineno else "script"
154
+ return f"SyntaxError ({where}): {exc.msg}"
155
+ own = [f for f in traceback.extract_tb(exc.__traceback__) if f.filename == _FILENAME]
156
+ lines = ["Traceback (most recent call last):\n"] if own else []
157
+ lines += traceback.StackSummary.from_list(own).format()
158
+ lines += traceback.format_exception_only(type(exc), exc)
159
+ return "".join(lines).rstrip()
160
+
161
+
162
+ def main(argv: list[str]) -> int:
163
+ channel = _Channel(int(argv[1]), int(argv[2]))
164
+ init = channel.receive()["init"]
165
+ _apply_limits(int(init.get("timeout", 30)) + 5)
166
+
167
+ sink = _Bounded(int(init.get("max_output", 20_000)))
168
+ namespace = {"__name__": "__main__", "zotero": _Zotero(channel, init["methods"])}
169
+ error = None
170
+ with contextlib.redirect_stdout(sink), contextlib.redirect_stderr(sink):
171
+ try:
172
+ _run(init["code"], namespace)
173
+ except SystemExit as exc:
174
+ error = None if exc.code in (None, 0) else f"SystemExit: {exc.code}"
175
+ except BaseException as exc: # noqa: BLE001 - the script's failure is the result
176
+ error = _format_error(exc)
177
+ channel.send({"done": True, "stdout": sink.getvalue(), "error": error, "truncated": sink.truncated})
178
+ return 0
179
+
180
+
181
+ if __name__ == "__main__":
182
+ sys.exit(main(sys.argv))
@@ -0,0 +1,116 @@
1
+ """Better BibTeX citation keys, read straight from its database.
2
+
3
+ Better BibTeX keeps its keys in ``better-bibtex.sqlite`` next to
4
+ ``zotero.sqlite``, in a ``citationkey`` table, and not in Zotero's own
5
+ ``citationKey`` field. The JSON-RPC route in ``better_bibtex_client`` needs
6
+ Zotero to be running; this one needs only the file, so it works with Zotero
7
+ closed and costs one dictionary lookup per key.
8
+
9
+ The file is Better BibTeX's, not ours: it is opened read-only, and a locked
10
+ or mid-write file is read from a private copy instead. Better BibTeX writes
11
+ it on its own schedule, so an item added minutes ago may not have a key here
12
+ yet. That item simply has no ``citationKey`` until Better BibTeX saves.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ import os
19
+ import shutil
20
+ import sqlite3
21
+ import tempfile
22
+ import threading
23
+ from pathlib import Path
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+ _FILENAME = "better-bibtex.sqlite"
28
+
29
+
30
+ def _read_rows(path: Path) -> list[tuple[str, int, str]]:
31
+ """``(itemKey, libraryID, citationKey)`` for every key, or [] if unreadable."""
32
+ query = "SELECT itemKey, libraryID, citationKey FROM citationkey ORDER BY libraryID, itemKey"
33
+ try:
34
+ with sqlite3.connect(f"file:{path}?mode=ro", uri=True, timeout=2) as con:
35
+ return [tuple(r) for r in con.execute(query)]
36
+ except sqlite3.OperationalError as first:
37
+ # A locked database, or a WAL file we cannot attach to read-only:
38
+ # read a private copy rather than waiting on Better BibTeX.
39
+ logger.debug("reading %s directly failed (%s); trying a copy", path, first)
40
+ try:
41
+ with tempfile.TemporaryDirectory() as tmp:
42
+ copy = Path(tmp) / _FILENAME
43
+ shutil.copyfile(path, copy)
44
+ for suffix in ("-wal", "-shm"):
45
+ side = Path(f"{path}{suffix}")
46
+ if side.is_file():
47
+ shutil.copyfile(side, Path(f"{copy}{suffix}"))
48
+ with sqlite3.connect(copy) as con:
49
+ return [tuple(r) for r in con.execute(query)]
50
+ except (sqlite3.Error, OSError) as exc:
51
+ logger.warning("could not read Better BibTeX keys from %s: %s", path, exc)
52
+ return []
53
+
54
+
55
+ class BetterBibTexKeys:
56
+ """Item key <-> citation key, from one ``better-bibtex.sqlite``.
57
+
58
+ The table is one row per item, so it is read whole and kept in memory;
59
+ it is read again when the file's size or modification time changes.
60
+ """
61
+
62
+ def __init__(self, path: str | os.PathLike[str]) -> None:
63
+ self.path = Path(path)
64
+ self._stamp: tuple[int, int] | None = None
65
+ self._by_item: dict[str, str] = {}
66
+ self._by_key: dict[str, list[str]] = {}
67
+ self._lock = threading.Lock()
68
+
69
+ @classmethod
70
+ def discover(cls, zotero_db_path: str | os.PathLike[str] | None = None) -> BetterBibTexKeys | None:
71
+ """The database named by ``ZOTERO_BBT_DB``, else the one beside ``zotero.sqlite``.
72
+
73
+ Returns None when there is none, which is the normal state for
74
+ anyone who does not use Better BibTeX.
75
+ """
76
+ env = os.getenv("ZOTERO_BBT_DB")
77
+ if env:
78
+ path = Path(env).expanduser()
79
+ return cls(path) if path.is_file() else None
80
+ if zotero_db_path:
81
+ beside = Path(zotero_db_path).expanduser().with_name(_FILENAME)
82
+ if beside.is_file():
83
+ return cls(beside)
84
+ return None
85
+
86
+ def _refresh(self) -> None:
87
+ try:
88
+ st = self.path.stat()
89
+ except OSError:
90
+ return
91
+ stamp = (st.st_mtime_ns, st.st_size)
92
+ with self._lock:
93
+ if stamp == self._stamp:
94
+ return
95
+ by_item: dict[str, str] = {}
96
+ by_key: dict[str, list[str]] = {}
97
+ for item_key, _library, citekey in _read_rows(self.path):
98
+ if not citekey:
99
+ continue
100
+ by_item[item_key] = citekey
101
+ by_key.setdefault(citekey, []).append(item_key)
102
+ self._by_item, self._by_key, self._stamp = by_item, by_key, stamp
103
+
104
+ def citekeys_for(self, item_keys: list[str]) -> dict[str, str]:
105
+ """Citation key for each item key that has one; the rest are left out."""
106
+ self._refresh()
107
+ return {k: self._by_item[k] for k in item_keys if k in self._by_item}
108
+
109
+ def item_keys_for(self, citekey: str) -> list[str]:
110
+ """Item keys carrying ``citekey``, personal library first.
111
+
112
+ Better BibTeX keeps keys unique within a library, not across them, so
113
+ a key shared by two libraries gives two item keys.
114
+ """
115
+ self._refresh()
116
+ return list(self._by_key.get(citekey, []))