Get all sentences in document id.

    Args:
        obj: BioCCollection, BioCDocument, or BioCPassage

    Yields:
        one sentence
323498
def sentences(obj: BioCCollection or BioCDocument or BioCPassage) \
        -> Generator[BioCSentence, None, None]:
    
    if isinstance(obj, BioCCollection):
        for document in obj.documents:
            yield from sentences(document)
    elif isinstance(obj, BioCDocument):
        for passage in obj.passages:
            yield from sentences(passage)
    elif isinstance(obj, BioCPassage):
        yield from obj.sentences
    else:
        raise TypeError(f'Object of type {obj.__class__.__name__} must be BioCCollection, '
                        f'BioCDocument, BioCPassage, or BioCSentence')
1112796
def get_comments(obj, request, oauth=False, paginate=False, cpp=10):
    
    model_object = type(obj).objects.get(id=obj.id)
    comments = Comment.objects.filter_by_object(model_object)
    comments_count = comments.count()
    if paginate:
        paginator = Paginator(comments, cpp)
        page = request.GET.get('page')
        try:
            comments = paginator.page(page)
        except PageNotAnInteger:
            comments = paginator.page(1)
        except EmptyPage:
            comments = paginator.page(paginator.num_pages)

    try:
        profile_app_name = settings.PROFILE_APP_NAME
        profile_model_name = settings.PROFILE_MODEL_NAME
    except AttributeError:
        profile_app_name = None
        profile_model_name = None

    try:
        if settings.LOGIN_URL.startswith("/"):
            login_url = settings.LOGIN_URL
        else:
            login_url = "/" + settings.LOGIN_URL
    except AttributeError:
        login_url = ""

    return {
        "commentform": CommentForm(),
        "model_object": obj,
        "user": request.user,
        "comments": comments,
        # "comments_count": comments_count,
        "oauth": oauth,
        "profile_app_name": profile_app_name,
        "profile_model_name": profile_model_name,
        "paginate": paginate,
        "login_url": login_url,
        "cpp": cpp
    }
694038
def _docspec_comments(obj) -> Dict[str, str]:
    
    # Sometimes our docstring is on the class, and sometimes it's on the initializer,
    # so we've got to check both.
    class_docstring = getattr(obj, '__doc__', None)
    init_docstring = getattr(obj.__init__, '__doc__', None) if hasattr(obj, '__init__') else None

    docstring = class_docstring or init_docstring or ''

    doc = NumpyDocString(docstring)
    params = doc["Parameters"]
    comments: Dict[str, str] = {}

    for line in params:
        # It looks like when there's not a space after the parameter name,
        # numpydocstring parses it incorrectly.
        name_bad = line[0]
        name = name_bad.split(":")[0]

        # Sometimes the line has 3 fields, sometimes it has 4 fields.
        comment = "\n".join(line[-1])

        comments[name] = comment

    return comments
925456
def each_object_id(collection):
    """"""
    c_path = collection_path(collection)
    paths = glob('%s/*.%s' % (c_path, _ext))
    for path in paths:
        match = regex.match(r'.+/(.+)\.%s$' % _ext, path)
        yield match.groups()[0]
755008
def get_document(self, document_id):
        
        key = 'doc.%s.%s' % (self.name, decode(document_id))
        return decode_dict(self.db.hgetall(key))
1282541
def write(self, obj: BioCDocument or BioCPassage or BioCSentence):
        
        if self.level == DOCUMENT and not isinstance(obj, BioCDocument):
            raise ValueError
        if self.level == PASSAGE and not isinstance(obj, BioCPassage):
            raise ValueError
        if self.level == SENTENCE and not isinstance(obj, BioCSentence):
            raise ValueError
        self.writer.write(BioCJSONEncoder().default(obj))
131693
def _get_object(data, position, obj_end, opts, dummy):
    """"""
    obj_size, end = _get_object_size(data, position, obj_end)
    if _raw_document_class(opts.document_class):
        return (opts.document_class(data[position:end + 1], opts),
                position + obj_size)

    obj = _elements_to_dict(data, position + 4, end, opts)

    position += obj_size
    if "$ref" in obj:
        return (DBRef(obj.pop("$ref"), obj.pop("$id", None),
                      obj.pop("$db", None), obj), position)
    return obj, position
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
794513
def get_sentence_id(self, element):
        """"""
        try:
            sentence_elem = element.iterancestors('sentence').next()
        except StopIteration as e:
            warnings.warn("<{}> element is not a descendant of a <sentence> "
                          "We'll try to extract the sentence ID from the "
                          "prefix of the element ID".format(element.tag))
            return self.get_element_id(element).split('_')[0]
        return self.get_element_id(sentence_elem)
1265355
def of(cls, *documents: BioCDocument):
        
        if len(documents) <= 0:
            raise ValueError("There has to be at least one document.")
        c = BioCCollection()
        for document in documents:
            if document is None:
                raise ValueError('Document is None')
            c.add_document(document)
        return c
623735
def getdoc(obj):
    
    inspect_got_doc = inspect.getdoc(obj)
    if inspect_got_doc in (object.__init__.__doc__, object.__doc__):
        return '' # We never want this builtin stuff
    return (inspect_got_doc or '').strip()
718511
def _get_evidence(self, event, adjectives):
        """"""
        provenance = event.get('provenance')

        # First try looking up the full sentence through provenance
        doc_id = provenance[0]['document']['@id']
        sent_id = provenance[0]['sentence']
        text = self.document_dict[doc_id]['sentences'][sent_id]
        text = self._sanitize(text)
        bounds = [provenance[0]['documentCharPositions'][k]
                  for k in ['start', 'end']]

        annotations = {
            'found_by': event.get('rule'),
            'provenance': provenance,
            'event_type': os.path.basename(event.get('type')),
            'adjectives': adjectives,
            'bounds': bounds
            }
        location = self.document_dict[doc_id]['location']
        ev = Evidence(source_api='hume', text=text, annotations=annotations,
                      pmid=location)
        return [ev]
154296
def load(fp, **kwargs) -> BioCCollection:
    
    obj = json.load(fp, **kwargs)
    return parse_collection(obj)
231614
def get_objects(self, subject, predicate):
        
        for statement in self.spo_search(subject=subject, predicate=predicate):
            yield str(statement[2])
61034
def dumps(obj, **kwargs) -> str:
    
    return json.dumps(obj, cls=BioCJSONEncoder, **kwargs)
1112489
def get_doc(self, objtxt):
        """"""
        if self._reading:
            return
        wait_loop = QEventLoop()
        self.sig_got_reply.connect(wait_loop.quit)
        self.silent_exec_method("get_ipython().kernel.get_doc('%s')" % objtxt)
        wait_loop.exec_()

        # Remove loop connection and loop
        self.sig_got_reply.disconnect(wait_loop.quit)
        wait_loop = None

        return self._kernel_reply
1322417
def _gen_sentence(self, assetid_body_tuple):
        '''
         
        '''
        asset_id, body = assetid_body_tuple
        text = self._process(body)
        sentence = LabeledSentence(text, labels=['DOC_%s' % str(asset_id)])
        return sentence