Fixed collecting content for snippet generation
[wolnelektury.git] / apps / search / index.py
index cc478ee..7ab3de9 100644 (file)
@@ -139,6 +139,7 @@ class Snippets(object):
         self.file.write(txt)
         pos = (self.position, l)
         self.position += l
         self.file.write(txt)
         pos = (self.position, l)
         self.position += l
+        print "SSSS %s - %s" % (pos, txt)
         return pos
 
     def get(self, pos):
         return pos
 
     def get(self, pos):
@@ -402,27 +403,25 @@ class Index(BaseIndex):
                 if header.tag in self.skip_header_tags:
                     continue
 
                 if header.tag in self.skip_header_tags:
                     continue
 
-                content = u' '.join([t for t in header.itertext()])
-                content = fix_format(content)
-
-                doc = add_part(snippets, header_index=position, header_type=header.tag, content=content)
-
-                self.index.addDocument(doc)
+                # section content
+                content = []
 
                 for start, end in walker(header):
 
                 for start, end in walker(header):
+                        # handle fragments and themes.
                     if start is not None and start.tag == 'begin':
                         fid = start.attrib['id'][1:]
                         fragments[fid] = {'content': [], 'themes': [], 'start_section': position, 'start_header': header.tag}
                     if start is not None and start.tag == 'begin':
                         fid = start.attrib['id'][1:]
                         fragments[fid] = {'content': [], 'themes': [], 'start_section': position, 'start_header': header.tag}
-                        fragments[fid]['content'].append(start.tail)
+
                     elif start is not None and start.tag == 'motyw':
                         fid = start.attrib['id'][1:]
                         if start.text is not None:
                             fragments[fid]['themes'] += map(str.strip, map(give_me_utf8, start.text.split(',')))
                     elif start is not None and start.tag == 'motyw':
                         fid = start.attrib['id'][1:]
                         if start.text is not None:
                             fragments[fid]['themes'] += map(str.strip, map(give_me_utf8, start.text.split(',')))
-                        fragments[fid]['content'].append(start.tail)
+
                     elif start is not None and start.tag == 'end':
                         fid = start.attrib['id'][1:]
                         if fid not in fragments:
                             continue  # a broken <end> node, skip it
                     elif start is not None and start.tag == 'end':
                         fid = start.attrib['id'][1:]
                         if fid not in fragments:
                             continue  # a broken <end> node, skip it
+                                      #                        import pdb; pdb.set_trace()
                         frag = fragments[fid]
                         if frag['themes'] == []:
                             continue  # empty themes list.
                         frag = fragments[fid]
                         if frag['themes'] == []:
                             continue  # empty themes list.
@@ -442,12 +441,23 @@ class Index(BaseIndex):
                                        themes=frag['themes'])
 
                         self.index.addDocument(doc)
                                        themes=frag['themes'])
 
                         self.index.addDocument(doc)
+
+                        # Collect content.
                     elif start is not None:
                         for frag in fragments.values():
                             frag['content'].append(start.text)
                     elif start is not None:
                         for frag in fragments.values():
                             frag['content'].append(start.text)
+                        content.append(start.text)
                     elif end is not None:
                         for frag in fragments.values():
                             frag['content'].append(end.tail)
                     elif end is not None:
                         for frag in fragments.values():
                             frag['content'].append(end.tail)
+                        content.append(end.tail)
+
+                        # in the end, add a section text.
+                doc = add_part(snippets, header_index=position, header_type=header.tag,
+                               content=fix_format(u' '.join(filter(lambda s: s is not None, frag['content']))))
+
+                self.index.addDocument(doc)
+
         finally:
             snippets.close()
 
         finally:
             snippets.close()
 
@@ -563,6 +573,8 @@ class SearchResult(object):
 
         fragment = stored.get("fragment_anchor")
 
 
         fragment = stored.get("fragment_anchor")
 
+        if snippets:
+            snippets = snippets.replace("/\n", "\n")
         hit = (sec + (header_span,), fragment, scoreDocs.score, {'how_found': how_found, 'snippets': snippets and [snippets] or []})
 
         self._hits.append(hit)
         hit = (sec + (header_span,), fragment, scoreDocs.score, {'how_found': how_found, 'snippets': snippets and [snippets] or []})
 
         self._hits.append(hit)
@@ -630,6 +642,7 @@ class SearchResult(object):
             frag = catalogue.models.Fragment.objects.get(anchor=f[FRAGMENT])
             m = {'score': f[SCORE],
                  'fragment': frag,
             frag = catalogue.models.Fragment.objects.get(anchor=f[FRAGMENT])
             m = {'score': f[SCORE],
                  'fragment': frag,
+                 'section_number': f[POSITION][POSITION_INDEX] + 1,
                  'themes': frag.tags.filter(category='theme')
                  }
             m.update(f[OTHER])
                  'themes': frag.tags.filter(category='theme')
                  }
             m.update(f[OTHER])
@@ -884,7 +897,7 @@ class Search(IndexStore):
                 self.chain_filters([only_in, self.term_filter(Term('is_book', 'true'))]),
                 max_results)
             for found in top.scoreDocs:
                 self.chain_filters([only_in, self.term_filter(Term('is_book', 'true'))]),
                 max_results)
             for found in top.scoreDocs:
-                books.append(SearchResult(self.searcher, found))
+                books.append(SearchResult(self.searcher, found, how_found="search_perfect_book"))
         return books
 
     def search_book(self, searched, max_results=20, fuzzy=False, hint=None):
         return books
 
     def search_book(self, searched, max_results=20, fuzzy=False, hint=None):
@@ -910,7 +923,7 @@ class Search(IndexStore):
                                    self.chain_filters([only_in, self.term_filter(Term('is_book', 'true'))]),
             max_results)
         for found in top.scoreDocs:
                                    self.chain_filters([only_in, self.term_filter(Term('is_book', 'true'))]),
             max_results)
         for found in top.scoreDocs:
-            books.append(SearchResult(self.searcher, found))
+            books.append(SearchResult(self.searcher, found, how_found="search_book"))
 
         return books
 
 
         return books
 
@@ -932,7 +945,7 @@ class Search(IndexStore):
                                                            flt]),
                                        max_results)
             for found in top.scoreDocs:
                                                            flt]),
                                        max_results)
             for found in top.scoreDocs:
-                books.append(SearchResult(self.searcher, found, snippets=self.get_snippets(found, q)))
+                books.append(SearchResult(self.searcher, found, snippets=self.get_snippets(found, q), how_found='search_perfect_parts'))
 
         return books
 
 
         return books
 
@@ -964,7 +977,7 @@ class Search(IndexStore):
 
         topDocs = self.searcher.search(q, only_in, max_results)
         for found in topDocs.scoreDocs:
 
         topDocs = self.searcher.search(q, only_in, max_results)
         for found in topDocs.scoreDocs:
-            books.append(SearchResult(self.searcher, found))
+            books.append(SearchResult(self.searcher, found, how_found='search_everywhere_themesXcontent'))
             print "* %s theme x content: %s" % (searched, books[-1]._hits)
 
         # query themes/content x author/title/tags
             print "* %s theme x content: %s" % (searched, books[-1]._hits)
 
         # query themes/content x author/title/tags
@@ -983,7 +996,7 @@ class Search(IndexStore):
 
         topDocs = self.searcher.search(q, only_in, max_results)
         for found in topDocs.scoreDocs:
 
         topDocs = self.searcher.search(q, only_in, max_results)
         for found in topDocs.scoreDocs:
-            books.append(SearchResult(self.searcher, found))
+            books.append(SearchResult(self.searcher, found, how_found='search_everywhere'))
             print "* %s scatter search: %s" % (searched, books[-1]._hits)
 
         return books
             print "* %s scatter search: %s" % (searched, books[-1]._hits)
 
         return books