ladl-py 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.
- ladl/__init__.py +724 -0
- ladl_py-0.1.0.dist-info/METADATA +7 -0
- ladl_py-0.1.0.dist-info/RECORD +5 -0
- ladl_py-0.1.0.dist-info/WHEEL +5 -0
- ladl_py-0.1.0.dist-info/top_level.txt +1 -0
ladl/__init__.py
ADDED
|
@@ -0,0 +1,724 @@
|
|
|
1
|
+
"""ladl: MN 112 labeling engine (Python port of the Ruby ladl reference).
|
|
2
|
+
|
|
3
|
+
Conformance contract: metanorma/ladl-testsuite. Faithful port of
|
|
4
|
+
Ladl::Runtime::Engine: the element's label resolves through the
|
|
5
|
+
association chain (declared context first, then ancestors nearest-first;
|
|
6
|
+
contexts that bind no labeller for the type are skipped — they scope but
|
|
7
|
+
do not label), counters are scoped by the declaring carrier element and
|
|
8
|
+
restart per hierarchical scope, %pn chains through the labeller parent
|
|
9
|
+
tree with an element-type fallback, and templates render %n, %pn,
|
|
10
|
+
%parent, %self with {key} vocabulary tokens resolved through the host
|
|
11
|
+
labels dictionary and the English default vocabulary.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
import yaml
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ParseError(ValueError):
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ResolutionError(ValueError):
|
|
28
|
+
pass
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class SequenceExhaustedError(ValueError):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
CYRILLIC_UPPER = [
|
|
36
|
+
"А", "Б", "В", "Г", "Д", "Е", "Ж", "З", "И", "Й", "К", "Л", "М", "Н",
|
|
37
|
+
"О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ы",
|
|
38
|
+
"Ь", "Э", "Ю", "Я",
|
|
39
|
+
]
|
|
40
|
+
CYRILLIC_LOWER = [c.lower() for c in CYRILLIC_UPPER]
|
|
41
|
+
GREEK_UPPER = [
|
|
42
|
+
"Α", "Β", "Γ", "Δ", "Ε", "Ζ", "Η", "Θ", "Ι", "Κ", "Λ", "Μ", "Ν", "Ξ",
|
|
43
|
+
"Ο", "Π", "Ρ", "Σ", "Τ", "Υ", "Φ", "Χ", "Ψ", "Ω",
|
|
44
|
+
]
|
|
45
|
+
GREEK_LOWER = [c.lower() for c in GREEK_UPPER]
|
|
46
|
+
HEBREW = [
|
|
47
|
+
"א", "ב", "ג", "ד", "ה", "ו", "ז", "ח", "ט", "י", "כ", "ל", "מ", "נ",
|
|
48
|
+
"ס", "ע", "פ", "צ", "ק", "ר", "ש", "ת",
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _numeric_spec(fmt):
|
|
53
|
+
return ("NumericSequence", {
|
|
54
|
+
"initial_value": 1, "increment": 1, "format": fmt,
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# The default sequences required of a LADL-compliant runtime (MN 112
|
|
59
|
+
# "NumericSequence"); built fresh on each lookup.
|
|
60
|
+
BUILTIN_SEQUENCE_SPECS = {
|
|
61
|
+
"DecimalNumericSequence": _numeric_spec("decimal"),
|
|
62
|
+
"ArabicNumericSequence": _numeric_spec("arabic_indic"),
|
|
63
|
+
"ArabicIndicNumericSequence": (
|
|
64
|
+
"NumericSequence",
|
|
65
|
+
{"initial_value": 1, "increment": 1, "format": "arabic_indic",
|
|
66
|
+
"char_direction": "rtl"},
|
|
67
|
+
),
|
|
68
|
+
"RomanUpperNumericSequence": _numeric_spec("roman_upper"),
|
|
69
|
+
"RomanLowerNumericSequence": _numeric_spec("roman_lower"),
|
|
70
|
+
"AlphaUpperNumericSequence": _numeric_spec("alpha_upper"),
|
|
71
|
+
"AlphaLowerNumericSequence": _numeric_spec("alpha_lower"),
|
|
72
|
+
"ChineseNumericSequence": _numeric_spec("chinese"),
|
|
73
|
+
"JapaneseNumericSequence": _numeric_spec("japanese"),
|
|
74
|
+
"KoreanNumericSequence": _numeric_spec("korean"),
|
|
75
|
+
"CyrillicUpperCharacterSequence": (
|
|
76
|
+
"CharacterSequence",
|
|
77
|
+
{"characters": list(CYRILLIC_UPPER), "expansion_rule": "prepend_prefix"},
|
|
78
|
+
),
|
|
79
|
+
"CyrillicLowerCharacterSequence": (
|
|
80
|
+
"CharacterSequence",
|
|
81
|
+
{"characters": list(CYRILLIC_LOWER), "expansion_rule": "prepend_prefix"},
|
|
82
|
+
),
|
|
83
|
+
"GreekUpperCharacterSequence": (
|
|
84
|
+
"CharacterSequence",
|
|
85
|
+
{"characters": list(GREEK_UPPER), "expansion_rule": "prepend_prefix"},
|
|
86
|
+
),
|
|
87
|
+
"GreekLowerCharacterSequence": (
|
|
88
|
+
"CharacterSequence",
|
|
89
|
+
{"characters": list(GREEK_LOWER), "expansion_rule": "prepend_prefix"},
|
|
90
|
+
),
|
|
91
|
+
"HebrewNumericSequence": (
|
|
92
|
+
"CharacterSequence",
|
|
93
|
+
{"characters": list(HEBREW), "expansion_rule": "prepend_prefix"},
|
|
94
|
+
),
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
ARABIC_INDIC_DIGITS = str.maketrans("0123456789", "٠١٢٣٤٥٦٧٨٩")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class Formatters:
|
|
101
|
+
"""Labeling formats: renders a 1-based numeric value in a particular
|
|
102
|
+
alphanumeric system (MN 112 "labeling format")."""
|
|
103
|
+
|
|
104
|
+
ROMAN_PAIRS = [
|
|
105
|
+
(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"),
|
|
106
|
+
(90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"),
|
|
107
|
+
(5, "V"), (4, "IV"), (1, "I"),
|
|
108
|
+
]
|
|
109
|
+
CJK_UNITS = {
|
|
110
|
+
"chinese": ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"],
|
|
111
|
+
"japanese": ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"],
|
|
112
|
+
"korean": ["영", "일", "이", "삼", "사", "오", "육", "칠", "팔", "구"],
|
|
113
|
+
}
|
|
114
|
+
CJK_SMALL_TEN = {"chinese": "十", "japanese": "十", "korean": "십"}
|
|
115
|
+
CJK_SMALL_HUNDRED = {"chinese": "百", "japanese": "百", "korean": "백"}
|
|
116
|
+
CJK_SMALL_THOUSAND = {"chinese": "千", "japanese": "千", "korean": "천"}
|
|
117
|
+
|
|
118
|
+
@classmethod
|
|
119
|
+
def format(cls, fmt: str, number: int) -> str:
|
|
120
|
+
if number < 1:
|
|
121
|
+
raise ResolutionError(
|
|
122
|
+
f"sequence value must be positive, got {number}"
|
|
123
|
+
)
|
|
124
|
+
if fmt == "decimal":
|
|
125
|
+
return str(number)
|
|
126
|
+
if fmt == "roman_upper":
|
|
127
|
+
return cls._roman(number)
|
|
128
|
+
if fmt == "roman_lower":
|
|
129
|
+
return cls._roman(number).lower()
|
|
130
|
+
if fmt == "alpha_upper":
|
|
131
|
+
return cls._alpha(number)
|
|
132
|
+
if fmt == "alpha_lower":
|
|
133
|
+
return cls._alpha(number).lower()
|
|
134
|
+
if fmt == "arabic_indic":
|
|
135
|
+
return str(number).translate(ARABIC_INDIC_DIGITS)
|
|
136
|
+
if fmt in cls.CJK_UNITS:
|
|
137
|
+
return cls._east_asian(fmt, number)
|
|
138
|
+
raise ResolutionError(f"unknown labeling format: {fmt!r}")
|
|
139
|
+
|
|
140
|
+
@classmethod
|
|
141
|
+
def _roman(cls, number: int) -> str:
|
|
142
|
+
out = ""
|
|
143
|
+
n = number
|
|
144
|
+
for value, letters in cls.ROMAN_PAIRS:
|
|
145
|
+
while n >= value:
|
|
146
|
+
out += letters
|
|
147
|
+
n -= value
|
|
148
|
+
return out
|
|
149
|
+
|
|
150
|
+
@classmethod
|
|
151
|
+
def _alpha(cls, number: int) -> str:
|
|
152
|
+
return "".join(chr(64 + d) for d in cls.digits(number, 26))
|
|
153
|
+
|
|
154
|
+
@classmethod
|
|
155
|
+
def _east_asian(cls, fmt: str, number: int) -> str:
|
|
156
|
+
units = cls.CJK_UNITS[fmt]
|
|
157
|
+
thousands, rest_thousands = divmod(number, 1000)
|
|
158
|
+
hundreds, rest_hundreds = divmod(rest_thousands, 100)
|
|
159
|
+
tens, ones = divmod(rest_hundreds, 10)
|
|
160
|
+
out = ""
|
|
161
|
+
if thousands > 0:
|
|
162
|
+
out += cls._compound(units, thousands,
|
|
163
|
+
cls.CJK_SMALL_THOUSAND[fmt],
|
|
164
|
+
drop_single_unit=False)
|
|
165
|
+
if hundreds > 0:
|
|
166
|
+
out += cls._compound(units, hundreds,
|
|
167
|
+
cls.CJK_SMALL_HUNDRED[fmt],
|
|
168
|
+
drop_single_unit=False)
|
|
169
|
+
if tens > 0:
|
|
170
|
+
out += cls._compound(units, tens, cls.CJK_SMALL_TEN[fmt])
|
|
171
|
+
if ones > 0:
|
|
172
|
+
out += units[ones]
|
|
173
|
+
return out
|
|
174
|
+
|
|
175
|
+
@staticmethod
|
|
176
|
+
def _compound(units, count: int, marker: str,
|
|
177
|
+
drop_single_unit: bool = True) -> str:
|
|
178
|
+
prefix = "" if count == 1 and drop_single_unit else units[count]
|
|
179
|
+
return f"{prefix}{marker}"
|
|
180
|
+
|
|
181
|
+
@staticmethod
|
|
182
|
+
def digits(number: int, radix: int) -> list[int]:
|
|
183
|
+
"""Bijective (spreadsheet-style) decomposition of a 1-based
|
|
184
|
+
number into digits of the given radix."""
|
|
185
|
+
digits = []
|
|
186
|
+
n = number
|
|
187
|
+
while n > 0:
|
|
188
|
+
n -= 1
|
|
189
|
+
digits.insert(0, (n % radix) + 1)
|
|
190
|
+
n //= radix
|
|
191
|
+
return digits
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@dataclass
|
|
195
|
+
class Instance:
|
|
196
|
+
name: str
|
|
197
|
+
type: str
|
|
198
|
+
properties: dict = field(default_factory=dict)
|
|
199
|
+
|
|
200
|
+
def ref(self, key: str) -> str:
|
|
201
|
+
value = self.properties.get(key)
|
|
202
|
+
if isinstance(value, dict):
|
|
203
|
+
return value.get("ref", "")
|
|
204
|
+
return value or ""
|
|
205
|
+
|
|
206
|
+
def refs(self, key: str) -> list[str]:
|
|
207
|
+
value = self.properties.get(key)
|
|
208
|
+
if value is None:
|
|
209
|
+
return []
|
|
210
|
+
values = value if isinstance(value, list) else [value]
|
|
211
|
+
return [
|
|
212
|
+
v.get("ref") if isinstance(v, dict) else v for v in values
|
|
213
|
+
]
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
@dataclass
|
|
217
|
+
class Profile:
|
|
218
|
+
instances: dict[str, Instance]
|
|
219
|
+
|
|
220
|
+
def instance(self, name: str) -> Instance | None:
|
|
221
|
+
return self.instances.get(name)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
@dataclass
|
|
225
|
+
class Element:
|
|
226
|
+
type: str
|
|
227
|
+
id: str
|
|
228
|
+
context: str | None = None
|
|
229
|
+
children: list["Element"] = field(default_factory=list)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
@dataclass
|
|
233
|
+
class Label:
|
|
234
|
+
value: str
|
|
235
|
+
reference: str
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
# The English label vocabulary backing {key} tokens in template
|
|
239
|
+
# patterns — the isodoc i18n key set, so a host document's i18n table
|
|
240
|
+
# slots in directly through Engine(labels:).
|
|
241
|
+
LABEL_VOCABULARY = {
|
|
242
|
+
"clause": "Clause",
|
|
243
|
+
"subclause": "Clause",
|
|
244
|
+
"annex": "Annex",
|
|
245
|
+
"appendix": "Appendix",
|
|
246
|
+
"section": "Section",
|
|
247
|
+
"figure": "Figure",
|
|
248
|
+
"table": "Table",
|
|
249
|
+
"formula": "Formula",
|
|
250
|
+
"inequality": "Inequality",
|
|
251
|
+
"note": "NOTE",
|
|
252
|
+
"note_xref": "NOTE",
|
|
253
|
+
"note_to_entry": "Note { $n } to entry",
|
|
254
|
+
"note_to_entry_xref": "{ $parent }, Note { $n } to entry",
|
|
255
|
+
"example": "EXAMPLE",
|
|
256
|
+
"example_xref": "EXAMPLE",
|
|
257
|
+
"termexample": "EXAMPLE",
|
|
258
|
+
"list": "List",
|
|
259
|
+
"introduction": "Introduction",
|
|
260
|
+
"norm_annex": "normative",
|
|
261
|
+
"inform_annex": "informative",
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
PLACEHOLDER = re.compile(r"%pn|%parent|%self|%n|\{([A-Za-z][A-Za-z0-9_]*)\}")
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
# Label catalog values are Fluent message patterns (metanorma/
|
|
268
|
+
# fluent-min semantics): `{ $var }` placeables bind from the labeller
|
|
269
|
+
# bindings, `{ message }` references resolve within the catalog
|
|
270
|
+
# (default vocabulary + host labels), depth is bounded, and a missing
|
|
271
|
+
# variable renders as its own literal `{ name }`.
|
|
272
|
+
FLUENT_MAX_DEPTH = 5
|
|
273
|
+
FLUENT_VARS = ("n", "pn", "parent", "self")
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def message_table(bindings: dict) -> dict:
|
|
277
|
+
table = dict(LABEL_VOCABULARY)
|
|
278
|
+
table.update(bindings.get("labels") or {})
|
|
279
|
+
return table
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def resolve_message(value: str, bindings: dict, depth: int = 0) -> str:
|
|
283
|
+
if depth > FLUENT_MAX_DEPTH:
|
|
284
|
+
raise ResolutionError("catalog message nesting too deep")
|
|
285
|
+
out: list[str] = []
|
|
286
|
+
i = 0
|
|
287
|
+
while i < len(value):
|
|
288
|
+
ch = value[i]
|
|
289
|
+
if ch == "\\" and i + 1 < len(value) and value[i + 1] in "{}\\\"":
|
|
290
|
+
out.append(value[i + 1])
|
|
291
|
+
i += 2
|
|
292
|
+
continue
|
|
293
|
+
if ch == "{":
|
|
294
|
+
end = value.find("}", i)
|
|
295
|
+
if end < 0:
|
|
296
|
+
out.append(ch)
|
|
297
|
+
i += 1
|
|
298
|
+
continue
|
|
299
|
+
inner = value[i + 1:end].strip()
|
|
300
|
+
if inner.startswith("$"):
|
|
301
|
+
name = inner[1:].strip()
|
|
302
|
+
v = bindings.get(name)
|
|
303
|
+
out.append("{" + name + "}" if v is None else str(v))
|
|
304
|
+
else:
|
|
305
|
+
ref = message_table(bindings).get(inner)
|
|
306
|
+
if ref is None:
|
|
307
|
+
raise ResolutionError(
|
|
308
|
+
"catalog message references unknown message "
|
|
309
|
+
f"{inner!r}"
|
|
310
|
+
)
|
|
311
|
+
out.append(resolve_message(ref, bindings, depth + 1))
|
|
312
|
+
i = end + 1
|
|
313
|
+
continue
|
|
314
|
+
out.append(ch)
|
|
315
|
+
i += 1
|
|
316
|
+
return "".join(out)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def render(pattern: str, bindings: dict) -> str:
|
|
320
|
+
def sub(match: re.Match) -> str:
|
|
321
|
+
token = match.group(0)
|
|
322
|
+
if token in ("%n", "%pn", "%parent", "%self"):
|
|
323
|
+
value = bindings.get(token[1:])
|
|
324
|
+
if value is None:
|
|
325
|
+
if token in ("%parent", "%self"):
|
|
326
|
+
return ""
|
|
327
|
+
raise ResolutionError(
|
|
328
|
+
f"template {bindings.get('pattern')!r} uses {token} "
|
|
329
|
+
"but the labeller has no parent labeller bound for "
|
|
330
|
+
"this element"
|
|
331
|
+
)
|
|
332
|
+
return str(value)
|
|
333
|
+
key = match.group(1)
|
|
334
|
+
labels = bindings.get("labels") or {}
|
|
335
|
+
if key in labels:
|
|
336
|
+
value = str(labels[key])
|
|
337
|
+
elif key in LABEL_VOCABULARY:
|
|
338
|
+
value = LABEL_VOCABULARY[key]
|
|
339
|
+
else:
|
|
340
|
+
raise ResolutionError(
|
|
341
|
+
f"template {bindings.get('pattern')!r} uses {{{key}}} but the "
|
|
342
|
+
"key is in neither the labels dictionary nor the default "
|
|
343
|
+
"vocabulary"
|
|
344
|
+
)
|
|
345
|
+
return resolve_message(value, bindings)
|
|
346
|
+
|
|
347
|
+
return PLACEHOLDER.sub(sub, pattern)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
class Resolver:
|
|
351
|
+
"""Indexes a loaded profile: labellers by (context, element type),
|
|
352
|
+
instance names, and the labeller-tree ancestor chains used for %pn."""
|
|
353
|
+
|
|
354
|
+
def __init__(self, profile: Profile):
|
|
355
|
+
self.profile = profile
|
|
356
|
+
self._name_of: dict[int, str] = {}
|
|
357
|
+
self.labellers_by_context: dict[str, dict[str, Instance]] = {}
|
|
358
|
+
for name, inst in profile.instances.items():
|
|
359
|
+
if inst.type != "Labeller":
|
|
360
|
+
continue
|
|
361
|
+
context = inst.ref("context")
|
|
362
|
+
if not context:
|
|
363
|
+
raise ResolutionError(
|
|
364
|
+
f"labeller {name!r} declares no context"
|
|
365
|
+
)
|
|
366
|
+
self._name_of[id(inst)] = name
|
|
367
|
+
element_type = inst.properties.get("type")
|
|
368
|
+
self.labellers_by_context.setdefault(context, {})[element_type] = inst
|
|
369
|
+
|
|
370
|
+
def labeller_for_context(
|
|
371
|
+
self, context_name: str, element_type: str
|
|
372
|
+
) -> Instance | None:
|
|
373
|
+
return self.labellers_by_context.get(context_name, {}).get(element_type)
|
|
374
|
+
|
|
375
|
+
def instance_name_of(self, labeller: Instance) -> str:
|
|
376
|
+
return self._name_of[id(labeller)]
|
|
377
|
+
|
|
378
|
+
def ancestor_chain(self, labeller_name: str) -> list[str]:
|
|
379
|
+
chain = [labeller_name]
|
|
380
|
+
seen = {labeller_name}
|
|
381
|
+
current = labeller_name
|
|
382
|
+
while True:
|
|
383
|
+
labeller = self.profile.instance(current)
|
|
384
|
+
if labeller is None:
|
|
385
|
+
break
|
|
386
|
+
parent = labeller.ref("parent")
|
|
387
|
+
if not parent or parent in seen:
|
|
388
|
+
break
|
|
389
|
+
chain.append(parent)
|
|
390
|
+
seen.add(parent)
|
|
391
|
+
current = parent
|
|
392
|
+
return chain
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
class ProfileLoader:
|
|
396
|
+
@classmethod
|
|
397
|
+
def load_yaml(cls, text: str) -> Profile:
|
|
398
|
+
data = yaml.safe_load(text)
|
|
399
|
+
entries = data.get("instances")
|
|
400
|
+
if not isinstance(entries, list):
|
|
401
|
+
raise ParseError("profile must be a mapping with an 'instances' list")
|
|
402
|
+
instances = {}
|
|
403
|
+
for entry in entries:
|
|
404
|
+
if not entry.get("name") or not entry.get("type"):
|
|
405
|
+
raise ParseError(f"instance needs name and type: {entry!r}")
|
|
406
|
+
instances[entry["name"]] = Instance(
|
|
407
|
+
name=entry["name"], type=entry["type"],
|
|
408
|
+
properties=entry.get("properties", {}),
|
|
409
|
+
)
|
|
410
|
+
return Profile(instances=instances)
|
|
411
|
+
|
|
412
|
+
@classmethod
|
|
413
|
+
def load_file(cls, path: str | Path) -> Profile:
|
|
414
|
+
return cls.load_yaml(Path(path).read_text(encoding="utf-8"))
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def load_profile(path: str | Path) -> Profile:
|
|
418
|
+
return ProfileLoader.load_file(path)
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
@dataclass
|
|
422
|
+
class Entry:
|
|
423
|
+
element: Element
|
|
424
|
+
etype: str
|
|
425
|
+
labeller: Instance
|
|
426
|
+
labeller_name: str
|
|
427
|
+
context_name: str
|
|
428
|
+
carrier_object_id: int
|
|
429
|
+
carrier_entry: "Entry | None"
|
|
430
|
+
position: int
|
|
431
|
+
raw_value: str | None
|
|
432
|
+
parent_hier: str | None
|
|
433
|
+
parent_entry: "Entry | None"
|
|
434
|
+
hierarchical: str | None
|
|
435
|
+
local: str | None = None
|
|
436
|
+
global_: str | None = None
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
class Engine:
|
|
440
|
+
"""The LADL labeling evaluator (MN 112 "Algorithm to resolve the
|
|
441
|
+
label for a content element") over a profile and a content tree."""
|
|
442
|
+
|
|
443
|
+
def __init__(self, profile: Profile, labels: dict | None = None):
|
|
444
|
+
self.resolved = Resolver(profile)
|
|
445
|
+
self.labels_input = labels or {}
|
|
446
|
+
self.plan: list[Entry] = []
|
|
447
|
+
self.totals: dict[tuple, int] = {}
|
|
448
|
+
self.labels: dict[str, Label] = {}
|
|
449
|
+
|
|
450
|
+
def label(self, root: Element) -> "Engine":
|
|
451
|
+
self.plan = []
|
|
452
|
+
self.totals = {}
|
|
453
|
+
self.labels = {}
|
|
454
|
+
self._walk(root, [])
|
|
455
|
+
self._render()
|
|
456
|
+
return self
|
|
457
|
+
|
|
458
|
+
def _walk(self, element: Element, ancestors: list[dict]):
|
|
459
|
+
labeller, context_name, label_carrier = self._resolve_own_label(
|
|
460
|
+
element, ancestors
|
|
461
|
+
)
|
|
462
|
+
association = self._nearest_association(element, ancestors)
|
|
463
|
+
frame = {"element": element, "declared": element.context, "entry": None}
|
|
464
|
+
if labeller is not None:
|
|
465
|
+
frame["entry"] = self._plan_element(
|
|
466
|
+
element, labeller, context_name, label_carrier,
|
|
467
|
+
association, ancestors,
|
|
468
|
+
)
|
|
469
|
+
ancestors.append(frame)
|
|
470
|
+
for child in element.children:
|
|
471
|
+
self._walk(child, ancestors)
|
|
472
|
+
ancestors.pop()
|
|
473
|
+
|
|
474
|
+
def _resolve_own_label(self, element: Element, ancestors: list[dict]):
|
|
475
|
+
if element.context:
|
|
476
|
+
labeller = self.resolved.labeller_for_context(
|
|
477
|
+
element.context, element.type
|
|
478
|
+
)
|
|
479
|
+
if labeller is not None:
|
|
480
|
+
carrier = {
|
|
481
|
+
"element": element,
|
|
482
|
+
"context_name": element.context,
|
|
483
|
+
"entry": None,
|
|
484
|
+
}
|
|
485
|
+
return labeller, element.context, carrier
|
|
486
|
+
for frame in reversed(ancestors):
|
|
487
|
+
if not frame["declared"]:
|
|
488
|
+
continue
|
|
489
|
+
labeller = self.resolved.labeller_for_context(
|
|
490
|
+
frame["declared"], element.type
|
|
491
|
+
)
|
|
492
|
+
if labeller is not None:
|
|
493
|
+
return labeller, frame["declared"], frame
|
|
494
|
+
return None, None, None
|
|
495
|
+
|
|
496
|
+
def _nearest_association(
|
|
497
|
+
self, element: Element, ancestors: list[dict]
|
|
498
|
+
) -> dict | None:
|
|
499
|
+
if element.context:
|
|
500
|
+
return {
|
|
501
|
+
"element": element,
|
|
502
|
+
"context_name": element.context,
|
|
503
|
+
"entry": None,
|
|
504
|
+
}
|
|
505
|
+
for frame in reversed(ancestors):
|
|
506
|
+
if frame["declared"]:
|
|
507
|
+
return frame
|
|
508
|
+
return None
|
|
509
|
+
|
|
510
|
+
def _plan_element(self, element, labeller, context_name, label_carrier,
|
|
511
|
+
scope_association, ancestors) -> Entry:
|
|
512
|
+
parent = self._find_parent_entry(labeller, ancestors)
|
|
513
|
+
parent_hier = parent.hierarchical if parent is not None else None
|
|
514
|
+
position = self._increment_counter(label_carrier, labeller, parent_hier)
|
|
515
|
+
raw = self._sequence_raw(labeller, position)
|
|
516
|
+
entry = Entry(
|
|
517
|
+
element=element,
|
|
518
|
+
etype=element.type,
|
|
519
|
+
labeller=labeller,
|
|
520
|
+
labeller_name=self.resolved.instance_name_of(labeller),
|
|
521
|
+
context_name=context_name,
|
|
522
|
+
carrier_object_id=id(label_carrier["element"]),
|
|
523
|
+
carrier_entry=(
|
|
524
|
+
scope_association["entry"]
|
|
525
|
+
if scope_association is not None else None
|
|
526
|
+
),
|
|
527
|
+
position=position,
|
|
528
|
+
raw_value=raw,
|
|
529
|
+
parent_hier=parent_hier,
|
|
530
|
+
parent_entry=parent,
|
|
531
|
+
hierarchical=self._join_hierarchical(parent_hier, raw),
|
|
532
|
+
)
|
|
533
|
+
if scope_association is not None and scope_association["element"] is element:
|
|
534
|
+
scope_association["entry"] = entry
|
|
535
|
+
entry.carrier_entry = entry
|
|
536
|
+
self.plan.append(entry)
|
|
537
|
+
return entry
|
|
538
|
+
|
|
539
|
+
def _find_parent_entry(self, labeller: Instance, ancestors: list[dict]):
|
|
540
|
+
parent_name = labeller.ref("parent")
|
|
541
|
+
if not parent_name:
|
|
542
|
+
return None
|
|
543
|
+
parent_labeller = self.resolved.profile.instance(parent_name)
|
|
544
|
+
if parent_labeller is None:
|
|
545
|
+
raise ResolutionError(
|
|
546
|
+
f"labeller {self.resolved.instance_name_of(labeller)!r} "
|
|
547
|
+
f"references undefined parent labeller {parent_name!r}"
|
|
548
|
+
)
|
|
549
|
+
chain = self.resolved.ancestor_chain(
|
|
550
|
+
self.resolved.instance_name_of(labeller)
|
|
551
|
+
)
|
|
552
|
+
for frame in reversed(ancestors):
|
|
553
|
+
entry = frame["entry"]
|
|
554
|
+
if entry is not None and entry.labeller_name in chain:
|
|
555
|
+
return entry
|
|
556
|
+
parent_type = parent_labeller.properties.get("type")
|
|
557
|
+
for frame in reversed(ancestors):
|
|
558
|
+
entry = frame["entry"]
|
|
559
|
+
if entry is not None and entry.etype == parent_type:
|
|
560
|
+
return entry
|
|
561
|
+
return None
|
|
562
|
+
|
|
563
|
+
def _increment_counter(self, carrier: dict, labeller: Instance,
|
|
564
|
+
parent_hier: str | None) -> int:
|
|
565
|
+
key = (
|
|
566
|
+
id(carrier["element"]),
|
|
567
|
+
self.resolved.instance_name_of(labeller),
|
|
568
|
+
parent_hier or "",
|
|
569
|
+
)
|
|
570
|
+
self.totals[key] = self.totals.get(key, 0) + 1
|
|
571
|
+
return self.totals[key]
|
|
572
|
+
|
|
573
|
+
def _sequence_raw(self, labeller: Instance, position: int) -> str | None:
|
|
574
|
+
sequence = labeller.ref("sequence")
|
|
575
|
+
if not sequence:
|
|
576
|
+
return None
|
|
577
|
+
return self._sequence_value(self._lookup_sequence(sequence), position)
|
|
578
|
+
|
|
579
|
+
def _lookup_sequence(self, name: str) -> Instance:
|
|
580
|
+
instance = self.resolved.profile.instance(name)
|
|
581
|
+
if instance is not None and instance.type in (
|
|
582
|
+
"NumericSequence", "CharacterSequence",
|
|
583
|
+
):
|
|
584
|
+
return instance
|
|
585
|
+
spec = BUILTIN_SEQUENCE_SPECS.get(name)
|
|
586
|
+
if spec is None:
|
|
587
|
+
raise ResolutionError(f"undefined sequence: {name!r}")
|
|
588
|
+
return Instance(name=name, type=spec[0], properties=dict(spec[1]))
|
|
589
|
+
|
|
590
|
+
def _sequence_value(self, sequence: Instance, position: int) -> str:
|
|
591
|
+
if sequence.type == "NumericSequence":
|
|
592
|
+
return self._numeric_value(sequence, position)
|
|
593
|
+
return self._character_value(sequence, position)
|
|
594
|
+
|
|
595
|
+
def _numeric_value(self, sequence: Instance, position: int) -> str:
|
|
596
|
+
initial = sequence.properties.get("initial_value") or 1
|
|
597
|
+
increment = sequence.properties.get("increment") or 1
|
|
598
|
+
raw = initial + (position - 1) * increment
|
|
599
|
+
base_name = sequence.ref("base_sequence")
|
|
600
|
+
if base_name:
|
|
601
|
+
return self._sequence_value(self._lookup_sequence(base_name), raw)
|
|
602
|
+
fmt = sequence.properties.get("format") or "decimal"
|
|
603
|
+
cycle_length = sequence.properties.get("cycle_length")
|
|
604
|
+
if isinstance(cycle_length, int) and cycle_length > 0:
|
|
605
|
+
return "".join(
|
|
606
|
+
Formatters.format(fmt, digit)
|
|
607
|
+
for digit in Formatters.digits(raw, cycle_length)
|
|
608
|
+
)
|
|
609
|
+
return Formatters.format(fmt, raw)
|
|
610
|
+
|
|
611
|
+
def _character_value(self, sequence: Instance, position: int) -> str:
|
|
612
|
+
chars = list(sequence.properties.get("characters") or [])
|
|
613
|
+
if not chars:
|
|
614
|
+
raise SequenceExhaustedError("sequence has no characters")
|
|
615
|
+
pos = position - 1
|
|
616
|
+
if 0 <= pos < len(chars):
|
|
617
|
+
return chars[pos]
|
|
618
|
+
size = len(chars)
|
|
619
|
+
cycle = pos // size
|
|
620
|
+
rule = sequence.properties.get("expansion_rule")
|
|
621
|
+
if rule == "repeat_label":
|
|
622
|
+
return chars[pos % size]
|
|
623
|
+
if rule == "prepend_prefix":
|
|
624
|
+
prefixes = self._prefixes_for(sequence, chars)
|
|
625
|
+
return prefixes[(cycle - 1) % len(prefixes)] + chars[pos % size]
|
|
626
|
+
if rule == "double_character":
|
|
627
|
+
return chars[pos % size] * (cycle + 1)
|
|
628
|
+
if rule == "append_suffix":
|
|
629
|
+
suffixes = self._prefixes_for(sequence, chars)
|
|
630
|
+
return chars[pos % size] + suffixes[(cycle - 1) % len(suffixes)]
|
|
631
|
+
if rule in ("none", None):
|
|
632
|
+
raise SequenceExhaustedError(
|
|
633
|
+
f"sequence exhausted at position {pos + 1} "
|
|
634
|
+
"(expansion_rule none)"
|
|
635
|
+
)
|
|
636
|
+
raise ResolutionError(f"unknown expansion_rule: {rule!r}")
|
|
637
|
+
|
|
638
|
+
@staticmethod
|
|
639
|
+
def _prefixes_for(sequence: Instance, chars: list[str]) -> list[str]:
|
|
640
|
+
prefixes = sequence.properties.get("expansion_prefix") or []
|
|
641
|
+
if isinstance(prefixes, str):
|
|
642
|
+
prefixes = [prefixes]
|
|
643
|
+
prefixes = [p for p in prefixes if p]
|
|
644
|
+
return prefixes if prefixes else chars
|
|
645
|
+
|
|
646
|
+
@staticmethod
|
|
647
|
+
def _join_hierarchical(parent_hier: str | None, raw: str | None):
|
|
648
|
+
if parent_hier and raw is None:
|
|
649
|
+
return parent_hier
|
|
650
|
+
if parent_hier is None:
|
|
651
|
+
return raw
|
|
652
|
+
return f"{parent_hier}.{raw}"
|
|
653
|
+
|
|
654
|
+
def _render(self):
|
|
655
|
+
for entry in self.plan:
|
|
656
|
+
labeller = entry.labeller
|
|
657
|
+
key = (
|
|
658
|
+
entry.carrier_object_id,
|
|
659
|
+
entry.labeller_name,
|
|
660
|
+
entry.parent_hier or "",
|
|
661
|
+
)
|
|
662
|
+
total = self.totals.get(key, 1)
|
|
663
|
+
local_template = self._select_template(
|
|
664
|
+
self._templates(labeller, "template"), total
|
|
665
|
+
)
|
|
666
|
+
if local_template is None:
|
|
667
|
+
raise ResolutionError(
|
|
668
|
+
f"labeller {entry.labeller_name!r} has no label template"
|
|
669
|
+
)
|
|
670
|
+
pattern = local_template.properties.get("pattern")
|
|
671
|
+
bindings = {
|
|
672
|
+
"n": entry.raw_value,
|
|
673
|
+
"pn": entry.parent_hier,
|
|
674
|
+
"parent": (
|
|
675
|
+
entry.carrier_entry.global_
|
|
676
|
+
if entry.carrier_entry is not None else None
|
|
677
|
+
),
|
|
678
|
+
"labels": self.labels_input,
|
|
679
|
+
"pattern": pattern,
|
|
680
|
+
}
|
|
681
|
+
entry.local = render(pattern, bindings)
|
|
682
|
+
globals_ = self._templates(labeller, "global_template")
|
|
683
|
+
if not globals_:
|
|
684
|
+
entry.global_ = entry.local
|
|
685
|
+
else:
|
|
686
|
+
global_template = self._select_template(globals_, total)
|
|
687
|
+
bindings = dict(
|
|
688
|
+
bindings,
|
|
689
|
+
pattern=global_template.properties.get("pattern"),
|
|
690
|
+
self=entry.local,
|
|
691
|
+
)
|
|
692
|
+
entry.global_ = render(
|
|
693
|
+
global_template.properties.get("pattern"), bindings
|
|
694
|
+
)
|
|
695
|
+
if entry.element.id:
|
|
696
|
+
self.labels[entry.element.id] = Label(
|
|
697
|
+
value=entry.local, reference=entry.global_
|
|
698
|
+
)
|
|
699
|
+
|
|
700
|
+
def _templates(self, labeller: Instance, key: str) -> list[Instance]:
|
|
701
|
+
names = labeller.refs(key)
|
|
702
|
+
found = [self.resolved.profile.instance(n) for n in names]
|
|
703
|
+
return [t for t in found if t is not None]
|
|
704
|
+
|
|
705
|
+
@staticmethod
|
|
706
|
+
def _select_template(templates: list[Instance], total: int):
|
|
707
|
+
for template in templates:
|
|
708
|
+
condition = template.properties.get("condition")
|
|
709
|
+
if condition is not None and Engine._condition_holds(condition, total):
|
|
710
|
+
return template
|
|
711
|
+
for template in templates:
|
|
712
|
+
if template.properties.get("condition") is None:
|
|
713
|
+
return template
|
|
714
|
+
return templates[0] if templates else None
|
|
715
|
+
|
|
716
|
+
@staticmethod
|
|
717
|
+
def _condition_holds(condition: dict, total: int) -> bool:
|
|
718
|
+
kind = condition.get("type", "")
|
|
719
|
+
threshold = condition.get("threshold")
|
|
720
|
+
if kind == "element_count_gt":
|
|
721
|
+
return total > threshold
|
|
722
|
+
if kind == "element_count_lt":
|
|
723
|
+
return total < threshold
|
|
724
|
+
return False
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
ladl/__init__.py,sha256=xjkhOZztoPf2fKmTf7NGWJx4ymFjjbK_C3msF9AKTww,26199
|
|
2
|
+
ladl_py-0.1.0.dist-info/METADATA,sha256=sR66W1v_2zUrdfihSZlkSKKYef9RQo7lxi1EOTMb5oI,178
|
|
3
|
+
ladl_py-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
4
|
+
ladl_py-0.1.0.dist-info/top_level.txt,sha256=V1BAXaeCLbu2wozOH0u1mVeRO2Peb80Qb1Q6TT459uI,5
|
|
5
|
+
ladl_py-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ladl
|