-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
database.py
278 lines (230 loc) · 7.39 KB
/
database.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import sqlite3
from pathlib import Path
from typing import Iterator
try:
from .utils import load_plugin_json
except ImportError:
from utils import load_plugin_json
def get_ll_path(asin: str, book_path: str) -> Path:
return Path(book_path).parent.joinpath(f"LanguageLayer.en.{asin}.kll")
def create_lang_layer(
asin: str, book_path: str, acr: str, revision: str
) -> tuple[sqlite3.Connection, Path]:
db_path = get_ll_path(asin, book_path)
ll_conn = sqlite3.connect(":memory:")
ll_conn.executescript(
"""
CREATE TABLE metadata (
key TEXT,
value TEXT
);
CREATE TABLE glosses (
start INTEGER PRIMARY KEY,
end INTEGER,
difficulty INTEGER,
sense_id INTEGER,
low_confidence BOOLEAN
);
"""
)
metadata = [
("acr", acr),
("targetLanguages", "en"),
("sidecarRevision", "9"),
("bookRevision", revision),
("sourceLanguage", "en"),
("enDictionaryVersion", "2016-09-14"),
("enDictionaryRevision", "57"),
("enDictionaryId", "kll.en.en"),
("sidecarFormat", "1.0"),
]
ll_conn.executemany("INSERT INTO metadata VALUES (?, ?)", metadata)
return ll_conn, db_path
def insert_lemma(ll_conn: sqlite3.Connection, data: tuple[int, int, int, int]) -> None:
ll_conn.execute(
"""
INSERT INTO glosses (start, end, difficulty, sense_id, low_confidence)
VALUES (?, ?, ?, ?, 0)
""",
data,
)
def get_x_ray_path(asin: str, book_path: str) -> Path:
return Path(book_path).parent.joinpath(f"XRAY.entities.{asin}.asc")
def create_x_ray_db(
asin: str,
book_path: str,
lang: str,
plugin_path: Path,
prefs: dict[str, str],
wiki_name: str,
) -> tuple[sqlite3.Connection, Path]:
db_path = get_x_ray_path(asin, book_path)
x_ray_conn = sqlite3.connect(":memory:")
x_ray_conn.executescript(
"""
PRAGMA user_version = 1;
CREATE TABLE book_metadata (
srl INTEGER,
erl INTEGER,
has_images TINYINT,
has_excerpts TINYINT,
show_spoilers_default TINYINT,
num_people INTEGER,
num_terms INTEGER,
num_images INTEGER,
preview_images TEXT);
CREATE TABLE entity (
id INTEGER PRIMARY KEY,
label TEXT,
loc_label INTEGER,
type INTEGER,
count INTEGER,
has_info_card TINYINT);
CREATE TABLE entity_description (
text TEXT,
source_wildcard TEXT,
source INTEGER,
entity INTEGER PRIMARY KEY);
CREATE TABLE entity_excerpt (
entity INTEGER,
excerpt INTEGER);
CREATE TABLE excerpt (
id INTEGER PRIMARY KEY,
start INTEGER,
length INTEGER,
image TEXT,
related_entities TEXT,
goto INTEGER);
CREATE TABLE occurrence (
entity INTEGER,
start INTEGER,
length INTEGER);
CREATE TABLE source (
id INTEGER PRIMARY KEY,
label INTEGER,
url INTEGER,
license_label INTEGER,
license_url INTEGER);
CREATE TABLE string (
id INTEGER,
language TEXT,
text TEXT);
CREATE TABLE type (
id INTEGER PRIMARY KEY,
label INTEGER,
singular_label INTEGER,
icon INTEGER,
top_mentioned_entities TEXT);
INSERT INTO entity (id, loc_label, has_info_card) VALUES(0, 1, 0);
INSERT INTO source (id, label, url) VALUES(0, 5, 20);
INSERT INTO source VALUES(1, 6, 21, 7, 8);
"""
)
str_list = load_plugin_json(plugin_path, "data/x_ray_strings.json")
str_list.append(
[
21,
"en",
f"https://zh.wikipedia.org/zh-{prefs['zh_wiki_variant']}/%s"
if lang == "zh"
else f"https://{lang}.wikipedia.org/wiki/%s",
]
)
str_list.append([22, "en", f"{prefs['mediawiki_api'].split('/', 1)[0]}/wiki/%s"])
x_ray_conn.execute(
"""
INSERT INTO source (id, label, url, license_label, license_url)
VALUES(2, 4, 22, 7, 8)
"""
)
x_ray_conn.executemany("INSERT INTO string VALUES(?, ?, ?)", str_list)
if wiki_name != "Wikipedia":
x_ray_conn.execute("UPDATE string SET text = ? WHERE id = 4", (wiki_name,))
return x_ray_conn, db_path
def create_x_indices(conn: sqlite3.Connection) -> None:
conn.executescript(
"""
CREATE INDEX idx_entity_type ON entity(type ASC);
CREATE INDEX idx_entity_excerpt ON entity_excerpt(entity ASC);
CREATE INDEX idx_occurrence_start ON occurrence(start ASC);
"""
)
def insert_x_book_metadata(
conn: sqlite3.Connection, erl: int, num_images: int, preview_images: str | None
) -> None:
num_people = 0
num_terms = 0
for (num,) in conn.execute("SELECT count(*) FROM entity WHERE type = 1"):
num_people = num
for (num,) in conn.execute("SELECT count(*) FROM entity WHERE type = 2"):
num_terms = num
conn.execute(
"INSERT INTO book_metadata VALUES(0, ?, ?, 0, 0, ?, ?, ?, ?)",
(erl, num_images > 0, num_people, num_terms, num_images, preview_images),
)
def insert_x_entities(
conn: sqlite3.Connection, data: Iterator[tuple[int, str, int, int]]
) -> None:
conn.executemany(
"""
INSERT INTO entity (id, label, type, count, has_info_card)
VALUES(?, ?, ?, ?, 1)
""",
data,
)
def insert_x_entity_description(
conn: sqlite3.Connection, data: tuple[str, str, int | None, int]
) -> None:
conn.execute("INSERT INTO entity_description VALUES(?, ?, ?, ?)", data)
def insert_x_occurrences(
conn: sqlite3.Connection, data: Iterator[tuple[int, int, int]]
) -> None:
conn.executemany("INSERT INTO occurrence VALUES(?, ?, ?)", data)
def get_top_ten_entities(conn: sqlite3.Connection, entity_type: int) -> str:
entity_ids = []
for (entity_id,) in conn.execute(
"SELECT id FROM entity WHERE type = ? ORDER BY count DESC LIMIT 10",
(entity_type,),
):
entity_ids.append(entity_id)
return ",".join(map(str, entity_ids))
def insert_x_types(conn: sqlite3.Connection) -> None:
insert_x_type(conn, (1, 14, 15, 1, get_top_ten_entities(conn, 1)))
insert_x_type(conn, (2, 16, 17, 2, get_top_ten_entities(conn, 2)))
def insert_x_type(
conn: sqlite3.Connection, data: tuple[int, int, int, int, str]
) -> None:
conn.execute("INSERT INTO type VALUES(?, ?, ?, ?, ?)", data)
def insert_x_excerpt_image(
conn: sqlite3.Connection, data: tuple[int, int, int, str, int]
) -> None:
conn.execute(
"INSERT INTO excerpt (id, start, length, image, goto) VALUES(?, ?, ?, ?, ?)",
data,
)
def save_db(source: sqlite3.Connection, dest_path: Path) -> None:
source.commit()
dest = sqlite3.connect(dest_path)
with dest:
source.backup(dest)
source.close()
dest.close()
def compare_klld_metadata(
conn_a: sqlite3.Connection, conn_b: sqlite3.Connection, key: str
) -> bool:
sql = "SELECT value FROM metadata WHERE key = ?"
for value_a in conn_a.execute(sql, (key,)):
for value_b in conn_b.execute(sql, (key,)):
return value_a == value_b
return False
def is_same_klld(path_a: Path, path_b: Path) -> bool:
conn_a = sqlite3.connect(path_a)
conn_b = sqlite3.connect(path_b)
for key in ["lemmaLanguage", "definitionLanguage", "version"]:
if not compare_klld_metadata(conn_a, conn_b, key):
conn_a.close()
conn_b.close()
return False
conn_a.close()
conn_b.close()
return True