on master help sign in
Merge pull request #3009 from kvch/pick-qwant-changes

Pick Qwant changes

commit2b0e37da339cb678ddc5949ed9b088b69cd50326 authorNoémi Ványi <kvch@users.noreply.github.com> dateSun 10 Oct 2021, 21:21 (5 years ago) parentb0888c6a0fb8eb
3 files changed+229−75
searx/data/engines_languages.json+43 searx/engines/qwant.py+172−69 searx/settings.yml+14−6
searx/data/engines_languages.json+43
@@ -25773,6 +25773,49 @@
2577325773 "zh-CN",
2577425774 "zh-HK"
2577525775 ],
25776+ "qwant videos": [
25777+ "bg-BG",
25778+ "ca-ES",
25779+ "cs-CZ",
25780+ "da-DK",
25781+ "de-AT",
25782+ "de-CH",
25783+ "de-DE",
25784+ "el-GR",
25785+ "en-AU",
25786+ "en-CA",
25787+ "en-GB",
25788+ "en-IE",
25789+ "en-IN",
25790+ "en-MY",
25791+ "en-NZ",
25792+ "en-US",
25793+ "es-AR",
25794+ "es-CL",
25795+ "es-ES",
25796+ "es-MX",
25797+ "et-EE",
25798+ "fi-FI",
25799+ "fr-BE",
25800+ "fr-CA",
25801+ "fr-CH",
25802+ "fr-FR",
25803+ "hu-HU",
25804+ "it-CH",
25805+ "it-IT",
25806+ "ko-KR",
25807+ "nb-NO",
25808+ "nl-BE",
25809+ "nl-NL",
25810+ "pl-PL",
25811+ "pt-BR",
25812+ "pt-PT",
25813+ "ro-RO",
25814+ "sv-SE",
25815+ "th-TH",
25816+ "zh-CN",
25817+ "zh-HK"
25818+ ],
2577625819 "startpage": {
2577725820 "af": {
2577825821 "alias": "afrikaans"
searx/engines/qwant.py+172−69
@@ -1,15 +1,41 @@
11# SPDX-License-Identifier: AGPL-3.0-or-later
2−"""
3− Qwant (Web, Images, News, Social)
2+# lint: pylint
3+"""Qwant (Web, News, Images, Videos)
4+
5+This engine uses the Qwant API (https://api.qwant.com/v3). The API is
6+undocumented but can be reverse engineered by reading the network log of
7+https://www.qwant.com/ queries.
8+
9+This implementation is used by different qwant engines in the settings.yml::
10+
11+ - name: qwant
12+ categories: general
13+ ...
14+ - name: qwant news
15+ categories: news
16+ ...
17+ - name: qwant images
18+ categories: images
19+ ...
20+ - name: qwant videos
21+ categories: videos
22+ ...
23+
424"""
525
6−from datetime import datetime
26+from datetime import (
27+ datetime,
28+ timedelta,
29+)
730from json import loads
831from urllib.parse import urlencode
9−from searx.utils import html_to_text, match_language
10−from searx.exceptions import SearxEngineAPIException, SearxEngineCaptchaException
32+from flask_babel import gettext
33+
34+from searx.utils import match_language
35+from searx.exceptions import SearxEngineAPIException
1136from searx.network import raise_for_httperror
1237
38+
1339# about
1440about = {
1541 "website": 'https://www.qwant.com/',
@@ -25,98 +51,175 @@ categories = []
2551paging = True
2652supported_languages_url = about['website']
2753
28−category_to_keyword = {'general': 'web',
29− 'images': 'images',
30− 'news': 'news'}
54+category_to_keyword = {
55+ 'general': 'web',
56+ 'news': 'news',
57+ 'images': 'images',
58+ 'videos': 'videos',
59+}
3160
3261# search-url
33−url = 'https://api.qwant.com/api/search/{keyword}?count=10&offset={offset}&f=&{query}&t={keyword}&uiv=4'
62+url = 'https://api.qwant.com/v3/search/{keyword}?q={query}&count={count}&offset={offset}'
3463
3564
36−# do search-request
3765def request(query, params):
38− offset = (params['pageno'] - 1) * 10
39−
40− if categories[0] and categories[0] in category_to_keyword:
41−
42− params['url'] = url.format(keyword=category_to_keyword[categories[0]],
43− query=urlencode({'q': query}),
44− offset=offset)
66+ """Qwant search request"""
67+ keyword = category_to_keyword[categories[0]]
68+ count = 10 # web: count must be equal to 10
69+
70+ if keyword == 'images':
71+ count = 50
72+ offset = (params['pageno'] - 1) * count
73+ # count + offset must be lower than 250
74+ offset = min(offset, 199)
4575 else:
46− params['url'] = url.format(keyword='web',
47− query=urlencode({'q': query}),
48− offset=offset)
76+ offset = (params['pageno'] - 1) * count
77+ # count + offset must be lower than 50
78+ offset = min(offset, 40)
79+
80+ params['url'] = url.format(
81+ keyword=keyword,
82+ query=urlencode({'q': query}),
83+ offset=offset,
84+ count=count,
85+ )
4986
5087 # add language tag
51− if params['language'] != 'all':
52− language = match_language(params['language'], supported_languages, language_aliases)
88+ if params['language'] == 'all':
89+ params['url'] += '&locale=en_us'
90+ else:
91+ language = match_language(
92+ params['language'],
93+ # pylint: disable=undefined-variable
94+ supported_languages,
95+ language_aliases,
96+ )
5397 params['url'] += '&locale=' + language.replace('-', '_').lower()
5498
55− params['headers']['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64; rv:69.0) Gecko/20100101 Firefox/69.0'
5699 params['raise_for_httperror'] = False
57100 return params
58101
59102
60−# get response from search-request
61103def response(resp):
62− results = []
104+ """Get response from Qwant's search request"""
105+ # pylint: disable=too-many-locals, too-many-branches, too-many-statements
63106
64− # According to https://www.qwant.com/js/app.js
65− if resp.status_code == 429:
66− raise SearxEngineCaptchaException()
67−
68− # raise for other errors
69− raise_for_httperror(resp)
107+ keyword = category_to_keyword[categories[0]]
108+ results = []
70109
71110 # load JSON result
72111 search_results = loads(resp.text)
112+ data = search_results.get('data', {})
73113
74114 # check for an API error
75115 if search_results.get('status') != 'success':
76− raise SearxEngineAPIException('API error ' + str(search_results.get('error', '')))
116+ msg = ",".join(data.get('message', ['unknown', ]))
117+ raise SearxEngineAPIException('API error::' + msg)
118+
119+ # raise for other errors
120+ raise_for_httperror(resp)
121+
122+ if keyword == 'web':
123+ # The WEB query contains a list named 'mainline'. This list can contain
124+ # different result types (e.g. mainline[0]['type'] returns type of the
125+ # result items in mainline[0]['items']
126+ mainline = data.get('result', {}).get('items', {}).get('mainline', {})
127+ else:
128+ # Queries on News, Images and Videos do not have a list named 'mainline'
129+ # in the response. The result items are directly in the list
130+ # result['items'].
131+ mainline = data.get('result', {}).get('items', [])
132+ mainline = [
133+ {'type': keyword, 'items': mainline},
134+ ]
77135
78136 # return empty array if there are no results
79− if 'data' not in search_results:
137+ if not mainline:
80138 return []
81139
82− data = search_results.get('data', {})
140+ for row in mainline:
141+
142+ mainline_type = row.get('type', 'web')
143+ if mainline_type == 'ads':
144+ # ignore adds
145+ continue
146+
147+ mainline_items = row.get('items', [])
148+ for item in mainline_items:
149+
150+ title = item.get('title', None)
151+ res_url = item.get('url', None)
152+
153+ if mainline_type == 'web':
154+ content = item['desc']
155+ results.append({
156+ 'title': title,
157+ 'url': res_url,
158+ 'content': content,
159+ })
160+
161+ elif mainline_type == 'news':
83162
84− res = data.get('result', {})
85−
86− # parse results
87− for result in res.get('items', {}):
88−
89− title = html_to_text(result['title'])
90− res_url = result['url']
91− content = html_to_text(result['desc'])
92−
93− if category_to_keyword.get(categories[0], '') == 'web':
94− results.append({'title': title,
95− 'content': content,
96− 'url': res_url})
97−
98− elif category_to_keyword.get(categories[0], '') == 'images':
99− thumbnail_src = result['thumbnail']
100− img_src = result['media']
101− results.append({'template': 'images.html',
102− 'url': res_url,
103− 'title': title,
104− 'content': '',
105− 'thumbnail_src': thumbnail_src,
106− 'img_src': img_src})
107−
108− elif category_to_keyword.get(categories[0], '') == 'news':
109− published_date = datetime.fromtimestamp(result['date'], None)
110− media = result.get('media', [])
111− if len(media) > 0:
112− img_src = media[0].get('pict', {}).get('url', None)
113− else:
163+ pub_date = item['date']
164+ if pub_date is not None:
165+ pub_date = datetime.fromtimestamp(pub_date)
166+ news_media = item.get('media', [])
114167 img_src = None
115− results.append({'url': res_url,
116− 'title': title,
117− 'publishedDate': published_date,
118− 'content': content,
119− 'img_src': img_src})
168+ if news_media:
169+ img_src = news_media[0].get('pict', {}).get('url', None)
170+ results.append({
171+ 'title': title,
172+ 'url': res_url,
173+ 'publishedDate': pub_date,
174+ 'img_src': img_src,
175+ })
176+
177+ elif mainline_type == 'images':
178+ thumbnail = item['thumbnail']
179+ img_src = item['media']
180+ results.append({
181+ 'title': title,
182+ 'url': res_url,
183+ 'template': 'images.html',
184+ 'thumbnail_src': thumbnail,
185+ 'img_src': img_src,
186+ })
187+
188+ elif mainline_type == 'videos':
189+ # some videos do not have a description: while qwant-video
190+ # returns an empty string, such video from a qwant-web query
191+ # miss the 'desc' key.
192+ d, s, c = item.get('desc'), item.get('source'), item.get('channel')
193+ content_parts = []
194+ if d:
195+ content_parts.append(d)
196+ if s:
197+ content_parts.append("%s: %s " % (gettext("Source"), s))
198+ if c:
199+ content_parts.append("%s: %s " % (gettext("Channel"), c))
200+ content = ' // '.join(content_parts)
201+ length = item['duration']
202+ if length is not None:
203+ length = timedelta(milliseconds=length)
204+ pub_date = item['date']
205+ if pub_date is not None:
206+ pub_date = datetime.fromtimestamp(pub_date)
207+ thumbnail = item['thumbnail']
208+ # from some locations (DE and others?) the s2 link do
209+ # response a 'Please wait ..' but does not deliver the thumbnail
210+ thumbnail = thumbnail.replace(
211+ 'https://s2.qwant.com',
212+ 'https://s1.qwant.com', 1
213+ )
214+ results.append({
215+ 'title': title,
216+ 'url': res_url,
217+ 'content': content,
218+ 'publishedDate': pub_date,
219+ 'thumbnail': thumbnail,
220+ 'template': 'videos.html',
221+ 'length': length,
222+ })
120223
121224 return results
122225
searx/settings.yml+14−6
@@ -988,18 +988,26 @@ engines:
988988 additional_tests:
989989 rosebud: *test_rosebud
990990
991− - name : qwant images
992− engine : qwant
993− shortcut : qwi
994− categories : images
995− network: qwant
996−
997991 - name : qwant news
998992 engine : qwant
999993 shortcut : qwn
1000994 categories : news
1001995 network: qwant
1002996
997+ - name: qwant images
998+ engine: qwant
999+ shortcut: qwi
1000+ categories: images
1001+ disabled: True
1002+ network: qwant
1003+
1004+ - name: qwant videos
1005+ engine: qwant
1006+ shortcut: qwv
1007+ categories: videos
1008+ disabled: True
1009+ network: qwant
1010+
10031011# - name: library
10041012# engine: recoll
10051013# shortcut: lib