File size: 3,847 Bytes
207e462
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"""
    Example data reader for the annotated SHINRA-5LDS
    Created May 2, 2024.
    Copyright Hassan S. Shavarani
"""
import json
import datetime
from zipfile import ZipFile
from tqdm import tqdm
from collections import namedtuple

ENELabel = namedtuple('ENELabel', ['level_id', 'name']) 


class ENEAnnotation:
    def __init__(self, ann):
        self.ene_id = ann['ene_id']
        self.representative_name = ann['representative_name']
        self._id = int(ann['_id'])
        self.original_level = ann['original_level']
        self.values = {x['level']: ENELabel(x['level_id'], x['name']) for x in ann['entities']}

class SHINRAAnnotation:
    def __init__(self, annotation):
        self.lang = annotation['lang'] # this value is always equal to 'ja' since all original annotations have been assigned in Japanese
        self.annotator = annotation['annotator']
        self.annotation_date = datetime.datetime.strptime(annotation['date'], '%Y-%m-%d %H:%M:%S')
        self.raw_flag = annotation['raw_flag']
        self.type = annotation['type']
        self.annotation_confidence = annotation['probability_score']
        self.labels = ENEAnnotation(annotation['ene_id'])


class SHINRAArticle:
    def __init__(self, article):
        self.title = article['title']
        self.content = article['content']
        self.url = article['url']
        self.page_id = article['page_id']
        self.links = article['links']
        self.summary = article['summary']
        self.categories = article['categories']

class SHINRARecord:
    def __init__(self, record):
        self.annotation_id = record['annotation_id']
        self.ene_level_ids = {
            "0": record['ene_level_ids']['level0'],
            "1": record['ene_level_ids']['level1'],
            "2": record['ene_level_ids']['level2'],
            "3": record['ene_level_ids']['level3']
        }
        self.ene_label_verified = record['ene_label_verified']
        self.annotations = [SHINRAAnnotation(x) for x in record['annotations'] if x['annotator'] == 'HAND']
        self.articles = {x['language']: SHINRAArticle(x) for x in record['annotation_articles']}
    
    @property
    def latest_annotation(self):
        return max(self.annotations, key=lambda x: x.annotation_date)

class SHINRA5LDS:
    """
    Size of the SHINRA-5LDS dataset (considering only the hand annotated records):
        ja: 118635 records
        en:  52445 records
        fr:  34432 records
        de:  29808 records
        fa:  14058 records
    """
    def __init__(self, zip_file_path, lang):
        self.zip_file_path = zip_file_path
        self.data = None
        self.lang = lang

    def _load_data(self):
        zip_ref = ZipFile(self.zip_file_path, 'r')
        self.data = zip_ref.open('data.jsonl')

    def __iter__(self):
        if self.data is None or len(self.data) == 0:
            self._load_data()
        return self

    def __next__(self):
        try:
            while True:
                next_line = self.data.readline()
                if not next_line:
                    self.data.close()
                    self.data = None
                    raise IndexError
                record = SHINRARecord(json.loads(next_line))
                if not record.annotations: # the annotation is machine generated
                    continue
                if self.lang in record.articles:
                    break
            return record.articles[self.lang], record.latest_annotation
        except IndexError:
            raise StopIteration
        except Exception as e:
            print(f"Error: {e}")
            return self.__next__()

if __name__ == "__main__":
    for article, annotation in tqdm(SHINRA5LDS('SHINRA-5LDS.zip', 'en')):
        print('='*80)
        print(article.title, annotation.labels.values)
        print('='*80)