processors.serialization   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 26
dl 0
loc 64
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A JSONSerializer.mentions_to_JSON_dict() 0 8 1
A JSONSerializer.mentions_to_JSON() 0 16 1
A JSONSerializer.mentions_from_JSON() 0 24 2
1
# -*- coding: utf-8 -*-
2
3
from __future__ import unicode_literals
4
from .ds import Document
5
from .odin import Mention
6
import json
7
8
9
class JSONSerializer(object):
10
    """
11
    Utilities for serialization/deserialization of data structures.
12
    
13
    """
14
    @staticmethod
15
    def mentions_to_JSON_dict(mentions):
16
        jdict = dict()
17
        docs = {m._doc_id:m.document.to_JSON_dict() for m in mentions}
18
        mns = {m.id:m.to_JSON_dict() for m in mentions}
19
        jdict["documents"] = docs
20
        jdict["mentions"] = mns
21
        return jdict
22
23
    @staticmethod
24
    def mentions_to_JSON(mentions):
25
        """
26
        Serializes a list of `processors.odin.Mention` to a JSON string.
27
28
        Parameters
29
        ----------
30
        mentions : [processors.odin.Mention]
31
            A list of `processors.odin.Mention` to be serialized to JSON.
32
33
        Returns
34
        -------
35
        str
36
            A JSON serialization (str) of a list of `processors.odin.Mention`.
37
        """
38
        return json.dumps(JSONSerializer.mentions_to_JSON_dict(mentions), sort_keys=True, indent=4)
39
40
    @staticmethod
41
    def mentions_from_JSON(jdict):
42
        """
43
        Loads `processors.odin.Mention` from a dictionary of JSON data (`jdict`).
44
45
        Parameters
46
        ----------
47
        jdict : dict
48
            A dictionary of JSON data encoding a list of `Mention`s and their corresponding `Document`s.
49
50
        Returns
51
        -------
52
        [processors.odin.Mention]
53
            A list of `processors.odin.Mention`
54
        """
55
        # build map of documents
56
        docs_dict = {doc_id:Document.load_from_JSON(djson) for (doc_id, djson) in jdict["documents"].items()}
57
        # deserialize mentions
58
        mns_json = jdict["mentions"]
59
        mentions = []
60
        for mjson in mns_json:
61
            m = Mention.load_from_JSON(mjson, docs_dict)
62
            mentions.append(m)
63
        return mentions
64