Ejemplo n.º 1
0
def item_from_graph(graph_path, ident):
    graph = ConjunctiveGraph()
    with open(graph_path) as graph_file:
        graph.parse(format='trig', data=graph_file.read())
    from rdflib_django import utils
    utils.get_conjunctive_graph().parse(data=graph.serialize(format='nquads'),
                                        format='nquads')
    item = Item(iri='http://dbpedia.org/resource/' + ident)
    item.save()
    return item
Ejemplo n.º 2
0
    def lineages(self, request, graph_identifier=None):
        if graph_identifier:
            graph = get_named_graph(graph_identifier)
        else:
            graph = get_conjunctive_graph()
        object = self.node()
        assert object
        MAX_DISTANCE = 5
        MAX_ITERATIONS = 5
        history = get_history(request)
        n_nodes = len(history)
        out_paths = []
        paths = [[[self, None]]] # start with only 1 path containing only a pseudo-edge
        while paths:
            path = paths[0] # 1st path
            object = path[0][0].node() # left element (subject) of first edge becomes target object of previous triples
            triples = list(graph.triples((None, None, object)))
            triples += get_reified_triples(object, graph)
            n_triples = len(triples)
            i = 0
            while n_triples and node_id(object) not in settings.EU_COUNTRY_KEYS:
                i += 1
                if i > MAX_ITERATIONS: # endless loops could result from bugs or wrong network
                    exit
                best_k = 0
                if n_triples > 1:
                    if history:
                        min_distance = MAX_DISTANCE
                        k_range = range(n_triples)
                        for k in k_range:
                            s, p, o = triples[k]
                            if node_id(s) in history:
                                distance = n_nodes - history.index(node_id(s))
                                if distance < min_distance:
                                    best_k = k
                s, p, o = triples[best_k]
                best_edge = [make_item(s), Predicate(uriref=p)]
                del triples[best_k]
                if not history:
                    for triple in triples:
                        edge = [make_item(triple[0]), Predicate(uriref=triple[1])]
                        # paths.append(deepcopy([edge]) + deepcopy(path))
                        paths.append([edge] + path)
                # path = deepcopy([best_edge]) + deepcopy(path)
                path = [best_edge] + path

                object = s
                triples = list(graph.triples((None, None, object)))
                triples += get_reified_triples(object, graph)
                n_triples = len(triples)
            out_paths.append(path[:-1])
            paths = paths[1:]
            # print_paths(out_paths)
        return out_paths
Ejemplo n.º 3
0
    def handle(self, *args, **options):
        store_id = options.get('store')
        context_id = options.get('context')
        target = args[0] if args else sys.stdout

        if context_id:
            graph = utils.get_named_graph(URIRef(context_id), store_id=store_id)
        else:
            graph = utils.get_conjunctive_graph(store_id)

        #noinspection PyUnresolvedReferences
        graph.serialize(target, format=options.get('format'))
Ejemplo n.º 4
0
    def handle(self, *args, **options):
        store_id = options.get('store')
        context_id = options.get('context')
        target = args[0] if args else sys.stdout

        if context_id:
            graph = utils.get_named_graph(URIRef(context_id),
                                          store_id=store_id)
        else:
            graph = utils.get_conjunctive_graph(store_id)

        # noinspection PyUnresolvedReferences
        graph.serialize(target, format=options.get('format'))
Ejemplo n.º 5
0
def list_statements(request, graph_identifier=None):
    lang = get_language()[:2]
    if graph_identifier:
        graph = get_named_graph(graph_identifier)
    else:
        graph = get_conjunctive_graph()
    statement_dicts = [{
        'graph': 'wikidata',
        'subject': friend_uri(s, lang=lang),
        'predicate': friend_uri(p, lang=lang),
        'object': friend_uri(o, lang=lang)
    } for s, p, o in graph]
    return render(request, 'list_statements.html',
                  {'statement_dicts': statement_dicts})
Ejemplo n.º 6
0
def removeProperty(request, item_code, graph_identifier=None):
    if graph_identifier:
        graph = get_named_graph(graph_identifier)
    else:
        graph = get_conjunctive_graph()
    subject = make_node(item_code)
    country_id = request.GET.get('c')
    property = make_node(request.GET.get('p'))
    datatype_id = request.GET.get('dt')
    object_value_or_id = request.GET.get('o')
    language = request.GET.get('lang', None)
    triples = graph.triples((subject, property, None))
    for triple in triples:
        object = triple[2]
        if isinstance(object, Literal):
            if datatype_id:
                if datatype_id == object.datatype_id(
                ) and object_value_or_id == str(object.value):
                    graph.remove(triple)
            elif language and object.language and (
                    language == object.language) and (object_value_or_id
                                                      == object.value):
                graph.remove(triple)
            elif language and not object.language and (object_value_or_id
                                                       == object.value):
                graph.remove(triple)
            elif not language and not object.language and (object_value_or_id
                                                           == object.value):
                graph.remove(triple)
            elif object_value_or_id == str(object.value):
                graph.remove(triple)
            """ MMR 200723
            elif language and language == object.language:
                graph.remove(triple)
            elif not language and not object.language:
                graph.remove(triple)
            """
        else:
            if isinstance(object, BNode):
                if object_value_or_id == str(object):
                    remove_node(object, graph)
                    graph.remove(triple)
            elif isinstance(object, URIRef):
                if id_from_uriref(object) == object_value_or_id:
                    remove_node(object, graph)
                    graph.remove(triple)
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Ejemplo n.º 7
0
 def post(self, request):
     save = request.POST.get('save', False)
     save_continue = request.POST.get('continue', False)
     item_code = request.POST['item']
     if is_bnode_id(item_code):
         item = Item(bnode=BNode(item_code))
         subject = item.bnode
     else:
         item = Item(id=item_code)
         subject = item.uriref
     if save or save_continue:
         conjunctive_graph = get_conjunctive_graph()
     field_dict = {}
     for name, value in request.POST.items():
         if name.count('_'):
             field_dict[name] = value
     for name in field_dict.keys():
         if save or save_continue:
             predicate_id, datatype_id, language = name.split('_')
             predicate = Predicate(id=predicate_id).uriref
             new_value = field_dict[name]
             quads = list(
                 conjunctive_graph.quads((subject, predicate, None)))
             for quad in quads:
                 (subject, predicate, object, graph) = quad
                 old_value = object.value
                 if datatype_id and datatype_id == object.datatype_id():
                     if new_value != old_value:
                         graph.add((subject, predicate,
                                    Literal(new_value,
                                            datatype=object.datatype)))
                         conjunctive_graph.remove(quad)
                 elif language and language == object.language:
                     if new_value != old_value:
                         graph.add((subject, predicate,
                                    Literal(new_value,
                                            lang=object.language)))
                         conjunctive_graph.remove(quad)
                 elif not language and not object.language:
                     if new_value != old_value:
                         graph.add((subject, predicate, Literal(new_value)))
                         conjunctive_graph.remove(quad)
     if save:
         return HttpResponseRedirect('/item/{}/'.format(item_code))
     elif save_continue:
         return HttpResponseRedirect('/item/{}/edit/'.format(item_code))
Ejemplo n.º 8
0
def remove_item(request, item_code, graph_identifier=None):
    if graph_identifier:
        graph = get_named_graph(graph_identifier)
    else:
        graph = get_conjunctive_graph()
    item = item_from_id(item_code)
    lineages = item.lineages(request)
    parent, predicate = lineages[0][-1]
    parent_code = parent.id
    node = item.uriref
    in_triple = next(graph.triples((parent.uriref, predicate.uriref, node)))
    graph.remove(in_triple)
    remove_node(node, graph)
    if parent_code in settings.EU_COUNTRY_KEYS:
        return HttpResponseRedirect('/country/{}/'.format(parent_code))
    else:
        return HttpResponseRedirect('/item/{}/'.format(parent_code))
Ejemplo n.º 9
0
 def __init__(self, uriref=None, id=None, bnode=None, graph=None, graph_identifier=None, in_predicate=None):
     assert uriref or id or bnode
     self.uriref = self.id = self.bnode = None
     if uriref:
         self.uriref = uriref
         self.id = id_from_uriref(uriref)
     elif id:
         self.id = id
         self.uriref = make_uriref(id)
     else:
         self.bnode = bnode
         self.id = str(bnode) # added 200708
     if graph_identifier:
         graph = get_named_graph(graph_identifier)
     elif not graph:
         graph = get_conjunctive_graph()
     self.graph = graph
     self.in_predicate = in_predicate
Ejemplo n.º 10
0
def ingest_graph(graph):
    from rdflib_django import utils
    utils.get_conjunctive_graph().parse(data=graph.serialize(format='nquads'),
                                        format='nquads')
Ejemplo n.º 11
0
def run_query(query, g=None):
    if not g:
        g = get_conjunctive_graph()
    query_result = g.query(query)
    return query_result