Datasets:
Matej Klemen commited on
Commit ·
6338ec1
1
Parent(s): ab36125
Breaking change: change format of instances to be unified with G-KOMET; refactor code
Browse filesFiles changed (2)
- dataset_infos.json+1-1
- komet.py+119-43
1{"default": {"description": "KOMET 1.0 is a hand-annotated corpus for metaphorical expressions which contains about 200,000 words from \nSlovene journalistic, fiction and on-line texts. \n\nTo annotate metaphors in the corpus an adapted and modified procedure of the MIPVU protocol \n(Steen et al., 2010: A method for linguistic metaphor identification: From MIP to MIPVU, https://www.benjamins.com/catalog/celcr.14) \nwas used. The lexical units (words) whose contextual meanings are opposed to their basic meanings are considered \nmetaphor-related words. The basic and contextual meaning for each word in the corpus was identified using the \nDictionary of the standard Slovene Language. The corpus was annotated for the metaphoric following relations: \nindirect metaphor (MRWi), direct metaphor (MRWd), borderline case (WIDLI) and metaphor signal (MFlag). \nIn addition, the corpus introduces a new 'frame' tag, which gives information about the concept to which it refers.\n", "citation": "@InProceedings{antloga2020komet,\ntitle = {Korpus metafor KOMET 1.0},\nauthor={Antloga, \u000b{S}pela},\nbooktitle={Proceedings of the Conference on Language Technologies and Digital Humanities (Student abstracts)},\nyear={2020},\npages={167-170}\n}\n", "homepage": "http://hdl.handle.net/11356/1293", "license": "Creative Commons - Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)", "features": {"document_name": {"dtype": "string", "id": null, "_type": "Value"}, "idx": {"dtype": "uint32", "id": null, "_type": "Value"}, "idx_paragraph": {"dtype": "uint32", "id": null, "_type": "Value"}, "idx_sentence": {"dtype": "uint32", "id": null, "_type": "Value"}, "sentence_words": {"feature": {"dtype": "string", "id": null, "_type": "Value"}, "length": -1, "id": null, "_type": "Sequence"}, "met_type": {"feature": {"dtype": "string", "id": null, "_type": "Value"}, "length": -1, "id": null, "_type": "Sequence"}, "met_frame": {"feature": {"dtype": "string", "id": null, "_type": "Value"}, "length": -1, "id": null, "_type": "Sequence"}}, "post_processed": null, "supervised_keys": null, "task_templates": null, "builder_name": "komet", "config_name": "default", "version": {"version_str": "1.0.0", "description": null, "major": 1, "minor": 0, "patch": 0}, "splits": {"train": {"name": "train", "num_bytes": 5739906, "num_examples": 13963, "dataset_name": "komet"}}, "download_checksums": {"https://www.clarin.si/repository/xmlui/bitstream/handle/11356/1293/komet.tei.zip": {"num_bytes": 7311643, "checksum": "213f8f5c5b4e4989705a88e014c345fa6038f66e14a83fecb94e08e9f0da6640"}}, "download_size": 7311643, "post_processing_size": null, "dataset_size": 5739906, "size_in_bytes": 13051549}}1{"default": {"description": "KOMET 1.0 is a hand-annotated corpus for metaphorical expressions which contains about 200,000 words from \nSlovene journalistic, fiction and on-line texts. \n\nTo annotate metaphors in the corpus an adapted and modified procedure of the MIPVU protocol \n(Steen et al., 2010: A method for linguistic metaphor identification: From MIP to MIPVU, https://www.benjamins.com/catalog/celcr.14) \nwas used. The lexical units (words) whose contextual meanings are opposed to their basic meanings are considered \nmetaphor-related words. The basic and contextual meaning for each word in the corpus was identified using the \nDictionary of the standard Slovene Language. The corpus was annotated for the metaphoric following relations: \nindirect metaphor (MRWi), direct metaphor (MRWd), borderline case (WIDLI) and metaphor signal (MFlag). \nIn addition, the corpus introduces a new 'frame' tag, which gives information about the concept to which it refers.\n", "citation": "@InProceedings{antloga2020komet,\ntitle = {Korpus metafor KOMET 1.0},\nauthor={Antloga, \u000b{S}pela},\nbooktitle={Proceedings of the Conference on Language Technologies and Digital Humanities (Student abstracts)},\nyear={2020},\npages={167-170}\n}\n", "homepage": "http://hdl.handle.net/11356/1293", "license": "Creative Commons - Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)", "features": {"document_name": {"dtype": "string", "id": null, "_type": "Value"}, "idx": {"dtype": "uint32", "id": null, "_type": "Value"}, "idx_paragraph": {"dtype": "uint32", "id": null, "_type": "Value"}, "idx_sentence": {"dtype": "uint32", "id": null, "_type": "Value"}, "sentence_words": {"feature": {"dtype": "string", "id": null, "_type": "Value"}, "length": -1, "id": null, "_type": "Sequence"}, "met_type": [{"type": {"dtype": "string", "id": null, "_type": "Value"}, "word_indices": {"feature": {"dtype": "uint32", "id": null, "_type": "Value"}, "length": -1, "id": null, "_type": "Sequence"}}], "met_frame": [{"type": {"dtype": "string", "id": null, "_type": "Value"}, "word_indices": {"feature": {"dtype": "uint32", "id": null, "_type": "Value"}, "length": -1, "id": null, "_type": "Sequence"}}]}, "post_processed": null, "supervised_keys": null, "task_templates": null, "builder_name": "komet", "config_name": "default", "version": {"version_str": "1.0.0", "description": null, "major": 1, "minor": 0, "patch": 0}, "splits": {"train": {"name": "train", "num_bytes": 3481821, "num_examples": 13963, "dataset_name": "komet"}}, "download_checksums": {"https://www.clarin.si/repository/xmlui/bitstream/handle/11356/1293/komet.tei.zip": {"num_bytes": 7311643, "checksum": "213f8f5c5b4e4989705a88e014c345fa6038f66e14a83fecb94e08e9f0da6640"}}, "download_size": 7311643, "post_processing_size": null, "dataset_size": 3481821, "size_in_bytes": 10793464}}
2 unmodified lines345678930 unmodified lines40414243444546474849505152535455565758596061626364656667686970717273747576777879808182831 unmodified line85868788899091929394959 unmodified lines10510610710810911011111220 unmodified lines1331341351361371384 unmodified lines1431441451461471481491501511521531541551561571581591601611621631641651661672 unmodified linesimport osimport reimport xml.etree.ElementTree as ETfrom typing import Listimport datasets30 unmodified lines}def namespace(element):# https://stackoverflow.com/a/12946675m = re.match(r'\{.*\}', element.tag)return m.group(0) if m else ''def resolve(element) -> List:def _resolve_recursively(element, metaphor_type: str, frame_buffer: List):# Leaf node: word or punctuation characterif element.tag.endswith(("w", "pc")):if len(frame_buffer) == 0:return element.text, metaphor_type, "O"else:# Frame annotations may be nested, encode them with a "/" separator;# e.g., the first annotation is the frame of the phrase involving current word and the last annotation# is the frame of a phrase partreturn element.text, metaphor_type, "/".join(frame_buffer)# Annotated word or word groupelif element.tag.endswith("seg"):mtype, new_frame_buffer = "O", list(frame_buffer)if element.attrib["subtype"] != "frame":mtype = element.attrib["subtype"]else:# Frame annotations in KOMET are prepended with "#met.", while those in GKomet are not: unifyif element.attrib["ana"].startswith("#met."):_mframe = element.attrib["ana"][5:]else:_mframe = element.attrib["ana"]new_frame_buffer.append(_mframe)parsed_data = []for child in element:# spaces between words, skipif child.tag.endswith("c"):continueres = _resolve_recursively(child, mtype, new_frame_buffer)if isinstance(res, list):parsed_data.extend(res)else:1 unmodified linereturn parsed_datacurr_annotations = _resolve_recursively(element, "O", [])if not isinstance(curr_annotations, list):curr_annotations = [curr_annotations]return curr_annotationsclass Komet(datasets.GeneratorBasedBuilder):9 unmodified lines"idx_paragraph": datasets.Value("uint32"),"idx_sentence": datasets.Value("uint32"), # index inside current paragraph"sentence_words": datasets.Sequence(datasets.Value("string")),"met_type": datasets.Sequence(datasets.Value("string")),"met_frame": datasets.Sequence(datasets.Value("string"))})return datasets.DatasetInfo(20 unmodified linescurr_path = os.path.join(data_dir, fname)if os.path.isfile(curr_path) and fname.endswith(".xml") and fname != "komet.xml": # komet.xml = meta-filedata_files.append(fname)idx_example = 0for fname in data_files:4 unmodified linesNAMESPACE = namespace(root)idx_sent_glob = 0for idx_par, curr_par in enumerate(root.iterfind(f"{NAMESPACE}p")):for idx_sent, curr_sent in enumerate(curr_par.iterfind(f"{NAMESPACE}s")):words, types, frames = [], [], []for curr_el in curr_sent:if curr_el.tag.endswith(("w", "pc", "seg")):curr_res = resolve(curr_el)for _el in curr_res:words.append(_el[0])types.append(_el[1])frames.append(_el[2])yield idx_example, {"document_name": fname,"idx": idx_sent_glob,"idx_paragraph": idx_par,"idx_sentence": idx_sent,"sentence_words": words,"met_type": types,"met_frame": frames}idx_example += 1idx_sent_glob += 12 unmodified lines345678930 unmodified lines4041424344454647484950515253545556575859606162636465666768697071721 unmodified line74757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341359 unmodified lines14514614714814915015115215315415515615715820 unmodified lines1791801811821831841854 unmodified lines1901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432 unmodified linesimport osimport reimport xml.etree.ElementTree as ETfrom typing import List, Tupleimport datasets30 unmodified lines}XML_NAMESPACE = "{http://www.w3.org/XML/1998/namespace}"EL_LEAF, EL_TYPE, EL_FRAME = range(3)def namespace(element):# https://stackoverflow.com/a/12946675m = re.match(r'\{.*\}', element.tag)return m.group(0) if m else ''def word_info(sent_el):def _resolve_recursively(element) -> List:""" Knowingly ignored tags: name (anonymized, without IDs), gap, vocal, pause, del,linkGrp (syntactic dependencies) """# Leaf node: word or punctuation characterif element.tag.endswith(("w", "pc")):id_curr = element.attrib[f"{XML_NAMESPACE}id"]return [(id_curr, element.text)]# Annotated word or word group - not interested in the annotations in this functionelif element.tag.endswith("seg"):parsed_data = []for child in element:if child.tag.endswith("c"): # empty space betw. wordscontinueres = _resolve_recursively(child)if isinstance(res, list):parsed_data.extend(res)else:1 unmodified linereturn parsed_dataid_words, words = [], []for child_el in sent_el:curr_annotations = _resolve_recursively(child_el)if curr_annotations is not None: # None = unrecognized ("unimportant") elementfor ann in curr_annotations:id_words.append(ann[0])words.append(ann[1])return id_words, wordsdef seg_info(sent_el):def _resolve_recursively(element) -> Tuple:""" Returns (type[, subtype], deeper_elements, latest_element)"""# Leaf node: word or punctuation characterif element.tag.endswith(("w", "pc")):id_curr = element.attrib[f"{XML_NAMESPACE}id"]return EL_LEAF, [], [id_curr]# Annotated word or word groupelif element.tag.endswith("seg"):if element.attrib["subtype"] == "frame":ann_type, subtype = EL_FRAME, element.attrib["ana"]if subtype.startswith("#met."): # for consistency with G-Komet, remove "#met." prefix from framessubtype = subtype[5:]elif element.attrib["type"] == "metaphor":ann_type = EL_TYPEsubtype = element.attrib["subtype"]else:raise ValueError(f"Unrecognized seg type: {element.attrib['type']}")deeper_elements = []latest_element = []for child in element:if child.tag.endswith(("c", "vocal", "pause")): # empty space betw. words or "special" wordcontinueres = _resolve_recursively(child)if res[0] == EL_LEAF:latest_element.extend(res[2])else:deeper_elements.append(res)latest_element.extend(res[3])return ann_type, subtype, deeper_elements, latest_elementannotations = []for child_el in sent_el:if not child_el.tag.endswith("seg"):continueann_type, subtype, deeper_elements, latest_element = _resolve_recursively(child_el)annotations.extend(list(map(lambda _tup: (_tup[0], _tup[1], _tup[3]), deeper_elements)))annotations.append((ann_type, subtype, latest_element))return annotationsclass Komet(datasets.GeneratorBasedBuilder):9 unmodified lines"idx_paragraph": datasets.Value("uint32"),"idx_sentence": datasets.Value("uint32"), # index inside current paragraph"sentence_words": datasets.Sequence(datasets.Value("string")),"met_type": [{"type": datasets.Value("string"),"word_indices": datasets.Sequence(datasets.Value("uint32"))}],"met_frame": [{"type": datasets.Value("string"),"word_indices": datasets.Sequence(datasets.Value("uint32"))}]})return datasets.DatasetInfo(20 unmodified linescurr_path = os.path.join(data_dir, fname)if os.path.isfile(curr_path) and fname.endswith(".xml") and fname != "komet.xml": # komet.xml = meta-filedata_files.append(fname)data_files = sorted(data_files)idx_example = 0for fname in data_files:4 unmodified linesNAMESPACE = namespace(root)idx_sent_glob = 0for idx_par, curr_par in enumerate(root.iterfind(f".//{NAMESPACE}p")):id2position = {} # {<idx_sent> -> {<id_word>: <position> foreach word} foreach sent}all_words = []# Pass#1: extract word informationfor idx_sent, curr_sent in enumerate(curr_par.iterfind(f"{NAMESPACE}s")):id_words, words = word_info(curr_sent)id2position[idx_sent] = dict(zip(id_words, range(len(words))))all_words.append(words)all_types, all_frames = [], []# Pass#2: extract annotations from <seg>mentsfor idx_sent, curr_sent in enumerate(curr_par.iterfind(f"{NAMESPACE}s")):annotated_segs = seg_info(curr_sent)all_types.append([])all_frames.append([])for curr_ann in annotated_segs:ann_type, ann_subtype, words_involved = curr_annif ann_type == EL_TYPE:all_types[idx_sent].append({"type": ann_subtype,"word_indices": [id2position[idx_sent][_id_word] for _id_word in words_involvedif _id_word in id2position[idx_sent]]})elif ann_type == EL_FRAME:all_frames[idx_sent].append({"type": ann_subtype,"word_indices": [id2position[idx_sent][_id_word] for _id_word in words_involvedif _id_word in id2position[idx_sent]]})idx_sent = 0for curr_words, curr_types, curr_frames in zip(all_words, all_types, all_frames):if len(curr_words) == 0:continueyield idx_example, {"document_name": fname,"idx": idx_sent_glob,"idx_paragraph": idx_par,"idx_sentence": idx_sent,"sentence_words": curr_words,"met_type": curr_types,"met_frame": curr_frames}idx_example += 1idx_sent += 1idx_sent_glob += 1
dataset_infos.json+1-1
komet.py+119-43