Ejemplo n.º 1
0
 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)
Ejemplo n.º 2
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)
Ejemplo n.º 3
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)
Ejemplo n.º 4
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)
Ejemplo n.º 5
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)
Ejemplo n.º 6
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)
Ejemplo n.º 7
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')
Ejemplo n.º 8
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
Ejemplo n.º 10
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)
Ejemplo n.º 11
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)
Ejemplo n.º 12
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)
Ejemplo n.º 13
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)
Ejemplo n.º 14
0
class mainRegionRule(InferenceRule):
    def __init__(self):
        self.baseEntity = "http://www.games.com/entity/"
        self.baseProperty = "http://www.games.com/pred/"
        self.endpoint = "http://localhost:7200"
        self.repo_name = "games"
        self.client = ApiClient(endpoint=self.endpoint)
        self.accessor = GraphDBApi(self.client)

    def get_inference_triples(self):
        query = """
            PREFIX pred: <http://www.games.com/pred/>
            SELECT ?s ?n ?e ?j ?o  
            WHERE 
            {
                ?s pred:na_sales ?n .
                ?s pred:eu_sales ?e .
                ?s pred:jp_sales ?j .
                ?s pred:other_sales ?o .
            }
        """
        payload_query = {"query": query}
        res = self.accessor.sparql_select(body=payload_query, repo_name=self.repo_name)
        res = json.loads(res)
        results = ""
        for result in res['results']['bindings']:
            sub = result['s']['value'].replace(self.baseEntity, '')
            NA = float(result['n']['value'])
            EU = float(result['e']['value'])
            JP = float(result['j']['value'])
            OT = float(result['o']['value'])
            region = {'North_America': NA, 'Europe': EU, 'Japan': JP, 'Others': OT}
            max_value = max(region, key=region.get)
            results += sub + ' Main_Region ' + max_value + ' .\n'
        return results
Ejemplo n.º 15
0
def database():
    endpoint = "http://localhost:7200"
    client = ApiClient(endpoint=endpoint)
    accessor = GraphDBApi(client)
    repo_name = "musicbox"

    return (repo_name, accessor)
Ejemplo n.º 16
0
class consoleTypeRule(InferenceRule):
    def __init__(self):
        self.baseEntity = "http://www.games.com/entity/"
        self.baseProperty = "http://www.games.com/pred/"
        self.endpoint = "http://localhost:7200"
        self.repo_name = "games"
        self.client = ApiClient(endpoint=self.endpoint)
        self.accessor = GraphDBApi(self.client)

    def get_inference_triples(self):
        query = """
            PREFIX pred: <http://www.games.com/pred/>
            SELECT ?s ?o 
            WHERE 
            {
                ?s pred:platform ?o .
            }
        """
        payload_query = {"query": query}
        res = self.accessor.sparql_select(body=payload_query,
                                          repo_name=self.repo_name)
        res = json.loads(res)
        results = ""
        for result in res['results']['bindings']:
            sub = result['s']['value'].replace('http://www.games.com/entity/',
                                               '')
            obj = result['o']['value'].replace('http://www.games.com/entity/',
                                               '')
            if obj == 'ds' or obj == 'gb' or obj == 'gba' or obj == 'psp':
                results += sub + ' Console_Type ' + 'Portable .\n'
            else:
                results += sub + ' Console_Type ' + 'Console .\n'
        return results
Ejemplo n.º 17
0
class orientation():
    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)

    def get_triples(self):
        query = """
                PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                PREFIX foaf:<http://xmlns.com/foaf/0.1/>
                PREFIX pred:<http://www.student-mat.com/pred/>
                select ?s ?o where { 
                    ?s pred:available ?o .
                    ?s rdf:type foaf:Person .
                    ?o rdf:type foaf:Person .
                } 
                 """
        payload_query = {"query": query}
        res = self.accessor.sparql_select(body=payload_query,
                                          repo_name=self.repo_name)
        res = json.loads(res)
        results = ""
        for result in res['results']['bindings']:
            sub = result['s']['value'].replace(self.baseEntity, '')
            sub2 = result['o']['value'].replace(self.baseEntity, '')
            if (sub != sub2):
                results += sub + ' hetero ' + 'yes' + ';' + sub2 + ' hetero ' + 'yes' + ';'
        return results
Ejemplo n.º 18
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('/')
Ejemplo n.º 19
0
class riskstudent():
    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)

    def get_triples(self):
        query = """
           PREFIX baseProperty: <http://www.student-mat.com/pred/>
           PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
           PREFIX baseStudent: <http://www.student-mat.com/class/>
           PREFIX baseEntity: <http://www.student-mat.com/entity/>
           PREFIX fb: <http://rdf.freebase.com/ns/>
           SELECT *
           WHERE {
               ?s baseProperty:age ?o .
               ?s baseProperty:famsup 'no' .
           }
              """
        payload_query = {"query": query}
        res = self.accessor.sparql_select(body=payload_query,
                                          repo_name=self.repo_name)
        res = json.loads(res)
        results = ""
        for result in res['results']['bindings']:
            sub = result['s']['value'].replace(self.baseEntity, '')
            age = float(result['o']['value'])
            if (int(age) < 18):
                results += sub + ' risk ' + 'yes;'
        return results
Ejemplo n.º 20
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})
Ejemplo n.º 21
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
Ejemplo n.º 22
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)
Ejemplo n.º 23
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)
Ejemplo n.º 24
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})
Ejemplo n.º 25
0
class relationavailable():
    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)

    def get_triples(self):
        query = """
              PREFIX baseProperty: <http://www.student-mat.com/pred/>
              PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
              PREFIX baseStudent: <http://www.student-mat.com/class/>
              PREFIX baseEntity: <http://www.student-mat.com/entity/>
              PREFIX fb: <http://rdf.freebase.com/ns/>
              SELECT *
              WHERE {
              {
                  ?s baseProperty:sex 'M' .
                  ?s baseProperty:romantic 'no'.
              }
              {
                  ?s2 baseProperty:sex 'F' .
                  ?s2 baseProperty:romantic 'no'.
              }
              }
                 """
        payload_query = {"query": query}
        res = self.accessor.sparql_select(body=payload_query,
                                          repo_name=self.repo_name)
        res = json.loads(res)
        results = ""
        for result in res['results']['bindings']:
            sub = result['s']['value'].replace(self.baseEntity, '')
            sub2 = result['s2']['value'].replace(self.baseEntity, '')
            if (sub != sub2):
                results += sub + ' available ' + sub2 + ';'
        return results
Ejemplo n.º 26
0
class laterReleaseRule(InferenceRule):
    def __init__(self):
        self.baseEntity = "http://www.games.com/entity/"
        self.baseProperty = "http://www.games.com/pred/"
        self.endpoint = "http://localhost:7200"
        self.repo_name = "games"
        self.client = ApiClient(endpoint=self.endpoint)
        self.accessor = GraphDBApi(self.client)

    def get_inference_triples(self):
        query = """
            PREFIX pred: <http://www.games.com/pred/>
            SELECT ?year1 ?year2 ?id1 ?id2
            WHERE
            {
                ?id1 pred:year ?year1 .       
                ?id2 pred:year ?year2 .
            }
            """
        payload_query = {"query": query}
        res = self.accessor.sparql_select(body=payload_query,
                                          repo_name=self.repo_name)
        res = json.loads(res)
        results = ""
        for result in res['results']['bindings']:
            first_year = int(result['year1']['value'])
            second_year = int(result['year2']['value'])
            id1 = result['id1']['value'].replace(self.baseEntity, '')
            id2 = result['id2']['value'].replace(self.baseEntity, '')
            if id1 != id2:
                if first_year < second_year:
                    results += id1 + ' Earlier ' + id2 + ' .\n'
                elif first_year == second_year:
                    results += id1 + ' Same ' + id2 + ' .\n'
                else:
                    results += id1 + ' Later ' + id2 + ' .\n'
        return results
Ejemplo n.º 27
0
class Unhappyrule():
    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)

    def get_triples(self):

        query = """
           PREFIX baseProperty: <http://www.student-mat.com/pred/>
           PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
           PREFIX baseStudent: <http://www.student-mat.com/class/>
           PREFIX baseEntity: <http://www.student-mat.com/entity/>
           PREFIX fb: <http://rdf.freebase.com/ns/>
           SELECT *
           WHERE {
               ?s baseProperty:romantic 'no' .
               ?s baseProperty:goout ?o .
               ?s baseProperty:walc ?al.
           }
              """
        payload_query = {"query": query}
        res = self.accessor.sparql_select(body=payload_query,
                                          repo_name=self.repo_name)
        res = json.loads(res)
        results = ""
        for result in res['results']['bindings']:
            sub = result['s']['value'].replace(self.baseEntity, '')
            goout = float(result['o']['value'])
            alc = float(result['al']['value'])
            if (int(goout) > 2 and (int(alc) > 1)):
                results += sub + ' state ' + 'unhappy;'
        return results
Ejemplo n.º 28
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 .
Ejemplo n.º 29
0
class Database:
    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)


    def parse_artists(self, artist):
        artist = bytes(bytearray(artist, encoding='utf-8'))
        dom = ET.fromstring(artist)
        xslt = ET.parse("artists.xslt")
        transform = ET.XSLT(xslt)
        newdom = transform(dom)
        content = ET.tostring(newdom, pretty_print=False).decode()
        return content

    """api queries"""

    def new_releases(self, token):
        headers = {"Authorization": "Bearer " + token["access_token"]}
        r = requests.get('https://api.spotify.com/v1/browse/new-releases', headers=headers)
        xmlString = xmltodict.unparse(json.loads(r.text), pretty=True)
        file = open("new-releases.xml", "w")
        file.write(xmlString)

    def top_tracks(self, token):
        headers = {"Authorization": "Bearer " + token["access_token"]}
        r = requests.get('https://api.spotify.com/v1/me/top/tracks', headers=headers)
        xmlString = xmltodict.unparse(json.loads(r.text), pretty=True)
        file = open("top-tracks.xml", "w")
        file.write(xmlString)

    def recently_played_by_user(self, token):
        headers = {"Authorization": "Bearer " + token}
        r = requests.get('https://api.spotify.com/v1/me/player/recently-played', headers=headers)
        xmlString = dicttoxml.dicttoxml(json.loads(r.text))
        file = open("recently-played-by-user.xml", "wb")
        file.write(xmlString)

    @staticmethod
    def getArtistTop(token):
        headers = {"Authorization": "Bearer " + token}
        r = requests.get('https://api.spotify.com/v1/me/top/artists', headers=headers)
        xmlString = dicttoxml.dicttoxml(json.loads(r.text))
        file = open("artists.xml", "wb")
        file.write(xmlString)

    """database queries"""

    def comment(self, uid, name, text, music_id,comment_id):
        update = """
                    PREFIX foaf: <http://xmlns.com/foaf/spec/>
                    PREFIX spot: <http://comments.org/pred/>
                    INSERT DATA {
                        <http://comments.com/items/"""+music_id+"""> spot:comment_id <http://comments.com/items/"""+music_id+"""/"""+comment_id+"""> .
                        <http://comments.com/items/"""+music_id+"""/"""+comment_id+"""> spot:profile_name \""""+name+"""\";
                        spot:profile_id \""""+uid+"""\" ;
                        spot:comment \""""+text+"""\" .
                    }
                    """

        payload_query = {"update": update}
        self.accessor.sparql_update(body=payload_query, repo_name=self.repo_name)

    def delcomment(self, uid, name, music_id, comment_id):
        update = """
                    PREFIX foaf: <http://xmlns.com/foaf/spec/>
                    PREFIX spot: <http://comments.org/pred/>
                    DELETE
                    WHERE{
                        <http://comments.com/items/"""+music_id+"""> spot:comment_id <http://comments.com/items/"""+music_id+"""/"""+comment_id+"""> .
                    }
                    """

        payload_query = {"update": update}
        self.accessor.sparql_update(body=payload_query, repo_name=self.repo_name)

    def get_comments(self, music_id):
        query = """
                    PREFIX foaf: <http://xmlns.com/foaf/spec/>
                    PREFIX spot: <http://comments.org/pred/>
                    SELECT ?user_id ?name ?comment_id ?comment
                    WHERE{
                        <http://comments.com/items/"""+music_id+"""> spot:comment_id ?comment_id .
                        ?comment_id spot:profile_name ?name .
                        ?comment_id spot:profile_id ?user_id .
                        ?comment_id spot:comment ?comment .
                    }
                    """

        payload_query = {"query": query}
        data = json.loads(self.accessor.sparql_select(body=payload_query, repo_name=self.repo_name))
        data = parse_response(data)
        return data

    def get_new_releases(self):
        query = """
                PREFIX foaf: <http://xmlns.com/foaf/spec/>
                PREFIX spot: <http://new-releases.org/pred/>
                SELECT ?name ?id ?src ?width
				(GROUP_CONCAT(DISTINCT ?nameartist ; SEPARATOR=",") as ?artists)
				(GROUP_CONCAT(DISTINCT ?artist_id ; SEPARATOR=",") as ?ids)
                WHERE {
                    ?p foaf:name_album ?name .
                    ?p spot:id ?id .
                    ?p spot:image ?url .
                    ?url spot:width ?width .
                    ?url foaf:url ?src .
                    ?p spot:artists ?artists .
                    ?artists foaf:name ?nameartist .
                    ?artists spot:id ?artist_id .
                    filter regex(str(?url), "300" )
                }
				GROUP BY  ?name ?id ?src ?width
                """

        payload_query = {"query": query}
        data = json.loads(self.accessor.sparql_select(body=payload_query, repo_name=self.repo_name))
        data = parse_response(data)
        return data

    def get_top_tracks(self):
        query = """
                PREFIX foaf: <http://xmlns.com/foaf/spec/>
                PREFIX spot: <http://top-tracks.org/pred/>
                SELECT ?name ?id ?src ?ids ?artists ?width
				(GROUP_CONCAT(DISTINCT ?nameartist ; SEPARATOR=",") as ?artists)
				(GROUP_CONCAT(DISTINCT ?artist_id ; SEPARATOR=",") as ?ids)
                WHERE {
                    ?p foaf:name_track ?name . 
                    ?p spot:id ?id .
                    ?p spot:image ?url .
                    ?url spot:width ?width .
                    ?url foaf:url ?src .
                    ?p spot:artists ?artists .
                    ?artists foaf:name ?nameartist .
                    ?artists spot:id ?artist_id .
                    filter regex(str(?url), "300" )
                }
				GROUP BY  ?name ?id ?src ?width
				"""

        payload_query = {"query": query}
        data = json.loads(self.accessor.sparql_select(body=payload_query, repo_name=self.repo_name))
        data = parse_response(data)
        return data

    def get_recently_played_by_user(self):
        query = """
                PREFIX foaf: <http://xmlns.com/foaf/spec/>
                PREFIX spot: <http://recently-played-by-user.org/pred/>
                SELECT ?id ?name ?href30sec ?image ?artists
                (GROUP_CONCAT(DISTINCT ?nameartist ; SEPARATOR=",") as ?artists)
                WHERE {
                    ?p spot:track ?track .
                    ?track spot:id ?id .
                    ?track spot:preview_url ?href30sec .
                    ?track foaf:name ?name .
                    ?p spot:artists ?artist .
                    ?artist foaf:name ?nameartist .
                    ?p spot:image ?url .
                    ?url foaf:url ?image .
                    filter regex(str(?url), "300" )
                }
                GROUP BY ?id ?name ?href30sec ?image
                """

        payload_query = {"query": query}
        data = parse_response(json.loads(self.accessor.sparql_select(body=payload_query, repo_name=self.repo_name)))
        return data

    def get_artists_info(self):
        query = """
                PREFIX foaf: <http://xmlns.com/foaf/spec/>
                PREFIX spot: <http://artists.org/pred/>
                SELECT ?name ?id ?image ?followers
                WHERE {
                        ?p foaf:name_artist ?name .
                        ?p spot:id ?id .
                        ?p spot:followers ?followers .
                        ?p spot:image ?url .
                        ?url foaf:url ?image .
                        filter regex(str(?url), "300" )
                }"""

        payload_query = {"query": query}
        data = json.loads(self.accessor.sparql_select(body=payload_query, repo_name=self.repo_name))
        return ((data["results"]["bindings"]))

    def get_music_info(self, id, token=None):
        query = """
            PREFIX foaf: <http://xmlns.com/foaf/spec/>
            PREFIX spot: <http://top-tracks.org/pred/>
            SELECT ?name_track ?external_urls ?href ?disc_number ?popularity ?preview_url ?track_number ?artists
            (GROUP_CONCAT(DISTINCT ?nameartist ; SEPARATOR=",") as ?artists)
            (GROUP_CONCAT(DISTINCT ?images_url ; SEPARATOR=",") as ?image_url)
            (GROUP_CONCAT(DISTINCT ?artist_id ; SEPARATOR=",") as ?artists_ids)
            WHERE {
                ?id spot:id \""""+id+"""\" .
                ?id foaf:name_track ?name_track .
                ?id spot:external_urls ?external_urls .
                ?id spot:href ?href .
                ?id spot:disc_number ?disc_number .
                ?id spot:popularity ?popularity .
                ?id spot:preview_url ?preview_url .
                ?id spot:track_number ?track_number .
                ?id spot:artists ?artists .
                ?artists foaf:name ?nameartist .
                ?artists spot:id ?artist_id .
                ?id spot:image ?images .
                ?images foaf:url ?images_url .
            } GROUP BY ?name_track ?external_urls ?href ?disc_number ?popularity ?preview_url ?track_number
        """
        payload_query = {"query": query}
        data = parse_response(json.loads(self.accessor.sparql_select(body=payload_query, repo_name=self.repo_name)))

        if len(data) == 0:
            # means it's empty
            # new releases
            query = """
                PREFIX foaf: <http://xmlns.com/foaf/spec/>
                PREFIX spot: <http://new-releases.org/pred/>
                SELECT ?name_track ?external_urls ?href ?preview_url
                (GROUP_CONCAT(DISTINCT ?nameartist ; SEPARATOR=",") as ?artists)
                (GROUP_CONCAT(DISTINCT ?images_url ; SEPARATOR=",") as ?image_url)
                (GROUP_CONCAT(DISTINCT ?artist_id ; SEPARATOR=",") as ?artists_ids)
                WHERE {
                    ?id spot:id \""""+id+"""\" .
                    ?id foaf:name_album ?name_track .
                    ?id spot:external_urls ?external_urls .
                    ?id spot:href ?href .
				    OPTIONAL {?id spot:preview_url ?preview_url .}
                    ?id spot:artists ?artists .
                    ?artists foaf:name ?nameartist .
                    ?artists spot:id ?artist_id .
                    ?id spot:image ?images .
                    ?images foaf:url ?images_url .
                } GROUP BY ?name_track ?external_urls ?href ?preview_url
            """
            payload_query = {"query": query}
            data = parse_response(json.loads(self.accessor.sparql_select(body=payload_query, repo_name=self.repo_name)))

        if len(data) == 0:
            # means it's empty
            # recently played by user
            query = """
                    PREFIX foaf: <http://xmlns.com/foaf/spec/>
                    PREFIX spot: <http://recently-played-by-user.org/pred/>
                    SELECT ?name_track ?external_urls ?href ?preview_url
                    (GROUP_CONCAT(DISTINCT ?nameartist ; SEPARATOR=",") as ?artists)
                    (GROUP_CONCAT(DISTINCT ?artist_id ; SEPARATOR=",") as ?artists_ids)
                    (GROUP_CONCAT(DISTINCT ?image ; SEPARATOR=",") as ?image_url)
                    WHERE {
                        ?p spot:track ?track .
                        ?track spot:id \""""+id+"""\" .
                        ?track spot:preview_url ?preview_url .
                        ?track spot:external_urls ?external_urls .
                        ?track foaf:name ?name_track .
                        ?track spot:href ?href .
                        ?p spot:artists ?artist .
                        ?artist foaf:name ?nameartist .
                        ?artist spot:id ?artist_id .
                        ?p spot:image ?url .
                        ?url foaf:url ?image .
                    }
                    GROUP BY ?name_track ?external_urls ?href ?preview_url
                """
            payload_query = {"query": query}
            data = parse_response(json.loads(self.accessor.sparql_select(body=payload_query, repo_name=self.repo_name)))

        if len(data) == 0 and token is not None:
            # means it's empty
            # get track from spotify
            data = {
                "name_track": "",
                "popularity": 0,
                "track_number": 1,
                "preview_url": "",
                "image_url": [],
                "href": "",
                "external_urls": "",
                "disc_number": 1,
                "artists_ids": [],
                "artists": []
            }

            # Get track
            headers = {"Authorization": "Bearer " + token}
            r = requests.get('https://api.spotify.com/v1/tracks/' + id, headers=headers)
            r = json.loads(r.text)

            if "name" in r:
                data["name_track"] = r["name"]

            if "popularity" in r:
                data["popularity"] = r["popularity"]

            if "track_number" in r:
                data["track_number"] = r["track_number"]

            if "preview_url" in r:
                data["preview_url"] = r["preview_url"]

            if "album" in r and "images" in r["album"]:
                data["image_url"] = [image["url"] for image in r["album"]["images"]]

            if "href" in r:
                data["href"] = r["href"]

            if "external_urls" in r:
                data["external_urls"] = r["external_urls"]["spotify"]

            if "disc_number" in r:
                data["disc_number"] = r["disc_number"]

            if "artists" in r:
                data["artists"] = [artist["name"] for artist in r["artists"]]

            if "artists_ids" in r:
                data["artists_ids"] = [artist["id"] for artist in r["artists"]]

        return data

    def search_artists(self, name):
        query = """
            PREFIX foaf:  <http://xmlns.com/foaf/spec/>
            PREFIX spot:  <http://new-releases.org/pred/>
            PREFIX spot2: <http://top-tracks.org/pred/>
            PREFIX spot3: <http://recently-played-by-user.org/pred/>
            PREFIX rdfs:  <http://www.w3.org/2000/01/rdf-schema#>

            SELECT ?nameartist (SAMPLE(?artist_id) AS ?artist_id)  {
                {
                    SELECT ?nameartist ?artist_id
                    WHERE {
                        ?p spot:artists ?artists .
                        ?artists foaf:name ?nameartist .
                        ?artists spot:id ?artist_id .
                    }
                }UNION {
                    SELECT ?nameartist ?artist_id
                    WHERE {
                        ?p spot2:artists ?artists .
                        ?artists foaf:name ?nameartist .
                        ?artists spot2:id ?artist_id .
                    }

                }UNION {
                    SELECT ?nameartist ?artist_id
                    WHERE {
                        ?p spot3:track ?track .
                        ?p spot3:artists ?artists .
                        ?artists foaf:name ?nameartist .
                        ?artists spot3:id ?artist_id .
                    }
                }
                FILTER(REGEX(STR(?nameartist), "%s.*$", "i"))
            } GROUP BY ?nameartist
        """ % name

        payload_query = {"query": query}
        data = parse_response(json.loads(self.accessor.sparql_select(body=payload_query, repo_name=self.repo_name)))

        return data

    def search_musics_and_albums(self, name):
        query = """
            PREFIX foaf:  <http://xmlns.com/foaf/spec/>
            PREFIX spot:  <http://new-releases.org/pred/>
            PREFIX spot2: <http://top-tracks.org/pred/>
            PREFIX spot3: <http://recently-played-by-user.org/pred/>
            PREFIX rdfs:  <http://www.w3.org/2000/01/rdf-schema#>

            SELECT DISTINCT ?name ?id  {
                {
                    # new releases
                    SELECT ?name ?id ?name_artist
                    WHERE {
                        ?p foaf:name_album ?name .
                        ?p spot:id ?id .
                        ?p spot:artists ?artists .
                        ?artists foaf:name ?name_artist
                    }
                }UNION {
                    # top tracks
                    SELECT ?name ?id
                    WHERE {
                        ?p foaf:name_track ?name .
                        ?p spot2:id ?id .
                        ?p spot2:artists ?artists .
                        ?artists foaf:name ?name_artist
                    }

                }UNION {
                    # recent played by user
                    SELECT ?name ?id
                    WHERE {
                        ?p spot3:track ?track .
                        ?track foaf:name ?name .
                        ?track spot3:id ?id .
                        ?p spot:artists ?artist .
                        ?artist foaf:name ?name_artist .
                    }
                }
                FILTER(REGEX(STR(?name), "%s.*$", "i") || REGEX(STR(?name_artist), "%s.*$", "i"))
            }
        """ % (name, name)

        payload_query = {"query": query}
        data = parse_response(json.loads(self.accessor.sparql_select(body=payload_query, repo_name=self.repo_name)))

        return data

    def get_best_followers(self):
        query = """
            PREFIX foaf:  <http://xmlns.com/foaf/spec/>
            PREFIX spot:  <http://artists1.org/pred/>
            
            PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
            SELECT ?name ?popularity ?id
                where {
                    ?p spot:id ?id .
                    ?p foaf:name ?name .
                    ?p spot:popularity ?popularity .
    				
                    
            } order by  DESC(xsd:integer(?popularity))
            limit 10
        """

        payload_query = {"query": query}
        data = parse_response(json.loads(self.accessor.sparql_select(body=payload_query, repo_name=self.repo_name)))
        return data



    def platform_data(self):
        query = """
            PREFIX foaf:  <http://xmlns.com/foaf/spec/>
            PREFIX spot:  <http://new-releases.org/pred/>
            PREFIX spot2: <http://top-tracks.org/pred/>
            PREFIX spot3: <http://recently-played-by-user.org/pred/>
            PREFIX rdfs:  <http://www.w3.org/2000/01/rdf-schema#>

            SELECT ?count {
                {
                    # counting artists [0]
                    SELECT (count(distinct ?nameartist) as ?count)  {
                    {
                        SELECT ?nameartist
                        WHERE {
                            ?p spot:artists ?artists .
                            ?artists foaf:name ?nameartist .
                        }
                    }UNION {
                        SELECT ?nameartist ?artist_id
                        WHERE {
                            ?p spot2:artists ?artists .
                            ?artists foaf:name ?nameartist .
                        }

                    }UNION {
                        SELECT ?nameartist
                        WHERE {
                            ?p spot3:track ?track .
                            ?p spot3:artists ?artists .
                            ?artists foaf:name ?nameartist .
                        }
                    }
                }
                }   UNION {
                    # counting musics [1]
                    SELECT (count(distinct ?name) as ?count)  {
                        {
                            # new releases
                            SELECT ?name ?id ?name_artist
                            WHERE {
                                ?p foaf:name_album ?name .
                                ?p spot:id ?id .
                                ?p spot:artists ?artists .
                                ?artists foaf:name ?name_artist
                            }
                        }UNION {
                            # top tracks
                            SELECT ?name ?id
                            WHERE {
                                ?p foaf:name_track ?name .
                                ?p spot2:id ?id .
                                ?p spot2:artists ?artists .
                                ?artists foaf:name ?name_artist
                            }

                        }UNION {
                            # recent played by user
                            SELECT ?name ?id
                            WHERE {
                                ?p spot3:track ?track .
                                ?track foaf:name ?name .
                                ?track spot3:id ?id .
                                ?p spot:artists ?artist .
                                ?artist foaf:name ?name_artist .
                            }
                        }
                    }
                } UNION {
                    # counting images [2]
                    SELECT (count(distinct ?src) as ?count)  {
                        {
                            # new releases
                            SELECT ?src
                            WHERE {
                                ?p spot:id ?id .
                                ?p spot:image ?url .
                                ?url foaf:url ?src .
                            }
                        }UNION {
                            # top tracks
                            SELECT ?src
                            WHERE {
                                ?p foaf:name_track ?name .
                                ?p spot2:id ?id .
                                ?p spot2:image ?url .
                                ?url foaf:url ?src .
                            }
                        }UNION {
                            # recent played by user
                            SELECT ?src
                            WHERE {
                                ?p spot3:track ?track .
                                ?track spot3:id ?id .
                                ?track spot3:preview_url ?href30sec .
                                ?track foaf:name ?name .
                                ?p spot3:image ?src .
                            }
                        }
                    }
                } UNION {
                    # counting albums [3]
                    SELECT (count(distinct ?id) as ?count)  {
                        {
                            # new releases
                            SELECT ?id
                            WHERE {
                                ?p spot:id ?id .
                            }
                        }UNION {
                            # top tracks
                            SELECT ?id
                            WHERE {
                                ?p spot2:album ?album .
                                ?album spot2:id ?id .
                            }
                        }UNION {
                            # recent played by user
                            SELECT ?src
                            WHERE {
                                ?p spot3:album ?album .
                                ?album spot3:id ?id .
                            }
                        }
                    }
                }
            }

        """
        payload_query = {"query": query}
        data = parse_response(json.loads(self.accessor.sparql_select(body=payload_query, repo_name=self.repo_name)))

        return data

    def get_artists(self):
        query = """
            PREFIX foaf:  <http://xmlns.com/foaf/spec/>
            PREFIX spot1:  <http://new-releases.org/pred/>
            PREFIX spot2:  <http://recently-played-by-user.org/pred/>
            PREFIX spot3:  <http://top-tracks.org/pred/>
            
            PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
            
            SELECT distinct ?name ?id
            where {
                {
                    ?p spot1:artists ?artists .
                    ?artists spot1:id ?id .
                    ?artists foaf:name ?name .
                    
                }
                union
                {
                    ?p spot2:artists ?artists .
                    ?artists foaf:name ?name .
                    ?artists spot2:id ?id .
                }
                 union
                {
                    ?p spot3:artists ?artists .
                    ?artists foaf:name ?name .
                    ?artists spot3:id ?id .
                }
            }
        """

        payload_query = {"query": query}
        data = parse_response(json.loads(self.accessor.sparql_select(body=payload_query, repo_name=self.repo_name)))
        return data

    def put_artist(self,headers,name,id):

        r = requests.get('https://api.spotify.com/v1/artists/'+id, headers=headers)
        r = json.loads(r.text)
        m = requests.get('https://api.spotify.com/v1/artists/'+id+'/top-tracks?country=PT', headers=headers)
        m = json.loads(m.text)

        self.put_top_tracks(m,id)

        update = """
        PREFIX spot:<http://artists1.org/pred/>
        PREFIX foaf:<http://xmlns.com/foaf/spec/>
        
        INSERT DATA
        {
             <http://artists1.com/itens/"""+id+"""> foaf:name '"""+name+"""' .
             <http://artists1.com/itens/"""+id+"""> spot:id  '"""+id+"""'.
             <http://artists1.com/itens/"""+id+"""> spot:followers  '"""+str(r['followers']['total'])+"""'.
             <http://artists1.com/itens/"""+id+"""> spot:image  '"""+str(r['images'][0]['url'])+"""'.
             <http://artists1.com/itens/"""+id+"""> spot:popularity  '"""+str(r['popularity'])+"""' .
             """
        for genre in r['genres']:
            update += """<http://artists1.com/itens/"""+id+"""> spot:genre  '"""+str(genre)+"""' . """

        update += """}"""

        payload_query = {"update": update}
        res = self.accessor.sparql_update(body=payload_query,repo_name=self.repo_name)


    def put_top_tracks(self,m,id):

        for music in m['tracks']:
            update = """
            PREFIX spot:<http://top.org/pred/>
            PREFIX foaf:<http://xmlns.com/foaf/spec/>
            PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

            INSERT DATA
            {
                 <http://top.com/itens/"""+ id +"""> spot:id <http://top.com/itens/""" + id + """/"""+str(music['id'])+"""> .
                 <http://top.com/itens/""" + id + """/"""+str(music['id'])+"""> spot:duration  '""" + str(self.mili2Time(music['duration_ms'])) + """'.
                 <http://top.com/itens/""" + id + """/"""+str(music['id'])+"""> spot:id  '""" + str(music['id']) + """'.
                 <http://top.com/itens/""" + id + """/"""+str(music['id'])+"""> spot:name  '""" + str(music['name']) + """'.
                 <http://top.com/itens/""" + id + """/"""+str(music['id'])+"""> spot:album  '""" + str(music['album']['name']) + """'.
                 <http://top.com/itens/""" + id + """/"""+str(music['id'])+"""> spot:popularity  '""" + str(music['popularity']) + """' .                
            }
            """

            payload_query = {"update": update}
            res = self.accessor.sparql_update(body=payload_query, repo_name=self.repo_name)

    def get_top_music(self,id):
        query = """
            PREFIX foaf:  <http://xmlns.com/foaf/spec/>
            PREFIX spot:  <http://top.org/pred/>
            SELECT ?name ?duration ?album ?popularity ?musicId
            where {
                <http://top.com/itens/"""+id+"""> spot:id ?id .
                ?id spot:name ?name ;
                    spot:duration ?duration ;
                    spot:album ?album ;
                    spot:popularity ?popularity ;
                    spot:id ?musicId
            }
        """

        payload_query = {"query": query}
        data = parse_response(json.loads(self.accessor.sparql_select(body=payload_query, repo_name=self.repo_name)))
        return data

    def get_artist_info(self,id):
        query = """
            PREFIX foaf:  <http://xmlns.com/foaf/spec/>
            PREFIX spot:  <http://artists1.org/pred/>
            SELECT ?name ?followers ?image ?popularity
            where {
                    <http://artists1.com/itens/"""+id+"""> foaf:name ?name ;
                        spot:id ?id ;
                        spot:followers ?followers ;
                        spot:image ?image ;
                        spot:popularity ?popularity .
            } 
        """

        payload_query = {"query": query}
        data = parse_response(json.loads(self.accessor.sparql_select(body=payload_query, repo_name=self.repo_name)))
        return data

    def mili2Time(self,mili):
        mili = int(mili)
        seconds = (mili / 1000) % 60
        seconds = str(int(seconds))
        minutes = (mili / (1000 * 60)) % 60
        minutes = str(int(minutes))

        time = minutes+":"+seconds
        return time
Ejemplo n.º 30
0
# AUTH AND ENDPOINT PREPARATION
api_key = ""  # change this
key_secret = ""  # change this

repo_name = "my_repo"

# add screenshot with exact location to copy this from
endpoint = "https://rdf.s4.ontotext.com/4830401327/TesterDataBase"


# INITIALIZE CLIENT OBJECT
client = ApiClient(
    api_key=api_key, key_secret=key_secret,
    endpoint=endpoint)
# INITIALIZE ACCESSOR OBJECT
accessor = GraphDBApi(client)


# CREATE REPOSITORY
# For a list of all supported rulesets, please visit .....
payload = {
    "repositoryID": repo_name,
    "label": "Description of your database",
    "ruleset": "owl-horst-optimized"
}
print("create first repo")  # won't show on the examples
print(accessor.create_repository(body=payload))


# DELETE REPOSITORY
print("delete repo")  # won't show on the examples
Ejemplo n.º 31
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)