predictingthepast 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.
- predictingthepast/__init__.py +13 -0
- predictingthepast/eval/__init__.py +13 -0
- predictingthepast/eval/inference.py +628 -0
- predictingthepast/models/__init__.py +13 -0
- predictingthepast/models/bigbird.py +116 -0
- predictingthepast/models/bigbird_attention.py +808 -0
- predictingthepast/models/common_layers.py +351 -0
- predictingthepast/models/model.py +416 -0
- predictingthepast/models/resnet.py +155 -0
- predictingthepast/models/t5_layers.py +1134 -0
- predictingthepast/util/__init__.py +13 -0
- predictingthepast/util/alphabet.py +268 -0
- predictingthepast/util/dates.py +76 -0
- predictingthepast/util/eval.py +639 -0
- predictingthepast/util/loss.py +121 -0
- predictingthepast/util/optim.py +179 -0
- predictingthepast/util/region_names.py +58 -0
- predictingthepast/util/text.py +191 -0
- predictingthepast-0.1.0.dist-info/METADATA +284 -0
- predictingthepast-0.1.0.dist-info/RECORD +24 -0
- predictingthepast-0.1.0.dist-info/WHEEL +5 -0
- predictingthepast-0.1.0.dist-info/licenses/AUTHORS +13 -0
- predictingthepast-0.1.0.dist-info/licenses/LICENSE +202 -0
- predictingthepast-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Copyright 2025 the Aeneas Authors
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Copyright 2025 the Aeneas Authors
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
@@ -0,0 +1,628 @@
|
|
|
1
|
+
# Copyright 2025 the Aeneas Authors
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
"""Module for performing inference using Jax, including decoding.
|
|
15
|
+
|
|
16
|
+
The module performs the main inference tasks via the functions attribute(),
|
|
17
|
+
restore(), and contextualize().
|
|
18
|
+
|
|
19
|
+
Both take a function called `forward`, a Jax function mapping from model inputs
|
|
20
|
+
(including parameters as the first argument) to the model output tuple.
|
|
21
|
+
This is in contrast to Ithaca's code which expected a forward function that
|
|
22
|
+
already wraps the model params.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
import json
|
|
26
|
+
import math
|
|
27
|
+
import pickle
|
|
28
|
+
import re
|
|
29
|
+
from typing import NamedTuple, Optional
|
|
30
|
+
|
|
31
|
+
import jax
|
|
32
|
+
import numpy as np
|
|
33
|
+
from PIL import Image
|
|
34
|
+
from predictingthepast.util import region_names
|
|
35
|
+
import predictingthepast.util.eval as eval_util
|
|
36
|
+
import predictingthepast.util.text as util_text
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ContextualizationResults(NamedTuple):
|
|
40
|
+
"""Similar inscriptions and related information."""
|
|
41
|
+
|
|
42
|
+
ids: list[str] # Inscription IDs
|
|
43
|
+
ids_alt: list[Optional[dict[str, str]]] # Inscription texts
|
|
44
|
+
text: list[str] # Inscription texts
|
|
45
|
+
location_ids: list[Optional[int]] # Location IDs
|
|
46
|
+
date_min: list[Optional[int]] # Lower bound of date range
|
|
47
|
+
date_max: list[Optional[int]] # Upper bound of date range
|
|
48
|
+
partner_link: list[Optional[str]] # Partner link urls when available
|
|
49
|
+
score: list[float] # Score of the similarity
|
|
50
|
+
|
|
51
|
+
def build_json(self):
|
|
52
|
+
return {
|
|
53
|
+
'ids': self.ids,
|
|
54
|
+
'ids_alt': self.ids_alt,
|
|
55
|
+
'text': self.text,
|
|
56
|
+
'location_ids': self.location_ids,
|
|
57
|
+
'date_min': self.date_min,
|
|
58
|
+
'date_max': self.date_max,
|
|
59
|
+
'partner_link': self.partner_link,
|
|
60
|
+
'score': self.score,
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
def json(self, **kwargs):
|
|
64
|
+
return json.dumps(self.build_json(), **kwargs)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class LocationPrediction(NamedTuple):
|
|
68
|
+
"""One location prediction and its associated probability."""
|
|
69
|
+
|
|
70
|
+
location_id: int
|
|
71
|
+
score: float
|
|
72
|
+
|
|
73
|
+
def build_json(self):
|
|
74
|
+
return {
|
|
75
|
+
'location_id': self.location_id,
|
|
76
|
+
'score': self.score,
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class AttributionResults(NamedTuple):
|
|
81
|
+
"""Immediate model output attribution predictions and related information."""
|
|
82
|
+
|
|
83
|
+
input_text: str
|
|
84
|
+
|
|
85
|
+
# List of pairs of location ID and probability
|
|
86
|
+
locations: list[LocationPrediction]
|
|
87
|
+
|
|
88
|
+
# Probabilities over year range [-800, -790, -780, ..., 790, 800]
|
|
89
|
+
year_scores: list[float] # length 160
|
|
90
|
+
|
|
91
|
+
# Per-character saliency maps:
|
|
92
|
+
date_saliency: list[float]
|
|
93
|
+
location_saliency: list[float] # originally called subregion
|
|
94
|
+
|
|
95
|
+
def build_json(self):
|
|
96
|
+
return {
|
|
97
|
+
'input_text': self.input_text,
|
|
98
|
+
'locations': [l.build_json() for l in self.locations],
|
|
99
|
+
'year_scores': self.year_scores,
|
|
100
|
+
'date_saliency': self.date_saliency,
|
|
101
|
+
'location_saliency': self.location_saliency,
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
def json(self, **kwargs):
|
|
105
|
+
return json.dumps(self.build_json(), **kwargs)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class Restoration(NamedTuple):
|
|
109
|
+
"""One restored candidate string from the beam search."""
|
|
110
|
+
|
|
111
|
+
text: str
|
|
112
|
+
restored: list[int] # char indices that were restored
|
|
113
|
+
score: float
|
|
114
|
+
|
|
115
|
+
def build_json(self):
|
|
116
|
+
return {'text': self.text, 'restored': self.restored, 'score': self.score}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class RestorationCharSaliency(NamedTuple):
|
|
120
|
+
"""Saliency entry for one predicted character of a prediction."""
|
|
121
|
+
|
|
122
|
+
text: str
|
|
123
|
+
restored_idx: int # which predicted character the saliency map corresponds to
|
|
124
|
+
saliency: list[float]
|
|
125
|
+
|
|
126
|
+
def build_json(self):
|
|
127
|
+
return {
|
|
128
|
+
'text': self.text,
|
|
129
|
+
'restored_idx': self.restored_idx,
|
|
130
|
+
'saliency': self.saliency,
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class RestorationResults(NamedTuple):
|
|
135
|
+
"""Contains all text-related restoration predictions."""
|
|
136
|
+
|
|
137
|
+
input_text: str
|
|
138
|
+
top_prediction: str
|
|
139
|
+
missing: list[int] # char indices with a missing character
|
|
140
|
+
|
|
141
|
+
# List of top N results from beam search:
|
|
142
|
+
predictions: list[Restoration]
|
|
143
|
+
|
|
144
|
+
# Saliency maps for each successive character of the best (greedy) prediction
|
|
145
|
+
prediction_saliency: list[RestorationCharSaliency]
|
|
146
|
+
|
|
147
|
+
def build_json(self):
|
|
148
|
+
return {
|
|
149
|
+
'input_text': self.input_text,
|
|
150
|
+
'top_prediction': self.top_prediction,
|
|
151
|
+
'predictions': [r.build_json() for r in self.predictions],
|
|
152
|
+
'prediction_saliency': [
|
|
153
|
+
m.build_json() for m in self.prediction_saliency
|
|
154
|
+
],
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
def json(self, **kwargs):
|
|
158
|
+
return json.dumps(self.build_json(), **kwargs)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def process_img(img, output_size=(224, 224)):
|
|
162
|
+
"""Process image."""
|
|
163
|
+
# Convert to grayscale
|
|
164
|
+
img = img.convert('L')
|
|
165
|
+
|
|
166
|
+
# Get image size
|
|
167
|
+
width, height = img.size
|
|
168
|
+
max_side = max(img.size)
|
|
169
|
+
|
|
170
|
+
# Create a square canvas with side length max_side
|
|
171
|
+
padded_img = Image.new('L', (max_side, max_side), (0,))
|
|
172
|
+
|
|
173
|
+
# Compute padding offsets
|
|
174
|
+
offset_x = (max_side - width) // 2
|
|
175
|
+
offset_y = (max_side - height) // 2
|
|
176
|
+
|
|
177
|
+
# Paste image onto canvas
|
|
178
|
+
padded_img.paste(img, (offset_x, offset_y))
|
|
179
|
+
|
|
180
|
+
# Crop the image
|
|
181
|
+
cropped_img = padded_img.crop((0, 0, max_side, max_side))
|
|
182
|
+
|
|
183
|
+
# Resize
|
|
184
|
+
cropped_img = cropped_img.resize(output_size)
|
|
185
|
+
|
|
186
|
+
return cropped_img
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
# These constants are fixed for all recent versions of the model.
|
|
190
|
+
MIN_TEXT_LEN = 25
|
|
191
|
+
TEXT_LEN = 768 # fixed model sequence length
|
|
192
|
+
DATE_MIN = -800
|
|
193
|
+
DATE_MAX = 800
|
|
194
|
+
DATE_INTERVAL = 10
|
|
195
|
+
RESTORATION_BEAM_WIDTH = 200
|
|
196
|
+
RESTORATION_TEMPERATURE = 1.0
|
|
197
|
+
UNK_RESTORATION_MAX_LEN = 20
|
|
198
|
+
A_PENALTY = 1.0
|
|
199
|
+
SEED = 1
|
|
200
|
+
ALPHABET_MISSING_RESTORE = '?' # missing characters to restore
|
|
201
|
+
ALPHABET_MISSING_UNK_RESTORE = '#' # missing characters to restore
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _prepare_text(
|
|
205
|
+
text, alphabet, check_length=True
|
|
206
|
+
) -> tuple[str, str, str, np.ndarray, list[int], np.ndarray, list[int]]:
|
|
207
|
+
"""Adds start of sequence symbol, and padding.
|
|
208
|
+
|
|
209
|
+
Also strips accents if present, trims whitespace, and generates arrays ready
|
|
210
|
+
for input into the model.
|
|
211
|
+
|
|
212
|
+
Args:
|
|
213
|
+
text: Raw text input string, no padding or start of sequence symbol.
|
|
214
|
+
alphabet: GreekAlphabet object containing index/character mappings.
|
|
215
|
+
check_length: Whether to check the length of the text.
|
|
216
|
+
|
|
217
|
+
Returns:
|
|
218
|
+
Tuple of cleaned text (str), padded text (str), char indices (array of batch
|
|
219
|
+
size 1), word indices (array of batch size 1), text length (list of size 1)
|
|
220
|
+
"""
|
|
221
|
+
text = re.sub(r'\s+', ' ', text.strip().lower())
|
|
222
|
+
text = util_text.strip_accents(text)
|
|
223
|
+
|
|
224
|
+
if check_length and len(text) < MIN_TEXT_LEN:
|
|
225
|
+
raise ValueError('Input text too short.')
|
|
226
|
+
|
|
227
|
+
if check_length and len(text) >= TEXT_LEN:
|
|
228
|
+
raise ValueError('Input text too long.')
|
|
229
|
+
|
|
230
|
+
text_sos = alphabet.sos + text
|
|
231
|
+
text_len = [len(text_sos)] # includes SOS, but not padding
|
|
232
|
+
|
|
233
|
+
restore_mask_idx = [
|
|
234
|
+
i
|
|
235
|
+
for i, c in enumerate(text_sos)
|
|
236
|
+
if c in [ALPHABET_MISSING_RESTORE, ALPHABET_MISSING_UNK_RESTORE]
|
|
237
|
+
]
|
|
238
|
+
|
|
239
|
+
text_padded = text_sos.replace(ALPHABET_MISSING_RESTORE, alphabet.missing)
|
|
240
|
+
text_padded = text_padded.replace(
|
|
241
|
+
ALPHABET_MISSING_UNK_RESTORE, alphabet.missing_unk
|
|
242
|
+
)
|
|
243
|
+
text_padded = text_padded + alphabet.pad * max(0, TEXT_LEN - len(text_sos))
|
|
244
|
+
|
|
245
|
+
text_char = util_text.text_to_idx(text_padded, alphabet).reshape(1, -1)
|
|
246
|
+
padding = np.where(text_char > 0, 1, 0)
|
|
247
|
+
|
|
248
|
+
return (
|
|
249
|
+
text,
|
|
250
|
+
text_sos,
|
|
251
|
+
text_padded,
|
|
252
|
+
text_char,
|
|
253
|
+
text_len,
|
|
254
|
+
padding,
|
|
255
|
+
restore_mask_idx,
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _generate_text_emb(params, forward, alphabet, input_text, emb_mode='avg'):
|
|
260
|
+
"""Computes model embeddings for retrieval."""
|
|
261
|
+
|
|
262
|
+
# Text preparation and inference
|
|
263
|
+
(_, _, _, text_char, text_len, _, _) = _prepare_text(input_text, alphabet)
|
|
264
|
+
|
|
265
|
+
# Generate embeddings
|
|
266
|
+
rng = jax.random.PRNGKey(SEED)
|
|
267
|
+
_, torso_outputs = forward(
|
|
268
|
+
params,
|
|
269
|
+
text_char=text_char,
|
|
270
|
+
output_return_emb=True,
|
|
271
|
+
rngs={'dropout': rng},
|
|
272
|
+
is_training=False,
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
if emb_mode == 'first':
|
|
276
|
+
return np.array(torso_outputs[0, 0])
|
|
277
|
+
elif emb_mode == 'avg':
|
|
278
|
+
return np.array(torso_outputs[0, : text_len[0]].mean(0))
|
|
279
|
+
else:
|
|
280
|
+
raise ValueError(f'Unknown emb_mode: {emb_mode}')
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _get_relevant_texts(
|
|
284
|
+
dataset,
|
|
285
|
+
retrieval,
|
|
286
|
+
text_emb,
|
|
287
|
+
exclude_id=None,
|
|
288
|
+
normalize=False,
|
|
289
|
+
include_test=False,
|
|
290
|
+
retrieval_top_k=20,
|
|
291
|
+
):
|
|
292
|
+
"""Returns retrieval stats for a given text embedding."""
|
|
293
|
+
if normalize:
|
|
294
|
+
text_emb = (text_emb - retrieval['emb_v_mean']) / retrieval['emb_v_std']
|
|
295
|
+
|
|
296
|
+
if include_test:
|
|
297
|
+
retrieval_k = retrieval['emb_k_all']
|
|
298
|
+
retrieval_v = retrieval['emb_v_all_normed']
|
|
299
|
+
else:
|
|
300
|
+
retrieval_k = retrieval['emb_k']
|
|
301
|
+
retrieval_v = retrieval['emb_v_normed']
|
|
302
|
+
|
|
303
|
+
# Cosine similarity
|
|
304
|
+
text_emb_norm = text_emb / np.linalg.norm(text_emb)
|
|
305
|
+
sim = np.dot(retrieval_v, text_emb_norm)
|
|
306
|
+
|
|
307
|
+
# Sort by highest similarity
|
|
308
|
+
sorted_idx = np.argsort(-sim)
|
|
309
|
+
if exclude_id is not None:
|
|
310
|
+
sorted_idx_mask = retrieval_k[sorted_idx] != exclude_id
|
|
311
|
+
sorted_idx = sorted_idx[sorted_idx_mask]
|
|
312
|
+
|
|
313
|
+
# Get stats
|
|
314
|
+
sorted_idx = sorted_idx[:retrieval_top_k]
|
|
315
|
+
retrieval_data = [dataset[int(d_id)] for d_id in retrieval_k[sorted_idx]]
|
|
316
|
+
retrieval_stats_sim = sim[sorted_idx]
|
|
317
|
+
|
|
318
|
+
return retrieval_data, retrieval_stats_sim
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def attribute(
|
|
322
|
+
text,
|
|
323
|
+
forward,
|
|
324
|
+
params,
|
|
325
|
+
alphabet,
|
|
326
|
+
vocab_char_size,
|
|
327
|
+
vision_img=None,
|
|
328
|
+
vision_output_size=(224, 224),
|
|
329
|
+
) -> AttributionResults:
|
|
330
|
+
"""Computes predicted date and geographical region."""
|
|
331
|
+
|
|
332
|
+
(text, _, _, text_char, text_len, padding, _) = _prepare_text(text, alphabet)
|
|
333
|
+
|
|
334
|
+
if vision_img is not None:
|
|
335
|
+
vision_img = process_img(vision_img, output_size=vision_output_size)
|
|
336
|
+
vision_img = np.array(vision_img)[None, ..., None]
|
|
337
|
+
vision_img = vision_img / 127.5 - 1.0
|
|
338
|
+
vision_available = np.ones((1,))
|
|
339
|
+
else:
|
|
340
|
+
vision_img = np.zeros((1, vision_output_size[0], vision_output_size[1], 1))
|
|
341
|
+
vision_available = np.zeros((1,))
|
|
342
|
+
|
|
343
|
+
rng = jax.random.PRNGKey(SEED)
|
|
344
|
+
date_logits, subregion_logits, _, _, _ = forward(
|
|
345
|
+
params,
|
|
346
|
+
text_char=text_char,
|
|
347
|
+
vision_img=vision_img,
|
|
348
|
+
vision_available=vision_available,
|
|
349
|
+
rngs={'dropout': rng},
|
|
350
|
+
is_training=False,
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
# Generate subregion predictions:
|
|
354
|
+
subregion_logits = np.array(subregion_logits)
|
|
355
|
+
subregion_pred_probs = eval_util.softmax(subregion_logits[0]).tolist()
|
|
356
|
+
location_predictions = [
|
|
357
|
+
LocationPrediction(location_id=id, score=prob)
|
|
358
|
+
for id, prob in enumerate(subregion_pred_probs)
|
|
359
|
+
]
|
|
360
|
+
location_predictions.sort(key=lambda loc: loc.score, reverse=True)
|
|
361
|
+
|
|
362
|
+
# Generate date predictions:
|
|
363
|
+
date_pred_probs = eval_util.softmax(date_logits[0])
|
|
364
|
+
|
|
365
|
+
# Gradients for saliency maps
|
|
366
|
+
date_saliency, subregion_saliency = (
|
|
367
|
+
eval_util.compute_attribution_saliency_maps(
|
|
368
|
+
text_char,
|
|
369
|
+
text_len,
|
|
370
|
+
padding,
|
|
371
|
+
forward,
|
|
372
|
+
params,
|
|
373
|
+
alphabet,
|
|
374
|
+
vocab_char_size,
|
|
375
|
+
)
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
# Skip start of sequence symbol (first char) for text and saliency maps:
|
|
379
|
+
return AttributionResults(
|
|
380
|
+
input_text=text,
|
|
381
|
+
locations=location_predictions,
|
|
382
|
+
year_scores=date_pred_probs.tolist(),
|
|
383
|
+
date_saliency=date_saliency.tolist()[1:],
|
|
384
|
+
location_saliency=subregion_saliency.tolist()[1:],
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def restore(
|
|
389
|
+
text,
|
|
390
|
+
forward,
|
|
391
|
+
params,
|
|
392
|
+
alphabet,
|
|
393
|
+
vocab_char_size,
|
|
394
|
+
beam_width=RESTORATION_BEAM_WIDTH,
|
|
395
|
+
temperature=RESTORATION_TEMPERATURE,
|
|
396
|
+
unk_restoration_max_len=UNK_RESTORATION_MAX_LEN,
|
|
397
|
+
a_penalty=A_PENALTY,
|
|
398
|
+
) -> RestorationResults:
|
|
399
|
+
"""Performs search to compute text restoration. Slower, runs synchronously."""
|
|
400
|
+
|
|
401
|
+
if (
|
|
402
|
+
ALPHABET_MISSING_RESTORE not in text
|
|
403
|
+
and ALPHABET_MISSING_UNK_RESTORE not in text
|
|
404
|
+
):
|
|
405
|
+
raise ValueError('At least one character must be missing.')
|
|
406
|
+
|
|
407
|
+
count_unk = text.count(ALPHABET_MISSING_UNK_RESTORE)
|
|
408
|
+
(text, _, text_padded, _, text_len, _, restore_mask_idx) = _prepare_text(
|
|
409
|
+
text, alphabet
|
|
410
|
+
)
|
|
411
|
+
|
|
412
|
+
# Check maximum length of unknown restoration
|
|
413
|
+
if ALPHABET_MISSING_UNK_RESTORE in text:
|
|
414
|
+
if unk_restoration_max_len < 1:
|
|
415
|
+
# Must be at least 1
|
|
416
|
+
raise ValueError('unk_restoration_max_len must be at least 1.')
|
|
417
|
+
elif unk_restoration_max_len > UNK_RESTORATION_MAX_LEN:
|
|
418
|
+
# Clip to the default maximum length
|
|
419
|
+
raise ValueError(
|
|
420
|
+
'unk_restoration_max_len=%d > maximum value %d.'
|
|
421
|
+
% (
|
|
422
|
+
unk_restoration_max_len,
|
|
423
|
+
UNK_RESTORATION_MAX_LEN,
|
|
424
|
+
)
|
|
425
|
+
)
|
|
426
|
+
|
|
427
|
+
# Define maximum restoration length
|
|
428
|
+
max_len = min(
|
|
429
|
+
text_len[0] - count_unk + unk_restoration_max_len,
|
|
430
|
+
TEXT_LEN,
|
|
431
|
+
)
|
|
432
|
+
else:
|
|
433
|
+
max_len = text_len[0]
|
|
434
|
+
|
|
435
|
+
beam_result = eval_util.beam_search_batch(
|
|
436
|
+
forward,
|
|
437
|
+
params,
|
|
438
|
+
alphabet,
|
|
439
|
+
text_padded,
|
|
440
|
+
restore_mask_idx,
|
|
441
|
+
max_len=max_len,
|
|
442
|
+
beam_width=beam_width,
|
|
443
|
+
temperature=temperature,
|
|
444
|
+
sequential_decoding=False,
|
|
445
|
+
a_penalty=a_penalty,
|
|
446
|
+
)
|
|
447
|
+
|
|
448
|
+
# For visualization purposes, we strip out the SOS and padding, and adjust
|
|
449
|
+
# restored_indices accordingly
|
|
450
|
+
predictions = [
|
|
451
|
+
Restoration(
|
|
452
|
+
text=beam_entry.text_pred[1:].rstrip(alphabet.pad),
|
|
453
|
+
restored=[i - 1 for i in beam_entry.mask_idx],
|
|
454
|
+
score=math.exp(beam_entry.pred_logprob),
|
|
455
|
+
)
|
|
456
|
+
for beam_entry in beam_result
|
|
457
|
+
]
|
|
458
|
+
missing_indices = [i - 1 for i in restore_mask_idx]
|
|
459
|
+
|
|
460
|
+
# Sequence of saliency maps for the top prediction's trajectory:
|
|
461
|
+
saliency_char_steps = []
|
|
462
|
+
if beam_result:
|
|
463
|
+
# Use the trajectory from the top beam result for saliency
|
|
464
|
+
top_beam_entry = beam_result[0]
|
|
465
|
+
saliency_generator = eval_util.sequential_restoration_saliency(
|
|
466
|
+
top_beam_entry.text_history, # Pass the history from the top beam
|
|
467
|
+
forward,
|
|
468
|
+
params,
|
|
469
|
+
alphabet,
|
|
470
|
+
vocab_char_size,
|
|
471
|
+
)
|
|
472
|
+
saliency_char_steps = [
|
|
473
|
+
RestorationCharSaliency(
|
|
474
|
+
step.text[1:].rstrip(alphabet.pad),
|
|
475
|
+
int(step.pred_char_pos) - 1,
|
|
476
|
+
step.saliency_map.tolist(),
|
|
477
|
+
)
|
|
478
|
+
for step in saliency_generator
|
|
479
|
+
]
|
|
480
|
+
|
|
481
|
+
return RestorationResults(
|
|
482
|
+
input_text=text,
|
|
483
|
+
# Handle case where predictions might be empty, though beam_search_batch
|
|
484
|
+
# is expected to return at least one result if successful.
|
|
485
|
+
top_prediction=predictions[0].text if predictions else '',
|
|
486
|
+
missing=missing_indices,
|
|
487
|
+
predictions=predictions,
|
|
488
|
+
prediction_saliency=saliency_char_steps,
|
|
489
|
+
)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def contextualize(
|
|
493
|
+
text,
|
|
494
|
+
dataset,
|
|
495
|
+
retrieval,
|
|
496
|
+
forward,
|
|
497
|
+
params,
|
|
498
|
+
alphabet,
|
|
499
|
+
region_map,
|
|
500
|
+
include_test=True,
|
|
501
|
+
top_k=20,
|
|
502
|
+
) -> ContextualizationResults:
|
|
503
|
+
"""Performs search to compute text restoration. Slower, runs synchronously."""
|
|
504
|
+
|
|
505
|
+
text_emb = _generate_text_emb(params, forward, alphabet, text, emb_mode='avg')
|
|
506
|
+
|
|
507
|
+
context_data, context_score = _get_relevant_texts(
|
|
508
|
+
dataset,
|
|
509
|
+
retrieval,
|
|
510
|
+
text_emb,
|
|
511
|
+
normalize=True,
|
|
512
|
+
include_test=include_test,
|
|
513
|
+
retrieval_top_k=top_k,
|
|
514
|
+
)
|
|
515
|
+
|
|
516
|
+
ids = []
|
|
517
|
+
ids_alt = []
|
|
518
|
+
text = []
|
|
519
|
+
location_ids = []
|
|
520
|
+
date_min = []
|
|
521
|
+
date_max = []
|
|
522
|
+
partner_link = []
|
|
523
|
+
score = []
|
|
524
|
+
for d, s in zip(context_data, context_score):
|
|
525
|
+
ids.append(d.get('record_number', d.get('id')))
|
|
526
|
+
ids_alt_dict = {k: str(v) for k, v in d['ids_alt'].items()}
|
|
527
|
+
ids_alt.append(ids_alt_dict)
|
|
528
|
+
text.append(d['text'])
|
|
529
|
+
score.append(float(s))
|
|
530
|
+
|
|
531
|
+
if 'region_sub' in d and d['region_sub'] is not None:
|
|
532
|
+
region_sub_name = region_names.region_name_filter(d['region_sub'])
|
|
533
|
+
location_ids.append(region_map['names_inv'][region_sub_name])
|
|
534
|
+
else:
|
|
535
|
+
location_ids.append(None)
|
|
536
|
+
|
|
537
|
+
if 'date_min' in d and d['date_min'] is not None:
|
|
538
|
+
date_min.append(int(d['date_min']))
|
|
539
|
+
else:
|
|
540
|
+
date_min.append(None)
|
|
541
|
+
|
|
542
|
+
if 'date_max' in d and d['date_max'] is not None:
|
|
543
|
+
date_max.append(int(d['date_max']))
|
|
544
|
+
else:
|
|
545
|
+
date_max.append(None)
|
|
546
|
+
|
|
547
|
+
if 'partner_link' in d:
|
|
548
|
+
partner_link.append(d['partner_link'])
|
|
549
|
+
else:
|
|
550
|
+
partner_link.append(None)
|
|
551
|
+
|
|
552
|
+
return ContextualizationResults(
|
|
553
|
+
ids=ids,
|
|
554
|
+
ids_alt=ids_alt,
|
|
555
|
+
text=text,
|
|
556
|
+
location_ids=location_ids,
|
|
557
|
+
date_min=date_min,
|
|
558
|
+
date_max=date_max,
|
|
559
|
+
partner_link=partner_link,
|
|
560
|
+
score=score,
|
|
561
|
+
)
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def load_dataset(path):
|
|
565
|
+
"""Loads a dataset json."""
|
|
566
|
+
with open(path, 'r') as f:
|
|
567
|
+
json_data = json.load(f)
|
|
568
|
+
dataset = {}
|
|
569
|
+
for d in json_data:
|
|
570
|
+
d['id'] = int(d['id'])
|
|
571
|
+
dataset[d['id']] = d
|
|
572
|
+
return dataset
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def load_retrieval(path):
|
|
576
|
+
"""Loads and preprocesses pre-computed embeddings for retrieval.
|
|
577
|
+
|
|
578
|
+
This function loads a pickle file containing embeddings, splits them into
|
|
579
|
+
training, testing, and "all" sets, normalizes them, and calculates
|
|
580
|
+
L2-normalized versions. The embeddings are assumed to be stored as a
|
|
581
|
+
dictionary where keys are integer IDs and values are dictionaries containing
|
|
582
|
+
at least an 'avg' key with the embedding vector.
|
|
583
|
+
|
|
584
|
+
Args:
|
|
585
|
+
path: Path to the pickle file containing the embeddings.
|
|
586
|
+
|
|
587
|
+
Returns:
|
|
588
|
+
A dictionary containing the processed embeddings and related information.
|
|
589
|
+
The dictionary has the following keys:
|
|
590
|
+
- 'emb_k': An array of embedding keys for training (excluding those
|
|
591
|
+
ending in 3 or 4).
|
|
592
|
+
- 'emb_k_all': An array of all embedding keys (integer IDs).
|
|
593
|
+
- 'emb_v': An array of embedding vectors for training.
|
|
594
|
+
- 'emb_v_all': An array of all embedding vectors.
|
|
595
|
+
- 'emb_v_mean': The mean of the training embeddings.
|
|
596
|
+
- 'emb_v_std': The standard deviation of the training embeddings.
|
|
597
|
+
- 'emb_v_normed': L2-normalized training embeddings.
|
|
598
|
+
- 'emb_v_all_normed': L2-normalized "all" embeddings.
|
|
599
|
+
"""
|
|
600
|
+
# Load embeddings
|
|
601
|
+
retrieval = {}
|
|
602
|
+
with open(path, 'rb') as f:
|
|
603
|
+
embed = pickle.load(f)
|
|
604
|
+
retrieval['emb_k_all'] = np.array(list(embed.keys()), dtype=np.int32)
|
|
605
|
+
|
|
606
|
+
# Embeddings for training and test
|
|
607
|
+
retrieval['emb_k'] = np.array(
|
|
608
|
+
[k for k in retrieval['emb_k_all'] if k % 10 not in [3, 4]],
|
|
609
|
+
dtype=np.int32,
|
|
610
|
+
)
|
|
611
|
+
emb_v = np.array([embed[k]['avg'] for k in retrieval['emb_k']])
|
|
612
|
+
emb_v_all = np.array([embed[k]['avg'] for k in retrieval['emb_k_all']])
|
|
613
|
+
|
|
614
|
+
# Normalize embeddings
|
|
615
|
+
retrieval['emb_v_mean'] = np.mean(emb_v, axis=0)
|
|
616
|
+
retrieval['emb_v_std'] = np.std(emb_v, axis=0)
|
|
617
|
+
emb_v_normed = (emb_v - retrieval['emb_v_mean']) / retrieval['emb_v_std']
|
|
618
|
+
emb_v_all_normed = (emb_v_all - retrieval['emb_v_mean']) / retrieval[
|
|
619
|
+
'emb_v_std'
|
|
620
|
+
]
|
|
621
|
+
|
|
622
|
+
retrieval['emb_v_normed'] = emb_v_normed / np.linalg.norm(
|
|
623
|
+
emb_v_normed, axis=1, keepdims=True
|
|
624
|
+
)
|
|
625
|
+
retrieval['emb_v_all_normed'] = emb_v_all_normed / np.linalg.norm(
|
|
626
|
+
emb_v_all_normed, axis=1, keepdims=True
|
|
627
|
+
)
|
|
628
|
+
return retrieval
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Copyright 2025 the Aeneas Authors
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|