komet / komet.py
Matej Klemen
Add first version of KOMET
388286d
raw
history blame
6.69 kB
"""Metaphor corpus KOMET 1.0"""
import os
import re
import xml.etree.ElementTree as ET
from typing import List
import datasets
_CITATION = """\
@InProceedings{antloga2020komet,
title = {Korpus metafor KOMET 1.0},
author={Antloga, \v{S}pela},
booktitle={Proceedings of the Conference on Language Technologies and Digital Humanities (Student abstracts)},
year={2020},
pages={167-170}
}
"""
_DESCRIPTION = """\
KOMET 1.0 is a hand-annotated corpus for metaphorical expressions which contains about 200,000 words from
Slovene journalistic, fiction and on-line texts.
To annotate metaphors in the corpus an adapted and modified procedure of the MIPVU protocol
(Steen et al., 2010: A method for linguistic metaphor identification: From MIP to MIPVU, https://www.benjamins.com/catalog/celcr.14)
was used. The lexical units (words) whose contextual meanings are opposed to their basic meanings are considered
metaphor-related words. The basic and contextual meaning for each word in the corpus was identified using the
Dictionary of the standard Slovene Language. The corpus was annotated for the metaphoric following relations:
indirect metaphor (MRWi), direct metaphor (MRWd), borderline case (WIDLI) and metaphor signal (MFlag).
In addition, the corpus introduces a new 'frame' tag, which gives information about the concept to which it refers.
"""
_HOMEPAGE = "http://hdl.handle.net/11356/1293"
_LICENSE = "Creative Commons - Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)"
_URLS = {
"komet": "https://www.clarin.si/repository/xmlui/bitstream/handle/11356/1293/komet.tei.zip"
}
def namespace(element):
# https://stackoverflow.com/a/12946675
m = 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 character
if 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 part
return element.text, metaphor_type, "/".join(frame_buffer)
# Annotated word or word group
elif element.tag.endswith("seg"):
mtype, new_frame_buffer = "O", 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: unify
if 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, skip
if child.tag.endswith("c"):
continue
res = _resolve_recursively(child, mtype, new_frame_buffer)
if isinstance(res, list):
parsed_data.extend(res)
else:
parsed_data.append(res)
return parsed_data
curr_annotations = _resolve_recursively(element, "O", [])
if not isinstance(curr_annotations, list):
curr_annotations = [curr_annotations]
return curr_annotations
class Komet(datasets.GeneratorBasedBuilder):
"""KOMET is a hand-annotated Slovenian corpus of metaphorical expressions."""
VERSION = datasets.Version("1.0.0")
def _info(self):
features = datasets.Features(
{
"document_name": datasets.Value("string"),
"idx": datasets.Value("uint32"), # index inside current document
"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(
description=_DESCRIPTION,
features=features,
homepage=_HOMEPAGE,
license=_LICENSE,
citation=_CITATION,
)
def _split_generators(self, dl_manager):
data_dir = dl_manager.download_and_extract(_URLS["komet"])
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={"data_dir": os.path.join(data_dir, "komet.tei")},
)
]
# method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
def _generate_examples(self, data_dir):
data_files = []
for fname in os.listdir(data_dir):
curr_path = os.path.join(data_dir, fname)
if os.path.isfile(curr_path) and fname.endswith(".xml") and fname != "komet.xml": # komet.xml = meta-file
data_files.append(fname)
idx_example = 0
for fname in data_files:
fpath = os.path.join(data_dir, fname)
curr_doc = ET.parse(fpath)
root = curr_doc.getroot()
NAMESPACE = namespace(root)
idx_sent_glob = 0
for 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 += 1
idx_sent_glob += 1