166011cc32fbfc370e4d89a0d4e7d2a33ec1f58f
[wolnelektury.git] / apps / search / views.py
1 # -*- coding: utf-8 -*-
2
3 from django.shortcuts import render_to_response, get_object_or_404
4 from django.template import RequestContext
5 from django.contrib.auth.decorators import login_required
6 from django.views.decorators import cache
7 from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect
8 from django.utils.translation import ugettext as _
9
10 from catalogue.utils import get_random_hash
11 from catalogue.models import Book, Tag, Fragment
12 from catalogue.fields import dumps
13 from catalogue.views import JSONResponse
14 from search import Search, JVM, SearchResult
15 from lucene import StringReader
16 from suggest.forms import PublishingSuggestForm
17
18 import enchant
19
20 dictionary = enchant.Dict('pl_PL')
21
22
23 def did_you_mean(query, tokens):
24     change = {}
25     # sprawdzić, czy słowo nie jest aby autorem - proste szukanie termu w author!
26     for t in tokens:
27         print("%s ok? %s, sug: %s" %(t, dictionary.check(t), dictionary.suggest(t)))
28         if not dictionary.check(t):
29             try:
30                 change[t] = dictionary.suggest(t)[0]
31             except IndexError:
32                 pass
33
34     if change == {}:
35         return None
36
37     for frm, to in change.items():
38         query = query.replace(frm, to)
39
40     return query
41
42
43 def hint(request):
44     prefix = request.GET.get('term', '')
45     if len(prefix) < 2:
46         return JSONResponse([])
47     JVM.attachCurrentThread()
48     s = Search()
49
50     hint = s.hint()
51     try:
52         tags = request.GET.get('tags', '')
53         hint.tags(Tag.get_tag_list(tags))
54     except:
55         pass
56
57     # tagi beda ograniczac tutaj
58     # ale tagi moga byc na ksiazce i na fragmentach
59     # jezeli tagi dot tylko ksiazki, to wazne zeby te nowe byly w tej samej ksiazce
60     # jesli zas dotycza themes, to wazne, zeby byly w tym samym fragmencie.
61
62     tags = s.hint_tags(prefix)
63     books = s.hint_books(prefix)
64
65     # TODO DODAC TU HINTY
66
67     return JSONResponse(
68         [{'label': t.name,
69           'category': _(t.category),
70           'id': t.id,
71           'url': t.get_absolute_url()}
72           for t in tags] + \
73           [{'label': b.title,
74             'category': _('book'),
75             'id': b.id,
76             'url': b.get_absolute_url()}
77             for b in books])
78
79
80 def main(request):
81     results = {}
82     JVM.attachCurrentThread()  # where to put this?
83     srch = Search()
84
85     results = None
86     query = None
87     fuzzy = False
88
89     if 'q' in request.GET:
90         tags = request.GET.get('tags', '')
91         query = request.GET['q']
92         book_id = request.GET.get('book', None)
93         book = None
94         if book_id is not None:
95             book = get_object_or_404(Book, id=book_id)
96
97         hint = srch.hint()
98         try:
99             tag_list = Tag.get_tag_list(tags)
100         except:
101             tag_list = []
102
103         if len(query) < 2:
104             return render_to_response('catalogue/search_too_short.html', {'tags': tag_list, 'prefix': query},
105                                       context_instance=RequestContext(request))
106
107         hint.tags(tag_list)
108         if book:
109             hint.books(book)
110
111         toks = StringReader(query)
112         fuzzy = 'fuzzy' in request.GET
113         if fuzzy:
114             fuzzy = 0.7
115
116         results = SearchResult.aggregate(srch.search_perfect_book(toks, fuzzy=fuzzy, hint=hint),
117                                          srch.search_book(toks, fuzzy=fuzzy, hint=hint),
118                                          srch.search_perfect_parts(toks, fuzzy=fuzzy, hint=hint),
119                                          srch.search_everywhere(toks, fuzzy=fuzzy, hint=hint))
120
121         for r in results:
122             r.process_hits()
123
124         results.sort(reverse=True)
125
126         for r in results:
127             print "-----"
128             for h in r.hits:
129                 print "- %s" % h
130
131         if len(results) == 1:
132             if len(results[0].hits) == 0:
133                 return HttpResponseRedirect(results[0].book.get_absolute_url())
134             elif len(results[0].hits) == 1 and results[0].hits[0] is not None:
135                 frag = Fragment.objects.get(anchor=results[0].hits[0])
136                 return HttpResponseRedirect(frag.get_absolute_url())
137         elif len(results) == 0:
138             form = PublishingSuggestForm(initial={"books": query + ", "})
139             return render_to_response('catalogue/search_no_hits.html',
140                                       {'tags': tag_list, 'prefix': query,
141                                        "form": form},
142                 context_instance=RequestContext(request))
143
144         return render_to_response('catalogue/search_multiple_hits.html',
145                                   {'tags': tag_list, 'prefix': query,
146                                    'results': results},
147             context_instance=RequestContext(request))