Commit ·
28ef031
1
Parent(s): 24ed17f
Update dataset files (#1)
Browse files- Update dataset files (c853efb46a492f79b823b4a1820c65bb2e51df30)
Co-authored-by: Rin Ldallit <idalr@users.noreply.huggingface.co>
Files changed (3)
- README.md+55-3
- argmicro.py+92-42
- requirements.txt+1-1
123---license: cc-by-nc-sa-4.0---12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455# PIE Dataset Card for "argmicro"This is a [PyTorch-IE](https://github.com/ChristophAlt/pytorch-ie) wrapper for the[ArgMicro Huggingface dataset loading script](https://huggingface.co/datasets/DFKI-SLT/argmicro).## Dataset VariantsThe dataset contains two `BuilderConfig`'s:- `de`: with the original texts collection in German- `en`: with the English-translated texts## Data SchemaThe document type for this dataset is `ArgMicroDocument` which defines the following data fields:- `text` (str)- `id` (str, optional)- `topic_id` (str, optional)- `metadata` (dictionary, optional)and the following annotation layers:- `stance` (annotation type: `Label`)- description: A document may contain one of these `stance` labels: `pro`, `con`, `unclear`, or no label when it is undefined (see [here](https://huggingface.co/datasets/DFKI-SLT/argmicro/blob/main/argmicro.py#L35) for reference).- `edus` (annotation type: `Span`, target: `text`)- `adus` (annotation type: `LabeledAnnotationCollection`, target: `edus`)- description: each element of `adus` may consist of several entries from `edus`, so we require `LabeledAnnotationCollection` as annotation type. This is originally indicated by `seg` edges in the data.- `LabeledAnnotationCollection` has the following fields:- `annotations` (annotation type: `Span`, target: `text`)- `label` (str, optional), values: `opp`, `pro` (see [here](https://huggingface.co/datasets/DFKI-SLT/argmicro/blob/main/argmicro.py#L36))- `relations` (annotation type: `MultiRelation`, target: `adus`)- description: Undercut (`und`) relations originally target other relations (i.e. edges), but we let them target the `head` of the targeted relation instead. The original state can be deterministically reconstructed by taking the label into account. Furthermore, the head of additional source (`add`) relations are integrated into the head of the target relation (note that this propagates along `und` relations). We model this with `MultiRelation`s whose `head` and `tail` are of type `LabeledAnnotationCollection`.- `MultiRelation` has the following fields:- `head` (tuple, annotation type: `LabeledAnnotationCollection`, target: `adus`)- `tail` (tuple, annotation type: `LabeledAnnotationCollection`, target: `adus`)- `label` (str, optional), values: `sup`, `exa`, `reb`, `und` (see [here](https://huggingface.co/datasets/DFKI-SLT/argmicro/blob/main/argmicro.py#L37) for reference, but note that helper relations `seg` and `add` are not there anymore, see above).See [here](https://github.com/ChristophAlt/pytorch-ie/blob/main/src/pytorch_ie/annotations.py) for the annotation type definitions.## Document ConvertersThe dataset provides document converters for the following target document types:- `pytorch_ie.documents.TextDocumentWithLabeledSpansAndBinaryRelations`- `LabeledSpans`, converted from `ArgMicroDocument`'s `adus`- labels: `opp`, `pro`- if an ADU contains multiple spans (i.e. EDUs), we take the start of the first EDU and the end of the last EDU as the boundaries of the new `LabeledSpan`. We also raise exceptions if any newly created `LabeledSpan`s overlap.- `BinraryRelations`, converted from `ArgMicroDocument`'s `relations`- labels: `sup`, `reb`, `und`, `joint`, `exa`- if the `head` or `tail` consists of multiple `adus`, then we build `BinaryRelation`s with all `head`-`tail` combinations and take the label from the original relation. Then, we build `BinaryRelations`' with label `joint` between each component that previously belongs to the same `head` or `tail`, respectively.- `metadata`, we keep the `ArgMicroDocument`'s `metadata`, but `stance` and `topic_id`.See [here](https://github.com/ChristophAlt/pytorch-ie/blob/main/src/pytorch_ie/documents.py) for the document typedefinitions.
123456789101112131415161718192021222324252627282912 unmodified lines424344454647481 unmodified line50515253545556575859606162636465662 unmodified lines697071727374758 unmodified lines8485868788899025 unmodified lines1161171181191201211221231241251261271281291301311321331341351361371381391401411427 unmodified lines15015115215315415515619 unmodified lines1761771781791801811824 unmodified lines1871881891901911921936 unmodified lines2002012022032042052063 unmodified lines210211212213214215216217218219220221222223224225226227228229230231232233import dataclassesfrom collections import defaultdictfrom typing import Any, Callable, Dict, List, Optional, Tupleimport datasetsimport pytorch_ie.data.builderfrom pytorch_ie.annotations import Spanfrom pytorch_ie.core import Annotation, AnnotationList, annotation_fieldfrom pytorch_ie.documents import TextBasedDocumentfrom src import utilslog = utils.get_pylogger(__name__)def dl2ld(dict_of_lists):return [dict(zip(dict_of_lists, t)) for t in zip(*dict_of_lists.values())]def ld2dl(list_of_dicts, keys: Optional[List[str]] = None, as_list: bool = False):if keys is None:keys = list_of_dicts[0].keys()if as_list:return [[d[k] for d in list_of_dicts] for k in keys]else:return {k: [d[k] for d in list_of_dicts] for k in keys}@dataclasses.dataclass(frozen=True)12 unmodified lines@dataclasses.dataclassclass ArgMicroDocument(TextBasedDocument):topic_id: Optional[str] = Nonestance: Optional[str] = Noneedus: AnnotationList[Span] = annotation_field(target="text")adus: AnnotationList[LabeledAnnotationCollection] = annotation_field(target="edus")relations: AnnotationList[MultiRelation] = annotation_field(target="adus")1 unmodified linedef example_to_document(example: Dict[str, Any],adu_type_int2str: Callable[[int], str],edge_type_int2str: Callable[[int], str],stance_int2str: Callable[[int], str],) -> ArgMicroDocument:stance = stance_int2str(example["stance"])document = ArgMicroDocument(id=example["id"],text=example["text"],topic_id=example["topic_id"] if example["topic_id"] != "UNDEFINED" else None,stance=stance if stance != "UNDEFINED" else None,)# build EDUsedus_dict = {edu["id"]: Span(start=edu["start"], end=edu["end"]) for edu in dl2ld(example["edus"])2 unmodified linesadu_id2edus = defaultdict(list)edges_multi_source = defaultdict(dict)for edge in dl2ld(example["edges"]):edge_type = edge_type_int2str(edge["type"])if edge_type == "seg":adu_id2edus[edge["trg"]].append(edus_dict[edge["src"]])elif edge_type == "add":8 unmodified linesedges_multi_source[edge["id"]]["src"].append(edge["src"])adus_dict = {}for adu in dl2ld(example["adus"]):adu_type = adu_type_int2str(adu["type"])adu_edus = adu_id2edus[adu["id"]]adus_dict[adu["id"]] = LabeledAnnotationCollection(annotations=tuple(adu_edus), label=adu_type25 unmodified linesdocument.metadata["rel_seg_ids"] = {edge["src"]: edge["id"]for edge in dl2ld(example["edges"])if edge_type_int2str(edge["type"]) == "seg"}document.metadata["rel_add_ids"] = {edge["src"]: edge["id"]for edge in dl2ld(example["edges"])if edge_type_int2str(edge["type"]) == "add"}return documentdef document_to_example(document: ArgMicroDocument,adu_type_str2int: Callable[[str], int],edge_type_str2int: Callable[[str], int],stance_str2int: Callable[[str], int],) -> Dict[str, Any]:result = {"id": document.id,"text": document.text,"topic_id": document.topic_id or "UNDEFINED","stance": stance_str2int(document.stance or "UNDEFINED"),}# construct EDUs7 unmodified lines# construct ADUsadus = {adu: {"id": adu_id, "type": adu_type_str2int(adu.label)}for adu_id, adu in zip(document.metadata["adu_ids"], document.adus)}result["adus"] = ld2dl(sorted(adus.values(), key=lambda x: x["id"]), keys=["id", "type"])19 unmodified lines"id": rel_id,"src": source_id,"trg": target_id,"type": edge_type_str2int(rel.label),}edges.append(edge)# if it is an additional support, we need to change the source to the relation that connects the source4 unmodified lines"id": edge_id,"src": source_id,"trg": rel_id,"type": edge_type_str2int("add"),}edges.append(edge)6 unmodified lines"id": edge_id,"src": source_id,"trg": target_id,"type": edge_type_str2int("seg"),}edges.append(edge)3 unmodified linesreturn resultclass ArgMicro(pytorch_ie.data.builder.GeneratorBasedBuilder):DOCUMENT_TYPE = ArgMicroDocumentBASE_DATASET_PATH = "DFKI-SLT/argmicro"BUILDER_CONFIGS = [datasets.BuilderConfig(name="en"), datasets.BuilderConfig(name="de")]def _generate_document_kwargs(self, dataset):return {"adu_type_int2str": dataset.features["adus"].feature["type"].int2str,"edge_type_int2str": dataset.features["edges"].feature["type"].int2str,"stance_int2str": dataset.features["stance"].int2str,}def _generate_document(self, example, adu_type_int2str, edge_type_int2str, stance_int2str):return example_to_document(example,adu_type_int2str=adu_type_int2str,edge_type_int2str=edge_type_int2str,stance_int2str=stance_int2str,)123456789101112131415161718192021222324252627282912 unmodified lines424344454647481 unmodified line505152535455565758596061626364656667682 unmodified lines717273747576778 unmodified lines8687888990919225 unmodified lines1181191201211221231241251261271281291301311321331341351361371381391401411421431441457 unmodified lines15315415515615715815919 unmodified lines1791801811821831841854 unmodified lines1901911921931941951966 unmodified lines2032042052062072082093 unmodified lines213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283import copyimport dataclassesimport loggingfrom collections import defaultdictfrom itertools import combinationsfrom typing import Any, Dict, List, Optional, Set, Tupleimport datasetsfrom pytorch_ie.annotations import BinaryRelation, Label, LabeledSpan, Spanfrom pytorch_ie.core import Annotation, AnnotationList, annotation_fieldfrom pytorch_ie.documents import (TextBasedDocument,TextDocumentWithLabeledSpansAndBinaryRelations,)from pie_datasets import GeneratorBasedBuilderlog = logging.getLogger(__name__)def dl2ld(dict_of_lists):return [dict(zip(dict_of_lists, t)) for t in zip(*dict_of_lists.values())]def ld2dl(list_of_dicts, keys: Optional[List[str]] = None):return {k: [d[k] for d in list_of_dicts] for k in keys}@dataclasses.dataclass(frozen=True)12 unmodified lines@dataclasses.dataclassclass ArgMicroDocument(TextBasedDocument):topic_id: Optional[str] = Nonestance: AnnotationList[Label] = annotation_field()edus: AnnotationList[Span] = annotation_field(target="text")adus: AnnotationList[LabeledAnnotationCollection] = annotation_field(target="edus")relations: AnnotationList[MultiRelation] = annotation_field(target="adus")1 unmodified linedef example_to_document(example: Dict[str, Any],adu_type_label: datasets.ClassLabel,edge_type_label: datasets.ClassLabel,stance_label: datasets.ClassLabel,) -> ArgMicroDocument:stance = stance_label.int2str(example["stance"])document = ArgMicroDocument(id=example["id"],text=example["text"],topic_id=example["topic_id"] if example["topic_id"] != "UNDEFINED" else None,)if stance != "UNDEFINED":document.stance.append(Label(label=stance))# build EDUsedus_dict = {edu["id"]: Span(start=edu["start"], end=edu["end"]) for edu in dl2ld(example["edus"])2 unmodified linesadu_id2edus = defaultdict(list)edges_multi_source = defaultdict(dict)for edge in dl2ld(example["edges"]):edge_type = edge_type_label.int2str(edge["type"])if edge_type == "seg":adu_id2edus[edge["trg"]].append(edus_dict[edge["src"]])elif edge_type == "add":8 unmodified linesedges_multi_source[edge["id"]]["src"].append(edge["src"])adus_dict = {}for adu in dl2ld(example["adus"]):adu_type = adu_type_label.int2str(adu["type"])adu_edus = adu_id2edus[adu["id"]]adus_dict[adu["id"]] = LabeledAnnotationCollection(annotations=tuple(adu_edus), label=adu_type25 unmodified linesdocument.metadata["rel_seg_ids"] = {edge["src"]: edge["id"]for edge in dl2ld(example["edges"])if edge_type_label.int2str(edge["type"]) == "seg"}document.metadata["rel_add_ids"] = {edge["src"]: edge["id"]for edge in dl2ld(example["edges"])if edge_type_label.int2str(edge["type"]) == "add"}return documentdef document_to_example(document: ArgMicroDocument,adu_type_label: datasets.ClassLabel,edge_type_label: datasets.ClassLabel,stance_label: datasets.ClassLabel,) -> Dict[str, Any]:stance = document.stance[0].label if len(document.stance) else "UNDEFINED"result = {"id": document.id,"text": document.text,"topic_id": document.topic_id or "UNDEFINED","stance": stance_label.str2int(stance),}# construct EDUs7 unmodified lines# construct ADUsadus = {adu: {"id": adu_id, "type": adu_type_label.str2int(adu.label)}for adu_id, adu in zip(document.metadata["adu_ids"], document.adus)}result["adus"] = ld2dl(sorted(adus.values(), key=lambda x: x["id"]), keys=["id", "type"])19 unmodified lines"id": rel_id,"src": source_id,"trg": target_id,"type": edge_type_label.str2int(rel.label),}edges.append(edge)# if it is an additional support, we need to change the source to the relation that connects the source4 unmodified lines"id": edge_id,"src": source_id,"trg": rel_id,"type": edge_type_label.str2int("add"),}edges.append(edge)6 unmodified lines"id": edge_id,"src": source_id,"trg": target_id,"type": edge_type_label.str2int("seg"),}edges.append(edge)3 unmodified linesreturn resultdef convert_to_text_document_with_labeled_spans_and_binary_relations(doc: ArgMicroDocument,) -> TextDocumentWithLabeledSpansAndBinaryRelations:# convert adus to entitiesentities = []adu2entity: Dict[LabeledAnnotationCollection, Span] = {}for adu in doc.adus:edus: Set[Span] = set(adu.annotations)start = min(edu.start for edu in edus)end = max(edu.end for edu in edus)# assert there are no edus overlapping with the adu, but not part of itfor edu in doc.edus:if (start <= edu.start < end or start < edu.end <= end) and edu not in edus:raise Exception(f"edu {edu} is overlapping with adu {adu}, but is not part of it")entity = LabeledSpan(start=start, end=end, label=adu.label)entities.append(entity)adu2entity[adu] = entityrelations = []for relation in doc.relations:# add all possible combinations of heads and tailsfor head in relation.heads:for tail in relation.tails:rel = BinaryRelation(label=relation.label, head=adu2entity[head], tail=adu2entity[tail])relations.append(rel)# also add the relations between the heads themselvesfor head1, head2 in combinations(relation.heads, 2):rel = BinaryRelation(label="joint", head=adu2entity[head1], tail=adu2entity[head2])relations.append(rel)# also add the reverse relationrel = BinaryRelation(label="joint", head=adu2entity[head2], tail=adu2entity[head1])relations.append(rel)metadata = copy.deepcopy(doc.metadata)if len(doc.stance) > 0:metadata["stance"] = doc.stance[0].labelmetadata["topic"] = doc.topic_idresult = TextDocumentWithLabeledSpansAndBinaryRelations(text=doc.text, id=doc.id, metadata=doc.metadata)result.labeled_spans.extend(entities)result.binary_relations.extend(relations)return resultclass ArgMicro(GeneratorBasedBuilder):DOCUMENT_TYPE = ArgMicroDocumentDOCUMENT_CONVERTERS = {TextDocumentWithLabeledSpansAndBinaryRelations: convert_to_text_document_with_labeled_spans_and_binary_relations}BASE_DATASET_PATH = "DFKI-SLT/argmicro"BASE_DATASET_REVISION = "282733d6d57243f2a202d81143c4e31bb250e663"BUILDER_CONFIGS = [datasets.BuilderConfig(name="en"), datasets.BuilderConfig(name="de")]def _generate_document_kwargs(self, dataset):return {"adu_type_label": dataset.features["adus"].feature["type"],"edge_type_label": dataset.features["edges"].feature["type"],"stance_label": dataset.features["stance"],}def _generate_document(self, example, **kwargs):return example_to_document(example, **kwargs)
1pytorch-ie>=0.24.0,<0.25.01pie-datasets>=0.3.3,<0.9.0
README.md+55-3
argmicro.py+92-42
requirements.txt+1-1