Repository navigation
Expand file tree
/
Copy pathvalue_usage.py
More file actions
431 lines (400 loc) · 16.3 KB
/
Copy pathvalue_usage.py
File metadata and controls
431 lines (400 loc) · 16.3 KB
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
from collections import defaultdict
import json
import os
import time
import urllib.parse
from typing import Any
import atf
import asl
time_reading_oracc_file = 0
time_loading_json = 0
language_to_value_to_period_to_occurrences : dict[
str, dict[
str, dict[
str, list[str]]]] = defaultdict(
lambda: defaultdict(
lambda: defaultdict(list)))
def index_values(text_json: Any,
artefact: str,
period: str,
genre: str,
lang: str = "und",
consecutive_values:list[str]|None=None):
if "det" in text_json:
if consecutive_values:
consecutive_values.clear()
return
if "lang" in text_json:
lang = text_json["lang"].split("-")[0]
if "cdl" in text_json:
for node in text_json["cdl"]:
index_values(node, artefact, period, genre, lang)
if "f" in text_json:
index_values(text_json["f"], artefact, period, genre, lang)
if "gdl" in text_json:
gdl_values : list[str] = []
for node in text_json["gdl"]:
index_values(node, artefact, period, genre, lang, gdl_values)
if "group" in text_json:
for node in text_json["group"]:
index_values(node, artefact, period, genre, lang)
if "seq" in text_json:
for node in text_json["seq"]:
index_values(node, artefact, period, genre, lang)
# We do not go down into "qualified" for now (the index is on default values).
if "v" in text_json:
if consecutive_values is not None:
if consecutive_values and atf.is_vc(text_json["v"]):
preceding = consecutive_values[-1]
this_vowel = atf.get_vowel(text_json["v"])
if atf.get_vowel(preceding, None) == this_vowel:
if atf.is_cv(preceding):
language_to_value_to_period_to_occurrences[
lang][preceding + "-" + text_json["v"]][period].append(artefact)
elif atf.is_v(preceding) and len(consecutive_values) >= 2:
if atf.is_cv(consecutive_values[-2]) and atf.get_vowel(consecutive_values[-2]) == this_vowel:
language_to_value_to_period_to_occurrences[
lang][consecutive_values[-2] + "-" +
preceding + "-" +
text_json["v"]][period].append(artefact)
if text_json.get("delim") == "-":
consecutive_values.append(text_json["v"])
else:
consecutive_values.clear()
language_to_value_to_period_to_occurrences[
lang][text_json["v"]][period].append(artefact)
elif consecutive_values:
consecutive_values.clear()
def index(directory: str):
global time_reading_oracc_file
global time_loading_json
listing = os.listdir(directory)
if "catalogue.json" in listing:
with open(directory + "/catalogue.json", encoding="utf-8") as f:
catalogue = json.loads(f.read())
files = [
(cdli_number,
directory + "/corpusjson/" + cdli_number + ".json",
metadata)
for cdli_number, metadata in catalogue["members"].items()
if os.path.isfile(directory + "/corpusjson/" + cdli_number + ".json")]
print(f"Indexing {len(files)} texts in {directory}...")
skipped : list[str] = []
for i, (cdli_number, text_file, metadata) in enumerate(files):
if i > 0 and i % 1000 == 0:
print(f" {i}/{len(files)}...")
with open(text_file, encoding="utf-8") as f:
start = time.time()
source = f.read()
time_reading_oracc_file += time.time() - start
if not source:
skipped.append(text_file)
continue
start = time.time()
text = json.loads(source)
time_loading_json += time.time() - start
index_values(
text,
cdli_number,
metadata.get("period", "unknown").replace("Neo ", "Neo-").replace(
"Old ", "O").replace("Middle ", "M").replace("Neo-", "N").replace(
"Assyrian", "A").replace("Babylonian", "B"),
metadata.get("genre", metadata.get("subgenre", "unclassified")).lower())
if skipped:
if len(skipped) < 10:
for file in skipped:
print(f"*** {file} was empty, skipped.")
else:
print(f"*** Skipped {len(skipped)} empty files.")
for f in listing:
if os.path.isdir(directory + "/" + f) and f != "corpusjson":
index(directory + "/" + f)
ORACC_PROJECTS = ("akklove", "atae", "babcity", "balt", "blms", "dcclt", "riao", "ribo", "rinap", "saao", "tcma")
start = time.time()
for project in ORACC_PROJECTS:
index(f"oracc/{project}")
time_indexing_oracc_values = time.time() - start
cdli_occurrences : list[str] = []
oracc_occurrences = [o
for l in language_to_value_to_period_to_occurrences
for v in language_to_value_to_period_to_occurrences[l]
for p in language_to_value_to_period_to_occurrences[l][v]
for o in language_to_value_to_period_to_occurrences[l][v][p]]
start = time.time()
for file in ("OAkk", "Early OB", "OA", "OB akk", "MA", "MB", "Early NB", "NA", "NB"):
covered_by_oracc : set[str] = set()
for v, occurrences in atf.get_value_counts(
f"cdli/{file}.atf",
"akk",
set((atf.SpanAttribute.DETERMINATIVE, atf.SpanAttribute.LOGOGRAM))).items():
cdli_occurrences += occurrences
oracc_texts = set(language_to_value_to_period_to_occurrences["akk"][v][file.removesuffix(" akk")])
for occurrence in occurrences:
if occurrence in oracc_texts:
covered_by_oracc.add(occurrence)
else:
language_to_value_to_period_to_occurrences["akk"][v][file.removesuffix(" akk")].append(occurrence)
print(f"--- {len(covered_by_oracc)} artefacts already covered by Oracc in {file}")
time_indexing_cdli_values = time.time() - start
print(f"--- Indexed {len(oracc_occurrences)} occurrences from {len(set(oracc_occurrences))} Oracc texts in {time_indexing_oracc_values} s")
print(f"--- Whereof {time_reading_oracc_file} s reading files")
print(f"--- Whereof {time_loading_json} s parsing JSON")
print(f"--- Indexed {len(cdli_occurrences)} occurrences from {len(set(cdli_occurrences))} CDLI texts in {time_indexing_cdli_values} s")
syllabary_index : list[asl.Sign] = []
base_to_values : dict[str, list[str]] = defaultdict(list)
HEAD = """
<html>
<head>
<style>
table {
border-collapse: collapse;
}
th {
border: 1px solid;
text-align: center;
}
td {
border: 1px solid;
text-align: center;
}
tr.𒆍𒀭𒊏𒆠 {
border-bottom: 3px double;
}
</style>
<script>
function update_from_query() {
params = (new URL(document.location)).searchParams;
document.querySelector('input[id="count-artefact"]').checked = params.get("count") === "artefact";
document.querySelector('input[id="over-homophones"]').checked = params.get("over") === "homophones";
document.querySelector('input[id="over-sign"]').checked = params.get("over") === "sign";
update_visibilities(false);
}
function update_visibilities(push_history = true) {
over_homophones = document.querySelector('input[id="over-homophones"]').checked;
over_sign = document.querySelector('input[id="over-sign"]').checked;
count = !over_homophones && !over_sign;
count_artefacts = document.querySelector('input[id="count-artefact"]').checked;
if (push_history) {
let query = [`count=${count_artefacts?"artefact":"occurrence"}`];
if (over_homophones) {
query.push("over=homophones");
} else if (over_sign) {
query.push("over=sign");
}
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + query.join("&");
window.history.pushState({ path: newurl }, '', newurl);
}
for (var div of document.getElementsByTagName("div")) {
if (div.className === "over-homophones") {
div.style = over_homophones ? "" : "display:none";
}
if (div.className === "over-sign") {
div.style = over_sign ? "" : "display:none";
}
if (div.className === "count") {
div.style = count ? "" : "display:none";
}
if (div.className === "count-artefact") {
div.style = count_artefacts ? "" : "display:none";
}
if (div.className === "count-occurrence") {
div.style = count_artefacts ? "display:none" : "";
}
}
}
window.onload = function () {
for (var input of document.getElementsByTagName("input")) {
input.onclick = update_visibilities;
}
update_from_query();
}
</script>
</head>
<body>
"""
SOURCE = f"""
<p>Based on transliterations from CDLI and Oracc projects {", ".join(ORACC_PROJECTS)}.</p>
"""
COUNT_SELECTOR = """
<p>
<input type="radio" name="count" value="occurrence" id="count-occurrence" checked>
<label for="count-occurrence">Count occurrences</label>
</p>
<p>
<input type="radio" name="count" value="artefact" id="count-artefact">
<label for="count-artefact">Count artefacts</label>
</p>
"""
RATIO_SELECTOR = """
<p>
<input type="radio" name="over" value="1" id="count" checked>
<label for="count">Show count</label>
</p>
<p>
<input type="radio" name="over" value="homophones" id="over-homophones">
<label for="over-homophones">Show count as a proportion of homophones in same period (e.g., qi₂ as a percentage of all qi, qi₂, qi₃, etc. in MA). For CVC values, CV-VC and CV-V-VC sequences are counted, e.g., taš₃ as a percentage of all taš, taš₂, taš₃, ta-aš, ta-aš₂, etc. in MA.</label>
</p>
<p>
<input type="radio" name="over" value="sign" id="over-sign">
<label for="over-sign">Show count as a proportion of usages of the sign in same period (e.g., qi₂ as a percentage of Akkadian syllabic 𒆠 in MA)</label>
</p>
"""
TABLE_PERIODS = """
<table>
<tr>
<th rowspan="2"></th>
<th rowspan="2">OAkk</th>
<th colspan="2">OA</th>
<th>MA</th>
<th colspan="2">NA</th>
</tr>
<tr class="𒆍𒀭𒊏𒆠">
<th>Early OB</th>
<th>OB</th>
<th>MB</th>
<th>Early NB</th>
<th>NB</th>
</tr>
"""
value_to_period_to_occurrences = language_to_value_to_period_to_occurrences["akk"]
sign_to_period_to_occurrences : dict[asl.Sign, dict[str, list[str]]] = defaultdict(lambda: defaultdict(list))
base_to_period_to_occurrences : dict[str, dict[str, list[str]]] = defaultdict(lambda: defaultdict(list))
base_to_signs_and_values : dict[str, list[tuple[tuple[asl.Sign, ...], tuple[asl.Value, ...]]]] = defaultdict(list)
text_to_value : dict[str, asl.Value] = {}
values_to_signs : dict[asl.Value, asl.Sign] = {}
for sign in asl.osl.signs:
if not isinstance(sign, asl.Sign) or sign.deprecated:
continue
for value in sign.values:
if value.deprecated:
continue
if value.text == "xₓ":
# A garbage value which somehow sneaks in unqualified in a few places in
# Oracc.
continue
if "-" in value.text:
# - in OSL values is an oddity which we ignore (otherwise it is
# ambiguous whether a sequence of values is one or two signs).
continue
text_to_value[value.text] = value
values_to_signs[value] = sign
usage = value_to_period_to_occurrences[value.text]
for period, occurrences in usage.items():
if "ₓ" in value.text:
raise ValueError(value.text, occurrences)
sign_to_period_to_occurrences[sign][period] += occurrences
base = atf.get_base(value.text)
base_to_signs_and_values[base].append(((sign,), (value,)))
for value, period_to_occurrences in value_to_period_to_occurrences.items():
if "-" in value:
base = atf.get_base(value)
subvalues = value.split("-")
# We should check that these error paths are CDLI-only (Oracc values should be in OSL).
unknown_values = False
for v in subvalues:
if v not in text_to_value:
print(f"*** Unknown value {v} in {value}")
unknown_values = True
if unknown_values:
continue
base_to_signs_and_values[base].append(
(tuple(values_to_signs[text_to_value[v]] for v in subvalues),
tuple(text_to_value[v] for v in subvalues)))
else:
base = atf.get_base(value)
for period, occurrences in period_to_occurrences.items():
base_to_period_to_occurrences[base][period] += occurrences
def entry(period: str, values: tuple[asl.Value, ...], sign: asl.Sign|None):
sign_occurrences = sign_to_period_to_occurrences[sign][period] if sign else None
homophone_occurrences = base_to_period_to_occurrences[atf.get_base("-".join(v.text for v in values))][period]
occurrences = value_to_period_to_occurrences["-".join(v.text for v in values)][period]
if len(occurrences) == 0:
return " "
else:
return f"""
<div class="count-occurrence">
<div class="count">{len(occurrences)}</div>
<div class="over-homophones">{len(occurrences) / len(homophone_occurrences):0.0%}</div>
{f'<div class="over-sign">{len(occurrences) / len(sign_occurrences):0.0%}</div>'
if sign_occurrences else ''}
</div>
<div class="count-artefact">
<div class="count">{len(set(occurrences))}</div>
<div class="over-homophones">{len(set(occurrences)) / len(set(homophone_occurrences)):0.0%}</div>
{f'<div class="over-sign">{len(set(occurrences)) / len(set(sign_occurrences)):0.0%}</div>'
if sign_occurrences else ''}
</div>"""
def table_row(values: tuple[asl.Value, ...], signs: tuple[asl.Sign, ...], sign_specific_table: bool):
text = "-".join(v.text for v in values)
base = atf.get_base(text)
only_sign = signs[0] if len(signs) == 1 else None
return f"""
<tr>
<th rowspan="2">{"-".join(f'''<a href="{
f"homophones/{('syllable-' if base == 'nul' else '')}{base}.html" if sign_specific_table else
f'../{sign.names[0].replace("|", "").replace("/", "-")}.html'
}">{
value.text
}{
"" if sign_specific_table else
f"({sign.unicode_cuneiform.text if sign.unicode_cuneiform else sign.names[0]})"
}</a>''' for value, sign in zip(values, signs, strict=True))}</th>
<td rowspan="2">{entry("OAkk", values, only_sign)}</td>
<td colspan="2">{entry("OA", values, only_sign)}</td>
<td>{entry("MA", values, only_sign)}</td>
<td colspan="2">{entry("NA", values, only_sign)}</td>
</tr>
<tr class="𒆍𒀭𒊏𒆠">
<td>{entry("Early OB", values, only_sign)}</td>
<td>{entry("OB", values, only_sign)}</td>
<td>{entry("MB", values, only_sign)}</td>
<td>{entry("Early NB", values, only_sign)}</td>
<td>{entry("NB", values, only_sign)}</td>
</tr>
"""
for sign in asl.osl.signs:
if isinstance(sign, asl.Sign):
if sign not in sign_to_period_to_occurrences:
continue
with open("syllabary/akk/" + sign.names[0].replace("|", "").replace("/", "-") + ".html", mode="w", encoding="utf-8") as f:
print(HEAD,
file=f)
print(f"<h1>Akkadian syllabic values of {sign.unicode_cuneiform.text if sign.unicode_cuneiform else sign.names[0]}</h1>", file=f)
print(SOURCE, file=f)
print(COUNT_SELECTOR, file=f)
print(RATIO_SELECTOR, file=f)
print(TABLE_PERIODS, file=f)
for value in sign.values:
if value.deprecated:
continue
if value.text == "xₓ":
continue
if not value_to_period_to_occurrences[value.text]:
continue
print(table_row((value,), (sign,), sign_specific_table=True), file=f)
print("</table></body></html>", file=f)
for base, signs_and_values in base_to_signs_and_values.items():
if not any(value_to_period_to_occurrences["-".join(v.text for v in values)] for _, values in signs_and_values):
continue
with open("syllabary/akk/homophones/" + ("syllable-" if base == "nul" else "") + base + ".html", mode="w", encoding="utf-8") as f:
print(HEAD,
file=f)
print(f"<h1>Akkadian spellings of /{base}/</h1>", file=f)
print(SOURCE, file=f)
print(COUNT_SELECTOR, file=f)
print(RATIO_SELECTOR, file=f)
print(TABLE_PERIODS, file=f)
for signs, values in sorted(signs_and_values, key=lambda sv: (len(sv[1]), "-".join (v.text for v in sv[1]))):
if not value_to_period_to_occurrences["-".join(v.text for v in values)]:
continue
print(table_row(values, signs, sign_specific_table=False), file=f)
print("</table></body></html>", file=f)
with open("syllabary/akk/index.html", mode="w", encoding="utf-8") as f:
print("<ul>", file=f)
for sign in asl.osl.signs:
if isinstance(sign, asl.Sign):
if sign not in sign_to_period_to_occurrences:
continue
print(f"<li><a href='{urllib.parse.quote(sign.names[0].replace('|', '').replace('/', '-'))}.html'>{sign.unicode_cuneiform.text if sign.unicode_cuneiform else ''} {sign.names[0]}</a></li>",
file=f)
print("</ul>", file=f)