+class PictureResult(object):
+ def __init__(self, doc, how_found=None, query_terms=None):
+ self.boost = 1.0
+ self.query_terms = query_terms
+ self._picture = None
+ self._hits = []
+ self._processed_hits = None
+
+ if 'score' in doc:
+ self._score = doc['score']
+ else:
+ self._score = 0
+
+ self.picture_id = int(doc["picture_id"])
+
+ if doc.get('area_id'):
+ hit = (self._score, {
+ 'how_found': how_found,
+ 'area_id': doc['area_id'],
+ 'themes': doc.get('themes', []),
+ 'themes_pl': doc.get('themes_pl', []),
+ })
+
+ self._hits.append(hit)
+
+ def __str__(self):
+ return u"<PR id=%d score=%f >" % (self.picture_id, self._score)
+
+ def __repr__(self):
+ return str(self)
+
+ @property
+ def score(self):
+ return self._score * self.boost
+
+ def merge(self, other):
+ if self.picture_id != other.picture_id:
+ raise ValueError(
+ "this search result is for picture %d; tried to merge with %d" % (self.picture_id, other.picture_id))
+ self._hits += other._hits
+ self._score += max(other._score, 0)
+ return self
+
+ SCORE = 0
+ OTHER = 1
+
+ @property
+ def hits(self):
+ if self._processed_hits is not None:
+ return self._processed_hits
+
+ hits = []
+ for hit in self._hits:
+ try:
+ area = picture.models.PictureArea.objects.get(id=hit[self.OTHER]['area_id'])
+ except picture.models.PictureArea.DoesNotExist:
+ # stale index
+ continue
+ # Figure out if we were searching for a token matching some word in theme name.
+ themes_hit = set()
+ if self.query_terms is not None:
+ for i in range(0, len(hit[self.OTHER]['themes'])):
+ tms = hit[self.OTHER]['themes'][i].split(r' +') + hit[self.OTHER]['themes_pl'][i].split(' ')
+ tms = map(str.lower, tms)
+ for qt in self.query_terms:
+ if qt in tms:
+ themes_hit.add(hit[self.OTHER]['themes'][i])
+ break
+
+ m = {
+ 'score': hit[self.SCORE],
+ 'area': area,
+ 'themes_hit': themes_hit,
+ }
+ m.update(hit[self.OTHER])
+ hits.append(m)
+
+ hits.sort(key=lambda h: h['score'], reverse=True)
+ hits = hits[:1]
+ self._processed_hits = hits
+ return hits
+
+ def get_picture(self):
+ if self._picture is None:
+ self._picture = picture.models.Picture.objects.get(id=self.picture_id)
+ return self._picture
+
+ picture = property(get_picture)
+
+ @staticmethod
+ def aggregate(*result_lists):
+ books = {}
+ for rl in result_lists:
+ for r in rl:
+ if r.picture_id in books:
+ books[r.picture_id].merge(r)
+ else:
+ books[r.picture_id] = r
+ return books.values()
+
+ def __cmp__(self, other):
+ return cmp(self.score, other.score)
+
+