Ejemplo n.º 1
0
    def route_dynamic(path):
        args = dict(request.args)
        if 'direction' in args:
            direction = args.pop('direction')
        else:
            direction = 'OUTGOING'  # should always be outgoing here since we can't specify?

        if 'format' in args:
            format_ = args.pop('format')
        else:
            format_ = None

        try:
            j = sgd.dispatch(path, **args)
        except rHTTPError as e:
            log.exception(e)
            abort(e.response.status_code)  # DO NOT PASS ALONG THE MESSAGE
        except ValueError as e:
            log.exception(e)
            abort(404)

        if j is None or 'edges' not in j or not j['edges']:
            log.error(pformat(j))
            log.debug(sgd._last_url)
            return abort(400)

        prov = [
            hfn.titletag(f'Dynamic query result for {path}'),
            f'<meta name="date" content="{UTCNOWISO()}">',
            f'<link rel="http://www.w3.org/ns/prov#wasGeneratedBy" href="{wgb}">',
            '<meta name="representation" content="SciGraph">',
            f'<link rel="http://www.w3.org/ns/prov#wasDerivedFrom" href="{sgd._last_url}">'
        ]

        kwargs = {'json': cleanBad(j), 'html_head': prov}
        tree, extras = creatTree(*Query(None, None, direction, None), **kwargs)
        #print(extras.hierarhcy)
        #print(tree)
        if format_ is not None:
            if format_ == 'table':
                #breakpoint()
                def nowrap(class_, tag=''):
                    return (f'{tag}.{class_}' '{ white-space: nowrap; }')

                ots = [
                    OntTerm(n) for n in flatten_tree(extras.hierarchy)
                    if 'CYCLE' not in n
                ]
                #rows = [[ot.label, ot.asId().atag(), ot.definition] for ot in ots]
                rows = [[ot.label,
                         hfn.atag(ot.iri, ot.curie), ot.definition]
                        for ot in ots]

                return hfn.htmldoc(hfn.render_table(rows, 'label', 'curie',
                                                    'definition'),
                                   styles=(hfn.table_style,
                                           nowrap('col-label', 'td')))

        return hfn.htmldoc(extras.html, other=prov, styles=hfn.tree_styles)
Ejemplo n.º 2
0
    def route_sparc_dynamic(path):
        args = dict(request.args)
        if 'direction' in args:
            direction = args.pop('direction')
        else:
            direction = 'OUTGOING'  # should always be outgoing here since we can't specify?

        if 'format' in args:
            format_ = args.pop('format')
        else:
            format_ = None

        j = data_sgd.dispatch(path, **args)
        #breakpoint()
        if not j['edges']:
            log.error(pprint(j))
            return abort(400)

        kwargs = {'json': j}
        tree, extras = creatTree(*Query(None, None, direction, None), **kwargs)
        #print(extras.hierarhcy)
        print(tree)
        if format_ is not None:
            if format_ == 'table':
                #breakpoint()
                def nowrap(class_, tag=''):
                    return (f'{tag}.{class_}' '{ white-space: nowrap; }')

                ots = [
                    OntTerm(n) for n in flatten_tree(extras.hierarchy)
                    if 'CYCLE' not in n
                ]
                #rows = [[ot.label, ot.asId().atag(), ot.definition] for ot in ots]
                rows = [[ot.label,
                         hfn.atag(ot.iri, ot.curie), ot.definition]
                        for ot in ots]

                return htmldoc(hfn.render_table(rows, 'label', 'curie',
                                                'definition'),
                               styles=(hfn.table_style,
                                       nowrap('col-label', 'td')))

        return htmldoc(extras.html, styles=hfn.tree_styles)
Ejemplo n.º 3
0
def render(pred, root, direction=None, depth=10, local_filepath=None,
           branch='master', restriction=False, wgb='FIXME', local=False,
           verbose=False, flatten=False,):

    kwargs = {'local':local, 'verbose':verbose}
    prov = makeProv(pred, root, wgb)
    if local_filepath is not None:
        github_link = ('https://github.com/SciCrunch/NIF-Ontology/raw/'
                       f'{branch}/{local_filepath}')
        prov.append('<link rel="http://www.w3.org/ns/prov#wasDerivedFrom" '
                    f'href="{github_link}">')
        graph = graphFromGithub(github_link, verbose)
        qname = graph.namespace_manager._qhrm  # FIXME
        labels_index = {qname(s):str(o) for s, o in graph[:rdfs.label:]}
        if pred == 'subClassOf':
            pred = 'rdfs:subClassOf'  # FIXME qname properly?
        elif pred == 'subPropertyOf':
            pred = 'rdfs:subPropertyOf'
        try:
            kwargs['json'] = graph.asOboGraph(pred, restriction=restriction)
            kwargs['prefixes'] = {k:str(v) for k, v in graph.namespace_manager}
        except KeyError as e:
            if verbose:
                log.error(str(e))
            return abort(422, 'Unknown predicate.')
    else:
        kwargs['graph'] = sgg
        # FIXME this does not work for a generic scigraph load ...
        # and it should not be calculated every time anyway!
        # oh look, here we are needed a class again
        if False:
            versionIRI = [
                e['obj']
                for e in sgg.getNeighbors('http://ontology.neuinfo.org/'
                                          'NIF/ttl/nif.ttl')['edges']
                if e['pred'] == 'versionIRI'][0]
            #print(versionIRI)
            prov.append('<link rel="http://www.w3.org/ns/prov#wasDerivedFrom" '
                        f'href="{versionIRI}">')  # FIXME wrong and wont resolve
        prov.append('<meta name="representation" content="SciGraph">')  # FIXME :/
    kwargs['html_head'] = prov
    try:
        if root.startswith('http'):  # FIXME this codepath is completely busted?
            if 'prefixes' in kwargs:
                rec = None
                for k, v in kwargs.items():
                    if root.startswith(v):
                        rec = k + 'r:' + root.strip(v)  # FIXME what?!
                        break
                if rec is None:
                    raise KeyError('no prefix found for {root}')
            else:
                rec = sgv.findById(root)
            if 'curie' in rec:
                root_curie = rec['curie']
                # FIXME https://github.com/SciGraph/SciGraph/issues/268
                if not root_curie.endswith(':') and '/' not in root_curie:
                    root = root_curie
                else:
                    kwargs['curie'] = root_curie
        elif 'prefixes' not in kwargs and root.endswith(':'):
            kwargs['curie'] = root
            root = sgc._curies[root.rstrip(':')]  # also 268

        tree, extras = creatTree(*Query(root, pred, direction, depth), **kwargs)
        dematerialize(list(tree.keys())[0], tree)
        if flatten:
            if local_filepath is not None:
                def safe_find(n):
                    return {'labels':[labels_index[n]],
                            'deprecated': False  # FIXME inacurate
                           }

            else:
                def safe_find(n):  # FIXME scigraph bug
                    if n.endswith(':'):
                        n = sgc._curies[n.rstrip(':')]
                    elif '/' in n:
                        prefix, suffix = n.split(':')
                        iriprefix = sgc._curies[prefix]
                        n = iriprefix + suffix

                    return sgv.findById(n)

            out = set(n for n in flatten_tree(extras.hierarchy))

            try:
                lrecs = Async()(deferred(safe_find)(n) for n in out)
            except RuntimeError:
                asyncio.set_event_loop(current_app.config['loop'])
                lrecs = Async()(deferred(safe_find)(n) for n in out)

            rows = sorted(((r['labels'][0] if r['labels'] else '')
                           + ',' + n for r, n in zip(lrecs, out)
                           # FIXME still stuff wrong, but better for non cache case
                           if not r['deprecated']), key=lambda lid: lid.lower())
            return '\n'.join(rows), 200, {'Content-Type':'text/plain;charset=utf-8'}

        else:
            return hfn.htmldoc(extras.html,
                               other=prov,
                               styles=hfn.tree_styles)

    except (KeyError, TypeError) as e:
        if verbose:
            log.error(f'{type(e)} {e}')
        if sgg.getNode(root):
            # FIXME distinguish these cases...
            message = 'Unknown predicate or no results.'
        elif 'json' in kwargs:
            message = 'Unknown root.'
            r = graph.namespace_manager.expand(root)
            for s in graph.subjects():
                if r == s:
                    message = ('No results. '
                               'You are querying a ttl file directly, '
                               'did you remember to set ?restriction=true?')
                    break
        else:
            message = 'Unknown root.'

        return abort(422, message)
Ejemplo n.º 4
0
def sparc_dynamic(data_sgd, data_sgc, path, wgb, process=lambda coll, blob: blob):
    args = dict(request.args)
    if 'direction' in args:
        direction = args.pop('direction')
    else:
        direction = 'OUTGOING'  # should always be outgoing here since we can't specify?

    if 'format' in args:
        format_ = args.pop('format')
    else:
        format_ = None

    if 'apinat' in path:  # FIXME bad hardcoded hack
        _old_get = data_sgd._get
        try:
            data_sgd._get = data_sgd._normal_get
            j = data_sgd.dispatch(path, **args)
        except ValueError as e:
            log.exception(e)
            abort(404)
        except rHTTPError as e:
            log.exception(e)
            abort(e.response.status_code)  # DO NOT PASS ALONG THE MESSAGE
        finally:
            data_sgd._get = _old_get
    else:
        try:
            j = data_sgd.dispatch(path, **args)
        except rHTTPError as e:
            log.exception(e)
            abort(e.response.status_code)  # DO NOT PASS ALONG THE MESSAGE
        except ValueError as e:
            log.exception(e)
            abort(404)

    j = process(collapse_apinat, j)

    if j is None or 'edges' not in j:
        log.error(pformat(j))
        return abort(400)

    elif not j['edges']:
        return node_list(j['nodes'])  # FIXME ... really should error?

    if path.endswith('housing-lyphs'):  # FIXME hack
        root = 'NLX:154731'
        #direction = 'INCOMING'
    else:
        root = None

    prov = [
        hfn.titletag(f'Dynamic query result for {path}'),
        f'<meta name="date" content="{UTCNOWISO()}">',
        f'<link rel="http://www.w3.org/ns/prov#wasGeneratedBy" href="{wgb}">',
        '<meta name="representation" content="SciGraph">',
        ('<link rel="http://www.w3.org/ns/prov#wasDerivedFrom" '
         f'href="{data_sgd._last_url}">')]

    kwargs = {'json': cleanBad(j),
                'html_head': prov,
                'prefixes': data_sgc.getCuries(),  # FIXME efficiency
    }
    tree, extras = creatTree(*Query(root, None, direction, None), **kwargs)
    #print(extras.hierarhcy)
    #print(tree)
    if format_ is not None:
        if format_ == 'table':
            #breakpoint()
            def nowrap(class_, tag=''):
                return (f'{tag}.{class_}'
                        '{ white-space: nowrap; }')

            ots = [OntTerm(n)
                   for n in flatten_tree(extras.hierarchy)
                   if 'CYCLE' not in n]
            #rows = [[ot.label, ot.asId().atag(), ot.definition] for ot in ots]
            rows = [[ot.label, hfn.atag(ot.iri, ot.curie), ot.definition]
                    for ot in ots]

            return hfn.htmldoc(hfn.render_table(rows, 'label', 'curie', 'definition'),
                               styles=(hfn.table_style, nowrap('col-label', 'td')))

    return hfn.htmldoc(extras.html,
                       other=prov,
                       styles=hfn.tree_styles)