Elron commited on
Commit
3478957
1 Parent(s): 6b6ce01

Upload templates.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. templates.py +182 -243
templates.py CHANGED
@@ -1,74 +1,42 @@
1
  import json
2
- from abc import ABC, abstractmethod
3
  from dataclasses import field
4
- from typing import Any, Dict, List, Optional, Union
5
 
6
- from .artifact import Artifact
7
  from .collections import ListCollection
8
  from .dataclass import NonPositionalField
9
- from .instructions import Instruction, TextualInstruction
10
  from .operator import StreamInstanceOperator
11
- from .random_utils import get_random
12
- from .text_utils import split_words
13
  from .type_utils import isoftype
14
 
15
 
16
- class Renderer(ABC):
17
- @abstractmethod
18
- def get_postprocessors(self) -> List[str]:
19
- pass
20
-
21
-
22
- class Template(Artifact):
23
- is_multi_target: bool = NonPositionalField(default=False)
24
- is_multi_reference: bool = NonPositionalField(default=False)
25
-
26
- @abstractmethod
27
- def process_inputs(self, inputs: Dict[str, object]) -> Dict[str, object]:
28
- pass
29
-
30
- @abstractmethod
31
- def process_outputs(self, outputs: Dict[str, object]) -> Dict[str, object]:
32
- pass
33
-
34
- @abstractmethod
35
- def get_postprocessors(self) -> List[str]:
36
- pass
37
-
38
 
39
- class RenderFormatTemplate(Renderer, StreamInstanceOperator):
40
- template: Template = None
41
- random_reference: bool = False
42
 
43
- def verify(self):
44
- assert isinstance(
45
- self.template, Template
46
- ), "Template must be an instance of Template"
47
- assert self.template is not None, "Template must be specified"
48
 
49
  def process(
50
  self, instance: Dict[str, Any], stream_name: Optional[str] = None
51
  ) -> Dict[str, Any]:
52
- return self.render(instance)
53
-
54
- def render(self, instance: Dict[str, Any]) -> Dict[str, Any]:
55
- inputs = instance.pop("inputs")
56
- outputs = instance.pop("outputs")
57
-
58
- source = self.template.process_inputs(inputs)
59
- targets = self.template.process_outputs(outputs)
60
-
61
- if self.template.is_multi_reference:
62
- references = targets
63
- if self.random_reference:
64
- target = get_random().choice(references)
65
- else:
66
- if len(references) == 0:
67
- raise ValueError("No references found")
68
- target = references[0]
69
- else:
70
- references = [targets]
71
- target = targets
72
 
73
  return {
74
  **instance,
@@ -77,106 +45,29 @@ class RenderFormatTemplate(Renderer, StreamInstanceOperator):
77
  "references": references,
78
  }
79
 
80
- def get_postprocessors(self) -> List[str]:
81
- return self.template.get_postprocessors()
82
-
83
-
84
- class RenderAutoFormatTemplate(RenderFormatTemplate):
85
- def prepare(self):
86
- if self.template is None:
87
- self.template = AutoInputOutputTemplate()
88
-
89
- def render(self, instance: Dict[str, object]) -> Dict[str, object]:
90
- try:
91
- if not self.template.is_complete():
92
- self.template.infer_missing(instance["inputs"], instance["outputs"])
93
- except:
94
- pass
95
-
96
- inputs = dict(instance["inputs"].items())
97
-
98
- return super().render({**instance, "inputs": inputs})
99
-
100
-
101
- class CharacterSizeLimiter(Artifact):
102
- limit: int = 1000
103
-
104
- def check(self, text: str) -> bool:
105
- return len(text) <= self.limit
106
-
107
-
108
- class RenderTemplatedICL(RenderAutoFormatTemplate):
109
- instruction: Instruction = None
110
- input_prefix: str = ""
111
- output_prefix: str = ""
112
- target_prefix: str = " "
113
- instruction_prefix: str = ""
114
- demos_field: str = None
115
- size_limiter: Artifact = None
116
- input_output_separator: str = "\n"
117
- demo_separator: str = "\n\n"
118
- system_prompt: str = None
119
-
120
- def render(self, instance: Dict[str, object]) -> Dict[str, object]:
121
- demos = instance.pop(self.demos_field, [])
122
-
123
- source = ""
124
-
125
- example = super().render(instance)
126
-
127
- input_str = (
128
- self.input_prefix
129
- + example["source"]
130
- + self.input_output_separator
131
- + self.output_prefix
132
- )
133
-
134
- if self.instruction is not None:
135
- source += self.instruction_prefix + self.instruction() + self.demo_separator
136
-
137
- for demo_instance in demos:
138
- demo_example = super().render(demo_instance)
139
- demo_str = (
140
- self.input_prefix
141
- + demo_example["source"]
142
- + self.input_output_separator
143
- + self.output_prefix
144
- + self.target_prefix
145
- + demo_example["target"]
146
- + self.demo_separator
147
- )
148
-
149
- if self.size_limiter is not None:
150
- if not self.size_limiter.check(
151
- source + demo_str + input_str + example["target"]
152
- ):
153
- continue
154
-
155
- source += demo_str
156
-
157
- source += input_str
158
 
159
- if self.system_prompt is not None:
160
- source = self.system_prompt.format(source)
 
 
 
161
 
162
- return {
163
- **example,
164
- "source": source,
165
- }
166
 
167
 
168
  class InputOutputTemplate(Template):
169
  input_format: str = None
170
  output_format: str = None
171
- postprocessors: List[str] = field(
172
- default_factory=lambda: ["processors.to_string_stripped"]
173
- )
174
 
175
  def process_template(self, template: str, data: Dict[str, object]) -> str:
176
  data = {k: ", ".join(v) if isinstance(v, list) else v for k, v in data.items()}
177
  return template.format(**data)
178
 
179
- def process_inputs(self, inputs: Dict[str, object]) -> str:
180
  try:
181
  return self.process_template(self.input_format, inputs)
182
  except KeyError as e:
@@ -184,16 +75,118 @@ class InputOutputTemplate(Template):
184
  f"Available inputs are {list(inputs.keys())} but input format requires a different ones: '{self.input_format}'"
185
  ) from e
186
 
187
- def process_outputs(self, outputs: Dict[str, object]) -> str:
188
  try:
189
- return self.process_template(self.output_format, outputs)
190
  except KeyError as e:
191
  raise KeyError(
192
  f"Available outputs are {outputs.keys()} but output format requires a different one: {self.output_format}"
193
  ) from e
194
 
195
- def get_postprocessors(self) -> List[str]:
196
- return self.postprocessors
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
 
198
 
199
  class YesNoTemplate(Template):
@@ -225,7 +218,7 @@ class YesNoTemplate(Template):
225
  default_factory=lambda: ["processors.to_string_stripped"]
226
  )
227
 
228
- def process_inputs(self, inputs: Dict[str, object]) -> str:
229
  try:
230
  data = {
231
  k: ", ".join(v) if isinstance(v, list) else v for k, v in inputs.items()
@@ -236,7 +229,7 @@ class YesNoTemplate(Template):
236
  f"Available inputs are {list(inputs.keys())} but input format requires a different one: {self.input_format}"
237
  ) from e
238
 
239
- def process_outputs(self, outputs: Dict[str, object]) -> str:
240
  try:
241
  gold_class_names = outputs[self.label_field]
242
  except KeyError as e:
@@ -263,9 +256,8 @@ class YesNoTemplate(Template):
263
  )
264
  queried_class_name = queried_class_names[0]
265
  if queried_class_name in gold_class_names:
266
- return self.yes_answer
267
-
268
- return self.no_answer
269
 
270
  def get_postprocessors(self) -> List[str]:
271
  return self.postprocessors
@@ -291,11 +283,11 @@ class KeyValTemplate(Template):
291
  }
292
  pairs = []
293
  for key, val in dic.items():
294
- key_val = [key, val] if use_keys else [val]
295
  pairs.append(key_val_sep.join(key_val))
296
  return pairs_sep.join(pairs)
297
 
298
- def process_inputs(self, inputs: Dict[str, object]) -> str:
299
  return self.process_dict(
300
  inputs,
301
  key_val_sep=self.key_val_seperator,
@@ -303,13 +295,14 @@ class KeyValTemplate(Template):
303
  use_keys=self.use_keys_for_inputs,
304
  )
305
 
306
- def process_outputs(self, outputs: Dict[str, object]) -> str:
307
- return self.process_dict(
308
  outputs,
309
  key_val_sep=self.key_val_seperator,
310
  pairs_sep=self.pairs_seperator,
311
  use_keys=self.use_keys_for_outputs,
312
  )
 
313
 
314
  def get_postprocessors(self) -> List[str]:
315
  return self.postprocessors
@@ -318,40 +311,55 @@ class KeyValTemplate(Template):
318
  class OutputQuantizingTemplate(InputOutputTemplate):
319
  quantum: float = 0.1
320
 
321
- def process_outputs(self, outputs: Dict[str, object]) -> str:
322
  quantized_outputs = {
323
  key: round(input_float / self.quantum) * self.quantum
324
  for key, input_float in outputs.items()
325
  }
326
- return super().process_outputs(quantized_outputs)
327
 
328
 
329
  class MultiLabelTemplate(InputOutputTemplate):
330
  labels_field: str = "labels"
331
  labels_seprator: str = ", "
332
- postprocessors = ["processors.to_list_by_comma"]
333
- output_format = "{labels}"
334
- empty_label = "None"
335
 
336
- def process_outputs(self, outputs: Dict[str, object]) -> str:
337
  labels = outputs[self.labels_field]
 
 
 
 
338
  if len(labels) == 0:
339
  labels = [self.empty_label]
340
  labels_str = self.labels_seprator.join(labels)
341
- return super().process_outputs({self.labels_field: labels_str})
342
 
343
 
344
  class MultiReferenceTemplate(InputOutputTemplate):
345
  references_field: str = "references"
346
- is_multi_reference = True
347
 
348
- def process_outputs(self, outputs: Dict[str, object]) -> List[str]:
349
  references = outputs[self.references_field]
350
  if not isoftype(references, List[str]):
351
  raise ValueError(
352
- f"MultiReferenceTemplate requires that references field {self.references_field} is of type List[str]."
 
 
 
 
353
  )
354
- return references
 
 
 
 
 
 
 
355
 
356
 
357
  def escape_chars(s, chars_to_escape):
@@ -381,10 +389,12 @@ class SpanLabelingBaseTemplate(MultiLabelTemplate):
381
  if self.labels_support is None or span[3] in self.labels_support:
382
  yield span[2], span[3]
383
 
384
- def process_outputs(self, outputs: Dict[str, object]) -> Dict[str, object]:
 
 
385
  span_lables_pairs = self.extract_span_label_pairs(outputs)
386
  targets = self.span_label_pairs_to_targets(span_lables_pairs)
387
- return super().process_outputs({"labels": targets})
388
 
389
  @abstractmethod
390
  def span_label_pairs_to_targets(self, pairs):
@@ -394,7 +404,7 @@ class SpanLabelingBaseTemplate(MultiLabelTemplate):
394
  class SpanLabelingTemplate(SpanLabelingBaseTemplate):
395
  span_label_format: str = "{span}: {label}"
396
  escape_characters: List[str] = [":", ","]
397
- postprocessors = ["processors.to_span_label_pairs"]
398
 
399
  def span_label_pairs_to_targets(self, span_label_pairs):
400
  targets = []
@@ -419,89 +429,18 @@ class SpanLabelingJsonTemplate(SpanLabelingBaseTemplate):
419
  groups[label] = []
420
  groups[label].append(span)
421
  if len(groups) > 0:
422
- targets = [json.dumps(groups)]
423
  else:
424
  targets = []
425
  return targets
426
 
427
 
428
- class AutoInputOutputTemplate(InputOutputTemplate):
429
- def infer_input_format(self, inputs):
430
- input_format = ""
431
- for key in inputs.keys():
432
- name = " ".join(
433
- word.lower().capitalize() for word in split_words(key) if word != " "
434
- )
435
- input_format += name + ": " + "{" + key + "}" + "\n"
436
- self.input_format = input_format
437
-
438
- def infer_output_format(self, outputs):
439
- self.output_format = "{" + next(iter(outputs.keys())) + "}"
440
-
441
- def infer_missing(self, inputs, outputs):
442
- if self.input_format is None:
443
- self.infer_input_format(inputs)
444
- if self.output_format is None:
445
- self.infer_output_format(outputs)
446
-
447
- def is_complete(self):
448
- return self.input_format is not None and self.output_format is not None
449
-
450
-
451
  class TemplatesList(ListCollection):
452
  def verify(self):
453
  for template in self.items:
454
  assert isinstance(template, Template)
455
 
456
 
457
- def outputs_inputs2templates(
458
- inputs: Union[str, List], outputs: Union[str, List]
459
- ) -> TemplatesList:
460
- """Combines input and output formats into their dot product.
461
-
462
- :param inputs: list of input formats (or one)
463
- :param outputs: list of output formats (or one)
464
- :return: TemplatesList of InputOutputTemplate.
465
- """
466
- templates = []
467
- if isinstance(inputs, str):
468
- inputs = [inputs]
469
- if isinstance(outputs, str):
470
- outputs = [outputs]
471
- for input in inputs:
472
- for output in outputs:
473
- templates.append(
474
- InputOutputTemplate(
475
- input_format=input.strip(),
476
- output_format=output.strip(),
477
- ),
478
- )
479
- return TemplatesList(templates)
480
-
481
-
482
- def instructions2templates(
483
- instructions: List[TextualInstruction], templates: List[InputOutputTemplate]
484
- ) -> TemplatesList:
485
- """Insert instructions into per demonstration templates.
486
-
487
- :param instructions:
488
- :param templates: strings containing {instuction} where the instruction should be placed
489
- :return:
490
- """
491
- res_templates = []
492
- for instruction in instructions:
493
- for template in templates:
494
- res_templates.append(
495
- InputOutputTemplate(
496
- input_format=template.input_format.replace(
497
- "{instruction}", instruction.text
498
- ),
499
- output_format=template.output_format,
500
- )
501
- )
502
- return TemplatesList(templates)
503
-
504
-
505
  class TemplatesDict(Dict):
506
  def verify(self):
507
  for _key, template in self.items():
 
1
  import json
2
+ from abc import abstractmethod
3
  from dataclasses import field
4
+ from typing import Any, Dict, List, Optional, Tuple
5
 
 
6
  from .collections import ListCollection
7
  from .dataclass import NonPositionalField
 
8
  from .operator import StreamInstanceOperator
9
+ from .random_utils import new_random_generator
 
10
  from .type_utils import isoftype
11
 
12
 
13
+ class Template(StreamInstanceOperator):
14
+ """The role of template is to take the fields of every instance and verbalize it.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ Meaning the template is taking the instance and generating source, target and references.
17
+ """
 
18
 
19
+ skip_rendered_instance: bool = NonPositionalField(default=True)
20
+ postprocessors: List[str] = NonPositionalField(
21
+ default_factory=lambda: ["processors.to_string_stripped"]
22
+ )
 
23
 
24
  def process(
25
  self, instance: Dict[str, Any], stream_name: Optional[str] = None
26
  ) -> Dict[str, Any]:
27
+ if self.skip_rendered_instance:
28
+ if (
29
+ "source" in instance
30
+ and "target" in instance
31
+ and "references" in instance
32
+ ):
33
+ return instance
34
+
35
+ inputs = instance.get("inputs")
36
+ outputs = instance.get("outputs")
37
+
38
+ source = self.inputs_to_source(inputs)
39
+ target, references = self.outputs_to_target_and_references(outputs)
 
 
 
 
 
 
 
40
 
41
  return {
42
  **instance,
 
45
  "references": references,
46
  }
47
 
48
+ @abstractmethod
49
+ def inputs_to_source(self, inputs: Dict[str, object]) -> str:
50
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
+ @abstractmethod
53
+ def outputs_to_target_and_references(
54
+ self, outputs: Dict[str, object]
55
+ ) -> Tuple[str, List[str]]:
56
+ pass
57
 
58
+ def get_postprocessors(self) -> List[str]:
59
+ return self.postprocessors
 
 
60
 
61
 
62
  class InputOutputTemplate(Template):
63
  input_format: str = None
64
  output_format: str = None
 
 
 
65
 
66
  def process_template(self, template: str, data: Dict[str, object]) -> str:
67
  data = {k: ", ".join(v) if isinstance(v, list) else v for k, v in data.items()}
68
  return template.format(**data)
69
 
70
+ def inputs_to_source(self, inputs: Dict[str, object]) -> str:
71
  try:
72
  return self.process_template(self.input_format, inputs)
73
  except KeyError as e:
 
75
  f"Available inputs are {list(inputs.keys())} but input format requires a different ones: '{self.input_format}'"
76
  ) from e
77
 
78
+ def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:
79
  try:
80
+ target = self.process_template(self.output_format, outputs)
81
  except KeyError as e:
82
  raise KeyError(
83
  f"Available outputs are {outputs.keys()} but output format requires a different one: {self.output_format}"
84
  ) from e
85
 
86
+ references = [target]
87
+ return target, references
88
+
89
+
90
+ class MultipleChoiceTemplate(Template):
91
+ input_format: str
92
+ target_prefix: str = ""
93
+ choices_field: str = "choices"
94
+ target_field: str = "label"
95
+ choices_seperator: str = ", "
96
+ source_choice_format: str = "{choice_numeral}. {choice_text}"
97
+ target_choice_format: str = "{choice_numeral}"
98
+ add_numerals_as_field: str = None
99
+ enumerator: str = "capitals"
100
+
101
+ def prepare(self):
102
+ super().prepare()
103
+ if self.enumerator == "capitals":
104
+ self.enumerator = "ABCDEFGHIJKLMNOP"
105
+ if self.enumerator == "lowercase":
106
+ self.enumerator = "abcdefghijklmnop"
107
+ if self.enumerator == "numbers":
108
+ self.enumerator = [str(i + 1) for i in range(20)]
109
+ if self.enumerator == "roman":
110
+ self.enumerator = [
111
+ "I",
112
+ "II",
113
+ "III",
114
+ "IV",
115
+ "V",
116
+ "VI",
117
+ "VII",
118
+ "VIII",
119
+ "IX",
120
+ "X",
121
+ "XI",
122
+ "XII",
123
+ "XIII",
124
+ "XIV",
125
+ "XV",
126
+ "XVI",
127
+ "XVII",
128
+ "XVIII",
129
+ "XIX",
130
+ "XX",
131
+ ]
132
+
133
+ def get_choices(self, data: Dict[str, object], choice_format: str) -> str:
134
+ choices = data[self.choices_field]
135
+ enumrated_choices = []
136
+ for i, choice in enumerate(choices):
137
+ enumrated_choices.append(
138
+ choice_format.format(
139
+ choice_text=choice,
140
+ choice_numeral=self.enumerator[i],
141
+ )
142
+ )
143
+ return enumrated_choices
144
+
145
+ def inputs_to_source(self, inputs: Dict[str, object]) -> str:
146
+ choices = self.get_choices(inputs, self.source_choice_format)
147
+ inputs = {
148
+ "numerals": ",".join(self.get_choices(inputs, "{choice_numeral}")),
149
+ **inputs,
150
+ self.choices_field: self.choices_seperator.join(choices),
151
+ }
152
+ try:
153
+ return self.input_format.format(**inputs)
154
+ except KeyError as e:
155
+ raise KeyError(
156
+ f"Available inputs are {inputs.keys()} but input format requires a different one: {self.input_format}"
157
+ ) from e
158
+
159
+ def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:
160
+ target = outputs[self.target_field]
161
+
162
+ if not isinstance(target, int):
163
+ try:
164
+ target = outputs[self.choices_field].index(target)
165
+ except ValueError as e:
166
+ raise ValueError(
167
+ f"MultipleChoiceTemplate could not locate textual target '{target}' in choices list: {outputs[self.choices_field]}"
168
+ ) from e
169
+
170
+ choices = self.get_choices(outputs, self.target_choice_format)
171
+
172
+ try:
173
+ target = choices[target]
174
+ except IndexError as e:
175
+ raise IndexError(
176
+ f"MultipleChoiceTemplate cannot find index number {target} in choices: {choices}"
177
+ ) from e
178
+
179
+ return target, [target]
180
+
181
+ def process(
182
+ self, instance: Dict[str, Any], stream_name: Optional[str] = None
183
+ ) -> Dict[str, Any]:
184
+ result = super().process(instance, stream_name)
185
+ if "options" not in result["outputs"]:
186
+ result["outputs"]["options"] = self.get_choices(
187
+ instance["outputs"], self.target_choice_format
188
+ )
189
+ return result
190
 
191
 
192
  class YesNoTemplate(Template):
 
218
  default_factory=lambda: ["processors.to_string_stripped"]
219
  )
220
 
221
+ def inputs_to_source(self, inputs: Dict[str, object]) -> str:
222
  try:
223
  data = {
224
  k: ", ".join(v) if isinstance(v, list) else v for k, v in inputs.items()
 
229
  f"Available inputs are {list(inputs.keys())} but input format requires a different one: {self.input_format}"
230
  ) from e
231
 
232
+ def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:
233
  try:
234
  gold_class_names = outputs[self.label_field]
235
  except KeyError as e:
 
256
  )
257
  queried_class_name = queried_class_names[0]
258
  if queried_class_name in gold_class_names:
259
+ return self.yes_answer, [self.yes_answer]
260
+ return self.no_answer, [self.no_answer]
 
261
 
262
  def get_postprocessors(self) -> List[str]:
263
  return self.postprocessors
 
283
  }
284
  pairs = []
285
  for key, val in dic.items():
286
+ key_val = [key, str(val)] if use_keys else [str(val)]
287
  pairs.append(key_val_sep.join(key_val))
288
  return pairs_sep.join(pairs)
289
 
290
+ def inputs_to_source(self, inputs: Dict[str, object]) -> str:
291
  return self.process_dict(
292
  inputs,
293
  key_val_sep=self.key_val_seperator,
 
295
  use_keys=self.use_keys_for_inputs,
296
  )
297
 
298
+ def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:
299
+ target = self.process_dict(
300
  outputs,
301
  key_val_sep=self.key_val_seperator,
302
  pairs_sep=self.pairs_seperator,
303
  use_keys=self.use_keys_for_outputs,
304
  )
305
+ return target, [target]
306
 
307
  def get_postprocessors(self) -> List[str]:
308
  return self.postprocessors
 
311
  class OutputQuantizingTemplate(InputOutputTemplate):
312
  quantum: float = 0.1
313
 
314
+ def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:
315
  quantized_outputs = {
316
  key: round(input_float / self.quantum) * self.quantum
317
  for key, input_float in outputs.items()
318
  }
319
+ return super().outputs_to_target_and_references(quantized_outputs)
320
 
321
 
322
  class MultiLabelTemplate(InputOutputTemplate):
323
  labels_field: str = "labels"
324
  labels_seprator: str = ", "
325
+ postprocessors: List[str] = ["processors.to_list_by_comma"]
326
+ output_format: str = "{labels}"
327
+ empty_label: str = "None"
328
 
329
+ def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:
330
  labels = outputs[self.labels_field]
331
+ if not isinstance(labels, list):
332
+ raise ValueError(
333
+ f"MultiLabelTemplate requires labels field '{self.labels_field}' to be a list. Got {self.labels_field}<{type(labels).__name__}>: {labels}"
334
+ )
335
  if len(labels) == 0:
336
  labels = [self.empty_label]
337
  labels_str = self.labels_seprator.join(labels)
338
+ return super().outputs_to_target_and_references({self.labels_field: labels_str})
339
 
340
 
341
  class MultiReferenceTemplate(InputOutputTemplate):
342
  references_field: str = "references"
343
+ random_reference: bool = False
344
 
345
+ def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> List[str]:
346
  references = outputs[self.references_field]
347
  if not isoftype(references, List[str]):
348
  raise ValueError(
349
+ f"MultiReferenceTemplate requires references field '{self.references_field}' to be List[str]. Got {self.references_field}<{type(references).__name__}>: {references}"
350
+ )
351
+ if len(references) == 0:
352
+ raise ValueError(
353
+ "No references found. MultiReferenceTemplate requires at least one reference."
354
  )
355
+
356
+ if self.random_reference:
357
+ random_generator = new_random_generator(outputs)
358
+ target = random_generator.choice(references)
359
+ else:
360
+ target = references[0]
361
+
362
+ return target, references
363
 
364
 
365
  def escape_chars(s, chars_to_escape):
 
389
  if self.labels_support is None or span[3] in self.labels_support:
390
  yield span[2], span[3]
391
 
392
+ def outputs_to_target_and_references(
393
+ self, outputs: Dict[str, object]
394
+ ) -> Dict[str, object]:
395
  span_lables_pairs = self.extract_span_label_pairs(outputs)
396
  targets = self.span_label_pairs_to_targets(span_lables_pairs)
397
+ return super().outputs_to_target_and_references({"labels": targets})
398
 
399
  @abstractmethod
400
  def span_label_pairs_to_targets(self, pairs):
 
404
  class SpanLabelingTemplate(SpanLabelingBaseTemplate):
405
  span_label_format: str = "{span}: {label}"
406
  escape_characters: List[str] = [":", ","]
407
+ postprocessors: List[str] = ["processors.to_span_label_pairs"]
408
 
409
  def span_label_pairs_to_targets(self, span_label_pairs):
410
  targets = []
 
429
  groups[label] = []
430
  groups[label].append(span)
431
  if len(groups) > 0:
432
+ targets = [json.dumps(groups, ensure_ascii=False)]
433
  else:
434
  targets = []
435
  return targets
436
 
437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
438
  class TemplatesList(ListCollection):
439
  def verify(self):
440
  for template in self.items:
441
  assert isinstance(template, Template)
442
 
443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
444
  class TemplatesDict(Dict):
445
  def verify(self):
446
  for _key, template in self.items():