Deserialize a dict obj to a BioCPassage object
421631
def parse_passage(obj: dict) -> BioCPassage:
    """"""
    passage = BioCPassage()
    passage.offset = obj['offset']
    passage.infons = obj['infons']
    if 'text' in obj:
        passage.text = obj['text']
    for sentence in obj['sentences']:
        passage.add_sentence(parse_sentence(sentence))
    for annotation in obj['annotations']:
        passage.add_annotation(parse_annotation(annotation))
    for relation in obj['relations']:
        passage.add_relation(parse_relation(relation))
    return passage
897258
def json_class_decoder_hook(d: Dict) -> Any:
    
    if TYPE_LABEL in d:
        typename = d.get(TYPE_LABEL)
        if typename in TYPE_MAP:
            if DEBUG:
                log.debug("Deserializing: {!r}", d)
            d.pop(TYPE_LABEL)
            descriptor = TYPE_MAP[typename]
            obj = descriptor.to_obj(d)
            if DEBUG:
                log.debug("... to: {!r}", obj)
            return obj
    return d
10436
def to_dict(obj):
    
    d = _to_json_type(obj)
    if isinstance(d, dict):
        return scrub_dict(d)
    else:
        raise ValueError("The value provided must be an object.")
958030
def _bson_to_dict(data, opts):
    """"""
    try:
        if _raw_document_class(opts.document_class):
            return opts.document_class(data, opts)
        _, end = _get_object_size(data, 0, len(data))
        return _elements_to_dict(data, 4, end, opts)
    except InvalidBSON:
        raise
    except Exception:
        # Change exception type to InvalidBSON but preserve traceback.
        _, exc_value, exc_tb = sys.exc_info()
        reraise(InvalidBSON, exc_value, exc_tb)
807107
def from_dict(cls, tree_dict, previous=None):
        """"""
        instance = cls(tree_dict['tree_type'])

        fitted = tree_dict['fitted']
        instance.fitted = fitted
        if fitted:
            instance.level = tree_dict['level']
            instance.n_nodes = tree_dict['n_nodes']
            instance.tau_matrix = np.array(tree_dict['tau_matrix'])
            instance.previous_tree = cls._deserialize_previous_tree(tree_dict, previous)
            instance.edges = [Edge.from_dict(edge) for edge in tree_dict['edges']]

        return instance
849290
def deserialize(self, value, **kwargs):
        """"""
        kwargs.update({'trusted': kwargs.get('trusted', False)})
        if self.deserializer is not None:
            return self.deserializer(value, **kwargs)
        if value is None:
            return None
        output_tuples = [
            (
                self.key_prop.deserialize(key, **kwargs),
                self.value_prop.deserialize(val, **kwargs)
            )
            for key, val in iteritems(value)
        ]
        try:
            output_dict = {key: val for key, val in output_tuples}
        except TypeError as err:
            raise TypeError('Dictionary property {} cannot be deserialized - '
                            'keys contain {}'.format(self.name, err))
        return self._class_container(output_dict)
858516
def deserialize(cls, string):
        """"""

        data = json.loads(string)
        for fieldname, value in data.items():
            data[fieldname] = getattr(cls, fieldname).cache_to_python(value)
        return cls(**data)
1011304
def from_serializable(cls, object_dict):
        

        key_class = cls._from_visible(cls.STARTS_WITH + 'class' + cls.ENDS_WITH)
        key_module = cls._from_visible(cls.STARTS_WITH + 'module' + cls.ENDS_WITH)

        obj_class = object_dict.pop(key_class)
        obj_module = object_dict.pop(key_module) if key_module in object_dict else None

        obj = cls._from_class(obj_class, obj_module)
        obj.modify_object(object_dict)
        return obj
1051933
def loads(s: str, **kwargs) -> BioCCollection:
    
    obj = json.loads(s, **kwargs)
    return parse_collection(obj)
665611
def _bson_to_dict(data, opts):
    """"""
    try:
        obj_size = _UNPACK_INT(data[:4])[0]
    except struct.error as exc:
        raise InvalidBSON(str(exc))
    if obj_size != len(data):
        raise InvalidBSON("invalid object size")
    if data[obj_size - 1:obj_size] != b"\x00":
        raise InvalidBSON("bad eoo")
    try:
        return _elements_to_dict(data, 4, obj_size - 1, opts)
    except InvalidBSON:
        raise
    except Exception:
        # Change exception type to InvalidBSON but preserve traceback.
        _, exc_value, exc_tb = sys.exc_info()
        reraise(InvalidBSON, exc_value, exc_tb)
824258
def get_text(obj) -> Tuple[int, str]:
    
    from bioc.bioc import BioCDocument, BioCPassage, BioCSentence

    if isinstance(obj, BioCSentence):
        return obj.offset, obj.text
    if isinstance(obj, BioCPassage):
        if obj.text:
            return obj.offset, obj.text
        text = ''
        for sentence in obj.sentences:
            try:
                text = pad_char(text, sentence.offset - obj.offset, ' ')
                assert sentence.text, f'BioC sentence has no text: {sentence.offset}'
                text += sentence.text
            except ValueError:
                raise ValueError(f'Overlapping sentences {sentence.offset}')
        return obj.offset, text
    if isinstance(obj, BioCDocument):
        text = ''
        for passage in obj.passages:
            try:
                text = pad_char(text, passage.offset)
                text += get_text(passage)[1]
            except ValueError:
                raise ValueError(f'{obj.id}: overlapping passages {passage.offset}')
        return 0, text
    raise TypeError(f'Object of type {obj.__class__.__name__} must be BioCCollection, '
                    f'BioCDocument, BioCPassage, or BioCSentence')
462223
def to_dict(obj):
    
    if isinstance(obj, dict):
        return obj
    elif hasattr(obj, "to_dict"):
        return obj.to_dict()
    try:
        return simple_object_to_dict(obj)
    except:
        raise ValueError(
            "Cannot convert %s : %s to dictionary" % (
                obj, type(obj)))
99196
def parse_sentence(obj: dict) -> BioCSentence:
    """"""
    sentence = BioCSentence()
    sentence.offset = obj['offset']
    sentence.infons = obj['infons']
    sentence.text = obj['text']
    for annotation in obj['annotations']:
        sentence.add_annotation(parse_annotation(annotation))
    for relation in obj['relations']:
        sentence.add_relation(parse_relation(relation))
    return sentence
234239
def json_repr(obj):
    

    def serialize(obj):
        """Recursively walk object's hierarchy.
        """
        if obj is None:
            return None
        if isinstance(obj, Enum):
            return str(obj)
        if isinstance(obj, (bool, int, float, str)):
            return obj
        if isinstance(obj, dict):
            obj = obj.copy()
            for key in sorted(obj.keys()):
                obj[key] = serialize(obj[key])
            return obj
        if isinstance(obj, list):
            return [serialize(item) for item in obj]
        if isinstance(obj, tuple):
            return tuple(serialize([item for item in obj]))
        if hasattr(obj, '__dict__'):
            return serialize(obj.__dict__)
        return repr(obj)

    return json.dumps(serialize(obj))
369316
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'environments' in _dict:
            args['environments'] = [
                Environment._from_dict(x) for x in (_dict.get('environments'))
            ]
        return cls(**args)
731691
def _deserialize_dict_attributes(cls, cls_context, dict_):
        

        dict_deserialized = {}

        for key in dict_.keys():
            key_deserialized = cls._deserialize_key(key)
            value_specs = cls._get_value_specs(cls_context, key_deserialized)

            if value_specs is not None:
                dict_deserialized[value_specs.name] = cls._deserialize_value(
                    value_specs.types,
                    dict_[key]
                )
            else:
                cls._warn_key_unknown(cls_context, key)

        return dict_deserialized
1225957
def dict_to_object(source):
    """"""
    target = inspectable_class.InspectableClass()
    for k, v in source.items():
        setattr(target, k, v)
    return target