seldon-runtime 0.1.1.dev0__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.
@@ -0,0 +1,684 @@
1
+ """Pure bounded collection kernels. Entity identity is never inferred by position.
2
+
3
+ Offsets are half-open Unicode codepoints in the original source. Retrieval is
4
+ lexical candidate generation, not semantic truth; omission is explicit evidence.
5
+ """
6
+
7
+ import re
8
+ import unicodedata
9
+ from decimal import Decimal
10
+
11
+ from .contracts import canonical, digest
12
+
13
+ OPERATORS = {
14
+ "normalize_text": (1, {"casefold"}),
15
+ "chunk_text": (1, {"size", "overlap", "unit"}),
16
+ "retrieve_candidates": (2, {"top_k"}),
17
+ "exact_links": (2, {"unique"}),
18
+ "resolve_links": (2, {"unique"}),
19
+ "assemble_records": (2, {"fields"}),
20
+ "align_spans": (2, set()),
21
+ "project_records": (1, {"fields"}),
22
+ "merge_spans": (2, set()),
23
+ "merge_records": (1, {"fields", "sums"}),
24
+ "merge_labels": (1, {"rule", "order"}),
25
+ }
26
+ MERGE_RULES = frozenset({"all_agree", "any_true", "max_ordinal", "union"})
27
+
28
+ NEW_OPERATORS = {"align_spans", "project_records"}
29
+ # Advertised only with the chunking construction. Legacy registries stay unchanged.
30
+ CHUNK_OPERATORS = {"merge_spans", "merge_records", "merge_labels"}
31
+
32
+
33
+ UNALIGNED_MODES = frozenset({"fail", "drop"})
34
+ # Quotations the kernel cannot place. In ``drop`` mode only these omit a record;
35
+ # every other validation error still raises.
36
+ UNPLACEABLE = ("ungrounded_span", "ambiguous_span")
37
+
38
+
39
+ def align_spans(text, records, *, unaligned="fail", context_policy="strict", diagnostics=None):
40
+ """Ground exact quotations without correcting provider offsets or guessing repeats.
41
+
42
+ ``unaligned="drop"`` (span-recipes-v2) omits a quotation that is absent or still
43
+ ambiguous after its prefix/suffix, and grounds the rest unchanged. ``diagnostics``
44
+ (a dict) then receives counts only, never quotation text, since quotes can be PII.
45
+ """
46
+ if (
47
+ not isinstance(unaligned, str)
48
+ or unaligned not in UNALIGNED_MODES
49
+ or not isinstance(context_policy, str)
50
+ or context_policy not in {"strict", "hint"}
51
+ ):
52
+ raise ValueError("invalid_kernel_configuration")
53
+ if not isinstance(text, str) or len(text.encode()) > 262144:
54
+ raise ValueError("invalid_text")
55
+ if not isinstance(records, list) or len(records) > 32:
56
+ raise ValueError("span_limit")
57
+ grounded = []
58
+ dropped = dict.fromkeys(UNPLACEABLE, 0)
59
+ repaired = 0
60
+ for record in records:
61
+ if not isinstance(record, dict):
62
+ raise ValueError("invalid_span")
63
+ quote, label = record.get("text"), record.get("label")
64
+ prefix, suffix = record.get("prefix", ""), record.get("suffix", "")
65
+ if not isinstance(quote, str) or not quote or not isinstance(label, str) or not label:
66
+ raise ValueError("invalid_span")
67
+ if not isinstance(prefix, str) or not isinstance(suffix, str):
68
+ raise ValueError("invalid_span_context")
69
+ if "start" in record or "end" in record:
70
+ normalized_span = normalize_spans(text, [record])[0]
71
+ start, end = normalized_span["start"], normalized_span["end"]
72
+ if not text[:start].endswith(prefix) or not text[end:].startswith(suffix):
73
+ raise ValueError("invalid_span_context")
74
+ grounded.append(normalized_span)
75
+ continue
76
+ matches, start = [], text.find(quote)
77
+ while start >= 0:
78
+ end = start + len(quote)
79
+ if text[:start].endswith(prefix) and text[end:].startswith(suffix):
80
+ matches.append((start, end))
81
+ if len(matches) > 1:
82
+ break
83
+ start = text.find(quote, start + 1)
84
+ reason = (
85
+ "ambiguous_span" if len(matches) > 1 else "ungrounded_span" if not matches else None
86
+ )
87
+ if reason == "ungrounded_span" and context_policy == "hint":
88
+ first = text.find(quote)
89
+ if first >= 0 and text.find(quote, first + 1) < 0:
90
+ matches = [(first, first + len(quote))]
91
+ reason = None
92
+ repaired += 1
93
+ if reason is not None:
94
+ if unaligned == "fail":
95
+ raise ValueError(reason)
96
+ dropped[reason] += 1
97
+ continue
98
+ start, end = matches[0]
99
+ grounded.append({"text": quote, "label": label, "start": start, "end": end})
100
+ if (unaligned == "drop" or context_policy == "hint") and diagnostics is not None:
101
+ diagnostics.update(
102
+ quoted_records=len(records),
103
+ dropped_quotations=sum(dropped.values()),
104
+ dropped_reasons=dropped,
105
+ )
106
+ if context_policy == "hint":
107
+ diagnostics["repaired_contexts"] = repaired
108
+ return normalize_spans(text, grounded)
109
+
110
+
111
+ def project_records(records, fields):
112
+ """Explicit JSON-pointer projections only; missing values are never filled."""
113
+ from .executor import pointer
114
+
115
+ if not isinstance(records, list) or len(records) > 32:
116
+ raise ValueError("record_limit")
117
+ result = []
118
+ for row in records:
119
+ if not isinstance(row, dict):
120
+ raise ValueError("invalid_record")
121
+ try:
122
+ result.append({name: pointer(row, path) for name, path in fields.items()})
123
+ except (KeyError, IndexError, TypeError, ValueError) as exc:
124
+ raise ValueError("missing_projection_field") from exc
125
+ return result
126
+
127
+
128
+ def bounded_rows(rows, limit, code):
129
+ if (
130
+ not isinstance(rows, list)
131
+ or len(rows) > limit
132
+ or any(not isinstance(r, dict) for r in rows)
133
+ ):
134
+ raise ValueError(code)
135
+ ids = [r.get("id") for r in rows]
136
+ if any(not isinstance(i, str) or not i or len(i) > 128 for i in ids) or len(set(ids)) != len(
137
+ ids
138
+ ):
139
+ raise ValueError("invalid_identity")
140
+ return {r["id"]: r for r in rows}
141
+
142
+
143
+ def normalized(text):
144
+ if not isinstance(text, str):
145
+ raise ValueError("invalid_text")
146
+ return " ".join(unicodedata.normalize("NFKC", text).casefold().split())
147
+
148
+
149
+ def normalize_spans(text, spans, *, unit="codepoint", document_id=None):
150
+ if not isinstance(text, str) or not isinstance(spans, list) or len(spans) > 32:
151
+ raise ValueError("span_limit")
152
+ if unit not in {"codepoint", "utf8"}:
153
+ raise ValueError("unsupported_offset_unit")
154
+ doc = document_id or digest(text)
155
+ byte_map, offset = {0: 0}, 0
156
+ for i, character in enumerate(text):
157
+ offset += len(character.encode())
158
+ byte_map[offset] = i + 1
159
+ output = {}
160
+ for span in spans:
161
+ if not isinstance(span, dict):
162
+ raise ValueError("invalid_span")
163
+ start, end = span.get("start"), span.get("end")
164
+ if type(start) is not int or type(end) is not int:
165
+ raise ValueError("invalid_span")
166
+ if unit == "utf8":
167
+ start, end = byte_map.get(start), byte_map.get(end)
168
+ if (
169
+ start is None
170
+ or end is None
171
+ or not 0 <= start < end <= len(text)
172
+ or text[start:end] != span.get("text")
173
+ ):
174
+ raise ValueError("invalid_span")
175
+ label = span.get("label", "entity")
176
+ if not isinstance(label, str) or len(label) > 128:
177
+ raise ValueError("invalid_span")
178
+ identity = digest([doc, start, end, label])
179
+ item = {
180
+ "id": identity,
181
+ "document_id": doc,
182
+ "start": start,
183
+ "end": end,
184
+ "text": text[start:end],
185
+ "label": label,
186
+ }
187
+ if "confidence" in span:
188
+ score = span["confidence"]
189
+ if type(score) not in {int, float} or not 0 <= score <= 1:
190
+ raise ValueError("invalid_span")
191
+ item["confidence"] = score
192
+ if identity in output and output[identity] != item:
193
+ raise ValueError("conflicting_span")
194
+ output[identity] = item
195
+ return sorted(output.values(), key=lambda v: (v["start"], v["end"], v["label"]))
196
+
197
+
198
+ def candidates(mentions, catalog, *, top_k=3):
199
+ bounded_rows(mentions, 32, "mention_limit")
200
+ bounded_rows(catalog, 500, "catalog_limit")
201
+ if type(top_k) is not int or top_k not in {1, 3, 5}:
202
+ raise ValueError("invalid_top_k")
203
+ catalog = sorted(catalog, key=lambda r: r["id"])
204
+ catalog_id = digest(catalog)
205
+ pairs, omitted = [], 0
206
+ for mention in mentions:
207
+ needle = normalized(mention.get("text"))
208
+ tokens = set(re.findall(r"\w+", needle))
209
+ matches = []
210
+ for row in catalog:
211
+ aliases = row.get("aliases", [])
212
+ if not isinstance(aliases, list) or len(aliases) > 32:
213
+ raise ValueError("invalid_aliases")
214
+ names = [normalized(row.get("name")), *[normalized(a) for a in aliases]]
215
+ score = max(
216
+ (
217
+ 1.0
218
+ if needle and needle == name
219
+ else len(tokens & set(re.findall(r"\w+", name)))
220
+ / max(1, len(tokens | set(re.findall(r"\w+", name))))
221
+ )
222
+ for name in names
223
+ )
224
+ if score > 0:
225
+ matches.append((score, row["id"]))
226
+ matches.sort(key=lambda v: (-v[0], v[1]))
227
+ omitted += max(0, len(matches) - top_k)
228
+ for score, candidate in matches[:top_k]:
229
+ pairs.append(
230
+ {
231
+ "id": digest([catalog_id, mention["id"], candidate]),
232
+ "mention_id": mention["id"],
233
+ "candidate_id": candidate,
234
+ "retrieval_score": score,
235
+ }
236
+ )
237
+ return {
238
+ "catalog_id": catalog_id,
239
+ "pairs": pairs,
240
+ "omitted_pairs": omitted,
241
+ "mention_ids": [r["id"] for r in mentions],
242
+ }
243
+
244
+
245
+ def resolve_links(retrieval, decisions, *, unique=False):
246
+ pairs = bounded_rows(retrieval["pairs"], 160, "pair_limit")
247
+ mentions = retrieval.get("mention_ids")
248
+ if (
249
+ not isinstance(mentions, list)
250
+ or len(mentions) > 32
251
+ or any(not isinstance(m, str) or not m or len(m) > 128 for m in mentions)
252
+ or len(set(mentions)) != len(mentions)
253
+ ):
254
+ raise ValueError("invalid_identity")
255
+ identities = set()
256
+ for pair in pairs.values():
257
+ identity = (pair.get("mention_id"), pair.get("candidate_id"))
258
+ if (
259
+ not all(isinstance(v, str) and 0 < len(v) <= 128 for v in identity)
260
+ or identity[0] not in mentions
261
+ or identity in identities
262
+ ):
263
+ raise ValueError("invalid_identity")
264
+ identities.add(identity)
265
+ judged = bounded_rows(decisions, 160, "pair_limit")
266
+ if pairs.keys() != judged.keys() or any(type(d.get("match")) is not bool for d in decisions):
267
+ raise ValueError("incomplete_pair_decisions")
268
+ matches = {m: [] for m in retrieval["mention_ids"]}
269
+ for identity, decision in judged.items():
270
+ if decision["match"]:
271
+ pair = pairs[identity]
272
+ matches[pair["mention_id"]].append(pair["candidate_id"])
273
+ chosen = [v[0] for v in matches.values() if len(v) == 1]
274
+ output = []
275
+ for mention, values in matches.items():
276
+ ambiguous = len(values) > 1 or (unique and values and chosen.count(values[0]) > 1)
277
+ output.append(
278
+ {
279
+ "mention_id": mention,
280
+ "candidate_id": values[0] if len(values) == 1 and not ambiguous else None,
281
+ "status": "ambiguous" if ambiguous else "matched" if values else "no_match",
282
+ }
283
+ )
284
+ return output
285
+
286
+
287
+ def retrieval_evidence(trace, expected):
288
+ """Teacher-labelled recall is separate from decisions on the retrieved pairs.
289
+
290
+ This diagnostic is never a qualification score or a planning feature. An
291
+ absent reference or omitted intermediate has no observed recall value.
292
+ """
293
+ if not isinstance(expected, dict):
294
+ return None
295
+ targets = {
296
+ (item["mention_id"], item["candidate_id"])
297
+ for values in expected.values()
298
+ if isinstance(values, list)
299
+ for item in values
300
+ if isinstance(item, dict)
301
+ and isinstance(item.get("mention_id"), str)
302
+ and isinstance(item.get("candidate_id"), str)
303
+ }
304
+ for step in trace:
305
+ if step["operator"] != "retrieve_candidates":
306
+ continue
307
+ value = (step.get("output") or {}).get("value")
308
+ if not isinstance(value, dict):
309
+ return {"state": "unavailable"}
310
+ pairs = {(p["mention_id"], p["candidate_id"]) for p in value["pairs"]}
311
+ return {
312
+ "state": "observed",
313
+ "positive_targets": len(targets),
314
+ "retrieved_targets": len(targets & pairs),
315
+ "missing_targets": [
316
+ {"mention_id": m, "candidate_id": c} for m, c in sorted(targets - pairs)
317
+ ],
318
+ "scope": "reference_labelled_targets",
319
+ }
320
+ return None
321
+
322
+
323
+ def assemble_records(mentions, relations, fields):
324
+ index = bounded_rows(mentions, 32, "mention_limit")
325
+ bounded_rows(relations, 32, "record_limit")
326
+ if (
327
+ not isinstance(fields, list)
328
+ or not 1 <= len(fields) <= 32
329
+ or any(not isinstance(f, str) or not f for f in fields)
330
+ or len(set(fields)) != len(fields)
331
+ ):
332
+ raise ValueError("invalid_fields")
333
+ output = []
334
+ for relation in relations:
335
+ record = {}
336
+ for field in fields:
337
+ identity = relation.get(field)
338
+ if identity is not None and identity not in index:
339
+ raise ValueError("unknown_mention")
340
+ record[field] = index[identity]["text"] if identity is not None else None
341
+ output.append(record)
342
+ return output
343
+
344
+
345
+ def validate_config(op, inputs, config):
346
+ from jsonschema import Draft202012Validator
347
+
348
+ from .components import semantic_contract
349
+
350
+ arity, keys = OPERATORS[op]
351
+ if op == "align_spans" and isinstance(config, dict) and "context_policy" in config:
352
+ if not isinstance(config["context_policy"], str) or config["context_policy"] not in {
353
+ "strict",
354
+ "hint",
355
+ }:
356
+ raise ValueError("invalid_kernel_configuration")
357
+ config = {k: v for k, v in config.items() if k != "context_policy"}
358
+ if op == "align_spans" and isinstance(config, dict) and "unaligned" in config:
359
+ # span-recipes-v2. Kept out of OPERATORS so the advertised component registry
360
+ # (and every frozen proposal envelope) stays byte-identical.
361
+ if not isinstance(config["unaligned"], str) or config["unaligned"] not in UNALIGNED_MODES:
362
+ raise ValueError("invalid_kernel_configuration")
363
+ config = {k: v for k, v in config.items() if k != "unaligned"}
364
+ if len(inputs) != arity or set(config) - keys:
365
+ raise ValueError("invalid_kernel_configuration")
366
+ if not Draft202012Validator(semantic_contract(op)["config_schema"]).is_valid(config):
367
+ raise ValueError("invalid_kernel_configuration")
368
+ if op == "project_records":
369
+ from .contracts import reference
370
+
371
+ for path in config["fields"].values():
372
+ reference("input#" + path)
373
+ if op == "retrieve_candidates" and (
374
+ type(config.get("top_k", 3)) is not int or config.get("top_k", 3) not in {1, 3, 5}
375
+ ):
376
+ raise ValueError("invalid_top_k")
377
+ if op == "chunk_text":
378
+ size, overlap = config.get("size", 4096), config.get("overlap", 128)
379
+ unit = config.get("unit", "chars")
380
+ if (
381
+ type(size) is not int
382
+ or type(overlap) is not int
383
+ or not 1 <= size <= 16384
384
+ or not 0 <= overlap < size
385
+ or unit not in {"chars", "tokens"}
386
+ ):
387
+ raise ValueError("invalid_chunk_configuration")
388
+ if op == "merge_labels":
389
+ rule = config.get("rule", "all_agree")
390
+ order = config.get("order")
391
+ if rule not in MERGE_RULES or (
392
+ rule == "max_ordinal" and (not isinstance(order, list) or len(order) < 2)
393
+ ):
394
+ raise ValueError("invalid_kernel_configuration")
395
+ if op == "merge_records":
396
+ fields = config.get("fields")
397
+ if not isinstance(fields, dict) or not fields:
398
+ raise ValueError("invalid_kernel_configuration")
399
+ if any(policy not in {"array", "scalar", "ignore"} for policy in fields.values()):
400
+ raise ValueError("invalid_kernel_configuration")
401
+ for key in ("casefold", "unique"):
402
+ if key in config and type(config[key]) is not bool:
403
+ raise ValueError("invalid_kernel_configuration")
404
+
405
+
406
+ def _chunk_count(length, size, overlap):
407
+ if length <= 0:
408
+ return 1
409
+ return max(1, (max(0, length - size) + size - overlap - 1) // (size - overlap) + 1)
410
+
411
+
412
+ def _char_chunk_spans(text, size, overlap):
413
+ count = _chunk_count(len(text), size, overlap)
414
+ if count > 32:
415
+ raise ValueError("chunk_limit")
416
+ return [
417
+ (start, min(start + size, len(text)))
418
+ for start in [i * (size - overlap) for i in range(count)]
419
+ ]
420
+
421
+
422
+ def _token_pieces(text):
423
+ import tiktoken
424
+
425
+ enc = tiktoken.get_encoding("o200k_base")
426
+ pieces, cursor = [], 0
427
+ for token in enc.encode(text):
428
+ piece = enc.decode([token])
429
+ if not text.startswith(piece, cursor):
430
+ pieces.append(text[cursor:])
431
+ return pieces
432
+ pieces.append(piece)
433
+ cursor += len(piece)
434
+ if cursor != len(text):
435
+ pieces.append(text[cursor:])
436
+ return pieces
437
+
438
+
439
+ def _snap_end(text, start, end, floor):
440
+ window = text[start:end]
441
+ best = None
442
+ for mark in ("\n\n", "\n", ". ", "? ", "! "):
443
+ found = window.rfind(mark)
444
+ if found < 0:
445
+ continue
446
+ cut = start + found + len(mark)
447
+ if cut >= floor and (best is None or cut > best):
448
+ best = cut
449
+ return best or end
450
+
451
+
452
+ def _token_chunk_spans(text, size, overlap, pieces=None, limit=32):
453
+ """``pieces`` may be precomputed by callers that try many sizes on one text;
454
+ ``limit=None`` lets context fit inspect chunk sizes beyond the kernel cap."""
455
+ pieces = _token_pieces(text) if pieces is None else pieces
456
+ count = _chunk_count(len(pieces), size, overlap)
457
+ if limit is not None and count > limit:
458
+ raise ValueError("chunk_limit")
459
+ offsets = [0]
460
+ for piece in pieces:
461
+ offsets.append(offsets[-1] + len(piece))
462
+ spans = []
463
+ step = size - overlap
464
+ for index in range(count):
465
+ token_start = index * step
466
+ token_end = min(token_start + size, len(pieces))
467
+ start = offsets[token_start]
468
+ end = offsets[token_end]
469
+ if index < count - 1:
470
+ next_start = offsets[min(token_start + step, len(pieces))]
471
+ end = _snap_end(text, start, end, next_start)
472
+ spans.append((start, end if end > start or not text else start))
473
+ if spans:
474
+ spans[-1] = (spans[-1][0], len(text))
475
+ elif not text:
476
+ spans = [(0, 0)]
477
+ return spans
478
+
479
+
480
+ def merge_spans(text, chunks):
481
+ """Shift chunk-local spans onto the original text and drop overlap duplicates."""
482
+ if not isinstance(text, str) or not isinstance(chunks, list) or len(chunks) > 32:
483
+ reason = "chunk_limit" if isinstance(chunks, list) and len(chunks) > 32 else "invalid_text"
484
+ raise ValueError(reason)
485
+ shifted = []
486
+ for chunk in chunks:
487
+ if not isinstance(chunk, dict):
488
+ raise ValueError("invalid_span")
489
+ base = chunk.get("start", 0)
490
+ width = chunk.get("end", base) - base
491
+ for span in chunk.get("value") or []:
492
+ if not isinstance(span, dict):
493
+ raise ValueError("invalid_span")
494
+ start, end = span.get("start"), span.get("end")
495
+ if type(start) is not int or type(end) is not int:
496
+ raise ValueError("invalid_span")
497
+ shifted.append(
498
+ {
499
+ **span,
500
+ "start": start + base,
501
+ "end": end + base,
502
+ "_edge": min(start, width - end),
503
+ }
504
+ )
505
+ kept = []
506
+ for span in shifted:
507
+ replaced = False
508
+ for index, prior in enumerate(kept):
509
+ overlaps = (
510
+ prior.get("label") == span.get("label")
511
+ and span["start"] < prior["end"]
512
+ and prior["start"] < span["end"]
513
+ )
514
+ if not overlaps:
515
+ continue
516
+ if span["_edge"] > prior["_edge"]:
517
+ kept[index] = span
518
+ replaced = True
519
+ break
520
+ if not replaced:
521
+ kept.append(span)
522
+ cleaned = [{k: v for k, v in span.items() if k != "_edge"} for span in kept]
523
+ return normalize_spans(text, cleaned)
524
+
525
+
526
+ def merge_records(chunks, fields, sums=None):
527
+ """Merge per-chunk records. Scalars must agree. Totals are recomputed."""
528
+ if not isinstance(chunks, list) or len(chunks) > 32:
529
+ raise ValueError("chunk_limit" if isinstance(chunks, list) else "invalid_input_shape")
530
+ merged, arrays = {}, {name: [] for name, policy in fields.items() if policy == "array"}
531
+ for chunk in chunks:
532
+ value = chunk.get("value") if isinstance(chunk, dict) else None
533
+ if not isinstance(value, dict):
534
+ raise ValueError("invalid_input_shape")
535
+ for name, policy in fields.items():
536
+ if policy == "ignore" or name not in value or value[name] is None:
537
+ continue
538
+ item = value[name]
539
+ if policy == "array":
540
+ if not isinstance(item, list):
541
+ raise ValueError("invalid_input_shape")
542
+ arrays[name].extend(item)
543
+ elif name in merged and merged[name] != item:
544
+ raise ValueError("merge_conflict")
545
+ else:
546
+ merged[name] = item
547
+ for name, items in arrays.items():
548
+ seen, unique = set(), []
549
+ for item in items:
550
+ key = canonical(item)
551
+ if key not in seen:
552
+ seen.add(key)
553
+ unique.append(item)
554
+ merged[name] = unique
555
+ for name, path in (sums or {}).items():
556
+ collection, _, field = str(path).partition("/")
557
+ total = Decimal(0)
558
+ for item in merged.get(collection, []):
559
+ if isinstance(item, dict) and item.get(field) not in {None, ""}:
560
+ total += Decimal(str(item[field]))
561
+ merged[name] = str(total)
562
+ return merged
563
+
564
+
565
+ def merge_labels(chunks, rule="all_agree", order=None):
566
+ """Combine per-chunk labels. Disagreement is a conflict unless the rule allows it."""
567
+ if not isinstance(chunks, list) or not chunks or len(chunks) > 32:
568
+ too_many = isinstance(chunks, list) and len(chunks) > 32
569
+ raise ValueError("chunk_limit" if too_many else "invalid_input_shape")
570
+ values = []
571
+ for chunk in chunks:
572
+ value = chunk.get("value") if isinstance(chunk, dict) else None
573
+ if not isinstance(value, dict):
574
+ raise ValueError("invalid_input_shape")
575
+ values.append(value)
576
+ rank = {label: index for index, label in enumerate(order or [])}
577
+ merged = {}
578
+ for key in set().union(*(value.keys() for value in values)):
579
+ present = [value[key] for value in values if key in value and value[key] is not None]
580
+ if not present:
581
+ merged[key] = None
582
+ elif rule == "any_true" and any(item is True for item in present):
583
+ merged[key] = True
584
+ elif rule == "any_true" and all(item is False for item in present):
585
+ merged[key] = False
586
+ elif rule == "max_ordinal":
587
+ if any(item not in rank for item in present):
588
+ raise ValueError("merge_conflict")
589
+ merged[key] = max(present, key=rank.__getitem__)
590
+ elif rule == "union":
591
+ union = []
592
+ for item in present:
593
+ for row in item if isinstance(item, list) else [item]:
594
+ if row not in union:
595
+ union.append(row)
596
+ merged[key] = union
597
+ elif any(item != present[0] for item in present):
598
+ raise ValueError("merge_conflict")
599
+ else:
600
+ merged[key] = present[0]
601
+ return merged
602
+
603
+
604
+ def kernel(op, args, config, diagnostics=None):
605
+ validate_config(op, args, config)
606
+ from jsonschema import Draft202012Validator
607
+
608
+ from .components import semantic_contract
609
+
610
+ if not Draft202012Validator(semantic_contract(op)["input_schema"]).is_valid(args):
611
+ raise ValueError("invalid_input_shape")
612
+ if op == "align_spans":
613
+ return align_spans(
614
+ *args,
615
+ unaligned=config.get("unaligned", "fail"),
616
+ context_policy=config.get("context_policy", "strict"),
617
+ diagnostics=diagnostics,
618
+ )
619
+ if op == "project_records":
620
+ return project_records(args[0], config["fields"])
621
+ if op == "exact_links":
622
+ mentions, catalog = args
623
+ bounded_rows(mentions, 32, "mention_limit")
624
+ bounded_rows(catalog, 500, "catalog_limit")
625
+ pairs = []
626
+ for mention in mentions:
627
+ needle = normalized(mention.get("text"))
628
+ for row in sorted(catalog, key=lambda r: r["id"]):
629
+ aliases = row.get("aliases", [])
630
+ if not isinstance(aliases, list) or len(aliases) > 32:
631
+ raise ValueError("invalid_aliases")
632
+ if needle and needle in [normalized(row.get("name")), *map(normalized, aliases)]:
633
+ pairs.append(
634
+ {
635
+ "id": digest([mention["id"], row["id"]]),
636
+ "mention_id": mention["id"],
637
+ "candidate_id": row["id"],
638
+ }
639
+ )
640
+ return resolve_links(
641
+ {"pairs": pairs, "mention_ids": [m["id"] for m in mentions]},
642
+ [{"id": p["id"], "match": True} for p in pairs],
643
+ **config,
644
+ )
645
+ if op == "retrieve_candidates":
646
+ return candidates(*args, **config)
647
+ if op == "resolve_links":
648
+ return resolve_links(*args, **config)
649
+ if op == "assemble_records":
650
+ return assemble_records(*args, config.get("fields"))
651
+ if op == "merge_spans":
652
+ return merge_spans(*args)
653
+ if op == "merge_records":
654
+ return merge_records(args[0], config.get("fields"), config.get("sums"))
655
+ if op == "merge_labels":
656
+ return merge_labels(args[0], config.get("rule", "all_agree"), config.get("order"))
657
+ text = args[0]
658
+ if not isinstance(text, str):
659
+ raise ValueError("invalid_text")
660
+ if op == "normalize_text":
661
+ # A per-output-codepoint source map makes expansion explicit. Never use
662
+ # normalized offsets as if they referred to the original document.
663
+ pieces = [c.casefold() if config.get("casefold", True) else c for c in text]
664
+ return {
665
+ "text": "".join(pieces),
666
+ "source_map": [i for i, p in enumerate(pieces) for _ in p],
667
+ "document_id": digest(text),
668
+ }
669
+ size, overlap = config.get("size", 4096), config.get("overlap", 128)
670
+ spans = (
671
+ _token_chunk_spans(text, size, overlap)
672
+ if config.get("unit") == "tokens"
673
+ else _char_chunk_spans(text, size, overlap)
674
+ )
675
+ return [
676
+ {
677
+ "id": digest([text, start, end]),
678
+ "document_id": digest(text),
679
+ "start": start,
680
+ "end": end,
681
+ "text": text[start:end],
682
+ }
683
+ for start, end in spans
684
+ ]