1 # -*- coding: utf-8 -*-
2 from django.conf import settings
3 from lucene import SimpleFSDirectory, IndexWriter, File, Field, \
4 NumericField, Version, Document, JavaError, IndexSearcher, \
5 QueryParser, Term, PerFieldAnalyzerWrapper, \
6 SimpleAnalyzer, PolishAnalyzer, ArrayList, \
7 KeywordAnalyzer, NumericRangeQuery, BooleanQuery, \
8 BlockJoinQuery, BlockJoinCollector, TermsFilter, \
9 HashSet, BooleanClause, Term, CharTermAttribute, \
10 PhraseQuery, StringReader
15 from librarian import dcparser
16 from librarian.parser import WLDocument
17 import catalogue.models
18 from multiprocessing.pool import ThreadPool
22 class WLAnalyzer(PerFieldAnalyzerWrapper):
24 polish = PolishAnalyzer(Version.LUCENE_34)
25 simple = SimpleAnalyzer(Version.LUCENE_34)
26 keyword = KeywordAnalyzer(Version.LUCENE_34)
27 # not sure if needed: there's NOT_ANALYZED meaning basically the same
29 PerFieldAnalyzerWrapper.__init__(self, polish)
31 self.addAnalyzer("tags", simple)
32 self.addAnalyzer("technical_editors", simple)
33 self.addAnalyzer("editors", simple)
34 self.addAnalyzer("url", keyword)
35 self.addAnalyzer("source_url", keyword)
36 self.addAnalyzer("source_name", simple)
37 self.addAnalyzer("publisher", simple)
38 self.addAnalyzer("author", simple)
39 self.addAnalyzer("is_book", keyword)
41 #self.addanalyzer("fragment_anchor", keyword)
44 class IndexStore(object):
47 self.store = SimpleFSDirectory(File(settings.SEARCH_INDEX))
49 def make_index_dir(self):
51 os.makedirs(settings.SEARCH_INDEX)
52 except OSError as exc:
53 if exc.errno == errno.EEXIST:
58 class Index(IndexStore):
59 def __init__(self, analyzer=None):
60 IndexStore.__init__(self)
63 analyzer = WLAnalyzer()
64 self.analyzer = analyzer
66 def open(self, analyzer=None):
68 raise Exception("Index is already opened")
69 self.index = IndexWriter(self.store, self.analyzer,\
70 IndexWriter.MaxFieldLength.LIMITED)
78 def remove_book(self, book):
79 q = NumericRangeQuery.newIntRange("book_id", book.id, book.id, True,True)
80 self.index.deleteDocuments(q)
82 def index_book(self, book, overwrite=True):
84 self.remove_book(book)
87 doc = self.extract_metadata(book)
88 parts = self.extract_content(book)
89 block = ArrayList().of_(Document)
94 self.index.addDocuments(block)
99 'dramat_wierszowany_l',
100 'dramat_wierszowany_lp',
101 'dramat_wspolczesny', 'liryka_l', 'liryka_lp',
105 skip_header_tags = ['autor_utworu', 'nazwa_utworu']
107 def create_book_doc(self, book):
109 Create a lucene document connected to the book
112 doc.add(NumericField("book_id", Field.Store.YES, True).setIntValue(book.id))
113 if book.parent is not None:
114 doc.add(NumericField("parent_id", Field.Store.YES, True).setIntValue(book.parent.id))
117 def extract_metadata(self, book):
118 book_info = dcparser.parse(book.xml_file)
120 doc = self.create_book_doc(book)
121 doc.add(Field("slug", book.slug, Field.Store.NO, Field.Index.ANALYZED_NO_NORMS))
122 doc.add(Field("tags", ','.join([t.name for t in book.tags]), Field.Store.NO, Field.Index.ANALYZED))
123 doc.add(Field("is_book", 'true', Field.Store.NO, Field.Index.NOT_ANALYZED))
126 for field in dcparser.BookInfo.FIELDS:
127 if hasattr(book_info, field.name):
128 if not getattr(book_info, field.name):
130 # since no type information is available, we use validator
131 type_indicator = field.validator
132 if type_indicator == dcparser.as_unicode:
133 s = getattr(book_info, field.name)
137 doc.add(Field(field.name, s, Field.Store.NO, Field.Index.ANALYZED))
138 except JavaError as je:
139 raise Exception("failed to add field: %s = '%s', %s(%s)" % (field.name, s, je.message, je.args))
140 elif type_indicator == dcparser.as_person:
141 p = getattr(book_info, field.name)
142 if isinstance(p, dcparser.Person):
145 persons = ', '.join(map(unicode, p))
146 doc.add(Field(field.name, persons, Field.Store.NO, Field.Index.ANALYZED))
147 elif type_indicator == dcparser.as_date:
148 dt = getattr(book_info, field.name)
149 doc.add(Field(field.name, "%04d%02d%02d" % (dt.year, dt.month, dt.day), Field.Store.NO, Field.Index.NOT_ANALYZED))
152 def get_master(self, root):
153 for master in root.iter():
154 if master.tag in self.master_tags:
158 def extract_content(self, book):
159 wld = WLDocument.from_file(book.xml_file.path)
160 root = wld.edoc.getroot()
162 # first we build a sequence of top-level items.
164 # header_index - the 0-indexed position of header element.
166 master = self.get_master(root)
171 for header, position in zip(list(master), range(len(master))):
172 if header.tag in self.skip_header_tags:
174 doc = self.create_book_doc(book)
175 doc.add(NumericField("header_index", Field.Store.YES, True).setIntValue(position))
176 doc.add(Field("header_type", header.tag, Field.Store.YES, Field.Index.NOT_ANALYZED))
177 content = u' '.join([t for t in header.itertext()])
178 doc.add(Field("content", content, Field.Store.NO, Field.Index.ANALYZED))
179 header_docs.append(doc)
183 for child in list(node):
184 for b, e in walker(child):
189 # Then we create a document for each fragments
190 # fragment_anchor - the anchor
191 # themes - list of themes [not indexed]
193 # will contain (framgent id -> { content: [], themes: [] }
195 for start, end in walker(master):
196 if start is not None and start.tag == 'begin':
197 fid = start.attrib['id'][1:]
198 fragments[fid] = {'content': [], 'themes': []}
199 fragments[fid]['content'].append(start.tail)
200 elif start is not None and start.tag == 'motyw':
201 fid = start.attrib['id'][1:]
202 fragments[fid]['themes'].append(start.text)
203 fragments[fid]['content'].append(start.tail)
204 elif start is not None and start.tag == 'end':
205 fid = start.attrib['id'][1:]
206 if fid not in fragments:
207 continue # a broken <end> node, skip it
208 frag = fragments[fid]
212 return u' '.join(map(
213 lambda x: x == None and u'(none)' or unicode(x),
216 doc = self.create_book_doc(book)
217 doc.add(Field("fragment_anchor", fid,
218 Field.Store.YES, Field.Index.NOT_ANALYZED))
219 doc.add(Field("content",
220 u' '.join(filter(lambda s: s is not None, frag['content'])),
221 Field.Store.NO, Field.Index.ANALYZED))
222 doc.add(Field("themes",
223 u' '.join(filter(lambda s: s is not None, frag['themes'])),
224 Field.Store.NO, Field.Index.ANALYZED))
226 fragment_docs.append(doc)
227 elif start is not None:
228 for frag in fragments.values():
229 frag['content'].append(start.text)
230 elif end is not None:
231 for frag in fragments.values():
232 frag['content'].append(end.tail)
234 return header_docs + fragment_docs
240 def __exit__(self, type, value, tb):
244 class ReusableIndex(Index):
246 Works like index, but does not close/optimize Lucene index
247 until program exit (uses atexit hook).
248 This is usefull for importbooks command.
250 if you cannot rely on atexit, use ReusableIndex.close_reusable() yourself.
256 def open(self, analyzer=None, threads=4):
257 if ReusableIndex.index is not None:
258 self.index = ReusableIndex.index
260 ReusableIndex.pool = ThreadPool(threads)
261 ReusableIndex.pool_jobs = []
262 Index.open(self, analyzer)
263 ReusableIndex.index = self.index
264 atexit.register(ReusableIndex.close_reusable)
266 def index_book(self, *args, **kw):
267 job = ReusableIndex.pool.apply_async(Index.index_book, (self,)+ args, kw)
268 ReusableIndex.pool_jobs.append(job)
271 def close_reusable():
272 import pdb; pdb.set_trace()
273 if ReusableIndex.index is not None:
274 for job in ReusableIndex.pool_jobs:
276 ReusableIndex.pool.close()
278 ReusableIndex.index.optimize()
279 ReusableIndex.index.close()
280 ReusableIndex.index = None
286 class Search(IndexStore):
287 def __init__(self, default_field="content"):
288 IndexStore.__init__(self)
289 self.analyzer = PolishAnalyzer(Version.LUCENE_34)
290 ## self.analyzer = WLAnalyzer()
291 self.searcher = IndexSearcher(self.store, True)
292 self.parser = QueryParser(Version.LUCENE_34, default_field,
295 self.parent_filter = TermsFilter()
296 self.parent_filter.addTerm(Term("is_book", "true"))
298 def query(self, query):
299 return self.parser.parse(query)
301 def wrapjoins(self, query, fields=[]):
303 This functions modifies the query in a recursive way,
304 so Term and Phrase Queries contained, which match
305 provided fields are wrapped in a BlockJoinQuery,
306 and so delegated to children documents.
308 if BooleanQuery.instance_(query):
309 qs = BooleanQuery.cast_(query)
311 clause = BooleanClause.cast_(clause)
312 clause.setQuery(self.wrapjoins(clause.getQuery(), fields))
316 query.extractTerms(termset)
319 if t.field() not in fields:
321 return BlockJoinQuery(query, self.parent_filter,
322 BlockJoinQuery.ScoreMode.Total)
324 def simple_search(self, query, max_results=50):
325 """Returns (books, total_hits)
328 tops = self.searcher.search(self.query(query), max_results)
330 for found in tops.scoreDocs:
331 doc = self.searcher.doc(found.doc)
332 bks.append(catalogue.models.Book.objects.get(id=doc.get("book_id")))
333 return (bks, tops.totalHits)
335 def search(self, query, max_results=50):
336 query = self.query(query)
337 query = self.wrapjoins(query, ["content", "themes"])
339 tops = self.searcher.search(query, max_results)
341 for found in tops.scoreDocs:
342 doc = self.searcher.doc(found.doc)
343 bks.append(catalogue.models.Book.objects.get(id=doc.get("book_id")))
344 return (bks, tops.totalHits)
346 def bsearch(self, query, max_results=50):
347 q = self.query(query)
348 bjq = BlockJoinQuery(q, self.parent_filter, BlockJoinQuery.ScoreMode.Avg)
350 tops = self.searcher.search(bjq, max_results)
352 for found in tops.scoreDocs:
353 doc = self.searcher.doc(found.doc)
354 bks.append(catalogue.models.Book.objects.get(id=doc.get("book_id")))
355 return (bks, tops.totalHits)
357 # TokenStream tokenStream = analyzer.tokenStream(fieldName, reader);
358 # OffsetAttribute offsetAttribute = tokenStream.getAttribute(OffsetAttribute.class);
359 # CharTermAttribute charTermAttribute = tokenStream.getAttribute(CharTermAttribute.class);
361 # while (tokenStream.incrementToken()) {
362 # int startOffset = offsetAttribute.startOffset();
363 # int endOffset = offsetAttribute.endOffset();
364 # String term = charTermAttribute.toString();
368 class MultiSearch(Search):
369 """Class capable of IMDb-like searching"""
370 def get_tokens(self, queryreader):
371 if isinstance(queryreader, str):
372 queryreader = StringReader(queryreader)
374 tokens = self.analyzer.reusableTokenStream('content', queryreader)
376 while tokens.incrementToken():
377 cta = tokens.getAttribute(CharTermAttribute.class_)
381 def make_phrase(self, tokens, field='content', joined=False):
382 phrase = PhraseQuery()
384 term = Term(field, t)
387 phrase = self.content_query(phrase)
390 def make_term_query(self, tokens, field='content', modal=BooleanClause.Occur.SHOULD, joined=False):
393 term = Term(field, t)
394 q.add(BooleanClause(term, modal))
396 self.content_query(q)
399 def content_query(self, query):
400 return BlockJoinQuery(query, self.parent_filter,
401 BlockJoinQuery.ScoreMode.Total)
403 def multiseach(self, query, max_results=50):
406 - (phrase) OR -> content
409 - (keywords) -> author
414 queryreader = StringReader(query)
415 tokens = self.get_tokens(queryreader)
417 top_level = BooleanQuery()
418 Should = BooleanClause.Occur.SHOULD
420 phrase_level = BooleanQuery()
422 p_content = self.make_phrase(tokens, joined=True)
423 p_title = self.make_phrase(tokens, 'title')
424 p_author = self.make_phrase(tokens, 'author')
426 phrase_level.add(BooleanClause(p_content, Should))
427 phrase_level.add(BooleanClause(p_title, Should))
428 phrase_level.add(BooleanClause(p_author, Should))
430 kw_level = BooleanQuery()
432 kw_level.add(self.make_term_query(tokens, 'author'), Should)
433 kw_level.add(self.make_term_query(tokens, 'themes', joined=True), Should)
434 kw_level.add(self.make_term_query(tokens, 'tags'), Should)
435 kw_level.add(self.make_term_query(tokens, joined=True), Should)
437 top_level.add(BooleanClause(phrase_level, Should))
438 top_level.add(BooleanClause(kw_level, Should))
440 tops = self.searcher.search(top_level, max_results)
442 for found in tops.scoreDocs:
443 doc = self.searcher.doc(found.doc)
444 bks.append(catalogue.models.Book.objects.get(id=doc.get("book_id")))
445 return (bks, tops.totalHits)