aboutsummaryrefslogtreecommitdiffstats
path: root/grobid_tei_xml/types.py
blob: b78b236fda2fb30f065a57454abe9f65f904c2c7 (plain)
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
from dataclasses import asdict, dataclass
from typing import List, Optional


@dataclass
class GrobidAddress:
    addr_line: Optional[str] = None
    post_code: Optional[str] = None
    settlement: Optional[str] = None
    country: Optional[str] = None
    country_code: Optional[str] = None  # XXX


@dataclass
class GrobidAffiliation:
    institution: Optional[str] = None
    department: Optional[str] = None
    laboratory: Optional[str] = None
    address: Optional[GrobidAddress] = None


@dataclass
class GrobidAuthor:
    full_name: Optional[str]
    given_name: Optional[str] = None
    middle: Optional[str] = None  # XXX
    surname: Optional[str] = None
    suffix: Optional[str] = None  # XXX
    email: Optional[str] = None  # XXX
    affiliation: Optional[GrobidAffiliation] = None

    def to_csl_dict(self) -> dict:
        d = dict(
            given=self.given_name,
            family=self.surname,
            suffix=self.suffix,
        )
        return _simplify_dict(d)


def _csl_date(s: Optional[str]) -> Optional[list]:
    if not s:
        return None

    # YYYY
    if len(s) >= 4 and s[0:4].isdigit():
        year = int(s[0:4])
    else:
        return None

    # YYYY-MM
    if len(s) >= 7 and s[4] == '-' and s[5:7].isdigit():
        month = int(s[5:7])
    else:
        return [[year]]

    # YYYY-MM-DD
    if len(s) == 10 and s[7] == '-' and s[8:10].isdigit():
        day = int(s[8:10])
        return [[year, month, day]]
    else:
        return [[year, month]]


def test_csl_date() -> None:
    assert _csl_date("1998") == [[1998]]
    assert _csl_date("1998-03") == [[1998, 3]]
    assert _csl_date("1998-03-12") == [[1998, 3, 12]]
    assert _csl_date("1998-blah") == [[1998]]
    assert _csl_date("asdf") is None


@dataclass
class GrobidCitation:
    authors: List[GrobidAuthor]

    index: Optional[int] = None
    id: Optional[str] = None
    date: Optional[str] = None
    issue: Optional[str] = None
    journal: Optional[str] = None  # XXX: venue? other?
    publisher: Optional[str] = None
    title: Optional[str] = None
    url: Optional[str] = None
    volume: Optional[str] = None
    pages: Optional[str] = None
    first_page: Optional[str] = None  # XXX
    last_page: Optional[str] = None  # XXX
    unstructured: Optional[str] = None
    arxiv_id: Optional[str] = None
    doi: Optional[str] = None
    pmid: Optional[str] = None
    pmcid: Optional[str] = None
    oa_url: Optional[str] = None
    note: Optional[str] = None

    def to_dict(self) -> dict:
        return _simplify_dict(asdict(self))

    def to_csl_dict(self, default_type: str = "article-journal") -> dict:
        """
        Transforms in to Citation Style Language (CSL) JSON schema
        """
        csl = dict(
            type=default_type,
            author=[a.to_csl_dict() for a in self.authors],
            issued=_csl_date(self.date),
            publisher=self.publisher,
            title=self.title,
            page=self.pages,
            URL=self.url,
            DOI=self.doi,
            PMID=self.pmid,
            PMCID=self.pmcid,
            note=self.note,
            # fields with '-' in the key name
            **{
                "container-title": self.journal,
                "page-first": self.first_page,
            })

        # numeric fields
        if self.issue and self.issue.isdigit():
            csl['issue'] = int(self.issue)
        if self.volume and self.volume.isdigit():
            csl['volume'] = int(self.volume)

        return _simplify_dict(csl)


@dataclass
class GrobidJournal:
    name: Optional[str] = None
    abbrev: Optional[str] = None
    publisher: Optional[str] = None
    volume: Optional[str] = None
    issue: Optional[str] = None
    issn: Optional[str] = None
    eissn: Optional[str] = None


@dataclass
class GrobidHeader:
    authors: List[GrobidAuthor]

    title: Optional[str] = None
    date: Optional[str] = None
    doi: Optional[str] = None
    journal: Optional[GrobidJournal] = None


@dataclass
class GrobidDocument:
    grobid_version: str
    grobid_timestamp: str
    header: GrobidHeader

    pdf_md5: Optional[str] = None
    language_code: Optional[str] = None
    citations: Optional[List[GrobidCitation]] = None
    abstract: Optional[str] = None
    body: Optional[str] = None
    acknowledgement: Optional[str] = None
    annex: Optional[str] = None

    def to_dict(self) -> dict:
        """
        Returns a dict version of this object which has no 'None' fields
        (recursively), and is appropriate for serializing to JSON with
        json.dumps().

        If you did want all the fields, you could use dataclasses.asdict()
        directly on thing object.
        """
        return _simplify_dict(asdict(self))

    def to_legacy_dict(self) -> dict:
        """
        Returns a dict in the old "grobid2json" format.
        """
        d = self.to_dict()

        # all header fields at top-level
        d.update(d.pop('header', {}))

        # files not in the old schema
        d.pop('pdf_md5', None)
        for c in d.get('citations', []):
            c.pop('note', None)

        # author changes
        for a in d['authors']:
            a['name'] = a.pop('full_name')
            addr = a.get('affiliation', {}).get('address')
            if addr and addr.get('post_code'):
                addr['postCode'] = addr.pop('post_code')
        for c in d['citations'] or []:
            for a in c['authors']:
                a['name'] = a.pop('full_name')
        return d

    def remove_encumbered(self) -> None:
        """
        This helper function removes fields from this object which might raise
        copyright concerns.
        """
        self.abstract = None
        self.body = None
        self.acknowledgement = None
        self.annex = None


def _simplify_dict(d: dict) -> dict:
    """
    Recursively remove empty dict values from a dict and all sub-lists and
    sub-dicts.

    TODO: should this return Optional[dict]?
    """
    if d in [None, {}, '']:
        return {}
    for k in list(d.keys()):
        if isinstance(d[k], dict):
            d[k] = _simplify_dict(d[k])
        elif isinstance(d[k], list):
            for i in range(len(d[k])):
                if isinstance(d[k][i], dict):
                    d[k][i] = _simplify_dict(d[k][i])
        if d[k] in [None, {}, '']:
            d.pop(k)
    return d