Esempio n. 1
0
def apply_searchActor(request):
    endpoint = "http://localhost:7200"
    repo_name = "moviesDB"
    client = ApiClient(endpoint=endpoint)
    accessor = GraphDBApi(client)
    query = """
                PREFIX pred: <http://moviesDB.com/predicate/>
                SELECT distinct ?name
                WHERE { 
                    ?movie pred:actor ?actor .
                    ?actor pred:name ?name .
                    FILTER (CONTAINS(lcase(?name), \"""" + request.POST[
        'search'].lower() + """\"))
                }
            """
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    actors = []
    for e in res['results']['bindings']:
        for v in e.values():
            actors.append(v['value'].split(" "))

    tparams = {
        'actors': actors,
    }
    return render(request, 'actors.html', tparams)
Esempio n. 2
0
def directors_list(request):
    endpoint = "http://localhost:7200"
    repo_name = "moviesDB"
    client = ApiClient(endpoint=endpoint)
    accessor = GraphDBApi(client)
    query = """
                PREFIX pred: <http://moviesDB.com/predicate/>
                SELECT distinct ?name
                WHERE { 
                    ?movie pred:director ?director .
                    ?director pred:name ?name .
                }
            """
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    directors = []
    for e in res['results']['bindings']:
        for v in e.values():
            directors.append(v['value'].split(" "))

    tparams = {
        'directors': directors,
    }
    return render(request, 'directors.html', tparams)
 def __init__(self):
     self.baseEntity = "http://www.student-mat.com/entity/"
     self.baseProperty = "http://www.student-mat.com/pred/"
     self.endpoint = "http://localhost:7200"
     self.repo_name = "trabalho2"
     self.client = ApiClient(endpoint=self.endpoint)
     self.accessor = GraphDBApi(self.client)
Esempio n. 4
0
def req(request):
    print(request.POST.get('myInput'))

    endpoint = "http://localhost:7200"
    repo_name = "football"
    client = ApiClient(endpoint=endpoint)
    acessor = GraphDBApi(client)
    query = """
                PREFIX fut:<http://worldfootball.org/pred/table/>
                SELECT ?team ?teamname ?points ?pos ?hw ?aw ?hd ?ad ?hl ?al ?goaldif ?link
                WHERE {{
                    ?team fut:team ?teamname .
                    ?team fut:position ?pos .
                    ?team fut:pts ?points .
                    ?team fut:hw ?hw .
                    ?team fut:aw ?aw .
                    ?team fut:hd ?hd .
                    ?team fut:ad ?ad .
                    ?team fut:hl ?hl .
                    ?team fut:al ?al .
                    ?team fut:dif ?goaldif.
                    ?team fut:link ?link.
                    FILTER (?teamname = "{0}")
                }} 
                """.format(request.POST.get('myInput'))

    payload_query = {"query": query}
    res = acessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    for e in res['results']['bindings']:
        aux2 = e['link']['value'].split('/')
        link = aux2[len(aux2) - 1]

    return HttpResponseRedirect('equipa?entity=' + link)
Esempio n. 5
0
def database():
    endpoint = "http://localhost:7200"
    client = ApiClient(endpoint=endpoint)
    accessor = GraphDBApi(client)
    repo_name = "musicbox"

    return (repo_name, accessor)
Esempio n. 6
0
def executeUpdate(update):  #function to avoid repeating code
    repo_name = "Guns"
    client = ApiClient(endpoint=endpoint)
    accessor = GraphDBApi(client)
    payload_update = {"update": update}
    print(payload_update)
    res = accessor.sparql_update(body=payload_update, repo_name=repo_name)
Esempio n. 7
0
def tabela(request):
    nomeclube = dict()
    vitorias = dict()
    empates = dict()
    derrotas = dict()
    goaldif = dict()
    posicao = dict()
    pontos = dict()
    link = dict()
    endpoint = "http://localhost:7200"
    repo_name = "football"
    client = ApiClient(endpoint=endpoint)
    acessor = GraphDBApi(client)
    query = """
            PREFIX fut:<http://worldfootball.org/pred/table/>
            SELECT ?team ?teamname ?points ?pos ?hw  ?hd  ?hl  ?goaldif ?link
            WHERE {
                ?team fut:team ?teamname .
                ?team fut:position ?pos .
                ?team fut:pts ?points .
                ?team fut:hw ?hw .
                ?team fut:hd ?hd .
                ?team fut:hl ?hl .
                ?team fut:dif ?goaldif.
                ?team fut:link ?link.
               
            }
             ORDER BY ASC (xsd:nonNegativeInteger(?pos))
            """
    payload_query = {"query": query}
    res = acessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)

    for e in res['results']['bindings']:

        nomeclube[e['team']['value']] = e['teamname']['value']
        vitorias[e['team']['value']] = int(e['hw']['value'])
        empates[e['team']['value']] = int(e['hd']['value'])
        derrotas[e['team']['value']] = int(e['hl']['value'])
        goaldif[e['team']['value']] = e['goaldif']['value']
        posicao[e['team']['value']] = e['pos']['value']
        pontos[e['team']['value']] = e['points']['value']
        aux = e['team']['value'].split('/')
        aux2 = e['link']['value'].split('/')
        link[e['team']['value']] = aux2[len(aux2) - 1]

    tparams = {
        'nomeclube': nomeclube,
        'vitorias': vitorias,
        'empates': empates,
        'derrotas': derrotas,
        'posicaoclube': posicao,
        'golos': goaldif,
        'pontos': pontos,
        'link': link
    }
    print(tparams)
    return render(request, 'tabela.html', tparams)
Esempio n. 8
0
def edit(request):
    pontos = request.POST.get('pontos')
    posicaoclube = request.POST.get('posicaoclube')
    vitorias = request.POST.get('vitorias')
    empates = request.POST.get('empates')
    derrotas = request.POST.get('derrotas')
    golos = request.POST.get('golos')
    nome = request.POST.get('Nome')
    id = "<http://worldfootball.org/suj/table/" + request.POST.get('id') + ">"

    pontos_ = request.POST.get('pontos_')
    posicaoclube_ = request.POST.get('posicaoclube_')
    vitorias_ = request.POST.get('vitorias_')
    empates_ = request.POST.get('empates_')
    derrotas_ = request.POST.get('derrotas_')
    golos_ = request.POST.get('golos_')

    if (int(golos) > 0):
        if "+" not in golos:
            golos = "+" + str(golos)

    endpoint = "http://localhost:7200"
    repo_name = "football"
    client = ApiClient(endpoint=endpoint)
    acessor = GraphDBApi(client)
    query = """
                PREFIX table:<http://worldfootball.org/pred/table/>
                DELETE DATA {{
                    {0} table:pts "{1}" .
                    {0} table:dif "{2}" .
                    {0} table:position "{3}" .
                    {0} table:hw "{4}" .
                    {0} table:hd "{5}" .
                    {0} table:hl "{6}" .
                }}
            """.format(id, pontos_, golos_, posicaoclube_, vitorias_, empates_,
                       derrotas_)
    print(query)
    payload_query = {"update": query}
    res = acessor.sparql_update(body=payload_query, repo_name=repo_name)

    query2 = """
                PREFIX table:<http://worldfootball.org/pred/table/>
                INSERT DATA {{
                    {0} table:pts "{1}" .
                    {0} table:dif "{2}" .
                    {0} table:position "{3}" .
                    {0} table:hw "{4}" .
                    {0} table:hd "{5}" .
                    {0} table:hl "{6}" .
                 }}
                """.format(id, pontos, golos, posicaoclube, vitorias, empates,
                           derrotas)
    payload_query = {"update": query2}
    res2 = acessor.sparql_update(body=payload_query, repo_name=repo_name)

    return HttpResponseRedirect('/tabela')
Esempio n. 9
0
def executeQuery(query):  #function to avoid repeating code
    repo_name = "Guns"
    client = ApiClient(endpoint=endpoint)
    accessor = GraphDBApi(client)
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    bindings = res['results']['bindings']
    return bindings
def executeQuery(query):
    client = ApiClient(endpoint=ENDPOINT)
    accessor = GraphDBApi(client)
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query, repo_name=REPO_NAME)
    try:
        return json.loads(res)
    except Exception as e:
        print(res)
        return None
Esempio n. 11
0
def director_profile(request, director):
    endpoint = "http://localhost:7200"
    repo_name = "moviesDB"
    client = ApiClient(endpoint=endpoint)
    accessor = GraphDBApi(client)
    query = """
                PREFIX pred: <http://moviesDB.com/predicate/>
                PREFIX movies: <http://moviesDB.com/entity/movies/>
                SELECT distinct ?person ?pred ?obj
                WHERE {
                    ?person pred:name \"""" + director.replace('_',
                                                               ' ') + """\".
                    ?person ?pred ?obj.
                }
            """
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    for e in res['results']['bindings']:
        if "name" in e['pred']['value']:
            name = e['obj']['value']
        elif "image" in e['pred']['value']:
            img = e['obj']['value']
        elif "bio" in e['pred']['value']:
            bio = e['obj']['value']

    query = """
                PREFIX pred: <http://moviesDB.com/predicate/>
                SELECT ?mname
                WHERE { 
                    ?director pred:name \"""" + director.replace('_',
                                                                 ' ') + """\" .
                    ?movie pred:director ?director .
                    ?movie pred:name ?mname .
                }
            """
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    listMovies = []
    for e in res['results']['bindings']:
        print(e)
        listMovies.append(e['mname']['value'])

    tparams = {
        'director_img': img,
        'director_bio': bio,
        'director_name': name,
        'movies': listMovies,
    }
    return render(request, 'director_profile.html', tparams)
Esempio n. 12
0
    def __init__(self):
        self.endpoint = "http://localhost:7200"
        self.repo_name = "Spotify"
        self.client = ApiClient(endpoint=self.endpoint)
        self.accessor = GraphDBApi(self.client)
        payload = {
            "repositoryID": self.repo_name,
            "label": "Spotify",
            "ruleset": "owl-horst-optimized"
        }

        self.accessor.create_repository(body=payload)

        dom = ET.parse("new-releases.xml")
        xslt = ET.parse("new-releases.xslt")
        transform = ET.XSLT(xslt)
        newdom = transform(dom)
        content = ET.tostring(newdom, pretty_print=False).decode()
        file = open("new-releases.rdf", "w")
        file.write(content)

        dom = ET.parse("top-tracks.xml")
        xslt = ET.parse("top-tracks.xslt")
        transform = ET.XSLT(xslt)
        newdom = transform(dom)
        content = ET.tostring(newdom, pretty_print=False).decode()
        file = open("top-tracks.rdf", "w")
        file.write(content)

        dom = ET.parse("recently-played-by-user.xml")
        xslt = ET.parse("recently-played-by-user.xslt")
        transform = ET.XSLT(xslt)
        newdom = transform(dom)
        content = ET.tostring(newdom, pretty_print=False).decode()
        file = open("recently-played-by-user.rdf", "w")
        file.write(content)

        dom = ET.parse("artists.xml")
        xslt = ET.parse("artists.xslt")
        transform = ET.XSLT(xslt)
        newdom = transform(dom)
        content = ET.tostring(newdom, pretty_print=False).decode()
        file = open("artists.rdf", "w")
        file.write(content)

        self.accessor.upload_data_file("new-releases.rdf", repo_name=self.repo_name)
        self.accessor.upload_data_file("top-tracks.rdf", repo_name=self.repo_name)
        self.accessor.upload_data_file("recently-played-by-user.rdf", repo_name=self.repo_name)
        self.accessor.upload_data_file("artists.rdf", repo_name=self.repo_name)
        self.accessor.upload_data_file("comments.rdf", repo_name=self.repo_name)
Esempio n. 13
0
def jogadores(request):
    nome = dict()
    nacionalidade = dict()
    posicao = dict()
    clube = dict()
    idade = dict()
    endpoint = "http://localhost:7200"
    repo_name = "football"
    client = ApiClient(endpoint=endpoint)
    acessor = GraphDBApi(client)
    query = """
            PREFIX player:<http://worldfootball.org/pred/player/>
            SELECT ?id ?name ?club ?age ?position ?nationality
            WHERE {
                ?id player:name ?name .
                ?id player:club ?club .
                ?id player:age ?age .
                ?id player:position ?position .
                ?id player:nationality ?nationality
            }
            """
    payload_query = {"query": query}
    res = acessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    id = dict()
    for e in res['results']['bindings']:
        aux = e['name']['value'].split(" ")
        if len(aux) > 1:
            nome[e['id']['value']] = aux[1]
        else:
            nome[e['id']['value']] = aux[0]

        nacionalidade[e['id']['value']] = e['nationality']['value']
        posicao[e['id']['value']] = e['position']['value']
        clube[e['id']['value']] = e['club']['value']
        idade[e['id']['value']] = e['age']['value']
        aux = e['id']['value'].split('/')
        id[e['id']['value']] = aux[len(aux) - 1]

    tparams = {
        'nome': nome,
        'nacionalidade': nacionalidade,
        'posicao': posicao,
        'clube': clube,
        'idade': idade,
        'id': id
    }
    print(tparams)
    return render(request, 'jogadores.html', tparams)
Esempio n. 14
0
def edit_club(request):

    link = 'http://www.wikidata.org/entity/' + request.GET['entity']
    endpoint = "http://localhost:7200"
    repo_name = "football"
    client = ApiClient(endpoint=endpoint)
    acessor = GraphDBApi(client)
    query = """
                            PREFIX fut:<http://worldfootball.org/pred/table/>
                            SELECT ?team ?teamname ?points ?pos ?hw ?hd  ?hl ?goaldif ?link
                            WHERE {{
                                ?team fut:team ?teamname .
                                ?team fut:hw ?hw .
                                ?team fut:position ?pos .
                                ?team fut:hd ?hd .
                                ?team fut:hl ?hl .
                                ?team fut:pts ?points .
                                ?team fut:dif ?goaldif.
                                ?team fut:link ?link.
                                FILTER (?link = <{0}>)
                            }} 
                            """.format(link)

    payload_query = {"query": query}
    res = acessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)

    for e in res['results']['bindings']:
        vitorias = int(e['hw']['value'])
        empates = int(e['hd']['value'])
        derrotas = int(e['hl']['value'])
        goaldif = e['goaldif']['value']
        posicao = e['pos']['value']
        pontos = e['points']['value']
        nome = e['teamname']['value']
        aux = e['team']['value'].split('/')
        id = aux[len(aux) - 1]

    tparams = {
        'vitorias': vitorias,
        'empates': empates,
        'derrotas': derrotas,
        'posicaoclube': posicao,
        'golos': goaldif,
        'pontos': pontos,
        'nome': nome,
        'id': id
    }
    return render(request, 'editar_clube.html', tparams)
Esempio n. 15
0
def delete_movie(request, movie):
    endpoint = "http://localhost:7200"
    repo_name = "moviesDB"
    client = ApiClient(endpoint=endpoint)
    accessor = GraphDBApi(client)
    update = """
            prefix predicate: <http://moviesDB.com/predicate/>
            DELETE {?film ?pred ?obj.} where{
                ?film ?pred ?obj.
                ?film predicate:name ?name.
                filter regex(?name,\"""" + movie + """\","i").
            }
            """
    payload_query = {"update": update}
    res = accessor.sparql_update(body=payload_query, repo_name=repo_name)
    return redirect('/')
Esempio n. 16
0
def interesses(request):

    endpoint = "http://localhost:7200"
    repo_name = "edcproj2"
    client = ApiClient(endpoint=endpoint)
    accessor = GraphDBApi(client)

    query = """
        prefix int: <https://interesse/pred/>
        prefix m: <https://municipio/pred/>
        select ?nome ?tipo ?regiao
        where {
            ?s_int int:nome ?nome.
            ?s_int int:tipo ?tipo.
            ?s_m m:interesse ?s_int.
            ?s_m m:regiao ?regiao.
        }
        """
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query,
                                 repo_name=repo_name)
    res = json.loads(res)

    send = {}
    cultura = {}
    lazer = {}
    gastronomia = {}
    patrimonio = {}

    for i in res['results']['bindings']:
        nomeint = i['nome']['value']
        tipoint = i['tipo']['value']
        regiaoint = i['regiao']['value']
        if tipoint=='Lazer':
            lazer[nomeint.replace(' ', '_')] = [nomeint, regiaoint]
        if tipoint=='Cultura':
            cultura[nomeint.replace(' ', '_')] = [nomeint, regiaoint]
        if tipoint=='Gastronomia e Vinho':
            gastronomia[nomeint.replace(' ', '_')] = [nomeint, regiaoint]
        if tipoint=='Patrimonio':
            patrimonio[nomeint.replace(' ', '_')] = [nomeint, regiaoint]

    send['cultura'] = cultura
    send['lazer'] = lazer
    send['gastronomia'] = gastronomia
    send['patrimonio'] = patrimonio
    return render(request, 'interesses.html', {"send": send})
Esempio n. 17
0
def queryDB(query):
    query = """
        PREFIX anpc: <http://centraldedados.pt/anpc-2018.csv#>
        PREFIX spif: <http://spinrdf.org/spif#>
        PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
    """ + query
    endpoint = "http://localhost:7200"
    repo = "anpc"
    client = ApiClient(endpoint=endpoint)
    accessor = GraphDBApi(client)
    if query.find('update') != -1 or query.find('insert') != -1:
        payload = {"update": query}
        accessor.sparql_update(body=payload, repo_name=repo)
    else:
        payload = {"query": query}
        result = accessor.sparql_select(body=payload, repo_name=repo)
        return json.loads(result)
Esempio n. 18
0
def queryDB(query, simplify=True, update=False):
    endpoint = "http://localhost:7200"
    repo_name = "bolsa"
    client = ApiClient(endpoint=endpoint)
    accessor = GraphDBApi(client)
    if not update:
        payload_query = {"query": query}
        res = accessor.sparql_select(body=payload_query,
                                 repo_name=repo_name)
    else:
        payload_query = {"update": query}
        res = accessor.sparql_update(body=payload_query,
                                     repo_name=repo_name)
    # If true returns a workable version of the query results
    if simplify:
        res = transformResults(res)
    return res
Esempio n. 19
0
def jogador(request):
    endpoint = "http://localhost:7200"
    repo_name = "football"
    client = ApiClient(endpoint=endpoint)
    acessor = GraphDBApi(client)

    query = """
                PREFIX player:<http://worldfootball.org/pred/player/>
                SELECT ?id ?name ?club ?age ?position ?nationality
                WHERE {{
                    ?id player:name ?name .
                    ?id player:club ?club .
                    ?id player:age ?age .
                    ?id player:position ?position .
                    ?id player:nationality ?nationality
                    filter( ?id=<http://worldfootball.org/data/player/{0}>)
            }}
            """.format(str(request.GET['id']))

    payload_query = {"query": query}
    res = acessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    print(res)
    for e in res['results']['bindings']:
        nome = e['name']['value']
        nacionalidade = e['nationality']['value']
        posicao = e['position']['value']
        clube = e['club']['value']
        idade = e['age']['value']

    tparams = {
        'nacionalidade': nacionalidade,
        'nome': nome,
        'posicao': posicao,
        'clube': clube,
        'idade': idade
    }
    print(tparams)
    return render(request, 'jogador.html', tparams)
Esempio n. 20
0
def distritos(request):
    endpoint = "http://localhost:7200"
    repo_name = "edcproj2"
    client = ApiClient(endpoint=endpoint)
    accessor = GraphDBApi(client)
    query = """
    prefix ns0: <https://municipio/pred/>
    prefix ns1: <https://distrito/pred/>
    SELECT ?municipio ?idmun ?nome ?regiao ?area ?pop  ?denspop
    WHERE {        
                   ?municipio ns0:idmun ?idmun .
                    ?municipio ns0:nome ?nome .
                   ?municipio ns0:regiao ?regiao .
                   ?municipio ns0:area ?area .
                   ?municipio ns0:pop ?pop .
                   ?municipio ns0:denspop ?denspop .

               }
    """
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query,
                                 repo_name=repo_name)
    res = json.loads(res)
    area = 0
    pop = 0
    for e in res['results']['bindings']:
        area = area + float((e['area']['value']))
        pop = pop + float((e['pop']['value']))

    denspop = round(pop / area, 2)
    pop = round(pop, 2)
    area = round(area, 2)
    infoportugal = {}
    infoportugal['totalpop'] = pop
    infoportugal['totalarea'] = area
    infoportugal['densidadeportugal'] = denspop
    return render(request, 'distritos.html', {"infoportugal": infoportugal})
def executeInsert(update):
    client = ApiClient(endpoint=ENDPOINT)
    accessor = GraphDBApi(client)
    payload_update = {"update": update}
    res = accessor.sparql_update(body=payload_update, repo_name=REPO_NAME)
    return res
Esempio n. 22
0
def distritoDetail(request):
    data = request.GET
    distrito = data['distrito']

    endpoint = "http://localhost:7200"
    repo_name = "edcproj2"
    client = ApiClient(endpoint=endpoint)
    accessor = GraphDBApi(client)
    f = distrito.replace('_',' ')

    query = """
    prefix ns0: <https://distrito/pred/>
    prefix ns1: <https://municipio/pred/>
    select ?distrito ?nome ?idmunicipio ?img ?nomedist ?area ?pop
    where { 
        ?distrito ns0:nome '""" +f+ """'.
        ?distrito ns0:municipio ?nomemunicipio.
        ?nomemunicipio ns1:nome ?nome.
        ?nomemunicipio ns1:idmun ?idmunicipio.
        ?distrito ns0:imagem ?img.
    	?distrito ns0:nome ?nomedist.
    	?nomemunicipio ns1:area ?area.
        ?nomemunicipio ns1:pop ?pop.
       
    }
    order by asc(?nome)
    """
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query,
    repo_name=repo_name)
    res = json.loads(res)
    municipios = {}
    interesses = {}
    area = 0
    pop = 0

    for e in res['results']['bindings']:
        nome2 = e['nome']['value'].replace(' ', '_')
        municipios[nome2] = e['nome']['value']
        area = area + float((e['area']['value']))
        pop = pop + float((e['pop']['value']))

    denspop = round(pop / area, 2)
    pop = round(pop, 2)
    area = round(area, 2)

    municipios['imagemdistrito'] = res['results']['bindings'][0]['img']['value']
    municipios['nomedistrito'] = res['results']['bindings'][0]['nomedist']['value']
    municipios['numpopulacao'] = pop
    municipios['areatotal'] = area
    municipios['densidadedistrito'] = denspop

    query = """
        prefix int: <https://interesse/pred/>
        prefix m: <https://municipio/pred/>
        prefix d: <https://distrito/pred/>
        select ?nome_int
        where {
           ?d d:nome '"""+distrito+"""'.
           ?d d:municipio ?s_nome.
           ?s_nome m:interesse ?s_int.
           ?s_int int:nome ?nome_int.
        }order by asc(?nome_int)
    """
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query,
                                 repo_name=repo_name)
    res = json.loads(res)

    for e in res['results']['bindings']:
        nome2 = e['nome_int']['value'].replace(' ', '_')
        interesses[nome2] = e['nome_int']['value']

    codes = {
        "Aveiro": 'Q485581',
        "Beja": 'Q213251',
        "Braga": 'Q83247',
        "Braganca": 'Q768261',
        "Castelo_Branco": 'Q12899232',
        "Coimbra": 'Q45412',
        "Evora": 'Q179948',
        "Faro": 'Q159457',
        "Guarda": 'Q750594',
        "Leiria": 'Q206933',
        "Lisboa": 'Q597',
        "Portalegre": 'Q622819',
        "Porto": 'Q36433',
        "Santarem": 'Q273877',
        "Setubal": 'Q173699',
        "Viana_do_Castelo": 'Q208158',
        "Vila_Real": 'Q503856',
        "Viseu": 'Q117676',
    }
    sparql = SPARQLWrapper("https://query.wikidata.org/sparql", agent='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36')
    sparql.setQuery("""
              SELECT DISTINCT ?coordinates ?imagemLabel ?timezoneLabel ?borderLabel
              WHERE {
                ?distrito wdt:P17 wd:Q45 .
                ?distrito wdt:P31 wd:Q41806065 .
                ?distrito wdt:P36 wd:"""+ codes.get(distrito) +""" .
                ?distrito wdt:P625 ?coordinates .
                OPTIONAL { ?distrito wdt:P2046 ?areaDistrito .}
                OPTIONAL { ?distrito wdt:P242 ?imagem .}
                OPTIONAL { ?distrito wdt:P421 ?timezone .}
                OPTIONAL { ?distrito wdt:P47 ?border .}
                SERVICE wikibase:label { bd:serviceParam wikibase:language "en, pt". }
              }
          """)
    sparql.setReturnFormat(JSON)
    results = sparql.query().convert()
    borders = []
    coord = ""
    tz = ""
    img = ""
    for result in results['results']['bindings']:
        if 'coordinates' in result:
            coord = result['coordinates']['value']
        if 'imagemLabel' in result:
            if img == "":
                img = result['imagemLabel']['value']
        if 'timezoneLabel' in result:
            tz = result['timezoneLabel']['value']
        if 'borderLabel' in result:
            if result['borderLabel']['value'] not in borders:
                borders.append(result['borderLabel']['value'])
    data = {}
    data['coord'] = coord
    data['img'] = img
    data['tz'] = tz
    data['borders'] = borders
    return render(request, 'distritoDetail.html', {"municipios":municipios,"interesses":interesses,"data":data})
Esempio n. 23
0
from s4api.swagger import ApiClient
from django.shortcuts import render, redirect
from .models import Book, Comment
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

# Imports from new implementations
from .forms import SignUpForm
from django.contrib.auth import login, authenticate
# from django.contrib.auth.forms import UserCreationForm
# from django.contrib.auth import logout
from django.http import HttpResponse, HttpResponseBadRequest

endpoint = "http://localhost:7200"
repo_name = "booksguru"
client = ApiClient(endpoint=endpoint)
accessor = GraphDBApi(client)
numb_results_per_page = 18


def index(request):
    """ This function runs three queries to return a set of book to show on home page. """
    top_recent = []
    popular = []
    best_rated = []
    query = """
        PREFIX books: <http://books.com/resource/>
        PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
        
        SELECT ?title ?image ?rating ?id
        WHERE { 
            ?s books:original_title ?title .
Esempio n. 24
0
def jogo(request):

    endpoint = "http://localhost:7200"
    repo_name = "football"
    client = ApiClient(endpoint=endpoint)
    acessor = GraphDBApi(client)

    #info game
    query = """
                PREFIX fut:<http://worldfootball.org/pred/>
                SELECT ?game ?roundnumber ?home ?away ?result ?stadium ?when
                WHERE {{
                    ?game <http://worldfootball.org/pred/game/Round_Number> ?roundnumber .
                    ?game fut:gameHome_Team ?home .
                    ?game fut:gameAway_Team? ?away .
                    ?game fut:gameResult ?result .
                    ?game fut:gameLocation ?stadium .
                    ?game fut:gameDate ?when .
                    filter( ?game=<http://worldfootball.org/data/game/{0}>)
                }}
                ORDER BY(?roundnumber)
                """.format(str(request.GET['id']))

    payload_query = {"query": query}
    res = acessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    for e in res['results']['bindings']:
        ronda = e['roundnumber']['value']
        casa = e['home']['value']
        fora = e['away']['value']
        resultado = e['result']['value']
        estadio = e['stadium']['value']
        quando = e['when']['value']
        aux = e['result']['value'].split("-")

        if int(aux[0]) > int(aux[1]):
            ganhou = 1
        elif int(aux[0]) < int(aux[1]):
            ganhou = 2
        else:
            ganhou = 0

    rounds = dict()

    query = """
            PREFIX fut:<http://worldfootball.org/pred/table/>
            SELECT ?team ?teamname ?link 
            WHERE {{
                ?team fut:team ?teamname.
                ?team fut:link ?link.
                FILTER (?teamname = "{0}")
            }}
            """.format(casa)

    payload_query = {"query": query}
    res = acessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    for e in res['results']['bindings']:
        aux = e['link']['value'].split('/')
        casalink = aux[len(aux) - 1]

    query = """
              PREFIX fut:<http://worldfootball.org/pred/table/>
              SELECT ?team ?teamname ?link
              WHERE {{
                  ?team fut:team ?teamname.
                  ?team fut:link ?link.
                  FILTER (?teamname = "{0}")
                  
              }}
              """.format(fora)

    payload_query = {"query": query}
    res = acessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    for e in res['results']['bindings']:
        aux = e['link']['value'].split('/')
        foralink = aux[len(aux) - 1]

    #estadio
    query = """
                   PREFIX stad:<http://worldfootball.org/pred/stadium/>
                   SELECT ?team ?link
                   WHERE {{
                       ?stadium stad:link ?link .
                       ?stadium stad:FDCOUK ?team .
                       FILTER (?team = "{0}")
                   }}
                   """.format(casa)

    payload_query = {"query": query}
    res = acessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)

    for e in res['results']['bindings']:
        estadiolink = e['link']['value']

        # estadio
    sparql2 = SPARQLWrapper("http://query.wikidata.org/sparql")
    query2 = """
               SELECT ?itemLabel ?image
               WHERE 
               {{
                 ?item wdt:P31 wd:Q483110.
                 ?item wdt:P18 ?image.
                 FILTER (?item = <{0}> )
                 SERVICE wikibase:label {{ bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }}
               }}
               """.format(estadiolink)

    sparql2.setQuery(query2)
    sparql2.setReturnFormat(JSON)
    results = sparql2.query().convert()
    image = ""
    for result in results['results']['bindings']:
        image = result['image']['value']

    # estadio
    query2 = """
                  SELECT ?itemLabel ?image
                  WHERE 
                  {{
                    ?item wdt:P31 wd:Q1154710.
                    ?item wdt:P18 ?image.
                    FILTER (?item = <{0}> )
                    SERVICE wikibase:label {{ bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }}
                  }}
                  """.format(estadiolink)
    sparql2.setQuery(query2)
    sparql2.setReturnFormat(JSON)
    results = sparql2.query().convert()
    for result in results['results']['bindings']:
        image = result['image']['value']

    sparql2.setQuery(query2)
    sparql2.setReturnFormat(JSON)
    results = sparql2.query().convert()

    for result in results['results']['bindings']:
        image = result['image']['value']

    for e in range(16):
        rounds[e] = str(e + 1)

    tparams = {
        'ronda': ronda,
        'casa': casa,
        'fora': fora,
        'resultado': resultado,
        'estadio': estadio,
        'quando': quando,
        'rr': rounds,
        'ganhou': ganhou,
        'casalink': casalink,
        'foralink': foralink,
        'image': image
    }
    return render(request, 'jogo.html', tparams)
Esempio n. 25
0
def new_movie(request):
    assert isinstance(request, HttpRequest)

    if 'title' in request.POST:
        # verify if the required info was provided
        if {'title', 'year', 'first_name1', 'last_name1', 'first_name2', 'last_name2', 'first_name3', 'last_name3',
            'duration', 'rating', 'genre1'} <= set(request.POST) \
                and "" not in {request.POST['title'], request.POST['year'], request.POST['first_name1'],
                               request.POST['last_name1'], request.POST['first_name2'], request.POST['last_name2'],
                               request.POST['first_name3'], request.POST['last_name3'], request.POST['duration'],
                               request.POST['rating'], request.POST['genre1']}:
            clean_title = request.POST['title'].lower().strip().replace(
                " ",
                "_").replace("-",
                             "_").replace(":",
                                          "").replace(",",
                                                      "").replace(".", "")

            endpoint = "http://localhost:7200"
            repo_name = "moviesDB"
            client = ApiClient(endpoint=endpoint)
            accessor = GraphDBApi(client)

            # Check if the genres exist in the DB (and adding connections to them if they do)
            genres = [request.POST['genre1']]
            if 'genre2' in request.POST and request.POST['genre2'] != "":
                genres.append(request.POST['genre2'])
            if 'genre3' in request.POST and request.POST['genre3'] != "":
                genres.append(request.POST['genre3'])
            if 'genre4' in request.POST and request.POST['genre4'] != "":
                genres.append(request.POST['genre4'])

            for g in genres:
                query = """
                            PREFIX gen: <http://moviesDB.com/entity/genres/>
                            PREFIX pred: <http://moviesDB.com/predicate/>
                            ASK {
                                { gen:""" + g.lower(
                ) + " pred:name \"" + g + """" . }
                                UNION
                                { ?movie pred:genre ?genre .
                                  ?genre pred:name \"""" + g + """" . 
                                }
                            }
                        """
                payload_query = {"query": query}
                res = accessor.sparql_select(body=payload_query,
                                             repo_name=repo_name)
                res = json.loads(res)
                if not res['boolean']:
                    return render(
                        request, 'newMovie.html', {
                            'error':
                            True,
                            'errormessage':
                            "The genre \"" + g +
                            "\" does not exist in the database."
                        })
                else:
                    query = """
                                PREFIX mov: <http://moviesDB.com/entity/mov>
                                PREFIX pred: <http://moviesDB.com/predicate/>
                                INSERT  { mov:""" + clean_title + """ pred:genre ?genre }
                                WHERE {
                                    ?movie pred:genre ?genre .
                                    ?genre pred:name ?name .
                                    FILTER (?name = \"""" + g + """")
                                }
                            """
                    payload_query = {"update": query}
                    accessor.sparql_update(body=payload_query,
                                           repo_name=repo_name)

                # Check if the rating exists in the DB (and adding the connection to it if it does)
                rating = request.POST['rating'].lower().replace(
                    "-", "_").replace(":", "").replace(",",
                                                       "").replace(".", "")
                query = """
                            PREFIX gen: <http://moviesDB.com/entity/ratings/>
                            PREFIX pred: <http://moviesDB.com/predicate/>
                            ASK {
                                { gen:""" + rating + " pred:name \"" + request.POST[
                    'rating'] + """" . }
                                UNION
                                { ?movie pred:rating ?rating .
                                  ?rating pred:name \"""" + request.POST[
                        'rating'] + """" . 
                                }
                            }
                        """
                payload_query = {"query": query}
                res = accessor.sparql_select(body=payload_query,
                                             repo_name=repo_name)
                res = json.loads(res)
                if not res['boolean']:
                    return render(
                        request, 'newMovie.html', {
                            'error':
                            True,
                            'errormessage':
                            "The rating \"" + request.POST['rating'] +
                            "\" does not exist in the database."
                        })
                else:
                    query = """
                                PREFIX mov: <http://moviesDB.com/entity/mov>
                                PREFIX pred: <http://moviesDB.com/predicate/>
                                INSERT  { mov:""" + clean_title + """ pred:rating ?rating }
                                WHERE {
                                    ?movie pred:rating ?rating .
                                    ?rating pred:name ?name .
                                    FILTER (?name = \"""" + request.POST[
                        'rating'] + """")
                                }
                            """
                    payload_query = {"update": query}
                    accessor.sparql_update(body=payload_query,
                                           repo_name=repo_name)

                # Adding the rest of the movie's information to the DB
                director = request.POST['first_name1'].replace("'","").replace("-","_").replace(" ","_") \
                           + "_" + request.POST['last_name1'].replace("'","").replace("-","_").replace(" ","_")
                actor1 = request.POST['first_name2'].replace("'","").replace("-","_").replace(" ","_") \
                         + "_" + request.POST['last_name2'].replace("'","").replace("-","_").replace(" ","_")
                actor2 = request.POST['first_name3'].replace("'","").replace("-","_").replace(" ","_") \
                         + "_" + request.POST['last_name3'].replace("'","").replace("-","_").replace(" ","_")
                actor3 = request.POST['first_name4'].replace("'","").replace("-","_").replace(" ","_") \
                         + "_" + request.POST['last_name4'].replace("'","").replace("-","_").replace(" ","_")

                if 'budget' in request.POST and request.POST['budget'] != "":
                    budget = request.POST['budget']
                else:
                    budget = "0"
                if 'country' in request.POST and request.POST['country'] != "":
                    country = request.POST['country']
                else:
                    country = "XXX"

                query = """
                            PREFIX mov: <http://moviesDB.com/entity/mov>
                            PREFIX pred: <http://moviesDB.com/predicate/>
                            INSERT DATA { 
                                mov:""" + clean_title + "	pred:name	\"" + request.POST[
                    'title'] + """" ;
                                    pred:year	\"""" + request.POST[
                        'year'] + """" ;
                                    pred:duration	\"""" + request.POST[
                            'duration'] + """" ;
                                    pred:director	<http://moviesDB.com/entity/person/""" + director + """> ;
                                    pred:actor	<http://moviesDB.com/entity/person/""" + actor1 + """> ,
                                                <http://moviesDB.com/entity/person/""" + actor2 + """> ,
                                                <http://moviesDB.com/entity/person/""" + actor3 + """> ;
                                    pred:budget	\"""" + budget + """" ;
                                    pred:country	\"""" + country + """" ;
                                    pred:language	"XXX" ;
                                    pred:poster	"https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcT16wQWF2p4_8GBLCNAMR9tOfs-q7o1TpLN23n7obheV5IroABG&fbclid=IwAR0YOgN094aLmuX7Z0VMd9xyXgiBZDQu7-HXpB7NAEm8CKiWxz_8JUQJ1nE" ;
                                    pred:score	"?" .
                            }
                        """
                payload_query = {"update": query}
                accessor.sparql_update(body=payload_query, repo_name=repo_name)

                return show_movie(request, request.POST['title'])
        else:
            return render(
                request, 'newMovie.html', {
                    'error': True,
                    'errormessage': "Please fill all the required fields."
                })
    else:
        return render(request, 'newMovie.html', {'error': False})
Esempio n. 26
0
def apply_filters(request):
    endpoint = "http://localhost:7200"
    repo_name = "moviesDB"
    client = ApiClient(endpoint=endpoint)
    accessor = GraphDBApi(client)
    query = """
                PREFIX mov: <http://moviesDB.com/predicate/>
                SELECT distinct ?genre_name
                WHERE { 
                    ?movie mov:genre ?genre .
                    ?genre mov:name ?genre_name .
                }
            """
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    genres = []
    for e in res['results']['bindings']:
        for v in e.values():
            genres.append(v['value'])

    query = """
                PREFIX pred: <http://moviesDB.com/predicate/>
                SELECT distinct ?year
                WHERE {
    	            ?movie pred:year ?year .
                } order by ?year
            """
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    years = []
    for e in res['results']['bindings']:
        for v in e.values():
            years.append(v['value'])

    query = """
                PREFIX pred: <http://moviesDB.com/predicate/>
                SELECT distinct ?rating_name
                WHERE {
    	            ?movie pred:rating ?rating .
                    ?rating pred:name ?rating_name .
                }
            """
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    ratings = []
    for e in res['results']['bindings']:
        for v in e.values():
            ratings.append(v['value'])

    query = """
                PREFIX pred: <http://moviesDB.com/predicate/>
                SELECT distinct ?title ?pred ?obj
                WHERE {
                    ?movie ?pred ?obj .
                    ?movie pred:rating ?rating .
                    ?movie pred:year ?year .
                    ?movie pred:genre ?genre .
                    ?rating pred:name ?rating_name .
                    ?genre pred:name ?genre_name .
                    ?movie pred:name ?title .
                    ?movie pred:score ?score .
                
            """

    genresToQuery = []
    for g in genres:
        if g in request.POST:
            genresToQuery.append(g)

    if len(genresToQuery) != 0:
        aux = ""
        for g in genresToQuery:
            aux += "\"" + g + "\","
        aux = aux[:-1]
        query += """FILTER(?genre_name IN(""" + aux + """))"""

    if 'ratings' in request.POST:
        query += """FILTER (?rating_name = \"""" + request.POST[
            'ratings'] + """\")"""

    if 'years' in request.POST:
        if request.POST['years'] != "":
            query += """FILTER (?year = \"""" + request.POST[
                'years'] + """\")"""

    query += """}"""

    if 'orderby' in request.POST:
        if request.POST['orderby'] != "":
            query += """ORDER BY ?""" + request.POST['orderby'].lower(
            ) + """"""

    movies = {}
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    for e in res['results']['bindings']:
        if e['title']['value'] not in movies.keys():
            if len(movies) == 0:
                obj = [e['obj']['value']]
                if e['pred']['value'].split("/")[-1] == 'genre':
                    i = e['obj']['value'].split("genres/")[1]
                    query = """
                                PREFIX genres: <http://moviesDB.com/entity/genres/>
                                prefix predicate: <http://moviesDB.com/predicate/>
                                    select ?name where{
                                    genres:""" + i + """ predicate:name ?name.
                                }
                            """
                    payload_query = {"query": query}
                    res = accessor.sparql_select(body=payload_query,
                                                 repo_name=repo_name)
                    res = json.loads(res)
                    for f in res['results']['bindings']:
                        obj = [f['name']['value']]
                movies = {
                    e['title']['value']: {
                        e['pred']['value'].split("/")[-1]: obj
                    }
                }
            else:
                obj = [e['obj']['value']]
                if e['pred']['value'].split("/")[-1] == 'genre':
                    i = e['obj']['value'].split("genres/")[1]
                    query = """
                                PREFIX genres: <http://moviesDB.com/entity/genres/>
                                prefix predicate: <http://moviesDB.com/predicate/>
                                select ?name where{
                                    genres:""" + i + """ predicate:name ?name.
                                }
                            """
                    payload_query = {"query": query}
                    res = accessor.sparql_select(body=payload_query,
                                                 repo_name=repo_name)
                    res = json.loads(res)
                    for f in res['results']['bindings']:
                        obj = [f['name']['value']]
                movies.update({
                    e['title']['value']: {
                        e['pred']['value'].split("/")[-1]: obj
                    }
                })
        else:
            if e['pred']['value'].split("/")[-1] in movies[e['title']
                                                           ['value']].keys():
                obj = movies[e['title']['value']][e['pred']['value'].split("/")
                                                  [-1]]
            else:
                obj = [e['obj']['value']]
            if e['pred']['value'].split("/")[-1] == 'genre':
                i = e['obj']['value'].split("genres/")[1]
                query = """
                            PREFIX genres: <http://moviesDB.com/entity/genres/>
                            prefix predicate: <http://moviesDB.com/predicate/>
                            select ?name where{
                                genres:""" + i + """ predicate:name ?name.
                            }
                        """
                payload_query = {"query": query}
                res = accessor.sparql_select(body=payload_query,
                                             repo_name=repo_name)
                res = json.loads(res)
                for f in res['results']['bindings']:
                    if e['pred']['value'].split("/")[-1] in movies[
                            e['title']['value']].keys():
                        obj.append(f['name']['value'])
                    else:
                        obj = [f['name']['value']]
            elif e['pred']['value'].split("/")[-1] == 'director':
                obj = [e['obj']['value'].split("person/")[1]]
                movie_director = e['obj']['value'].split("person/")[1]
                query = """
                            PREFIX person: <http://moviesDB.com/entity/person/>
                            PREFIX predicate: <http://moviesDB.com/predicate/>
                            SELECT ?name WHERE{
                                person:""" + movie_director + """ predicate:name ?name.
                            }
                        """
                payload_query = {"query": query}
                res = accessor.sparql_select(body=payload_query,
                                             repo_name=repo_name)
                res = json.loads(res)
                for f in res['results']['bindings']:
                    obj = [f['name']['value']]
            elif e['pred']['value'].split("/")[-1] == 'actor':
                i = e['obj']['value'].split("person/")[1]
                query = """
                            PREFIX person: <http://moviesDB.com/entity/person/>
                            prefix predicate: <http://moviesDB.com/predicate/>
                            select ?name where{
                                person:""" + i + """ predicate:name ?name.
                            }
                        """
                payload_query = {"query": query}
                res = accessor.sparql_select(body=payload_query,
                                             repo_name=repo_name)
                res = json.loads(res)
                for f in res['results']['bindings']:
                    if e['pred']['value'].split("/")[-1] in movies[
                            e['title']['value']].keys():
                        obj.append(f['name']['value'])
                    else:
                        obj = [f['name']['value']]
                if len(res['results']['bindings']) == 0:
                    if e['pred']['value'].split("/")[-1] in movies[
                            e['title']['value']].keys():
                        obj.append(i)
                    else:
                        obj = [i]
            movies[e['title']['value']].update(
                {e['pred']['value'].split("/")[-1]: obj})
    tparams = {
        'movies': movies,
        "genres": genres,
        "ratings": ratings,
        "years": years
    }
    return render(request, 'index.html', tparams)
Esempio n. 27
0
def jogos(request):
    ronda = dict()
    casa = dict()
    fora = dict()
    resultado = dict()
    estadio = dict()
    quando = dict()
    ganhou = dict()
    endpoint = "http://localhost:7200"
    repo_name = "football"
    client = ApiClient(endpoint=endpoint)
    acessor = GraphDBApi(client)
    id = dict()
    query = """
            PREFIX fut:<http://worldfootball.org/pred/>
            SELECT ?game ?roundnumber ?home ?away ?result ?stadium ?when
            WHERE {
                ?game <http://worldfootball.org/pred/game/Round_Number> ?roundnumber .
                ?game fut:gameHome_Team ?home .
                ?game fut:gameAway_Team? ?away .
                ?game fut:gameResult ?result .
                ?game fut:gameLocation ?stadium .
                ?game fut:gameDate ?when .
            }
            ORDER BY(?roundnumber)
            """

    payload_query = {"query": query}
    res = acessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    for e in res['results']['bindings']:
        ronda[e['game']['value']] = e['roundnumber']['value']
        casa[e['game']['value']] = e['home']['value']
        fora[e['game']['value']] = e['away']['value']
        resultado[e['game']['value']] = e['result']['value']
        estadio[e['game']['value']] = e['stadium']['value']
        quando[e['game']['value']] = e['when']['value']
        aux = e['result']['value'].split("-")

        aux2 = e['game']['value'].split('/')
        id[e['game']['value']] = aux2[len(aux2) - 1]
        if int(aux[0]) > int(aux[1]):
            ganhou[e['game']['value']] = 1
        elif int(aux[0]) < int(aux[1]):
            ganhou[e['game']['value']] = 2
        else:
            ganhou[e['game']['value']] = 0

    rounds = dict()

    for e in range(16):
        rounds[e] = str(e + 1)

    tparams = {
        'ronda': ronda,
        'casa': casa,
        'fora': fora,
        'resultado': resultado,
        'estadio': estadio,
        'quando': quando,
        'rr': rounds,
        'ganhou': ganhou,
        'id': id
    }
    print(tparams)
    return render(request, 'jogos.html', tparams)
Esempio n. 28
0
def show_movie(request, movie):
    endpoint = "http://localhost:7200"
    repo_name = "moviesDB"
    client = ApiClient(endpoint=endpoint)
    accessor = GraphDBApi(client)
    query = """
                PREFIX mov: <http://moviesDB.com/entity/mov>
                prefix predicate: <http://moviesDB.com/predicate/>
                select ?pred ?obj where{
                    ?film ?pred ?obj.
                    ?film predicate:name ?name
                    filter regex(?name,\"""" + movie.replace("/", " ").replace(
        "!", "") + """\",+\"i\").
                }
            """
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    movie_genres = []
    plot_keywords = []
    movie_secondary_actors = []
    movie_main_actors = []
    rating = ""
    for e in res['results']['bindings']:
        if "name" in e['pred']['value']:
            name = e['obj']['value']
        elif "year" in e['pred']['value']:
            year = e['obj']['value']
        elif "poster" in e['pred']['value']:
            poster = e['obj']['value']
        elif "poster" in e['pred']['value']:
            poster = e['obj']['value']
        elif "score" in e['pred']['value']:
            score = e['obj']['value']
        elif "actor" in e['pred']['value']:
            movie_main_actors.append(e['obj']['value'])
        elif "director" in e['pred']['value']:
            movie_director = e['obj']['value']
        elif "genre" in e['pred']['value']:
            movie_genres.append(e['obj']['value'])
        elif "plot_keyword" in e['pred']['value']:
            plot_keywords.append(e['obj']['value'])
        elif "country" in e['pred']['value']:
            country = e['obj']['value']
        elif "language" in e['pred']['value']:
            language = e['obj']['value']
        elif "rating" in e['pred']['value']:
            rating = e['obj']['value']
        elif "duration" in e['pred']['value']:
            duration = e['obj']['value']
        elif "budget" in e['pred']['value']:
            budget = e['obj']['value']

    rating = rating.split("ratings/")[1]
    query = """
                PREFIX ratings: <http://moviesDB.com/entity/ratings/>
                PREFIX predicate: <http://moviesDB.com/predicate/>
                SELECT ?name WHERE{
                    ratings:""" + rating + """ predicate:name ?name.
                }
            """
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    for e in res['results']['bindings']:
        rating = e['name']['value']

    genres = []
    for i in movie_genres:
        i = i.split("genres/")[1]
        query = """
                    PREFIX genres: <http://moviesDB.com/entity/genres/>
                    prefix predicate: <http://moviesDB.com/predicate/>
                    select ?name where{
                        genres:""" + i + """ predicate:name ?name.
                    }
                """
        payload_query = {"query": query}
        res = accessor.sparql_select(body=payload_query, repo_name=repo_name)
        res = json.loads(res)
        for e in res['results']['bindings']:
            genres.append(e['name']['value'])

    movie_director = movie_director.split("person/")[1]
    query = """
                PREFIX person: <http://moviesDB.com/entity/person/>
                PREFIX predicate: <http://moviesDB.com/predicate/>
                SELECT ?name WHERE{
                    person:""" + movie_director + """ predicate:name ?name.
                }
            """
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    for e in res['results']['bindings']:
        movie_director = e['name']['value']

    actors = []
    for i in movie_main_actors:
        i = i.split("person/")[1]
        query = """
                   PREFIX person: <http://moviesDB.com/entity/person/>
                   prefix predicate: <http://moviesDB.com/predicate/>
                   select ?name where{
                        person:""" + i + """ predicate:name ?name.
                   }
                """
        payload_query = {"query": query}
        res = accessor.sparql_select(body=payload_query, repo_name=repo_name)
        res = json.loads(res)
        for e in res['results']['bindings']:
            actors.append(e['name']['value'])
        if len(res['results']['bindings']) == 0:
            actors.append(i)
    tparams = {
        'movie_name': name,
        'movie_img': poster,
        'movie_year': year,
        'movie_score': score,
        'movie_main_actors': actors,
        'movie_secondary_actors': movie_secondary_actors[1:],
        'movie_director': movie_director,
        'movie_genres': genres,
        'movie_rating': rating,
        'movie_language': language,
        'movie_country': country,
        'movie_duration': duration,
        'movie_plot_keywords': plot_keywords,
        'movie_budget': budget
    }
    return render(request, 'movie_page.html', tparams)
Esempio n. 29
0
def apply_search(request):
    endpoint = "http://localhost:7200"
    repo_name = "moviesDB"
    client = ApiClient(endpoint=endpoint)
    accessor = GraphDBApi(client)
    query = """
                PREFIX mov: <http://moviesDB.com/predicate/>
                SELECT distinct ?genre_name
                WHERE { 
                    ?movie mov:genre ?genre .
                    ?genre mov:name ?genre_name .
        	    }
            """
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    genres = []
    for e in res['results']['bindings']:
        for v in e.values():
            genres.append(v['value'])

    query = """
                PREFIX pred: <http://moviesDB.com/predicate/>
                SELECT distinct ?year
                WHERE {
    	            ?movie pred:year ?year .
                } order by ?year
            """
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    years = []
    for e in res['results']['bindings']:
        for v in e.values():
            years.append(v['value'])

    query = """
                PREFIX pred: <http://moviesDB.com/predicate/>
                SELECT distinct ?rating_name
                WHERE {
    	            ?movie pred:rating ?rating .
                    ?rating pred:name ?rating_name .
                }
            """
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    ratings = []
    for e in res['results']['bindings']:
        for v in e.values():
            ratings.append(v['value'])

    query = """
                PREFIX pred: <http://moviesDB.com/predicate/>
                SELECT distinct ?title ?pred ?obj
                WHERE {
                    {
                        ?movie ?pred ?obj .
                        ?movie pred:director ?director.
                        ?movie pred:name ?title .
                        FILTER(CONTAINS(lcase(?title), \"""" + request.POST[
        'search'].lower() + """\"))
                    } UNION {
                        ?movie ?pred ?obj .
                        ?movie pred:name ?title .
                        ?movie pred:plot_keyword ?keywords .
                        FILTER(CONTAINS(lcase(?keywords), \"""" + request.POST[
            'search'].lower() + """\"))
                    }
                }
           """
    payload_query = {"query": query}
    res = accessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    movies = {}
    for e in res['results']['bindings']:
        if e['title']['value'] not in movies.keys():
            if len(movies) == 0:
                movies = {
                    e['title']['value']: {
                        e['pred']['value'].split("/")[-1]: [e['obj']['value']]
                    }
                }
            else:
                movies.update({
                    e['title']['value']: {
                        e['pred']['value'].split("/")[-1]: [e['obj']['value']]
                    }
                })
        else:
            if e['pred']['value'].split("/")[-1] in movies[e['title']
                                                           ['value']].keys():
                obj = movies[e['title']['value']][e['pred']['value'].split("/")
                                                  [-1]]
            else:
                obj = [e['obj']['value']]
            if e['pred']['value'].split("/")[-1] == 'genre':
                i = e['obj']['value'].split("genres/")[1]
                query = """
                            PREFIX genres: <http://moviesDB.com/entity/genres/>
                            prefix predicate: <http://moviesDB.com/predicate/>
                                select ?name where{
                                genres:""" + i + """ predicate:name ?name.
                            }
                        """
                payload_query = {"query": query}
                res = accessor.sparql_select(body=payload_query,
                                             repo_name=repo_name)
                res = json.loads(res)
                for f in res['results']['bindings']:
                    if (e['pred']['value'].split("/")[-1]
                            in movies[e['title']['value']].keys()):
                        obj.append(f['name']['value'])
                    else:
                        obj = [f['name']['value']]
            elif e['pred']['value'].split("/")[-1] == 'director':
                obj = [e['obj']['value'].split("person/")[1]]
                movie_director = e['obj']['value'].split("person/")[1]
                query = """
                            PREFIX person: <http://moviesDB.com/entity/person/>
                            PREFIX predicate: <http://moviesDB.com/predicate/>
                            SELECT ?name WHERE{
                                person:""" + movie_director + """ predicate:name ?name.
                            }
                        """
                payload_query = {"query": query}
                res = accessor.sparql_select(body=payload_query,
                                             repo_name=repo_name)
                res = json.loads(res)
                for f in res['results']['bindings']:
                    obj = [f['name']['value']]
            elif e['pred']['value'].split("/")[-1] == 'actor':
                i = e['obj']['value'].split("person/")[1]
                query = """
                            PREFIX person: <http://moviesDB.com/entity/person/>
                            prefix predicate: <http://moviesDB.com/predicate/>
                            select ?name where{
                                person:""" + i + """ predicate:name ?name.
                            }
                        """
                payload_query = {"query": query}
                res = accessor.sparql_select(body=payload_query,
                                             repo_name=repo_name)
                res = json.loads(res)
                for f in res['results']['bindings']:
                    if e['pred']['value'].split("/")[-1] in movies[
                            e['title']['value']].keys():
                        obj.append(f['name']['value'])
                    else:
                        obj = [f['name']['value']]
                if len(res['results']['bindings']) == 0:
                    if e['pred']['value'].split("/")[-1] in movies[
                            e['title']['value']].keys():
                        obj.append(i)
                    else:
                        obj = [i]
            movies[e['title']['value']].update(
                {e['pred']['value'].split("/")[-1]: obj})

        print(e)
    print(movies)
    tparams = {
        'movies': movies,
        "genres": genres,
        "ratings": ratings,
        "years": years
    }
    return render(request, 'index.html', tparams)
Esempio n. 30
0
def infoclube(request):

    link = 'http://www.wikidata.org/entity/' + request.GET['entity']
    #em runtime aplica a query sobre a wikidata para obter informação
    sparql = SPARQLWrapper("http://query.wikidata.org/sparql")
    query2 = """
             SELECT ?itemLabel ?date ?locationLabel ?coachLabel ?stadiumLabel ?stadium ?site
             WHERE
              {{ 
                 ?item wdt:P571 ?date.
                 ?item wdt:P159 ?location.
                 ?item wdt:P286 ?coach.
                 ?item wdt:P115 ?stadium.
                 ?item wdt:P856 ?site.
                FILTER ( ?item = <{0}> ) 
                SERVICE wikibase:label {{ bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }}
              }}
              """.format(link)
    sparql.setQuery(query2)
    sparql.setReturnFormat(JSON)
    results = sparql.query().convert()

    for result in results['results']['bindings']:
        stad = result['stadium']['value']
        nome = result['itemLabel']['value']
        aux = result['date']['value'].split('T')
        data = aux[0]
        site = result['site']['value']

        cidade = result['locationLabel']['value']
        treinador = result['coachLabel']['value']
        estadio = result['stadiumLabel']['value']

    #tabela
    endpoint = "http://localhost:7200"
    repo_name = "football"
    client = ApiClient(endpoint=endpoint)
    acessor = GraphDBApi(client)
    query = """
                        PREFIX fut:<http://worldfootball.org/pred/table/>
                        SELECT  ?points ?pos ?hw  ?hd  ?hl  ?goaldif ?link
                        WHERE {{
                            ?team fut:hw ?hw .
                            ?team fut:position ?pos .
                            ?team fut:hd ?hd .
                            ?team fut:hl ?hl .
                            ?team fut:pts ?points .
                            ?team fut:dif ?goaldif.
                            ?team fut:link ?link.
                            FILTER (?link = <{0}>)
                        }} 
                        """.format(link)

    payload_query = {"query": query}
    res = acessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)

    for e in res['results']['bindings']:
        vitorias = int(e['hw']['value'])
        empates = int(e['hd']['value'])
        derrotas = int(e['hl']['value'])
        goaldif = e['goaldif']['value']
        posicao = e['pos']['value']
        pontos = e['points']['value']

    #estadio
    sparql2 = SPARQLWrapper("http://query.wikidata.org/sparql")
    query2 = """
            SELECT ?itemLabel ?image
            WHERE 
            {{
              ?item wdt:P31 wd:Q483110.
              ?item wdt:P18 ?image.
              FILTER (?item = <{0}> )
              SERVICE wikibase:label {{ bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }}
            }}
            """.format(stad)

    sparql2.setQuery(query2)
    sparql2.setReturnFormat(JSON)
    results = sparql2.query().convert()
    image = ""
    for result in results['results']['bindings']:
        image = result['image']['value']

    #estadio
    query2 = """
               SELECT ?itemLabel ?image
               WHERE 
               {{
                 ?item wdt:P31 wd:Q1154710.
                 ?item wdt:P18 ?image.
                 FILTER (?item = <{0}> )
                 SERVICE wikibase:label {{ bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }}
               }}
               """.format(stad)
    sparql2.setQuery(query2)
    sparql2.setReturnFormat(JSON)
    results = sparql2.query().convert()
    for result in results['results']['bindings']:
        image = result['image']['value']

    query = """
                PREFIX stad:<http://worldfootball.org/pred/stadium/>
                SELECT ?capacity ?team
                WHERE {{
                    ?stadium stad:link ?link .
                    ?stadium stad:teamlink ?team .
                    ?stadium stad:Capacity ?capacity
                    FILTER (?link = <{0}>)
                }}
                """.format(stad)
    print(query)
    capacidade = ""
    payload_query = {"query": query}
    res = acessor.sparql_select(body=payload_query, repo_name=repo_name)
    res = json.loads(res)
    for e in res['results']['bindings']:
        capacidade = e['capacity']['value']

    tparams = {
        'nome': nome,
        'data': data,
        'cidade': cidade,
        'treinador': treinador,
        'estadio': estadio,
        'vitorias': vitorias,
        'empates': empates,
        'derrotas': derrotas,
        'posicaoclube': posicao,
        'golos': goaldif,
        'pontos': pontos,
        'imageS': image,
        'capacidade': capacidade,
        'site': site
    }

    return render(request, 'clube.html', tparams)