conjugo 0.2.1__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.
- conj/__init__.py +15 -0
- conj/build.py +546 -0
- conj/cli.py +101 -0
- conj/compound.py +415 -0
- conj/db.py +202 -0
- conj/langs/__init__.py +12 -0
- conj/langs/base.py +72 -0
- conj/langs/de.py +55 -0
- conj/langs/en.py +63 -0
- conj/langs/es.py +57 -0
- conj/langs/fr.py +51 -0
- conj/langs/it.py +49 -0
- conj/langs/pt.py +63 -0
- conj/langs/ru.py +42 -0
- conj/link.py +36 -0
- conj/normalize.py +89 -0
- conj/pronominal.py +188 -0
- conj/render.py +126 -0
- conj/search.py +127 -0
- conj/tags.py +121 -0
- conj/tui/__init__.py +0 -0
- conj/tui/app.py +523 -0
- conj/tui/app.tcss +111 -0
- conj/tui/layout.py +131 -0
- conj/tui/widgets.py +101 -0
- conjugo-0.2.1.dist-info/METADATA +285 -0
- conjugo-0.2.1.dist-info/RECORD +31 -0
- conjugo-0.2.1.dist-info/WHEEL +4 -0
- conjugo-0.2.1.dist-info/entry_points.txt +4 -0
- conjugo-0.2.1.dist-info/licenses/DATA_LICENSE.md +30 -0
- conjugo-0.2.1.dist-info/licenses/LICENSE +24 -0
conj/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Conjugo: verb conjugation in the terminal for French, Italian, Spanish, Portuguese, English,
|
|
2
|
+
German and Russian.
|
|
3
|
+
|
|
4
|
+
The command is `conj`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
__version__ = version("conjugo") # PyPI name; the one source is pyproject.toml (uv version --bump)
|
|
11
|
+
except PackageNotFoundError: # running from a source tree that was never installed
|
|
12
|
+
__version__ = "0+unknown"
|
|
13
|
+
NAME = "Conjugo"
|
|
14
|
+
AUTHOR = "Guilherme D. Garcia"
|
|
15
|
+
WEBSITE = "gdgarcia.ca"
|
conj/build.py
ADDED
|
@@ -0,0 +1,546 @@
|
|
|
1
|
+
"""Build the conjugation database from Wiktextract (kaikki.org) verb dumps.
|
|
2
|
+
|
|
3
|
+
Usage: uv run python -m conj.build [--src DIR] [--refresh]
|
|
4
|
+
|
|
5
|
+
Data: Wiktionary contributors, extracted by Wiktextract (Ylonen 2022),
|
|
6
|
+
CC BY-SA 4.0. See DATA_LICENSE.md.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import datetime as dt
|
|
13
|
+
import gzip
|
|
14
|
+
import hashlib
|
|
15
|
+
import json
|
|
16
|
+
import math
|
|
17
|
+
import re
|
|
18
|
+
import shutil
|
|
19
|
+
import sqlite3
|
|
20
|
+
import sys
|
|
21
|
+
import urllib.request
|
|
22
|
+
import zlib
|
|
23
|
+
from collections.abc import Iterator
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
from .langs.base import (
|
|
27
|
+
ASPECT, FINITE, IMP, IND_FUT, IND_PRS, IND_PST, INF, META, NONFINITE, PARTNERS, PERSONS, PTCP_PRS,
|
|
28
|
+
PTCP_PST, SBJV_IPFV, SBJV_PRS, SEARCH_ONLY,
|
|
29
|
+
)
|
|
30
|
+
from .normalize import fold, it_orthography, ru_orthography
|
|
31
|
+
from .tags import cells
|
|
32
|
+
|
|
33
|
+
KAIKKI = "https://kaikki.org/dictionary/{name}/pos-verb/kaikki.org-dictionary-{name}-by-pos-verb.jsonl"
|
|
34
|
+
SOURCES = {"fr": "French", "it": "Italian", "en": "English", "es": "Spanish", "pt": "Portuguese",
|
|
35
|
+
"de": "German", "ru": "Russian"}
|
|
36
|
+
OUT = Path(__file__).parent / "data" / "conj.sqlite.gz"
|
|
37
|
+
|
|
38
|
+
Paradigm = dict[str, dict[str, list[str]] | list[str]]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# ---------------------------------------------------------------- download
|
|
42
|
+
def download(lang: str, src: Path, refresh: bool) -> Path:
|
|
43
|
+
name = SOURCES[lang]
|
|
44
|
+
path = src / f"{name}.jsonl"
|
|
45
|
+
if path.exists() and not refresh:
|
|
46
|
+
return path
|
|
47
|
+
src.mkdir(parents=True, exist_ok=True)
|
|
48
|
+
url = KAIKKI.format(name=name)
|
|
49
|
+
print(f"downloading {url}", file=sys.stderr)
|
|
50
|
+
# kaikki serves the dumps gzip-encoded on request: ~10x smaller to download.
|
|
51
|
+
req = urllib.request.Request(url, headers={"User-Agent": "conj-build/0.1", "Accept-Encoding": "gzip"})
|
|
52
|
+
tmp = path.with_suffix(".part")
|
|
53
|
+
with urllib.request.urlopen(req) as resp, open(tmp, "wb") as fh:
|
|
54
|
+
body = gzip.GzipFile(fileobj=resp) if resp.headers.get("Content-Encoding") == "gzip" else resp
|
|
55
|
+
shutil.copyfileobj(body, fh, length=1 << 20)
|
|
56
|
+
tmp.rename(path)
|
|
57
|
+
return path
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def entries(path: Path) -> Iterator[dict]:
|
|
61
|
+
with open(path, encoding="utf-8") as fh:
|
|
62
|
+
for line in fh:
|
|
63
|
+
entry = json.loads(line)
|
|
64
|
+
if entry.get("pos") == "verb":
|
|
65
|
+
yield entry
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# ---------------------------------------------------------------- glosses
|
|
69
|
+
_PAREN = re.compile(r"\([^)]*\)|\[[^\]]*\]|\{[^}]*\}")
|
|
70
|
+
# Senses that are not a current, general meaning of the verb. Dropped unless
|
|
71
|
+
# nothing else is left (estudar: "alternative form of estuprar", an Internet euphemism).
|
|
72
|
+
SENSE_NOISE = frozenset({
|
|
73
|
+
"alt-of", "obsolete", "archaic", "dialectal", "rare", "Internet", "misspelling",
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def glosses(entry: dict, want: str | None = None) -> list[str]:
|
|
78
|
+
"""Sense glosses, skipping inflected-form senses. `want` filters by sense tag."""
|
|
79
|
+
main, fallback = [], []
|
|
80
|
+
for sense in entry.get("senses", []):
|
|
81
|
+
tags = sense.get("tags", [])
|
|
82
|
+
if "form-of" in tags or sense.get("form_of"):
|
|
83
|
+
continue
|
|
84
|
+
if want and want not in tags:
|
|
85
|
+
continue
|
|
86
|
+
g = sense.get("glosses")
|
|
87
|
+
if not g:
|
|
88
|
+
continue
|
|
89
|
+
noisy = sense.get("alt_of") or SENSE_NOISE.intersection(tags)
|
|
90
|
+
bucket = fallback if noisy else main
|
|
91
|
+
if g[-1] not in bucket:
|
|
92
|
+
bucket.append(g[-1])
|
|
93
|
+
return main or fallback
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# ---------------------------------------------------------------- paradigms
|
|
97
|
+
def add(par: Paradigm, key: str, persons: tuple[str, ...], form: str) -> None:
|
|
98
|
+
if key in NONFINITE or key == SEARCH_ONLY:
|
|
99
|
+
bucket = par.setdefault(key, [])
|
|
100
|
+
if form not in bucket:
|
|
101
|
+
bucket.append(form)
|
|
102
|
+
return
|
|
103
|
+
table = par.setdefault(key, {})
|
|
104
|
+
for p in persons:
|
|
105
|
+
bucket = table.setdefault(p, [])
|
|
106
|
+
if form not in bucket:
|
|
107
|
+
bucket.append(form)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def merge(into: Paradigm, other: Paradigm) -> None:
|
|
111
|
+
"""Fill cells of `into` that are missing, from `other`."""
|
|
112
|
+
for key, val in other.items():
|
|
113
|
+
if key not in into:
|
|
114
|
+
into[key] = val
|
|
115
|
+
elif isinstance(val, dict):
|
|
116
|
+
for p, forms in val.items():
|
|
117
|
+
into[key].setdefault(p, forms)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _clean(form: str, lang: str) -> str | None:
|
|
121
|
+
form = form.strip()
|
|
122
|
+
if not form or form in {"-", "—", "–"} or form.startswith("'"):
|
|
123
|
+
return None
|
|
124
|
+
if any("\u0250" <= ch <= "\u02af" for ch in form): # IPA leaked into a cell (paʁl)
|
|
125
|
+
return None
|
|
126
|
+
if lang == "it":
|
|
127
|
+
return it_orthography(form)
|
|
128
|
+
if lang == "ru":
|
|
129
|
+
if re.search(r"[A-Za-z]", form): # untagged transliteration (jestʹ, govoríl)
|
|
130
|
+
return None
|
|
131
|
+
return ru_orthography(form)
|
|
132
|
+
return form
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _aux_fr(text: str) -> list[str]:
|
|
136
|
+
"""'avoir + past participle' -> ['avoir']; 'avoir or être + ...' -> both, in order."""
|
|
137
|
+
head = text.split(" + ")[0]
|
|
138
|
+
found = [(m.start(), m.group()) for m in re.finditer(r"\b(avoir|être)\b", head)]
|
|
139
|
+
return [aux for _, aux in sorted(found)]
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# Être-verbs that take avoir when transitive (il est monté / il a monté l'escalier).
|
|
143
|
+
FR_DUAL_AUX = {
|
|
144
|
+
"monter", "descendre", "sortir", "rentrer", "retourner", "passer", "remonter",
|
|
145
|
+
"redescendre", "ressortir", "repasser", "demeurer", "accourir", "apparaître",
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
# Spanish and Portuguese form every compound tense with one auxiliary.
|
|
150
|
+
ROMANCE_AUX = {"es": "haber", "pt": "ter"}
|
|
151
|
+
DE_AUX = ("haben", "sein")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _aux_de(text: str) -> list[str]:
|
|
155
|
+
"""'haben or sein' -> ['sein', 'haben']: sein first for dual-auxiliary verbs.
|
|
156
|
+
|
|
157
|
+
Verbs listed with both (aufstehen, fahren) take sein when intransitive, the
|
|
158
|
+
reading learners need first (ich bin aufgestanden); `a` switches to haben.
|
|
159
|
+
"""
|
|
160
|
+
found = [a for a in DE_AUX if re.search(rf"\b{a}\b", text)]
|
|
161
|
+
return sorted(found, key=lambda a: a != "sein") if len(found) > 1 else found
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def romance_records(entry: dict, lang: str) -> list[dict]:
|
|
165
|
+
"""One record per paradigm in the entry.
|
|
166
|
+
|
|
167
|
+
An entry can hold several conjugation tables: French adds pronominal ones
|
|
168
|
+
(se laver, s'en aller), Italian adds variant ones for the same verb. Each
|
|
169
|
+
table is keyed by its own infinitive; tables sharing an infinitive merge.
|
|
170
|
+
"""
|
|
171
|
+
rows = [f for f in entry.get("forms", []) if f.get("source") == "conjugation"]
|
|
172
|
+
if not rows:
|
|
173
|
+
return []
|
|
174
|
+
tables: list[dict] = []
|
|
175
|
+
for row in rows:
|
|
176
|
+
tags = row.get("tags", [])
|
|
177
|
+
if "table-tags" in tags or not tables:
|
|
178
|
+
tables.append({"par": {}, "aux": [], "lemma": None, "refl": False})
|
|
179
|
+
rec = tables[-1]
|
|
180
|
+
rec["refl"] |= "reflexive" in tags
|
|
181
|
+
form = row.get("form", "")
|
|
182
|
+
if "auxiliary" in tags and lang == "it":
|
|
183
|
+
aux = fold(form)
|
|
184
|
+
if aux not in rec["aux"]:
|
|
185
|
+
rec["aux"].append(aux)
|
|
186
|
+
continue
|
|
187
|
+
if "auxiliary" in tags and lang == "de":
|
|
188
|
+
for aux in _aux_de(form):
|
|
189
|
+
if aux not in rec["aux"]:
|
|
190
|
+
rec["aux"].append(aux)
|
|
191
|
+
continue
|
|
192
|
+
if lang == "de" and "subordinate-clause" in tags:
|
|
193
|
+
# Separable verbs: "aufstehe" for the table's "stehe auf". Searchable, not shown.
|
|
194
|
+
cell = cells([t for t in tags if t != "subordinate-clause"], lang)
|
|
195
|
+
form = _clean(form, lang)
|
|
196
|
+
if cell and form:
|
|
197
|
+
add(rec["par"], SEARCH_ONLY, (), form)
|
|
198
|
+
continue
|
|
199
|
+
if lang == "fr" and "infinitive" in tags and "multiword-construction" in tags:
|
|
200
|
+
rec["aux"] = _aux_fr(form)
|
|
201
|
+
continue
|
|
202
|
+
cell = cells(tags, lang)
|
|
203
|
+
if cell is None:
|
|
204
|
+
continue
|
|
205
|
+
form = _clean(form, lang)
|
|
206
|
+
if form is None:
|
|
207
|
+
continue
|
|
208
|
+
if cell[0] == INF and rec["lemma"] is None:
|
|
209
|
+
rec["lemma"] = form
|
|
210
|
+
add(rec["par"], *cell, form)
|
|
211
|
+
|
|
212
|
+
word = entry["word"]
|
|
213
|
+
merged: dict[str, dict] = {}
|
|
214
|
+
for rec in tables:
|
|
215
|
+
if not rec["par"]:
|
|
216
|
+
continue
|
|
217
|
+
lemma = rec["lemma"] or word
|
|
218
|
+
pronominal = lemma != word and (rec["refl"] or lemma.startswith(("se ", "s'")) or lang == "it")
|
|
219
|
+
if lemma != word and not pronominal:
|
|
220
|
+
lemma = word # spelling variant of the same infinitive
|
|
221
|
+
have = merged.get(lemma)
|
|
222
|
+
if have:
|
|
223
|
+
merge(have["par"], rec["par"])
|
|
224
|
+
have["aux"] += [a for a in rec["aux"] if a not in have["aux"]]
|
|
225
|
+
continue
|
|
226
|
+
if lemma == word:
|
|
227
|
+
gl = glosses(entry)
|
|
228
|
+
else:
|
|
229
|
+
gl = glosses(entry, "reflexive") or glosses(entry, "pronominal") or glosses(entry)
|
|
230
|
+
merged[lemma] = {"lemma": lemma, "par": rec["par"], "aux": list(rec["aux"]),
|
|
231
|
+
"glosses": gl, "table": True}
|
|
232
|
+
|
|
233
|
+
for lemma, rec in merged.items():
|
|
234
|
+
aux = [a for a in rec["aux"] if a in ("avoir", "être", "avere", "essere")]
|
|
235
|
+
if lang == "fr":
|
|
236
|
+
if lemma != word or lemma.startswith(("se ", "s'")):
|
|
237
|
+
aux = ["être"]
|
|
238
|
+
elif lemma in FR_DUAL_AUX:
|
|
239
|
+
aux = (aux or ["être"]) + [a for a in ("être", "avoir") if a not in aux]
|
|
240
|
+
aux = aux or ["avoir"]
|
|
241
|
+
elif lang in ROMANCE_AUX: # one auxiliary for every verb: haber, ter
|
|
242
|
+
aux = [ROMANCE_AUX[lang]]
|
|
243
|
+
elif lang == "de":
|
|
244
|
+
aux = [a for a in rec["aux"] if a in DE_AUX]
|
|
245
|
+
if len(aux) > 1:
|
|
246
|
+
aux = sorted(aux, key=lambda a: a != "sein")
|
|
247
|
+
aux = aux or ["haben"]
|
|
248
|
+
elif not aux and not rec["aux"]:
|
|
249
|
+
aux = ["avere"] # no auxiliary row at all; "-" means no compound tenses
|
|
250
|
+
rec["aux"] = aux
|
|
251
|
+
return list(merged.values())
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
_PERSON_TAGS = {"first-person", "second-person", "third-person"}
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def russian_record(entry: dict) -> dict | None:
|
|
258
|
+
"""One Russian verb: forms, aspect and aspect partners.
|
|
259
|
+
|
|
260
|
+
The past tense agrees in gender and number, not person: Wiktionary lists
|
|
261
|
+
masculine / feminine / neuter / plural rows. They become a person table with
|
|
262
|
+
gender marks (я говори́л(а), он говори́л / она говори́ла / оно говори́ло), and
|
|
263
|
+
the bare forms go to the search index (говори́ла finds говори́ть).
|
|
264
|
+
"""
|
|
265
|
+
rows = [f for f in entry.get("forms", []) if f.get("source") == "conjugation"]
|
|
266
|
+
if not rows:
|
|
267
|
+
return None
|
|
268
|
+
par: Paradigm = {}
|
|
269
|
+
past: dict[str, str] = {}
|
|
270
|
+
for row in rows:
|
|
271
|
+
tags = row.get("tags", [])
|
|
272
|
+
form = _clean(row.get("form", ""), "ru")
|
|
273
|
+
if form is None or "dated" in tags:
|
|
274
|
+
continue
|
|
275
|
+
if "past" in tags and "participle" not in tags and not _PERSON_TAGS & set(tags):
|
|
276
|
+
slot = "plural" if "plural" in tags else next(
|
|
277
|
+
(g for g in ("masculine", "feminine", "neuter") if g in tags), None)
|
|
278
|
+
if slot and slot not in past:
|
|
279
|
+
past[slot] = form
|
|
280
|
+
add(par, SEARCH_ONLY, (), form)
|
|
281
|
+
continue
|
|
282
|
+
cell = cells(tags, "ru")
|
|
283
|
+
if cell:
|
|
284
|
+
add(par, *cell, form)
|
|
285
|
+
if entry["word"] == "быть" and IND_PRS in par:
|
|
286
|
+
# Modern Russian: есть for every person. The table also lists the Church
|
|
287
|
+
# Slavonic set (е́смь, еси́, есмы́, е́сте, су́ть) without an archaic tag.
|
|
288
|
+
par[IND_PRS] = {p: ["есть"] for p in PERSONS}
|
|
289
|
+
m, f, n, pl = (past.get(k) for k in ("masculine", "feminine", "neuter", "plural"))
|
|
290
|
+
if m and f and pl:
|
|
291
|
+
both = f"{m}(а)" if f == m + "а" else f"{m} / {f}"
|
|
292
|
+
par[IND_PST] = {"1s": [both], "2s": [both], "3s": [" / ".join(x for x in (m, f, n) if x)],
|
|
293
|
+
"1p": [pl], "2p": [pl], "3p": [pl]}
|
|
294
|
+
if not par.get(INF):
|
|
295
|
+
return None
|
|
296
|
+
args = next((t.get("args", {}) for t in entry.get("head_templates", [])
|
|
297
|
+
if t.get("name") == "ru-verb"), {})
|
|
298
|
+
aspect = {"impf": "impf", "pf": "pf", "both": "both"}.get(args.get("2", ""), "")
|
|
299
|
+
partner_key = "pf" if aspect == "impf" else "impf" if aspect == "pf" else ""
|
|
300
|
+
partners = [p.strip() for p in args.get(partner_key, "").split(",") if p.strip()]
|
|
301
|
+
if aspect:
|
|
302
|
+
par[ASPECT] = [aspect]
|
|
303
|
+
if partners:
|
|
304
|
+
par[PARTNERS] = partners
|
|
305
|
+
return {"lemma": entry["word"], "par": par, "aux": [], "glosses": glosses(entry), "table": True}
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _en_parts(entry: dict) -> dict[str, list[str]]:
|
|
309
|
+
parts: dict[str, list[str]] = {"s3": [], "ing": [], "past": [], "pp": []}
|
|
310
|
+
for f in entry.get("forms", []):
|
|
311
|
+
if f.get("source"):
|
|
312
|
+
continue
|
|
313
|
+
tags = frozenset(f.get("tags", []))
|
|
314
|
+
if tags & {"archaic", "obsolete", "nonstandard", "dialectal", "rare", "alternative"}:
|
|
315
|
+
continue
|
|
316
|
+
form = f.get("form", "").strip()
|
|
317
|
+
if not form or form.startswith("'") or form == "-":
|
|
318
|
+
continue
|
|
319
|
+
if tags == {"present", "singular", "third-person"}:
|
|
320
|
+
slot = "s3"
|
|
321
|
+
elif tags == {"participle", "present"}:
|
|
322
|
+
slot = "ing"
|
|
323
|
+
elif tags == {"participle", "past"}:
|
|
324
|
+
slot = "pp"
|
|
325
|
+
elif tags == {"past"}:
|
|
326
|
+
slot = "past"
|
|
327
|
+
else:
|
|
328
|
+
continue
|
|
329
|
+
if form not in parts[slot]:
|
|
330
|
+
parts[slot].append(form)
|
|
331
|
+
return parts
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def english_record(entry: dict) -> dict | None:
|
|
335
|
+
gl = glosses(entry)
|
|
336
|
+
if not gl:
|
|
337
|
+
return None # only inflected-form senses ("walked: simple past of walk")
|
|
338
|
+
word = entry["word"]
|
|
339
|
+
par: Paradigm = {}
|
|
340
|
+
parts = _en_parts(entry)
|
|
341
|
+
if parts["s3"] and parts["past"]:
|
|
342
|
+
base = [word]
|
|
343
|
+
pp = parts["pp"] or parts["past"]
|
|
344
|
+
ing = parts["ing"] or [word + "ing"]
|
|
345
|
+
par[IND_PRS] = {p: list(base) for p in PERSONS}
|
|
346
|
+
par[IND_PRS]["3s"] = parts["s3"]
|
|
347
|
+
par[IND_PST] = {p: list(parts["past"]) for p in PERSONS}
|
|
348
|
+
par[SBJV_PRS] = {p: list(base) for p in PERSONS}
|
|
349
|
+
par[SBJV_IPFV] = {p: list(parts["past"]) for p in PERSONS}
|
|
350
|
+
par[INF], par[PTCP_PRS], par[PTCP_PST] = base, ing, pp
|
|
351
|
+
|
|
352
|
+
table: Paradigm = {}
|
|
353
|
+
for row in entry.get("forms", []):
|
|
354
|
+
if row.get("source") != "conjugation":
|
|
355
|
+
continue
|
|
356
|
+
cell = cells(row.get("tags", []))
|
|
357
|
+
form = _clean(row.get("form", ""), "en")
|
|
358
|
+
if cell and form:
|
|
359
|
+
add(table, *cell, form)
|
|
360
|
+
if table:
|
|
361
|
+
# Modern English "you" shares the plural forms (are/were, not art/wast).
|
|
362
|
+
for key in (IND_PRS, IND_PST):
|
|
363
|
+
if key in table and "2p" in table[key]:
|
|
364
|
+
table[key]["2s"] = list(table[key]["2p"])
|
|
365
|
+
for key, val in table.items():
|
|
366
|
+
par[key] = val
|
|
367
|
+
if not par:
|
|
368
|
+
return None
|
|
369
|
+
base = (par.get(INF) or [word])[0]
|
|
370
|
+
par[IMP] = {"2s": [base], "1p": [f"let's {base}"], "2p": [base]}
|
|
371
|
+
return {"lemma": word, "par": par, "aux": [], "glosses": gl, "table": bool(table)}
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
# ---------------------------------------------------------------- database
|
|
375
|
+
SCHEMA = """
|
|
376
|
+
CREATE TABLE meta(k TEXT PRIMARY KEY, v TEXT);
|
|
377
|
+
CREATE TABLE lemma(
|
|
378
|
+
id INTEGER PRIMARY KEY, lang TEXT NOT NULL, lemma TEXT NOT NULL, key TEXT NOT NULL,
|
|
379
|
+
score INTEGER NOT NULL, aux TEXT NOT NULL, glosses TEXT NOT NULL,
|
|
380
|
+
paradigm BLOB NOT NULL
|
|
381
|
+
);
|
|
382
|
+
CREATE TABLE rev(key TEXT NOT NULL, lemma_id INTEGER NOT NULL, PRIMARY KEY (key, lemma_id)) WITHOUT ROWID;
|
|
383
|
+
"""
|
|
384
|
+
INDEXES = """
|
|
385
|
+
CREATE INDEX lemma_key ON lemma(lang, key);
|
|
386
|
+
"""
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
# Closed class: no infinitive, participles, imperative or periphrastic tenses.
|
|
390
|
+
EN_MODALS = {"can", "could", "may", "might", "must", "shall", "should", "will", "would", "ought"}
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def finalize(lang: str, rec: dict) -> None:
|
|
394
|
+
par = rec["par"]
|
|
395
|
+
if lang == "it":
|
|
396
|
+
# Italian tables list regional/literary variants (damo, demo) after the
|
|
397
|
+
# standard form, often without any tag: keep the standard one.
|
|
398
|
+
for key, val in par.items():
|
|
399
|
+
if isinstance(val, list):
|
|
400
|
+
par[key] = val[:1]
|
|
401
|
+
else:
|
|
402
|
+
for p in val:
|
|
403
|
+
val[p] = val[p][:1]
|
|
404
|
+
if lang == "en" and rec["lemma"] in EN_MODALS:
|
|
405
|
+
rec["par"] = {k: v for k, v in par.items() if k in (IND_PRS, IND_PST)}
|
|
406
|
+
for table in rec["par"].values():
|
|
407
|
+
for p in PERSONS: # modals do not inflect for person
|
|
408
|
+
table[p] = list(table.get("1s") or table.get(p) or [])
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def collect(lang: str, path: Path) -> dict[str, dict]:
|
|
412
|
+
records: dict[str, dict] = {}
|
|
413
|
+
for entry in entries(path):
|
|
414
|
+
if lang == "en":
|
|
415
|
+
recs = english_record(entry)
|
|
416
|
+
elif lang == "ru":
|
|
417
|
+
recs = russian_record(entry)
|
|
418
|
+
else:
|
|
419
|
+
recs = romance_records(entry, lang)
|
|
420
|
+
for rec in [recs] if isinstance(recs, dict) else recs or []:
|
|
421
|
+
have = records.get(rec["lemma"])
|
|
422
|
+
if have is None:
|
|
423
|
+
records[rec["lemma"]] = rec
|
|
424
|
+
continue
|
|
425
|
+
merge(have["par"], rec["par"])
|
|
426
|
+
have["glosses"] += [g for g in rec["glosses"] if g not in have["glosses"]]
|
|
427
|
+
have["aux"] += [a for a in rec["aux"] if a not in have["aux"]]
|
|
428
|
+
have["table"] |= rec["table"]
|
|
429
|
+
for rec in records.values():
|
|
430
|
+
finalize(lang, rec)
|
|
431
|
+
return records
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def coverage(lang: str, records: dict[str, dict]) -> None:
|
|
435
|
+
core = {"en": (IND_PRS, IND_PST, PTCP_PST), "ru": (INF, IND_PST)}.get(lang, (IND_PRS, PTCP_PST))
|
|
436
|
+
missing = [l for l, r in records.items() if any(k not in r["par"] for k in core)
|
|
437
|
+
and l not in EN_MODALS]
|
|
438
|
+
if lang == "ru": # imperfectives need a present, perfectives a (synthetic) future
|
|
439
|
+
missing += [l for l, r in records.items() if l not in missing and IND_PRS not in r["par"]
|
|
440
|
+
and IND_FUT not in r["par"]]
|
|
441
|
+
print(f"{lang}: {len(records):>6} lemmas, {len(missing)} missing core cells "
|
|
442
|
+
f"(e.g. {', '.join(sorted(missing)[:8])})", file=sys.stderr)
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
PRONOMINAL_ENDINGS = {"it": ("rsi", "rsene"), "es": ("rse",), "pt": ("-se",)}
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def frequency(lang: str, rec: dict) -> int:
|
|
449
|
+
"""Corpus frequency of the verb: summed over its distinct forms, as Zipf x 100.
|
|
450
|
+
|
|
451
|
+
Wiktionary has no frequency data; wordfreq (CC BY-SA 4.0 data) is used at
|
|
452
|
+
build time only, to rank search results and translation candidates.
|
|
453
|
+
"""
|
|
454
|
+
from wordfreq import word_frequency
|
|
455
|
+
|
|
456
|
+
forms: set[str] = set()
|
|
457
|
+
for key, val in rec["par"].items():
|
|
458
|
+
if key in META:
|
|
459
|
+
continue
|
|
460
|
+
for fs in [val] if isinstance(val, list) else val.values():
|
|
461
|
+
if lang == "ru": # stress marks (говори́ть) are not in corpus text
|
|
462
|
+
forms.update(f.replace("\u0301", "") for f in fs if " " not in f)
|
|
463
|
+
continue
|
|
464
|
+
if lang == "de":
|
|
465
|
+
# Only one-word forms: "habe frei" would score freihaben as haben (and
|
|
466
|
+
# "stehe auf" as auf). Infinitive, participles and subordinate forms
|
|
467
|
+
# (freihabe) are single words and belong to the verb alone.
|
|
468
|
+
forms.update(f for f in fs if " " not in f)
|
|
469
|
+
continue
|
|
470
|
+
# the verb itself: "me lève" -> "lève", but "parks in" -> "parks"
|
|
471
|
+
forms.update(f.split(" ")[0 if lang == "en" else -1] for f in fs)
|
|
472
|
+
if lang == "en": # "walk" is also a noun: count only the inflected forms too
|
|
473
|
+
forms.add(rec["lemma"])
|
|
474
|
+
total = sum(word_frequency(f, lang) for f in forms)
|
|
475
|
+
score = round(100 * (math.log10(total) + 9)) if total > 0 else 0
|
|
476
|
+
# Pronominals were scored on their base verb's forms (si vuole -> vuole): rank them below it.
|
|
477
|
+
# Same for English phrasal verbs (find out -> find).
|
|
478
|
+
if " " in rec["lemma"] or rec["lemma"].endswith(PRONOMINAL_ENDINGS.get(lang, ())):
|
|
479
|
+
score -= 100
|
|
480
|
+
return max(score, 0)
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def write(db_path: Path, data: dict[str, dict[str, dict]]) -> None:
|
|
484
|
+
if db_path.exists():
|
|
485
|
+
db_path.unlink()
|
|
486
|
+
con = sqlite3.connect(db_path)
|
|
487
|
+
con.executescript(SCHEMA)
|
|
488
|
+
lid = 0
|
|
489
|
+
for lang, records in data.items():
|
|
490
|
+
for rec in records.values():
|
|
491
|
+
lid += 1
|
|
492
|
+
score = frequency(lang, rec)
|
|
493
|
+
blob = zlib.compress(json.dumps(rec["par"], ensure_ascii=False).encode(), 9)
|
|
494
|
+
con.execute(
|
|
495
|
+
"INSERT INTO lemma VALUES (?,?,?,?,?,?,?,?)",
|
|
496
|
+
(lid, lang, rec["lemma"], fold(rec["lemma"]), score,
|
|
497
|
+
json.dumps(rec["aux"], ensure_ascii=False),
|
|
498
|
+
json.dumps(rec["glosses"][:8], ensure_ascii=False), blob),
|
|
499
|
+
)
|
|
500
|
+
keys = set()
|
|
501
|
+
for key, val in rec["par"].items():
|
|
502
|
+
if key in META: # aspect partners are other verbs, not forms of this one
|
|
503
|
+
continue
|
|
504
|
+
for forms in [val] if isinstance(val, list) else val.values():
|
|
505
|
+
keys.update(fold(f) for f in forms)
|
|
506
|
+
con.executemany("INSERT INTO rev VALUES (?,?)", [(k, lid) for k in keys])
|
|
507
|
+
con.executemany("INSERT INTO meta VALUES (?,?)", [
|
|
508
|
+
("built", dt.date.today().isoformat()),
|
|
509
|
+
("source", "Wiktionary via Wiktextract/kaikki.org"),
|
|
510
|
+
("license", "CC BY-SA 4.0"),
|
|
511
|
+
])
|
|
512
|
+
con.executescript(INDEXES)
|
|
513
|
+
con.commit()
|
|
514
|
+
con.execute("VACUUM")
|
|
515
|
+
con.close()
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def main(argv: list[str] | None = None) -> None:
|
|
519
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
520
|
+
ap.add_argument("--src", type=Path, default=Path.home() / ".cache" / "conj-build",
|
|
521
|
+
help="where the kaikki dumps are downloaded (default: %(default)s)")
|
|
522
|
+
ap.add_argument("--refresh", action="store_true", help="re-download the dumps")
|
|
523
|
+
ap.add_argument("--out", type=Path, default=OUT, help="output .sqlite.gz (default: %(default)s)")
|
|
524
|
+
ap.add_argument("--langs", default=",".join(SOURCES), help="comma-separated (default: %(default)s)")
|
|
525
|
+
args = ap.parse_args(argv)
|
|
526
|
+
|
|
527
|
+
data = {}
|
|
528
|
+
for lang in args.langs.split(","):
|
|
529
|
+
data[lang] = collect(lang, download(lang, args.src, args.refresh))
|
|
530
|
+
coverage(lang, data[lang])
|
|
531
|
+
|
|
532
|
+
raw = args.out.with_suffix("") # .sqlite
|
|
533
|
+
raw.parent.mkdir(parents=True, exist_ok=True)
|
|
534
|
+
write(raw, data)
|
|
535
|
+
with open(raw, "rb") as src, gzip.open(args.out, "wb", compresslevel=9) as dst:
|
|
536
|
+
shutil.copyfileobj(src, dst)
|
|
537
|
+
print(f"wrote {args.out} ({args.out.stat().st_size / 1e6:.1f} MB; "
|
|
538
|
+
f"uncompressed {raw.stat().st_size / 1e6:.1f} MB)", file=sys.stderr)
|
|
539
|
+
sha = hashlib.sha256(args.out.read_bytes()).hexdigest()
|
|
540
|
+
print(f"sha256 {sha}\n(to publish: new GitHub release, then set DATA_TAG and DATA_SHA256 in db.py)",
|
|
541
|
+
file=sys.stderr)
|
|
542
|
+
raw.unlink()
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
if __name__ == "__main__":
|
|
546
|
+
main()
|
conj/cli.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Command-line entry point."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from . import AUTHOR, NAME, __version__
|
|
10
|
+
from .compound import conjugate
|
|
11
|
+
from .db import DB
|
|
12
|
+
from .langs import LANGS
|
|
13
|
+
from .normalize import fold
|
|
14
|
+
from .render import as_dict, describe, plain
|
|
15
|
+
from .search import resolve, search
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def main(argv: list[str] | None = None) -> None:
|
|
19
|
+
ap = argparse.ArgumentParser(
|
|
20
|
+
prog="conj",
|
|
21
|
+
description=f"{NAME}: verb conjugation for French, Italian, Spanish, Portuguese, "
|
|
22
|
+
"English, German and Russian. Without --plain, opens the interactive TUI.",
|
|
23
|
+
epilog="Examples: conj · conj venir · conj it andare · conj --plain fr aller · conj -p went",
|
|
24
|
+
)
|
|
25
|
+
ap.add_argument("words", nargs="*", metavar="[LANG] VERB",
|
|
26
|
+
help="verb or inflected form, optionally preceded by fr/it/es/pt/en/de/ru")
|
|
27
|
+
ap.add_argument("-V", "--version", action="version",
|
|
28
|
+
version=f"{NAME} {__version__} (conj) by {AUTHOR}")
|
|
29
|
+
ap.add_argument("-p", "--plain", action="store_true", help="print the table instead of opening the TUI")
|
|
30
|
+
ap.add_argument("-s", "--simple", action="store_true", help="simple tenses only")
|
|
31
|
+
ap.add_argument("-j", "--json", action="store_true",
|
|
32
|
+
help="print the conjugation as JSON (exact matches only; for editor plugins)")
|
|
33
|
+
ap.add_argument("--prefer", choices=sorted(LANGS), metavar="LANG",
|
|
34
|
+
help="with --json: list this language's verbs first (without restricting)")
|
|
35
|
+
ap.add_argument("-a", "--aux", help="auxiliary for compound tenses (e.g. essere / avere)")
|
|
36
|
+
args = ap.parse_args(argv)
|
|
37
|
+
|
|
38
|
+
lang = None
|
|
39
|
+
words = " ".join(args.words).split()
|
|
40
|
+
if words and words[0].lower() in LANGS and len(words) > 1:
|
|
41
|
+
lang = words.pop(0).lower()
|
|
42
|
+
query = " ".join(words)
|
|
43
|
+
|
|
44
|
+
try:
|
|
45
|
+
db = DB()
|
|
46
|
+
except FileNotFoundError as e:
|
|
47
|
+
sys.exit(str(e))
|
|
48
|
+
|
|
49
|
+
if args.json:
|
|
50
|
+
print_json(db, query, lang, args.aux, compounds=not args.simple, prefer=args.prefer)
|
|
51
|
+
return
|
|
52
|
+
|
|
53
|
+
if not args.plain:
|
|
54
|
+
from .tui.app import ConjApp
|
|
55
|
+
ConjApp(db, query=query, lang=lang).run()
|
|
56
|
+
return
|
|
57
|
+
|
|
58
|
+
if not query:
|
|
59
|
+
ap.error("--plain needs a verb")
|
|
60
|
+
hits = search(db, query, lang, limit=8)
|
|
61
|
+
if not hits:
|
|
62
|
+
sys.exit(f"no verb found for {query!r}")
|
|
63
|
+
hit = hits[0]
|
|
64
|
+
verb = resolve(db, hit)
|
|
65
|
+
conj = conjugate(db, verb, args.aux)
|
|
66
|
+
if hit.via == "form":
|
|
67
|
+
where = describe(conj, conj.find(query)) # empty for search-only forms (de: aufstehe)
|
|
68
|
+
print(f"{query} → {verb.lemma}" + (f" ({where})" if where else "") + "\n")
|
|
69
|
+
elif hit.via == "fuzzy":
|
|
70
|
+
print(f"(no exact match for {query!r}; showing {verb.lemma})\n")
|
|
71
|
+
sys.stdout.write(plain(conj, compounds=not args.simple))
|
|
72
|
+
others = [f"{h.lemma} ({h.lang})" for h in hits[1:6] if h.via != "fuzzy"]
|
|
73
|
+
if others:
|
|
74
|
+
print(f"\nalso: {', '.join(others)}")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def print_json(db: DB, query: str, lang: str | None, aux: str | None, compounds: bool,
|
|
78
|
+
prefer: str | None = None, max_candidates: int = 6) -> None:
|
|
79
|
+
"""Exact matches only: an inflected form or a lemma, never a prefix or a typo.
|
|
80
|
+
|
|
81
|
+
The top level is the best match; `candidates` holds every match (best first), each
|
|
82
|
+
with its own full conjugation, so an editor can switch between them without
|
|
83
|
+
running conj again. `prefer` moves that language's matches to the front (a guess,
|
|
84
|
+
e.g. the editor's spell-check language), unlike `lang`, which restricts.
|
|
85
|
+
"""
|
|
86
|
+
key = fold(query)
|
|
87
|
+
hits = search(db, query, lang, limit=16) if key else []
|
|
88
|
+
exact = [h for h in hits if h.via in ("form", "pronominal") or fold(h.lemma) == key]
|
|
89
|
+
if prefer:
|
|
90
|
+
exact.sort(key=lambda h: h.lang != prefer) # stable: rank kept within each group
|
|
91
|
+
if not exact:
|
|
92
|
+
out = {"found": False, "query": query}
|
|
93
|
+
else:
|
|
94
|
+
candidates = []
|
|
95
|
+
for hit in exact[:max_candidates]:
|
|
96
|
+
conj = conjugate(db, resolve(db, hit), aux)
|
|
97
|
+
candidates.append({"query": query, **as_dict(conj, conj.find(query), compounds)})
|
|
98
|
+
out = {**candidates[0], "candidates": candidates,
|
|
99
|
+
"also": [f"{c['lemma']} ({c['lang']})" for c in candidates[1:]]}
|
|
100
|
+
json.dump(out, sys.stdout, ensure_ascii=False)
|
|
101
|
+
sys.stdout.write("\n")
|