book detail page - now with media / custom pdf
[wolnelektury.git] / apps / search / index.py
index 6e2140a..10069e4 100644 (file)
@@ -53,8 +53,9 @@ class WLAnalyzer(PerFieldAnalyzerWrapper):
         self.addAnalyzer("source_url", keyword)
         self.addAnalyzer("source_name", simple)
         self.addAnalyzer("publisher", simple)
-        self.addAnalyzer("author", simple)
+        self.addAnalyzer("authors", simple)
         self.addAnalyzer("is_book", keyword)
+        # shouldn't the title have two forms? _pl and simple?
 
         self.addAnalyzer("themes", simple)
         self.addAnalyzer("themes_pl", polish)
@@ -62,6 +63,8 @@ class WLAnalyzer(PerFieldAnalyzerWrapper):
         self.addAnalyzer("tag_name", simple)
         self.addAnalyzer("tag_name_pl", polish)
 
+        self.addAnalyzer("translators", simple)
+
         self.addAnalyzer("KEYWORD", keyword)
         self.addAnalyzer("SIMPLE", simple)
         self.addAnalyzer("POLISH", polish)
@@ -171,12 +174,12 @@ class Index(IndexStore):
         q = NumericRangeQuery.newIntRange("book_id", book.id, book.id, True, True)
         self.index.deleteDocuments(q)
 
-    def index_book(self, book, overwrite=True):
+    def index_book(self, book, book_info=None, overwrite=True):
         if overwrite:
             self.remove_book(book)
 
         book_doc = self.create_book_doc(book)
-        meta_fields = self.extract_metadata(book)
+        meta_fields = self.extract_metadata(book, book_info)
         for f in meta_fields.values():
             if isinstance(f, list) or isinstance(f, tuple):
                 for elem in f:
@@ -187,7 +190,7 @@ class Index(IndexStore):
         self.index.addDocument(book_doc)
         del book_doc
 
-        self.index_content(book, book_fields=[meta_fields['title'], meta_fields['author']])
+        self.index_content(book, book_fields=[meta_fields['title'], meta_fields['authors']])
 
     master_tags = [
         'opowiadanie',
@@ -210,11 +213,11 @@ class Index(IndexStore):
             doc.add(NumericField("parent_id", Field.Store.YES, True).setIntValue(book.parent.id))
         return doc
 
-    def extract_metadata(self, book):
+    def extract_metadata(self, book, book_info=None):
         fields = {}
-        book_info = dcparser.parse(book.xml_file)
 
-        print("extract metadata for book %s id=%d, thread%d" % (book.slug, book.id, current_thread().ident))
+        if book_info is None:
+            book_info = dcparser.parse(open(book.xml_file.path))
 
         fields['slug'] = Field("slug", book.slug, Field.Store.NO, Field.Index.ANALYZED_NO_NORMS)
         fields['tags'] = self.add_gaps([Field("tags", t.name, Field.Store.NO, Field.Index.ANALYZED) for t in book.tags], 'tags')
@@ -246,6 +249,7 @@ class Index(IndexStore):
                     dt = getattr(book_info, field.name)
                     fields[field.name] = Field(field.name, "%04d%02d%02d" %\
                                                (dt.year, dt.month, dt.day), Field.Store.NO, Field.Index.NOT_ANALYZED)
+
         return fields
 
     def get_master(self, root):
@@ -260,7 +264,7 @@ class Index(IndexStore):
         return reduce(lambda a, b: a + b, zip(fields, gap()))[0:-1]
 
     def index_content(self, book, book_fields=[]):
-        wld = WLDocument.from_file(book.xml_file.path)
+        wld = WLDocument.from_file(book.xml_file.path, parse_dublincore=False)
         root = wld.edoc.getroot()
 
         master = self.get_master(root)
@@ -408,35 +412,23 @@ class ReusableIndex(Index):
     if you cannot rely on atexit, use ReusableIndex.close_reusable() yourself.
     """
     index = None
-    pool = None
-    pool_jobs = None
 
     def open(self, analyzer=None, threads=4):
         if ReusableIndex.index is not None:
             self.index = ReusableIndex.index
         else:
             print("opening index")
-            ReusableIndex.pool = ThreadPool(threads, initializer=lambda: JVM.attachCurrentThread() )
-            ReusableIndex.pool_jobs = []
             Index.open(self, analyzer)
             ReusableIndex.index = self.index
             atexit.register(ReusableIndex.close_reusable)
 
-    def index_book(self, *args, **kw):
-        job = ReusableIndex.pool.apply_async(log_exception_wrapper(Index.index_book), (self,) + args, kw)
-        ReusableIndex.pool_jobs.append(job)
+    def index_book(self, *args, **kw):
+        job = ReusableIndex.pool.apply_async(log_exception_wrapper(Index.index_book), (self,) + args, kw)
+        ReusableIndex.pool_jobs.append(job)
 
     @staticmethod
     def close_reusable():
         if ReusableIndex.index is not None:
-            print("wait for indexing to finish")
-            for job in ReusableIndex.pool_jobs:
-                job.get()
-                sys.stdout.write('.')
-                sys.stdout.flush()
-            print("done.")
-            ReusableIndex.pool.close()
-
             ReusableIndex.index.optimize()
             ReusableIndex.index.close()
             ReusableIndex.index = None
@@ -494,6 +486,7 @@ class Search(IndexStore):
             bks.append(catalogue.models.Book.objects.get(id=doc.get("book_id")))
         return (bks, tops.totalHits)
 
+
     def search(self, query, max_results=50):
         query = self.query(query)
         query = self.wrapjoins(query, ["content", "themes"])
@@ -623,10 +616,10 @@ class Hint(object):
         self.search = search
         self.book_tags = {}
         self.part_tags = []
-        self._book = None
+        self._books = []
 
-    def book(self, book):
-        self._book = book
+    def books(self, *books):
+        self._books = books
 
     def tags(self, tags):
         for t in tags:
@@ -660,20 +653,26 @@ class Hint(object):
         fs = []
         if self.part_tags:
             fs.append(self.tag_filter(self.part_tags, field='themes'))
-        if self._book is not None:
-            fs.append(NumericRangeFilter.newIntRange('book_id', self._book.id, self._book.id, True, True))
+
+        if self._books != []:
+            bf = BooleanFilter()
+            for b in self._books:
+                id_filter = NumericRangeFilter.newIntRange('book_id', b.id, b.id, True, True)
+                bf.add(FilterClause(id_filter, BooleanClause.Occur.SHOULD))
+            fs.append(bf)
+
         return MultiSearch.chain_filters(fs)
-            
+
     def should_search_for_book(self):
-        return self._book is None
+        return self._books == []
 
     def just_search_in(self, all):
         """Holds logic to figure out which indexes should be search, when we have some hinst already"""
         some = []
         for field in all:
-            if field == 'author' and 'author' in self.book_tags:
+            if field == 'authors' and 'author' in self.book_tags:
                 continue
-            if field == 'title' and self._book is not None:
+            if field == 'title' and self._books != []:
                 continue
             if (field == 'themes' or field == 'themes_pl') and self.part_tags:
                 continue
@@ -746,12 +745,12 @@ class MultiSearch(Search):
             q.add(BooleanClause(term, modal))
         return q
 
-    def content_query(self, query):
-        return BlockJoinQuery(query, self.parent_filter,
-                              BlockJoinQuery.ScoreMode.Total)
+    def content_query(self, query):
+        return BlockJoinQuery(query, self.parent_filter,
+                              BlockJoinQuery.ScoreMode.Total)
 
     def search_perfect_book(self, searched, max_results=20, fuzzy=False, hint=None):
-        fields_to_search = ['author', 'title']
+        fields_to_search = ['authors', 'title']
         only_in = None
         if hint:
             if not hint.should_search_for_book():
@@ -813,10 +812,10 @@ class MultiSearch(Search):
 
         # query themes/content x author/title/tags
         q = BooleanQuery()
-        in_meta = BooleanQuery()
+        #        in_meta = BooleanQuery()
         in_content = BooleanQuery()
 
-        for fld in ['themes', 'content', 'tags', 'author', 'title']:
+        for fld in ['themes', 'content', 'tags', 'authors', 'title']:
             in_content.add(BooleanClause(self.make_term_query(tokens, field=fld, fuzzy=False), BooleanClause.Occur.SHOULD))
 
         topDocs = self.searcher.search(q, only_in, max_results)
@@ -824,15 +823,14 @@ class MultiSearch(Search):
             books.append(SearchResult(self.searcher, found))
 
         return books
-    
 
     def multisearch(self, query, max_results=50):
         """
         Search strategy:
         - (phrase) OR -> content
                       -> title
-                      -> author
-        - (keywords)  -> author
+                      -> authors
+        - (keywords)  -> authors
                       -> motyw
                       -> tags
                       -> content
@@ -930,6 +928,14 @@ class MultiSearch(Search):
 
         return tags
 
+    def search_books(self, query, filter=None, max_results=10):
+        bks = []
+        tops = self.searcher.search(query, filter, max_results)
+        for found in tops.scoreDocs:
+            doc = self.searcher.doc(found.doc)
+            bks.append(catalogue.models.Book.objects.get(id=doc.get("book_id")))
+        return bks
+
     def create_prefix_phrase(self, toks, field):
         q = MultiPhraseQuery()
         for i in range(len(toks)):