Upload templates.py with huggingface_hub
Browse files8 unmodified lines9101112131411 unmodified lines26272829303132339 unmodified lines434445464748492 unmodified lines525354555657585960616263643 unmodified lines6869707172734 unmodified lines787980818283848586878889909192939495969798991001011021031041051061072 unmodified lines1101111121131141151161171181191201211221231241251261271286 unmodified lines13513613713813914014128 unmodified lines1701711721731741751765 unmodified lines1821831841851861871881891901911921931941951961971981992002012022036 unmodified lines2102112122132142152169 unmodified lines22622722822923023123226 unmodified lines25926026126226326426526626726826927027127227327427527639 unmodified lines3163173183193203213223233243253263273283293303313323333343353363373383393403418 unmodified linesfrom .type_utils import isoftypeclass Template(StreamInstanceOperator):"""The role of template is to take the fields of every instance and verbalize it.11 unmodified linespostprocessors: List[str] = NonPositionalField(default_factory=lambda: ["processors.to_string_stripped"])instruction: str = NonPositionalField(default_factory=lambda: "")target_prefix: str = NonPositionalField(default_factory=lambda: "")def process(self, instance: Dict[str, Any], stream_name: Optional[str] = None9 unmodified linesinputs = instance.get("inputs")outputs = instance.get("outputs")source, instruction = self.inputs_to_source(inputs)target, references = self.outputs_to_target_and_references(outputs)return {2 unmodified lines"target": target,"references": references,"instruction": instruction,"target_prefix": self.target_prefix.format(**inputs),}@abstractmethoddef inputs_to_source(self, inputs: Dict[str, object]) -> Tuple[str, str]:pass@abstractmethoddef outputs_to_target_and_references(self, outputs: Dict[str, object]3 unmodified linesdef get_postprocessors(self) -> List[str]:return self.postprocessorsclass InputOutputTemplate(Template):"""Generate field 'source' from fields designated as input, and fields 'target' and 'references' from fields designated as output, of the processed instance.4 unmodified linesinput_format: str = Noneoutput_format: str = Nonedef process_template(self, template: str, data: Dict[str, object]) -> str:data = {k: ", ".join(v) if isinstance(v, list) else v for k, v in data.items()}return template.format(**data)def inputs_to_source(self, inputs: Dict[str, object]) -> Tuple[str, str]:formatted = []for formatting in [self.input_format, self.instruction]:try:formatted.append(self.process_template(formatting, inputs))except KeyError as e:raise KeyError(f"Available inputs are {list(inputs.keys())} but input format requires a different ones: '{formatting}'") from ereturn tuple(formatted)def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:try:target = self.process_template(self.output_format, outputs)except KeyError as e:raise KeyError(f"Available outputs are {outputs.keys()} but output format requires a different one: {self.output_format}") from ereferences = [target]return target, references2 unmodified linesreference: strdef outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:output_fields = {}for name, val in [("target", self.output_format),("reference", self.reference),]:try:result = self.process_template(val, outputs)output_fields[name] = resultexcept KeyError as e:raise KeyError(f"Available outputs are {outputs.keys()} but {name} requires a different one: {val}") from ereturn output_fields["target"], [output_fields["reference"]]class MultipleChoiceTemplate(Template):6 unmodified lineschoices_seperator: str = ", "source_choice_format: str = "{choice_numeral}. {choice_text}"target_choice_format: str = "{choice_numeral}"add_numerals_as_field: str = Noneenumerator: str = "capitals"def prepare(self):28 unmodified lines"XX",]def get_choices(self, data: Dict[str, object], choice_format: str) -> str:choices = data[self.choices_field]enumrated_choices = []for i, choice in enumerate(choices):5 unmodified lines)return enumrated_choicesdef inputs_to_source(self, inputs: Dict[str, object]) -> Tuple[str, str]:choices = self.get_choices(inputs, self.source_choice_format)inputs = {"numerals": ",".join(self.get_choices(inputs, "{choice_numeral}")),**inputs,self.choices_field: self.choices_seperator.join(choices),}formatted = []for formatting in [self.input_format, self.instruction]:try:formatted.append(formatting.format(**inputs))except KeyError as e:raise KeyError(f"Available inputs are {inputs.keys()} but input format requires a different one: {formatting}") from ereturn tuple(formatted)def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:target = outputs[self.target_field]6 unmodified linesf"MultipleChoiceTemplate could not locate textual target '{target}' in choices list: {outputs[self.choices_field]}") from echoices = self.get_choices(outputs, self.target_choice_format)try:target = choices[target]9 unmodified lines) -> Dict[str, Any]:result = super().process(instance, stream_name)if "options" not in result["outputs"]:result["outputs"]["options"] = self.get_choices(instance["outputs"], self.target_choice_format)return result26 unmodified linesno_answer: str = "No"def inputs_to_source(self, inputs: Dict[str, object]) -> Tuple[str, str]:data = {k: ", ".join(v) if isinstance(v, list) else v for k, v in inputs.items()}formatted = []for formatting in [self.input_format, self.instruction]:try:formatted.append(formatting.format(**data))except KeyError as e:raise RuntimeError(f"Available inputs are {list(inputs.keys())} but input format requires a different one: {formatting}") from ereturn tuple(formatted)def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:try:39 unmodified linesuse_keys_for_outputs: bool = Falsedef process_dict(self, dic: Dict[str, object], key_val_sep, pairs_sep, use_keys) -> str:dic = {k: ", ".join([str(vi) for vi in v]) if isinstance(v, list) else vfor k, v in dic.items()}pairs = []for key, val in dic.items():key_val = [key, str(val)] if use_keys else [str(val)]pairs.append(key_val_sep.join(key_val))return pairs_sep.join(pairs)def inputs_to_source(self, inputs: Dict[str, object]) -> Tuple[str, str]:ret = self.process_dict(inputs,key_val_sep=self.key_val_seperator,pairs_sep=self.pairs_seperator,use_keys=self.use_keys_for_inputs,)return (ret, ret)def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:target = self.process_dict(8 unmodified lines9101112131415161718192021222311 unmodified lines3536373839404142434445464748495051529 unmodified lines6263646566676869707172732 unmodified lines76777879808182838485868788899091923 unmodified lines969798991001011021031041051061071081091101111121131141151161171181194 unmodified lines1241251261271281291301311321331341351361371382 unmodified lines1411421431441451461471481491501511521536 unmodified lines16016116216316416528 unmodified lines1941951961971981992005 unmodified lines2062072082092102112122132142152162172182192202212222232242252262272282292302312322336 unmodified lines2402412422432442452469 unmodified lines25625725825926026126226 unmodified lines28929029129229329429529629739 unmodified lines3373383393403413423433443453463473483493503513523533543553563573588 unmodified linesfrom .type_utils import isoftypeclass TemplateFormatKeyError(KeyError):def __init__(self, template, data, data_type, format_str, format_name):keys = ", ".join(data.keys())super().__init__(f"Available {data_type}s are [{keys}] "f"but {template.__class__.__name__}.{format_name} format requires a different ones: '{format_str}'")class Template(StreamInstanceOperator):"""The role of template is to take the fields of every instance and verbalize it.11 unmodified linespostprocessors: List[str] = NonPositionalField(default_factory=lambda: ["processors.to_string_stripped"])instruction: str = NonPositionalField(default="")target_prefix: str = NonPositionalField(default="")title_fields: List[str] = NonPositionalField(default_factory=list)def inputs_to_instruction_and_target_prefix(self, inputs):instruction = self.apply_formatting(inputs, "input", self.instruction, "instruction", serialize=True)target_prefix = self.apply_formatting(inputs, "input", self.target_prefix, "target_prefix", serialize=True)return instruction, target_prefixdef process(self, instance: Dict[str, Any], stream_name: Optional[str] = None9 unmodified linesinputs = instance.get("inputs")outputs = instance.get("outputs")self.set_titles(inputs)source = self.inputs_to_source(inputs)instruction, target_prefix = self.inputs_to_instruction_and_target_prefix(inputs)target, references = self.outputs_to_target_and_references(outputs)return {2 unmodified lines"target": target,"references": references,"instruction": instruction,"target_prefix": target_prefix,}@abstractmethoddef inputs_to_source(self, inputs: Dict[str, object]) -> Tuple[str, str]:passdef set_titles(self, data):for field in self.title_fields:data[field] = data[field].title()@abstractmethoddef outputs_to_target_and_references(self, outputs: Dict[str, object]3 unmodified linesdef get_postprocessors(self) -> List[str]:return self.postprocessorsdef serialize_data(self, data):return {k: ", ".join(str(t) for t in v) if isinstance(v, list) else vfor k, v in data.items()}def apply_formatting(self, data, data_type, format_str, format_name, serialize=False) -> str:if serialize:data = self.serialize_data(data)try:return format_str.format(**data)except KeyError as e:raise TemplateFormatKeyError(self, data, data_type, format_str, format_name) from eclass InputOutputTemplate(Template):"""Generate field 'source' from fields designated as input, and fields 'target' and 'references' from fields designated as output, of the processed instance.4 unmodified linesinput_format: str = Noneoutput_format: str = Nonedef inputs_to_source(self, inputs: Dict[str, object]) -> Tuple[str, str]:return self.apply_formatting(inputs, "input", self.input_format, "input_format", serialize=True)def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:target = self.apply_formatting(outputs, "output", self.output_format, "output_format", serialize=True)references = [target]return target, references2 unmodified linesreference: strdef outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:target = self.apply_formatting(outputs, "output", self.output_format, "output_format", serialize=True)reference = self.apply_formatting(outputs, "output", self.reference, "reference", serialize=True)return target, [reference]class MultipleChoiceTemplate(Template):6 unmodified lineschoices_seperator: str = ", "source_choice_format: str = "{choice_numeral}. {choice_text}"target_choice_format: str = "{choice_numeral}"enumerator: str = "capitals"def prepare(self):28 unmodified lines"XX",]def inputs_to_choices(self, data: Dict[str, object], choice_format: str) -> str:choices = data[self.choices_field]enumrated_choices = []for i, choice in enumerate(choices):5 unmodified lines)return enumrated_choicesdef inputs_to_numerals(self, inputs: Dict[str, object]) -> Tuple[str, str]:return self.inputs_to_choices(inputs, "{choice_numeral}")def prepare_multiple_choice_inputs(self, inputs: Dict[str, object]) -> Dict[str, object]:choices = self.inputs_to_choices(inputs, self.source_choice_format)return {"numerals": self.inputs_to_numerals(inputs),**inputs,self.choices_field: self.choices_seperator.join(choices),}def inputs_to_source(self, inputs: Dict[str, object]) -> Tuple[str, str]:inputs = self.prepare_multiple_choice_inputs(inputs)return self.apply_formatting(inputs, "input", self.input_format, "input_format", serialize=True)def inputs_to_instruction_and_target_prefix(self, inputs):inputs = self.prepare_multiple_choice_inputs(inputs)return super().inputs_to_instruction_and_target_prefix(inputs)def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:target = outputs[self.target_field]6 unmodified linesf"MultipleChoiceTemplate could not locate textual target '{target}' in choices list: {outputs[self.choices_field]}") from echoices = self.inputs_to_choices(outputs, self.target_choice_format)try:target = choices[target]9 unmodified lines) -> Dict[str, Any]:result = super().process(instance, stream_name)if "options" not in result["outputs"]:result["outputs"]["options"] = self.inputs_to_choices(instance["outputs"], self.target_choice_format)return result26 unmodified linesno_answer: str = "No"def inputs_to_source(self, inputs: Dict[str, object]) -> Tuple[str, str]:return self.apply_formatting(inputs, "input", self.input_format, "input_format", serialize=True)def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:try:39 unmodified linesuse_keys_for_outputs: bool = Falsedef process_dict(self, data: Dict[str, object], key_val_sep, pairs_sep, use_keys) -> str:data = self.serialize_data(data)pairs = []for key, val in data.items():key_val = [key, str(val)] if use_keys else [str(val)]pairs.append(key_val_sep.join(key_val))return pairs_sep.join(pairs)def inputs_to_source(self, inputs: Dict[str, object]) -> Tuple[str, str]:return self.process_dict(inputs,key_val_sep=self.key_val_seperator,pairs_sep=self.pairs_seperator,use_keys=self.use_keys_for_inputs,)def outputs_to_target_and_references(self, outputs: Dict[str, object]) -> str:target = self.process_dict(
templates.py+92-75