look changes
[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     
63     tags = s.hint_tags(prefix)
64     books = s.hint_books(prefix)
65
66     # TODO DODAC TU HINTY
67
68     return JSONResponse(
69         [{'label': t.name,
70           'category': _(t.category),
71           'id': t.id,
72           'url': t.get_absolute_url()}
73           for t in tags] + \
74           [{'label': b.title,
75             'category': _('book'),
76             'id': b.id,
77             'url': b.get_absolute_url()}
78             for b in books])
79
80
81 def foo(s, q, tag_list=None):
82     hint = s.hint()
83     try:
84         tag_list = Tag.get_tag_list(tag_list)
85         hint.tags(tag_list)
86     except:
87         tag_list = None
88
89     q = StringReader(q)
90     return (q, hint)
91
92
93 def main(request):
94     results = {}
95     JVM.attachCurrentThread()  # where to put this?
96     srch = Search()
97
98     results = None
99     query = None
100     fuzzy = False
101
102     if 'q' in request.GET:
103         tags = request.GET.get('tags', '')
104         query = request.GET['q']
105         book_id = request.GET.get('book', None)
106         book = None
107         if book_id is not None:
108             book = get_object_or_404(Book, id=book_id)
109
110         hint = srch.hint()
111         try:
112             tag_list = Tag.get_tag_list(tags)
113         except:
114             tag_list = []
115
116         if len(query) < 2:
117             return render_to_response('catalogue/search_too_short.html', {'tags': tag_list, 'prefix': query},
118                                       context_instance=RequestContext(request))
119
120         hint.tags(tag_list)
121         if book:
122             hint.books(book)
123
124         toks = StringReader(query)
125         fuzzy = 'fuzzy' in request.GET
126         if fuzzy:
127             fuzzy = 0.7
128
129         results = SearchResult.aggregate(srch.search_perfect_book(toks, fuzzy=fuzzy, hint=hint),
130                                          srch.search_book(toks, fuzzy=fuzzy, hint=hint),
131                                          srch.search_perfect_parts(toks, fuzzy=fuzzy, hint=hint),
132                                          srch.search_everywhere(toks, fuzzy=fuzzy, hint=hint))
133
134         for r in results:
135             r.process_hits()
136
137         results.sort(reverse=True)
138
139         for r in results:
140             print "-----"
141             for h in r.hits:
142                 print "- %s" % h
143
144         if len(results) == 1:
145             if len(results[0].hits) == 0:
146                 return HttpResponseRedirect(results[0].book.get_absolute_url())
147             elif len(results[0].hits) == 1 and results[0].hits[0] is not None:
148                 frag = Fragment.objects.get(anchor=results[0].hits[0])
149                 return HttpResponseRedirect(frag.get_absolute_url())
150         elif len(results) == 0:
151             form = PublishingSuggestForm(initial={"books": query + ", "})
152             return render_to_response('catalogue/search_no_hits.html',
153                                       {'tags': tag_list, 'prefix': query,
154                                        "form": form},
155                 context_instance=RequestContext(request))
156
157         return render_to_response('catalogue/search_multiple_hits.html',
158                                   {'tags': tag_list, 'prefix': query,
159                                    'results': results},
160             context_instance=RequestContext(request))
161
162     # return render_to_response('newsearch/search.html', {'results': results,
163     #                                                     'did_you_mean': (query is not None) and
164     #                                                     did_you_mean(query, srch.get_tokens(query, field='SIMPLE')),
165     #                                                     'fuzzy': fuzzy},
166     #                           context_instance=RequestContext(request))