search demo
[wolnelektury.git] / apps / search / views.py
1
2 from django.shortcuts import render_to_response, get_object_or_404
3 from django.template import RequestContext
4 from django.contrib.auth.decorators import login_required
5 from django.views.decorators import cache
6
7 from catalogue.utils import get_random_hash
8 from catalogue.models import Book, Tag
9 from catalogue import forms
10 from search import MultiSearch, JVM, SearchResult
11 from lucene import StringReader
12
13 import enchant
14
15 dictionary = enchant.Dict('pl_PL')
16
17
18 def did_you_mean(query, tokens):
19     change = {}
20     
21     for t in tokens:
22         print("%s ok? %s, sug: %s" %(t, dictionary.check(t), dictionary.suggest(t)))
23         if not dictionary.check(t):
24             try:
25                 change[t] = dictionary.suggest(t)[0]
26             except IndexError:
27                 pass
28
29     if change == {}:
30         return None
31
32     for frm, to in change.items():
33         query = query.replace(frm, to)
34         
35     return query
36
37
38 def main(request):
39     results = {}
40     JVM.attachCurrentThread()  # where to put this?
41     srch = MultiSearch()
42
43     results = None
44     query = None
45     fuzzy = False
46     if 'q' in request.GET:
47         query = request.GET['q']
48         toks = StringReader(query)
49         fuzzy = 'fuzzy' in request.GET
50         if fuzzy:
51             fuzzy = 0.7
52
53
54         results = SearchResult.aggregate(srch.search_perfect_book(toks, fuzzy=fuzzy),
55                                          srch.search_perfect_parts(toks, fuzzy=fuzzy),
56                                          srch.search_everywhere(toks, fuzzy=fuzzy))
57         results.sort(reverse=True)
58
59         for r in results:
60             print r.parts
61
62     return render_to_response('newsearch/search.html', {'results': results,
63                                                         'did_you_mean': (query is not None) and 
64                                                         did_you_mean(query, srch.get_tokens(query, field='SIMPLE')),
65                                                         'fuzzy': fuzzy},
66                               context_instance=RequestContext(request))