def seen_by_friends(request):
	
	userUri = URIRef( request.user.get_profile().uri )
	
	seen_by_me = graph.query("""SELECT ?m WHERE {
				?me smdb:hasSeen ?m .
				}""", initBindings={'me': userUri})
	
	res = graph.query("""SELECT ?m ?t ?f WHERE {
				?m rdf:type smdb:Movie .
				?m smdb:title ?t .
				?f smdb:hasSeen ?m .
				?f smdb:isFriendsWith ?me .
				}""", initBindings={'me': userUri})
	
	#pprint(res)
	
	res = [ (m, t, f) for (m, t, f) in res if m not in seen_by_me]
	
	sorted_res = sort_by_count(res, [0,1], 2)
	sorted_res = sorted_res[:5]
	sorted_res = [ el[0] + (el[1],) for el in sorted_res ]	# Flatten the results so that it's (uri, title, friend, score)
	
	#pprint(sorted_res)
	
	return sorted_res
def recommended_users(request):
	userUri = URIRef(request.user.get_profile().uri)
	
	friends = graph.query("""SELECT ?u WHERE {
					?u smdb:isFriendsWith ?me .
					}""", initBindings={'me': userUri})

	res = graph.query("""SELECT ?u ?f WHERE {
					?u rdf:type smdb:SMDBUser .
					?u smdb:hasSeen ?m .
					?me smdb:hasSeen ?m .
					OPTIONAL{ ?me smdb:isFriendsWith ?f . ?u smdb:isFriendsWith ?f } .
					FILTER( ?u != ?me) .
					}""", initBindings={'me': userUri})
					

	res = [ (SMDBUser(u), f) for (u, f) in res if u and u not in friends]
	
	sorted_res = sort_by_count(res, [0], 1)
	sorted_res = sorted_res[:4]
	sorted_res = [ el[0] + (el[1],) for el in sorted_res ]	# Flatten the results so that it's (uri, title, friend, score)
	
	#for r in sorted_res: print r
	
	return sorted_res
def movie_suggestions(uri):
	
	related = dict()
	titles = dict()
	
	query = """SELECT DISTINCT ?m ?t ?g WHERE{
				<%s> smdb:isOfGenre ?g .
				?m smdb:isOfGenre ?g .
				?m smdb:title ?t .
				FILTER( ?m != <%s> ).
				}
			""" % (uri,uri)


	sameGenre = graph.query(query)
	
	for movie in sameGenre:
		if movie[0] in related.keys():
			related[movie[0]] += 1
		else:
			related[movie[0]] = 1
			titles[movie[0]] = movie[1]
	
	query = """SELECT DISTINCT ?m ?p ?t WHERE{
				?p ?r1 <%s> .
				?p ?r ?m .
				?m smdb:title ?t .
				?r rdfs:subPropertyOf smdb:participatedInMovie .
				?r1 rdfs:subPropertyOf smdb:participatedInMovie .
				FILTER( ?m != <%s> ) .
				}
			""" % (uri, uri)
	
			
	samePeople = graph.query(query)
	
	
	for movie in samePeople:
		if movie[0] in related.keys():
			related[movie[0]] += 1
		else:
			related[movie[0]] = 1
			titles[movie[0]] = movie[2]
	
	
	results = [ [uri, titles[uri], related[uri]] for uri in related.keys() ]
	
	sortedResults = sorted(results, key = lambda pair : pair[2], reverse = True )
	
	#for result in sortedResults:
	#	print result
		
	return sortedResults[:5]
def browse_users(filters, user):
	userUri = URIRef(user.get_profile().uri) if user.is_authenticated() else ''
	
	initBindings = {}
	
	filterToQuery = { 'similar': '<%s> smdb:hasSeen ?m1 .\n ?u smdb:hasSeen ?m1 .\n' % userUri,
					  'foaf': '<%s> smdb:isFriendsWith ?u1 .\n ?u smdb:isFriendsWith ?u1 .\n' % userUri,
					  'reviewer': '?r1 smdb:writtenByUser ?u .\n',
					}
	
	f = SMDBUser.getFilterList(user.is_authenticated(), filters)
	
	query = """SELECT DISTINCT ?u ?m1 ?u1 WHERE {
				?u rdf:type smdb:SMDBUser .
				?u smdb:username ?un . 
			"""
	
	for o in filters:
		if o in filterToQuery: query += filterToQuery[o]
	
	if 'similar' in filters or 'foaf' in filters: query += """FILTER(?u != <%s>) .\n""" % userUri
	
	res = graph.query(query + "OPTIONAL { ?u smdb:fullName ?fn . }}", initBindings=initBindings)
	res = merge_results(res, filters)
	
	return [f, res]
	def get_actor_character(self):
		for uriActor, uriCharacter in graph.query("""SELECT ?a ?c WHERE {
										?a smdb:performedIn ?u.
										?c smdb:inMovie ?u .
										?c smdb:portrayedBy ?a .
										}""", initBindings={'u': self.uri}):
			yield Person(uriActor), Character(uriCharacter)
def browse_movies(year, director, genre, location, rating):
	initBindings = {}
	
	f = Movie.getFilterList(year, director, genre, location, rating)
	
	query = """SELECT ?a ?b ?y WHERE {
				?a rdf:type smdb:Movie .
				?a smdb:title ?b .
				?a smdb:releaseDate ?y .
				"""
	
	# Query additions
	if director: query += '?d smdb:directed ?a .\n'
	if genre: query += '?a smdb:isOfGenre ?g .\n'
	if location: query += '?a smdb:shotIn ?l .\n'
	if rating: query += '?a smdb:hasRating ?r .\n'
	
	# Filters	
	if year: query += """FILTER(?y = "%s") .\n""" % Literal(year)
	if director: query += """FILTER(?d = <%s>) .\n""" % URIRef(director)
	if genre: query += """FILTER(?g = <%s>) .\n""" % graph.ontologies['smdb'][genre]
	if location: query += """FILTER(?l = "%s") .\n""" % Literal(location)
	if rating: query += """FILTER(?r = <%s>) .\n""" % URIRef(rating)
	
	res = graph.query(query + "} ORDER BY ?y", initBindings=initBindings)
	
	return [f, res]
	def get_movie_actors(self):
		for uriMovie, uriActor, year in graph.query("""SELECT ?m ?a ?y WHERE {
										?a smdb:performedIn ?m.
										?c smdb:inMovie ?m .
										?m smdb:releaseDate ?y .
										?c smdb:portrayedBy ?a .
										} ORDER BY ?y""", initBindings={'c': self.uri}):
			yield Movie(uriMovie), Person(uriActor)
	def get_movie_characters(self):
		for uriMovie, uriCharacter, year in graph.query("""SELECT ?m ?c ?y WHERE {
										?a smdb:performedIn ?m.
										?c smdb:inMovie ?m .
										?m smdb:releaseDate ?y .
										?c smdb:portrayedBy ?a .
										} ORDER BY ?y""", initBindings={'a': self.uri}):
			yield Movie(uriMovie), Character(uriCharacter)
	def getFilterList(model, year=None, director=None, genre=None, location=None, rating=None):
		
		# Define the filtering rules so that we can filter the options themselves
		f_rules = [
					"?m smdb:releaseDate \"%s\" . " % Literal(year) if year else "",
					"<%s> smdb:directed ?m . " % URIRef(director) if director else "",
					"?m smdb:isOfGenre smdb:%s . " % URIRef(genre) if genre else "",
					"?m smdb:shotIn \"%s\" . " % Literal(location) if location else "",
					"?m smdb:hasRating <%s> . " % URIRef(rating) if rating else "",
				]
		
		# Years
		years = graph.query("SELECT DISTINCT ?y WHERE { ?m smdb:releaseDate ?y . %s} ORDER BY ?y" \
				% ( ''.join(f_rules) ), initBindings={'y':Literal(year)} if year else {})
		
		# Directors
		directors = graph.query("SELECT DISTINCT ?n ?d WHERE { ?d smdb:name ?n . ?d smdb:directed ?m . %s}" \
				% ( ''.join(f_rules) ), initBindings={'d':URIRef(director)} if director else {})
		
		# Genre
		genres = graph.query("""SELECT DISTINCT ?g WHERE {
				?u rdfs:subClassOf smdb:Genre . ?m smdb:isOfGenre ?u . ?u rdfs:label ?g .%s }""" \
				% ( ''.join(f_rules) ), initBindings={'g':Literal(genre, datatype=graph.ontologies['xsd'].string)} if genre else {})
				
		
		# Location
		locations = graph.query("SELECT DISTINCT ?l WHERE { ?m smdb:shotIn ?l . %s}" \
				% ( ''.join(f_rules) ), initBindings={'l':Literal(location)} if location else {})
		
		# Rating
		ratings = graph.query("""SELECT DISTINCT ?r ?u WHERE {
				?u rdfs:subClassOf smdb:MPAA_Rating . ?u rdfs:label ?r . ?m smdb:hasRating ?u . %s} ORDER BY ?r
				"""% ( ''.join(f_rules) ), initBindings={'u':URIRef(rating)} if rating else {})
		
		ratings = [ (label.split(' ')[0], uri) for (label, uri) in ratings ]	# Make the label shorter
		
		return [
			Filter(header='Genre', label='genre', obj_list=genres, target_o=genre),
			Filter(header='Director', label='director', obj_list=directors, target_o=director),
			Filter(header='Year', label='year', obj_list=years, target_o=year),
			Filter(header='Shot In', label='location', obj_list=locations, target_o=location),
			Filter(header='Rating', label='rating', obj_list=ratings, target_o=rating),
		]
Beispiel #10
0
def get_objects(tp,dic):
	q = ['%s rdf:type me:%s' % (obj_dic[tp][1],tp)]
	for k in dic.keys():
		if k != tp:
			q.append('%s me:%s %s' % (obj_dic[tp][1],obj_dic[k][0],obj_dic[k][1]) )
			q.append('%s rdf:type me:%s' % (obj_dic[k][1],k) )	
		for i in dic[k]:
			q.append('%s me:%s %s' % (obj_dic[k][1],i[0],i[1]))
			if len(i) == 3: #Filter
				q.append(i[2])
	s = " . ".join(q)
	qy = """ SELECT %s WHERE { %s . } """ % (obj_dic[tp][1],s)
	print qy
	return map(lambda inst: obj_dic[tp][2](inst), list(set(graph.query(qy))) )
def popular_movies():
				
	res = graph.query("""SELECT ?m ?t ?u WHERE {
				?m rdf:type smdb:Movie .
				?m smdb:title ?t .
				OPTIONAL{ ?u smdb:hasSeen ?m . }
				}""", initBindings={})
	
	#pprint(res)
	
	sorted_res = sort_by_count(res, [0,1], 2)
	sorted_res = sorted_res[:5]
	sorted_res = [ el[0] + (el[1],) for el in sorted_res ]	# Flatten the results so that it's (uri, title, score)
	
	#pprint(sorted_res)
	
	return sorted_res
def get_favorite_directors(user):
	res = dict()

	query = """SELECT DISTINCT ?m ?p WHERE{
				?m rdf:type smdb:Movie .
				<%s> smdb:hasSeen ?m .
				?p smdb:directed ?m .
				}""" % user

	directors = graph.query(query)

	for director in directors:
		if director[1] in res.keys():
			res[director[1]] += 1
		else:
			res[director[1]] = 1

	return res
def get_favorite_writers(user):
	res = dict()

	query = """SELECT DISTINCT ?m ?p WHERE{
				?m rdf:type smdb:Movie .
				<%s> smdb:hasSeen ?m .
				?p smdb:wrote ?m .
				}""" % user

	writers = graph.query(query)

	for writer in writers:
		if writer[1] in res.keys():
			res[writer[1]] += 1
		else:
			res[writer[1]] = 1

	return res
def get_favorite_genres(user):
	res = dict()
	
	query = """SELECT DISTINCT ?m ?g WHERE{
				?m rdf:type smdb:Movie .
				<%s> smdb:hasSeen ?m .
				?m smdb:isOfGenre ?g .
				}""" % user
				
	genres = graph.query(query)
	
	for genre in genres:
		if genre[1] in res.keys():
			res[genre[1]] += 1
		else:
			res[genre[1]] = 1
	
	return res
def browse_people(occupations):
	initBindings = {}
	
	occupationToQuery = { 'writer': '?u smdb:wrote ?m1 .\n',
						  'actor': '?u smdb:performedIn ?m2 .\n',
						  'director': '?u smdb:directed ?m3 .\n',
						}
	
	
	f = Person.getFilterList(occupations)
	
	query = """SELECT DISTINCT ?u ?n WHERE {
				?u rdf:type smdb:Person .
				?u smdb:name ?n .
				"""
	
	for o in occupations:
		if o in occupationToQuery: query += occupationToQuery[o]
	
	res = graph.query(query + "}", initBindings=initBindings)
	return [f, res]
def movies_of_the_year():
	# This is popular_movies filtered by the current year
	
	year = datetime.datetime.now().year
	
	res = graph.query("""SELECT ?m ?t ?u WHERE {
				?m rdf:type smdb:Movie .
				?m smdb:title ?t .
				?m smdb:releaseDate "%s" .
				OPTIONAL{ ?u smdb:hasSeen ?m . }
				}""" % Literal(year), initBindings={})
	
	#pprint(res)
	
	sorted_res = sort_by_count(res, [0,1], 2)
	sorted_res = sorted_res[:5]
	sorted_res = [ el[0] + (el[1],) for el in sorted_res ]	# Flatten the results so that it's (uri, title, score)
	
	#pprint(sorted_res)
	
	return sorted_res
def person_suggestions(uri):
	
	score = dict()
	name = dict()
	
	query = """SELECT DISTINCT ?p ?n ?m WHERE {
				?m rdf:type smdb:Movie .
				<%s> ?r ?m .
				?r rdfs:subPropertyOf smdb:participatedInMovie .
				?p ?r1 ?m .
				?r1 rdfs:subPropertyOf smdb:participatedInMovie .
				?p smdb:name ?n .
				FILTER( ?p != <%s> ) .
			}
			""" % (uri,uri)
	
	relatedPeople = graph.query(query)
	
	for person in relatedPeople:
		if person[0] in score.keys():
			score[person[0]] += 1
		else:
			score[person[0]] = 1
			name[person[0]] = person[1]
		
	
	results = [ [uri, name[uri], score[uri]] for uri in score.keys() ]
	
	sortedResults = sorted(results, key = lambda pair : pair[2], reverse = True )
	
	#for result in sortedResults[:5]:
	#	print results
	
	res = sortedResults[:5]
	
	for r in res:
		if r[1] == 0:
			res.remove(r)
	
	return res
	def friends_who_watched(self, user):
		for uri in graph.query("""SELECT ?u WHERE {
										?u smdb:hasSeen ?m .
										?u smdb:isFriendsWith ?me .
										}""", initBindings={'m': self.uri, 'me': URIRef(user)}):
			yield SMDBUser(uri) 
Beispiel #19
0
	def single_query(self,prop,func):
		for p in graph.query(""" SELECT ?prop WHERE { ?inst me:%s ?prop . } """ % prop, initBindings={'inst': self.uri}):
			return func(p)
Beispiel #20
0
	def inverse_multiple_query(self,prop,func):
		return map(lambda a: func(a), graph.query(""" SELECT ?ev WHERE { ?ev me:%s ?art . } """ % prop, initBindings={'art': self.uri}))
Beispiel #21
0
	def has_more_artists(self):
		return len(graph.query(""" SELECT ?art WHERE { ?ev me:performed_by ?art . } """, initBindings={'ev': self.uri})) > 1
def recommended_movies(request):
	
	userURI = request.user.get_profile().uri
	related = dict()
	titles = dict()
	
	favGenres = get_favorite_genres(userURI)
	favDirectors = get_favorite_directors(userURI)
	favWriters = get_favorite_writers(userURI)
	
	#for director in zip(favDirectors.keys(), favDirectors.values()): print director
		
	#for writer in zip(favWriters.keys(), favWriters.values()): print writer
			
	#for genre in zip(favGenres.keys(), favGenres.values()): print genre
	
	query = """SELECT DISTINCT ?m ?f ?u ?t WHERE {
						?m rdf:type smdb:Movie .
						?m smdb:title ?t .
						OPTIONAL{ ?f smdb:hasSeen ?m .
								  ?f smdb:isFriendsWith <%s> .
								  } .
						OPTIONAL{ ?u smdb:hasSeen ?m .
								  FILTER( ?u = <%s>) . 
								  } .
						}""" % (userURI, userURI)
	
	#print query
	
	notSeen = graph.query(query)
	
	for movie in notSeen:
		if not movie[2]:
			if movie[0] in related.keys():
				related[movie[0]] += 1
			else:
				titles[movie[0]] = movie[3]
				if movie[1]:
					related[movie[0]] = 1
				else:
					related[movie[0]] = 0
	
	#for movie in zip(related.keys(), related.values()):
	#	print movie
	
	genreQuery = """SELECT DISTINCT ?m ?g WHERE {
					?m rdf:type smdb:Movie . 
					?m smdb:isOfGenre ?g . 
					}"""
					
	allGenres = graph.query(genreQuery)	
	
	
	directorQuery = """SELECT DISTINCT ?m ?p WHERE {
					?m rdf:type smdb:Movie .
					?p smdb:directed ?m .
					}"""
	
	allDirectors = graph.query(directorQuery)
	
	
	writerQuery = """SELECT DISTINCT ?m ?p WHERE {
					?m rdf:type smdb:Movie .
					?p smdb:wrote ?m .
					}"""
	
	allDirectors = graph.query(writerQuery)
	
	
	for movie in allGenres:
		if movie[1] in favGenres.keys() and movie[0] in related.keys():
			related[movie[0]] += favGenres[movie[1]]
	
	for movie in allDirectors:
		if movie[1] in favDirectors.keys() and movie[0] in related.keys():
			related[movie[0]] += favDirectors[movie[1]]

	for movie in allGenres:
		if movie[1] in favWriters.keys() and movie[0] in related.keys():
			related[movie[0]] += favWriters[movie[1]]
	
	
	
	results = [ [uri, titles[uri], related[uri]] for uri in related.keys() ]
	
	sortedResults = sorted(results, key = lambda pair : pair[2], reverse = True )
	
	#for result in sortedResults: print result
		
	return sortedResults[:5]
Beispiel #23
0
def event_search(request):
	d = {'artist':(['Performer','Name','?an'],[]),'event':(['Event','Name','?en'],[]),'day':(['Date','DayNumber','?dn'],[]),'month':(['Date','MonthName','?mn'],[]),'year':(['Date','Year','?y'],[]),'hour':(['Date','Hour','?h'],[]),'place':(['Place','Locality','?lo'],[]),'genre':(['Performer','Genre','?g'],[])}
	ambiguous = []
	l = []
	event_list = []
	dics = []
	words = request.GET['search_words'].split()
	weight = len(words)
	print words
	for word in words:
		if l:
			if l[0] in d.keys():
				d[l[0]][1].append((word,weight))
				l.pop()
			elif word in d.keys():
				d[word][1].append((l[0],weight))
				l.pop()
			else:
				ambiguous.append((l.pop(),weight))
				l.append(word)
			weight -= 1
		else:
			l.append(word)
	if l:
		ambiguous.append((l.pop(),weight))	
	
	print ambiguous
	print d
	
	for i in d.keys():
		wds = d[i][1]
		for j in wds:			
			if i in ['day','year','hour']:
				try: 
					val = int(j[0])
					prop = (d[i][0][1],j[0])
				except:
					continue
			else:
				f = 'FILTER (regex(%s, "%s+?", "i"))' % (d[i][0][2],j[0])
				prop = (d[i][0][1],d[i][0][2],f)
				
			evts = get_objects('Event', {d[i][0][0]:[prop]} )
			for e in evts:
				e.weight = j[1]
			dics.append(evts)
	
	for i in ambiguous:
		val = i[0]
		q1 = '''?ev rdf:type me:Event . ?ev me:Name ?ename .
		?ev me:starts_at ?d . ?d me:DayNumber ?dnm . ?d me:MonthName ?mnm . ?d me:Year ?y . ?d me:Hour ?h . 
		?ev me:performed_by ?art . ?art me:Name ?aname . ?art me:Genre ?gr . 
		?ev me:takes_place ?p . ?p me:Locality ?l . 
		FILTER ( regex(?ename, "%s+?", "i") || regex(?edes, "%s+?", "i") || regex(?dnm, "%s+?", "i") || 
		regex(?mnm, "%s+?", "i") || regex(?y, "%s+?", "i") || regex(?h, "%s+?", "i") || regex(?aname, "%s+?", "i") || 
		regex(?gr, "%s+?", "i") || regex(?l, "%s+?", "i"))''' % (val,val,val,val,val,val,val,val,val)
		q = """ SELECT ?ev WHERE { %s . } """ % (q1)
		evts = map(lambda a: Event(a), list(set(graph.query(q))) ) 
		for e in evts:
			e.weight = i[1]
		dics.append(evts)
	
	if dics:
		event_list = reduce(event_match,dics)
		event_list = sorted(event_list,cmp= lambda a,b: cmp(b.weight,a.weight))
	
	res = len(event_list)
	
	return render(request,'events/event_list.html', {'event_list' : event_list, 'results' : res})