lightkone 0.1.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.
@@ -0,0 +1,7 @@
1
+ node_modules/
2
+ dist/
3
+ .DS_Store
4
+ .wrangler/
5
+ __pycache__/
6
+ *.egg-info/
7
+ .pytest_cache/
@@ -0,0 +1,73 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+
41
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42
+
43
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60
+
61
+ Copyright [yyyy] [name of copyright owner]
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.
lightkone-0.1.0/NOTICE ADDED
@@ -0,0 +1,27 @@
1
+ Lightkone CLI
2
+ Copyright 2026 the Lightkone authors
3
+
4
+ Licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ Parts of this package come from Kirsche (https://github.com/kausalflow/kirsche),
7
+ released under the MIT License:
8
+
9
+ Copyright (c) 2021 Lei Ma
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
@@ -0,0 +1,81 @@
1
+ Metadata-Version: 2.5
2
+ Name: lightkone
3
+ Version: 0.1.0
4
+ Summary: Lightkone from the command line and from Python: your papers, tags, folders, notes, BibTeX and citation map, in the same files as the web app.
5
+ Project-URL: Homepage, https://lightkone.lab.kausalflow.com
6
+ Project-URL: Documentation, https://lightkone.lab.kausalflow.com/docs/cli.html
7
+ Author: KausalFlow
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ License-File: NOTICE
11
+ Keywords: bibtex,citations,lightkone,papers,references,research
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Scientific/Engineering
16
+ Requires-Python: >=3.10
17
+ Requires-Dist: click>=8.1.7
18
+ Requires-Dist: requests>=2.26
19
+ Requires-Dist: typer>=0.12
20
+ Provides-Extra: all
21
+ Requires-Dist: cryptography>=41; extra == 'all'
22
+ Requires-Dist: networkx>=3.0; extra == 'all'
23
+ Requires-Dist: pandas>=2.0; extra == 'all'
24
+ Provides-Extra: crypto
25
+ Requires-Dist: cryptography>=41; extra == 'crypto'
26
+ Provides-Extra: data
27
+ Requires-Dist: pandas>=2.0; extra == 'data'
28
+ Provides-Extra: dev
29
+ Requires-Dist: cryptography>=41; extra == 'dev'
30
+ Requires-Dist: networkx>=3.0; extra == 'dev'
31
+ Requires-Dist: pandas>=2.0; extra == 'dev'
32
+ Requires-Dist: pytest>=8; extra == 'dev'
33
+ Provides-Extra: graph
34
+ Requires-Dist: networkx>=3.0; extra == 'graph'
35
+ Description-Content-Type: text/markdown
36
+
37
+ # Lightkone CLI
38
+
39
+ The command line and Python package for [Lightkone](https://lightkone.lab.kausalflow.com),
40
+ the web reference manager. It works on the same library as the web app: the
41
+ plain files in your Cloudflare R2 / S3 bucket, your GitHub repository, or a
42
+ folder on disk. Search, add, tag, file, annotate, export BibTeX and draw the
43
+ citation map from the terminal, a script or a notebook.
44
+
45
+ ```bash
46
+ pipx install lightkone # or: pip install lightkone
47
+ lightkone login --from-backup lightkone-settings.json # Lightkone: Settings → Backup → Export settings
48
+ lightkone ls author:hinton year:2010-2015
49
+ lightkone add 2106.09685 10.1103/PhysRevLett.116.061102 -t lensing -f Physics/GR
50
+ lightkone export in:Thesis -o thesis.bib
51
+ lightkone map in:Thesis --open # which of your papers cite which
52
+ lightkone open Hinton2012-in -p 3 # read it in the web app, at page 3
53
+ ```
54
+
55
+ Extras: `lightkone[data]` (pandas DataFrames), `lightkone[graph]` (networkx,
56
+ GraphML and GEXF), `lightkone[crypto]` (encrypted settings backups), or
57
+ `lightkone[all]`.
58
+
59
+ The full guide is at <https://lightkone.lab.kausalflow.com/docs/cli.html>
60
+ (`docs/CLI.md` in the repository).
61
+
62
+ ## Working on it
63
+
64
+ ```bash
65
+ cd cli
66
+ pip install -e ".[dev]"
67
+ pytest
68
+ ```
69
+
70
+ `tests/data/golden.json` holds what Lightkone's TypeScript code produces for
71
+ the same inputs (BibTeX parsing, citation keys, `library.json` and
72
+ `library.bib` text, search, merging, filing, the citation graph). It is
73
+ written by `tests/cli-golden.test.ts` in the app's tests, and `npm run check`
74
+ fails when the app's output no longer matches it. After changing one of those
75
+ formats in the app, run `UPDATE_GOLDEN=1 npx vitest run tests/cli-golden.test.ts`
76
+ and make the Python side pass `pytest` again.
77
+
78
+ ## License
79
+
80
+ Apache-2.0 (see the `LICENSE` and `NOTICE` files that come with it). The Lightkone web
81
+ app in the rest of this repository is under AGPL-3.0.
@@ -0,0 +1,45 @@
1
+ # Lightkone CLI
2
+
3
+ The command line and Python package for [Lightkone](https://lightkone.lab.kausalflow.com),
4
+ the web reference manager. It works on the same library as the web app: the
5
+ plain files in your Cloudflare R2 / S3 bucket, your GitHub repository, or a
6
+ folder on disk. Search, add, tag, file, annotate, export BibTeX and draw the
7
+ citation map from the terminal, a script or a notebook.
8
+
9
+ ```bash
10
+ pipx install lightkone # or: pip install lightkone
11
+ lightkone login --from-backup lightkone-settings.json # Lightkone: Settings → Backup → Export settings
12
+ lightkone ls author:hinton year:2010-2015
13
+ lightkone add 2106.09685 10.1103/PhysRevLett.116.061102 -t lensing -f Physics/GR
14
+ lightkone export in:Thesis -o thesis.bib
15
+ lightkone map in:Thesis --open # which of your papers cite which
16
+ lightkone open Hinton2012-in -p 3 # read it in the web app, at page 3
17
+ ```
18
+
19
+ Extras: `lightkone[data]` (pandas DataFrames), `lightkone[graph]` (networkx,
20
+ GraphML and GEXF), `lightkone[crypto]` (encrypted settings backups), or
21
+ `lightkone[all]`.
22
+
23
+ The full guide is at <https://lightkone.lab.kausalflow.com/docs/cli.html>
24
+ (`docs/CLI.md` in the repository).
25
+
26
+ ## Working on it
27
+
28
+ ```bash
29
+ cd cli
30
+ pip install -e ".[dev]"
31
+ pytest
32
+ ```
33
+
34
+ `tests/data/golden.json` holds what Lightkone's TypeScript code produces for
35
+ the same inputs (BibTeX parsing, citation keys, `library.json` and
36
+ `library.bib` text, search, merging, filing, the citation graph). It is
37
+ written by `tests/cli-golden.test.ts` in the app's tests, and `npm run check`
38
+ fails when the app's output no longer matches it. After changing one of those
39
+ formats in the app, run `UPDATE_GOLDEN=1 npx vitest run tests/cli-golden.test.ts`
40
+ and make the Python side pass `pytest` again.
41
+
42
+ ## License
43
+
44
+ Apache-2.0 (see the `LICENSE` and `NOTICE` files that come with it). The Lightkone web
45
+ app in the rest of this repository is under AGPL-3.0.
@@ -0,0 +1,23 @@
1
+ """Read and write a Lightkone library from Python: the same files the web app keeps in your storage."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from lightkone.library import BIB_PATH, LIBRARY_PATH, Library
6
+ from lightkone.storage import (
7
+ FolderStorage,
8
+ GitHubStorage,
9
+ S3Storage,
10
+ Storage,
11
+ StorageError,
12
+ )
13
+
14
+ __all__ = [
15
+ "Library",
16
+ "Storage",
17
+ "FolderStorage",
18
+ "S3Storage",
19
+ "GitHubStorage",
20
+ "StorageError",
21
+ "LIBRARY_PATH",
22
+ "BIB_PATH",
23
+ ]
@@ -0,0 +1,376 @@
1
+ """BibTeX reading and writing, the same way Lightkone does it.
2
+
3
+ A forgiving reader (braces, quotes, nested braces, numbers, ``@string``
4
+ macros, month names and ``#`` concatenation) and the plain writer Lightkone
5
+ uses for ``lightkone/library.bib``. Kept in step with Lightkone's
6
+ ``src/core/bibtex.ts`` so a library saved by either tool reads the same.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ import unicodedata
13
+ from dataclasses import dataclass, field
14
+ from typing import Any
15
+
16
+ MONTHS = {
17
+ "jan": "January",
18
+ "feb": "February",
19
+ "mar": "March",
20
+ "apr": "April",
21
+ "may": "May",
22
+ "jun": "June",
23
+ "jul": "July",
24
+ "aug": "August",
25
+ "sep": "September",
26
+ "oct": "October",
27
+ "nov": "November",
28
+ "dec": "December",
29
+ }
30
+
31
+
32
+ @dataclass
33
+ class BibEntry:
34
+ type: str
35
+ key: str
36
+ fields: dict[str, str] = field(default_factory=dict)
37
+
38
+
39
+ _WORD_STOP = set(' \t\r\n,={}()"#')
40
+
41
+
42
+ def parse_bibtex(text: str) -> list[BibEntry]:
43
+ """Every entry in a BibTeX text, with lower-cased field names and raw values."""
44
+ entries: list[BibEntry] = []
45
+ macros = dict(MONTHS)
46
+ n = len(text)
47
+ i = 0
48
+
49
+ def skip_space() -> None:
50
+ nonlocal i
51
+ while i < n and text[i].isspace():
52
+ i += 1
53
+
54
+ def read_word() -> str:
55
+ nonlocal i
56
+ start = i
57
+ while i < n and text[i] not in _WORD_STOP and not text[i].isspace():
58
+ i += 1
59
+ return text[start:i]
60
+
61
+ def read_braced() -> str:
62
+ nonlocal i
63
+ depth = 0
64
+ start = i + 1
65
+ while i < n:
66
+ c = text[i]
67
+ if c == "\\":
68
+ i += 2
69
+ continue
70
+ if c == "{":
71
+ depth += 1
72
+ elif c == "}":
73
+ depth -= 1
74
+ if depth == 0:
75
+ i += 1
76
+ return text[start : i - 1]
77
+ i += 1
78
+ return text[start:]
79
+
80
+ def read_quoted() -> str:
81
+ nonlocal i
82
+ depth = 0
83
+ i += 1
84
+ start = i
85
+ while i < n:
86
+ c = text[i]
87
+ if c == "\\":
88
+ i += 2
89
+ continue
90
+ if c == "{":
91
+ depth += 1
92
+ elif c == "}":
93
+ depth -= 1
94
+ elif c == '"' and depth == 0:
95
+ i += 1
96
+ return text[start : i - 1]
97
+ i += 1
98
+ return text[start:]
99
+
100
+ def read_value() -> str:
101
+ nonlocal i
102
+ parts: list[str] = []
103
+ while True:
104
+ skip_space()
105
+ c = text[i] if i < n else ""
106
+ if c == "{":
107
+ parts.append(read_braced())
108
+ elif c == '"':
109
+ parts.append(read_quoted())
110
+ else:
111
+ w = read_word()
112
+ if not w:
113
+ break
114
+ parts.append(w if w.isdigit() else macros.get(w.lower(), w))
115
+ skip_space()
116
+ if i < n and text[i] == "#":
117
+ i += 1
118
+ continue
119
+ break
120
+ return "".join(parts)
121
+
122
+ while i < n:
123
+ at = text.find("@", i)
124
+ if at < 0:
125
+ break
126
+ i = at + 1
127
+ typ = read_word().lower()
128
+ skip_space()
129
+ opening = text[i] if i < n else ""
130
+ if opening not in ("{", "("):
131
+ continue
132
+ close = "}" if opening == "{" else ")"
133
+ i += 1
134
+ if typ == "comment":
135
+ i = at + 1
136
+ continue
137
+ if typ == "preamble":
138
+ read_value()
139
+ continue
140
+ if typ == "string":
141
+ skip_space()
142
+ name = read_word().lower()
143
+ skip_space()
144
+ if i < n and text[i] == "=":
145
+ i += 1
146
+ macros[name] = read_value()
147
+ continue
148
+ skip_space()
149
+ key_start = i
150
+ depth = 0
151
+ # Braces in a key ("Erd\H{o}s1959") are part of it, not the end of the entry.
152
+ while i < n and (depth > 0 or (text[i] != "," and text[i] != close)):
153
+ if text[i] == "{":
154
+ depth += 1
155
+ elif text[i] == "}":
156
+ depth -= 1
157
+ i += 1
158
+ key = text[key_start:i].strip()
159
+ fields: dict[str, str] = {}
160
+ while i < n and text[i] != close:
161
+ if text[i] == ",":
162
+ i += 1
163
+ skip_space()
164
+ if i >= n or text[i] == close:
165
+ break
166
+ name = read_word().lower()
167
+ skip_space()
168
+ if not name or i >= n or text[i] != "=":
169
+ # Malformed field: skip its values, then to the next comma or the end of the entry.
170
+ while i < n and text[i] != "," and text[i] != close:
171
+ if text[i] == "{":
172
+ read_braced()
173
+ elif text[i] == '"':
174
+ read_quoted()
175
+ else:
176
+ i += 1
177
+ continue
178
+ i += 1
179
+ fields[name] = re.sub(r"\s+", " ", read_value()).strip()
180
+ skip_space()
181
+ i += 1
182
+ if key or fields:
183
+ entries.append(BibEntry(typ, key, fields))
184
+ return entries
185
+
186
+
187
+ _ACCENTS = {
188
+ '"': "\u0308",
189
+ "'": "\u0301",
190
+ "`": "\u0300",
191
+ "^": "\u0302",
192
+ "~": "\u0303",
193
+ "=": "\u0304",
194
+ ".": "\u0307",
195
+ "c": "\u0327",
196
+ "v": "\u030c",
197
+ "u": "\u0306",
198
+ "H": "\u030b",
199
+ }
200
+ _LETTERS = {
201
+ "ss": "ß",
202
+ "o": "ø",
203
+ "O": "Ø",
204
+ "ae": "æ",
205
+ "AE": "Æ",
206
+ "l": "ł",
207
+ "L": "Ł",
208
+ "i": "ı",
209
+ }
210
+
211
+ _ACCENT_RE = re.compile(
212
+ r"\{?\\([\"'`^~=.]|[cvuH](?=[\s{]))\s*\{?([A-Za-z]|\\[ij]\b)\}?\}?"
213
+ )
214
+ _LETTER_RE = re.compile(r"\{\\(ss|o|O|ae|AE|l|L|i)\}|\\(ss|o|O|ae|AE|l|L|i)\b ?")
215
+
216
+
217
+ def plain(value: str) -> str:
218
+ """Remove protective braces and the most common LaTeX escapes, for display and search."""
219
+ v = _ACCENT_RE.sub(
220
+ lambda m: unicodedata.normalize(
221
+ "NFC", m.group(2).replace("\\", "") + _ACCENTS[m.group(1)]
222
+ ),
223
+ value,
224
+ )
225
+ v = _LETTER_RE.sub(lambda m: _LETTERS[m.group(1) or m.group(2)], v)
226
+ v = re.sub(r"\\(?:emph|textit|textbf|mathrm|textrm)\{([^{}]*)\}", r"\1", v)
227
+ v = re.sub(r"\\([&%$#_{}])", r"\1", v)
228
+ v = re.sub(r"(?<!\\)[{}]", "", v)
229
+ v = v.replace("~", " ")
230
+ return re.sub(r"\s+", " ", v).strip()
231
+
232
+
233
+ _ARXIV_IN_URL = re.compile(
234
+ r"arxiv\.org/(?:abs|pdf|html)/([^\s?#]+?)(?:v\d+)?(?:\.pdf)?(?:[?#]|$)", re.I
235
+ )
236
+ _ID_KEYWORD = re.compile(r"^(doi|url|arxiv|isbn|issn|pmid|pmc):|https?://", re.I)
237
+
238
+
239
+ def split_authors(value: str) -> list[str]:
240
+ """BibTeX ``author`` field to "Last, First" strings."""
241
+ if not value.strip():
242
+ return []
243
+ out = []
244
+ for raw in re.split(r"\s+and\s+", value, flags=re.I):
245
+ raw = raw.strip()
246
+ a = plain(raw)
247
+ if not a:
248
+ continue
249
+ # "{LIGO Scientific Collaboration}" is a corporate name: never flip it.
250
+ if "," in a or a.lower() == "others" or re.match(r"^\{.*\}$", raw, re.S):
251
+ out.append(a)
252
+ continue
253
+ parts = a.split(" ")
254
+ out.append(f"{parts[-1]}, {' '.join(parts[:-1])}" if len(parts) > 1 else a)
255
+ return out
256
+
257
+
258
+ def entry_to_draft(entry: BibEntry) -> dict[str, Any]:
259
+ """A BibTeX entry as a paper draft (a paper without id and added date)."""
260
+ f = dict(entry.fields)
261
+
262
+ def take(name: str) -> str | None:
263
+ return f.pop(name, None)
264
+
265
+ title = plain(take("title") or "")
266
+ author = take("author")
267
+ editor = take("editor")
268
+ authors = split_authors(author if author is not None else (editor or ""))
269
+ year_raw = take("year")
270
+ m = re.search(r"\d{4}", year_raw or "")
271
+ year = int(m.group(0)) if m else None
272
+ journal = take("journal")
273
+ booktitle = take("booktitle")
274
+ venue = (
275
+ plain(journal or "")
276
+ or plain(booktitle or "")
277
+ or plain(f.get("publisher") or "")
278
+ )
279
+ abstract = take("abstract")
280
+ doi = take("doi")
281
+ if doi:
282
+ doi = re.sub(r"^https?://(dx\.)?doi\.org/", "", doi, flags=re.I)
283
+ url = take("url")
284
+ eprint = take("eprint")
285
+ arxivid = take("arxivid")
286
+ prefix = (f.get("archiveprefix") or f.get("eprinttype") or "").lower()
287
+ arxiv = arxivid or (eprint if prefix == "arxiv" else None)
288
+ if not arxiv and url:
289
+ mm = _ARXIV_IN_URL.search(url)
290
+ arxiv = mm.group(1) if mm else None
291
+ if not arxiv and eprint and re.match(r"^\d{4}\.\d{4,5}", eprint):
292
+ arxiv = eprint
293
+ if arxiv:
294
+ for k in ("archiveprefix", "eprinttype", "primaryclass"):
295
+ f.pop(k, None)
296
+ elif eprint:
297
+ f["eprint"] = eprint
298
+ tags = [plain(t) for t in re.split(r"[;,]", take("keywords") or "")]
299
+ tags = [t for t in tags if t and not _ID_KEYWORD.search(t)]
300
+ file = take("file")
301
+ annote = take("annote")
302
+ note = take("note")
303
+ notes = annote if annote is not None else note
304
+ draft: dict[str, Any] = {
305
+ "key": entry.key,
306
+ "type": entry.type,
307
+ "title": title,
308
+ "authors": authors,
309
+ "year": year,
310
+ "venue": venue or None,
311
+ "abstract": plain(abstract) if abstract else None,
312
+ "doi": doi or None,
313
+ "arxiv": (
314
+ re.sub(r"v\d+$", "", re.sub(r"^arxiv:", "", arxiv, flags=re.I))
315
+ if arxiv
316
+ else None
317
+ ),
318
+ "url": url,
319
+ "tags": tags,
320
+ "file": file,
321
+ "notes": notes,
322
+ "fields": f,
323
+ }
324
+ return {k: v for k, v in draft.items() if v is not None}
325
+
326
+
327
+ def parse_bibtex_to_drafts(text: str) -> list[dict[str, Any]]:
328
+ return [entry_to_draft(e) for e in parse_bibtex(text) if e.fields.get("title")]
329
+
330
+
331
+ def _escape(v: str) -> str:
332
+ return re.sub(r"\\?([&%#])", r"\\\1", v)
333
+
334
+
335
+ def paper_to_bibtex(p: dict[str, Any]) -> str:
336
+ """One paper as BibTeX, exactly as Lightkone writes it."""
337
+ lines: list[tuple[str, str]] = []
338
+
339
+ def add(name: str, value: Any) -> None:
340
+ if value is not None and value != "":
341
+ lines.append((name, str(value)))
342
+
343
+ add("title", "{" + _escape(p.get("title", "")) + "}")
344
+ add(
345
+ "author",
346
+ " and ".join(
347
+ a if ("," in a or a == "others") else "{" + a + "}"
348
+ for a in p.get("authors", [])
349
+ ),
350
+ )
351
+ add("year", p.get("year"))
352
+ fields = p.get("fields") or {}
353
+ venue_field = (
354
+ "booktitle" if p.get("type") in ("inproceedings", "incollection") else "journal"
355
+ )
356
+ if p.get("venue") and not fields.get(venue_field):
357
+ add(venue_field, _escape(p["venue"]))
358
+ add("doi", p.get("doi"))
359
+ if p.get("arxiv"):
360
+ add("eprint", p["arxiv"])
361
+ add("archiveprefix", "arXiv")
362
+ add("url", p.get("url"))
363
+ add("abstract", _escape(p["abstract"]) if p.get("abstract") else None)
364
+ if p.get("tags"):
365
+ add("keywords", ";".join(p["tags"]))
366
+ add("file", p.get("file"))
367
+ for k, v in fields.items():
368
+ if not k.startswith("lightkone-"):
369
+ add(k, v)
370
+ width = max(len(k) for k, _ in lines)
371
+ body = ",\n".join(f" {k.ljust(width)} = {{{v}}}" for k, v in lines)
372
+ return f"@{p.get('type') or 'misc'}{{{p['key']},\n{body}\n}}\n"
373
+
374
+
375
+ def library_to_bibtex(papers: list[dict[str, Any]]) -> str:
376
+ return "\n".join(paper_to_bibtex(p) for p in papers)