コード例 #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)
コード例 #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)
コード例 #3
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)
コード例 #4
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('/')
コード例 #5
0
ファイル: views.py プロジェクト: chiplo1/edcproj2
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})
コード例 #6
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
コード例 #7
0
ファイル: views.py プロジェクト: chiplo1/edcproj2
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})
コード例 #8
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})
コード例 #9
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)
コード例 #10
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)
コード例 #11
0
ファイル: views.py プロジェクト: chiplo1/edcproj2
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})