.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
searx.engines.wikipedia Namespace Reference

Functions

 get_wiki_params (sxng_locale, eng_traits)
 
 request (query, params)
 
 response (resp)
 
 fetch_traits (EngineTraits engine_traits)
 
 fetch_wikimedia_traits (EngineTraits engine_traits)
 

Variables

dict about
 
list display_type = ["infobox"]
 
bool send_accept_language_header = True
 
str list_of_wikipedias = 'https://meta.wikimedia.org/wiki/List_of_Wikipedias'
 
str wikipedia_article_depth = 'https://meta.wikimedia.org/wiki/Wikipedia_article_depth'
 
str rest_v1_summary_url = 'https://{wiki_netloc}/api/rest_v1/page/summary/{title}'
 
dict wiki_lc_locale_variants
 
dict wikipedia_script_variants
 
 lang_map = locales.LOCALE_BEST_MATCH.copy()
 

Detailed Description

This module implements the Wikipedia engine.  Some of this implementations
are shared by other engines:

- :ref:`wikidata engine`

The list of supported languages is :py:obj:`fetched <fetch_wikimedia_traits>` from
the article linked by :py:obj:`list_of_wikipedias`.

Unlike traditional search engines, wikipedia does not support one Wikipedia for
all languages, but there is one Wikipedia for each supported language. Some of
these Wikipedias have a LanguageConverter_ enabled
(:py:obj:`rest_v1_summary_url`).

A LanguageConverter_ (LC) is a system based on language variants that
automatically converts the content of a page into a different variant. A variant
is mostly the same language in a different script.

- `Wikipedias in multiple writing systems`_
- `Automatic conversion between traditional and simplified Chinese characters`_

PR-2554_:
  The Wikipedia link returned by the API is still the same in all cases
  (`https://zh.wikipedia.org/wiki/出租車`_) but if your browser's
  ``Accept-Language`` is set to any of ``zh``, ``zh-CN``, ``zh-TW``, ``zh-HK``
  or .. Wikipedia's LC automatically returns the desired script in their
  web-page.

  - You can test the API here: https://reqbin.com/gesg2kvx

.. _https://zh.wikipedia.org/wiki/出租車:
   https://zh.wikipedia.org/wiki/%E5%87%BA%E7%A7%9F%E8%BB%8A

To support Wikipedia's LanguageConverter_, a SearXNG request to Wikipedia uses
:py:obj:`get_wiki_params` and :py:obj:`wiki_lc_locale_variants' in the
:py:obj:`fetch_wikimedia_traits` function.

To test in SearXNG, query for ``!wp 出租車`` with each of the available Chinese
options:

- ``!wp 出租車 :zh``    should show 出租車
- ``!wp 出租車 :zh-CN`` should show 出租车
- ``!wp 出租車 :zh-TW`` should show 計程車
- ``!wp 出租車 :zh-HK`` should show 的士
- ``!wp 出租車 :zh-SG`` should show 德士

.. _LanguageConverter:
   https://www.mediawiki.org/wiki/Writing_systems#LanguageConverter
.. _Wikipedias in multiple writing systems:
   https://meta.wikimedia.org/wiki/Wikipedias_in_multiple_writing_systems
.. _Automatic conversion between traditional and simplified Chinese characters:
   https://en.wikipedia.org/wiki/Chinese_Wikipedia#Automatic_conversion_between_traditional_and_simplified_Chinese_characters
.. _PR-2554: https://github.com/searx/searx/pull/2554

Function Documentation

◆ fetch_traits()

searx.engines.wikipedia.fetch_traits ( EngineTraits engine_traits)

Definition at line 240 of file wikipedia.py.

240def fetch_traits(engine_traits: EngineTraits):
241 fetch_wikimedia_traits(engine_traits)
242 print("WIKIPEDIA_LANGUAGES: %s" % len(engine_traits.custom['WIKIPEDIA_LANGUAGES']))
243
244

◆ fetch_wikimedia_traits()

searx.engines.wikipedia.fetch_wikimedia_traits ( EngineTraits engine_traits)
Fetch languages from Wikipedia.  Not all languages from the
:py:obj:`list_of_wikipedias` are supported by SearXNG locales, only those
known from :py:obj:`searx.locales.LOCALE_NAMES` or those with a minimal
:py:obj:`editing depth <wikipedia_article_depth>`.

The location of the Wikipedia address of a language is mapped in a
:py:obj:`custom field <searx.enginelib.traits.EngineTraits.custom>`
(``wiki_netloc``).  Here is a reduced example:

.. code:: python

   traits.custom['wiki_netloc'] = {
       "en": "en.wikipedia.org",
       ..
       "gsw": "als.wikipedia.org",
       ..
       "zh": "zh.wikipedia.org",
       "zh-classical": "zh-classical.wikipedia.org"
   }

Definition at line 245 of file wikipedia.py.

245def fetch_wikimedia_traits(engine_traits: EngineTraits):
246 """Fetch languages from Wikipedia. Not all languages from the
247 :py:obj:`list_of_wikipedias` are supported by SearXNG locales, only those
248 known from :py:obj:`searx.locales.LOCALE_NAMES` or those with a minimal
249 :py:obj:`editing depth <wikipedia_article_depth>`.
250
251 The location of the Wikipedia address of a language is mapped in a
252 :py:obj:`custom field <searx.enginelib.traits.EngineTraits.custom>`
253 (``wiki_netloc``). Here is a reduced example:
254
255 .. code:: python
256
257 traits.custom['wiki_netloc'] = {
258 "en": "en.wikipedia.org",
259 ..
260 "gsw": "als.wikipedia.org",
261 ..
262 "zh": "zh.wikipedia.org",
263 "zh-classical": "zh-classical.wikipedia.org"
264 }
265 """
266 # pylint: disable=too-many-branches
267 engine_traits.custom['wiki_netloc'] = {}
268 engine_traits.custom['WIKIPEDIA_LANGUAGES'] = []
269
270 # insert alias to map from a script or region to a wikipedia variant
271
272 for eng_tag, sxng_tag_list in wikipedia_script_variants.items():
273 for sxng_tag in sxng_tag_list:
274 engine_traits.languages[sxng_tag] = eng_tag
275 for eng_tag, sxng_tag_list in wiki_lc_locale_variants.items():
276 for sxng_tag in sxng_tag_list:
277 engine_traits.regions[sxng_tag] = eng_tag
278
279 resp = _network.get(list_of_wikipedias)
280 if not resp.ok:
281 print("ERROR: response from Wikipedia is not OK.")
282
283 dom = html.fromstring(resp.text)
284 for row in dom.xpath('//table[contains(@class,"sortable")]//tbody/tr'):
285
286 cols = row.xpath('./td')
287 if not cols:
288 continue
289 cols = [c.text_content().strip() for c in cols]
290
291 depth = float(cols[11].replace('-', '0').replace(',', ''))
292 articles = int(cols[4].replace(',', '').replace(',', ''))
293
294 eng_tag = cols[3]
295 wiki_url = row.xpath('./td[4]/a/@href')[0]
296 wiki_url = urllib.parse.urlparse(wiki_url)
297
298 try:
299 sxng_tag = locales.language_tag(babel.Locale.parse(lang_map.get(eng_tag, eng_tag), sep='-'))
300 except babel.UnknownLocaleError:
301 # print("ERROR: %s [%s] is unknown by babel" % (cols[0], eng_tag))
302 continue
303 finally:
304 engine_traits.custom['WIKIPEDIA_LANGUAGES'].append(eng_tag)
305
306 if sxng_tag not in locales.LOCALE_NAMES:
307
308 if articles < 10000:
309 # exclude languages with too few articles
310 continue
311
312 if int(depth) < 20:
313 # Rough indicator of a Wikipedia’s quality, showing how
314 # frequently its articles are updated.
315 continue
316
317 conflict = engine_traits.languages.get(sxng_tag)
318 if conflict:
319 if conflict != eng_tag:
320 print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_tag))
321 continue
322
323 engine_traits.languages[sxng_tag] = eng_tag
324 engine_traits.custom['wiki_netloc'][eng_tag] = wiki_url.netloc
325
326 engine_traits.custom['WIKIPEDIA_LANGUAGES'].sort()

◆ get_wiki_params()

searx.engines.wikipedia.get_wiki_params ( sxng_locale,
eng_traits )
Returns the Wikipedia language tag and the netloc that fits to the
``sxng_locale``.  To support LanguageConverter_ this function rates a locale
(region) higher than a language (compare :py:obj:`wiki_lc_locale_variants`).

Definition at line 143 of file wikipedia.py.

143def get_wiki_params(sxng_locale, eng_traits):
144 """Returns the Wikipedia language tag and the netloc that fits to the
145 ``sxng_locale``. To support LanguageConverter_ this function rates a locale
146 (region) higher than a language (compare :py:obj:`wiki_lc_locale_variants`).
147
148 """
149 eng_tag = eng_traits.get_region(sxng_locale, eng_traits.get_language(sxng_locale, 'en'))
150 wiki_netloc = eng_traits.custom['wiki_netloc'].get(eng_tag, 'en.wikipedia.org')
151 return eng_tag, wiki_netloc
152
153

◆ request()

searx.engines.wikipedia.request ( query,
params )
Assemble a request (`wikipedia rest_v1 summary API`_).

Definition at line 154 of file wikipedia.py.

154def request(query, params):
155 """Assemble a request (`wikipedia rest_v1 summary API`_)."""
156 if query.islower():
157 query = query.title()
158
159 _eng_tag, wiki_netloc = get_wiki_params(params['searxng_locale'], traits)
160 title = urllib.parse.quote(query)
161 params['url'] = rest_v1_summary_url.format(wiki_netloc=wiki_netloc, title=title)
162
163 params['raise_for_httperror'] = False
164 params['soft_max_redirects'] = 2
165
166 return params
167
168
169# get response from search-request

◆ response()

searx.engines.wikipedia.response ( resp)

Definition at line 170 of file wikipedia.py.

170def response(resp):
171
172 results = []
173 if resp.status_code == 404:
174 return []
175 if resp.status_code == 400:
176 try:
177 api_result = resp.json()
178 except Exception: # pylint: disable=broad-except
179 pass
180 else:
181 if (
182 api_result['type'] == 'https://mediawiki.org/wiki/HyperSwitch/errors/bad_request'
183 and api_result['detail'] == 'title-invalid-characters'
184 ):
185 return []
186
187 _network.raise_for_httperror(resp)
188
189 api_result = resp.json()
190 title = utils.html_to_text(api_result.get('titles', {}).get('display') or api_result.get('title'))
191 wikipedia_link = api_result['content_urls']['desktop']['page']
192
193 if "list" in display_type or api_result.get('type') != 'standard':
194 # show item in the result list if 'list' is in the display options or it
195 # is a item that can't be displayed in a infobox.
196 results.append({'url': wikipedia_link, 'title': title, 'content': api_result.get('description', '')})
197
198 if "infobox" in display_type:
199 if api_result.get('type') == 'standard':
200 results.append(
201 {
202 'infobox': title,
203 'id': wikipedia_link,
204 'content': api_result.get('extract', ''),
205 'img_src': api_result.get('thumbnail', {}).get('source'),
206 'urls': [{'title': 'Wikipedia', 'url': wikipedia_link}],
207 }
208 )
209
210 return results
211
212
213# Nonstandard language codes
214#
215# These Wikipedias use language codes that do not conform to the ISO 639
216# standard (which is how wiki subdomains are chosen nowadays).
217

Variable Documentation

◆ about

dict searx.engines.wikipedia.about
Initial value:
1= {
2 "website": 'https://www.wikipedia.org/',
3 "wikidata_id": 'Q52',
4 "official_api_documentation": 'https://en.wikipedia.org/api/',
5 "use_official_api": True,
6 "require_api_key": False,
7 "results": 'JSON',
8}

Definition at line 70 of file wikipedia.py.

◆ display_type

list searx.engines.wikipedia.display_type = ["infobox"]

Definition at line 79 of file wikipedia.py.

◆ lang_map

searx.engines.wikipedia.lang_map = locales.LOCALE_BEST_MATCH.copy()

Definition at line 218 of file wikipedia.py.

◆ list_of_wikipedias

str searx.engines.wikipedia.list_of_wikipedias = 'https://meta.wikimedia.org/wiki/List_of_Wikipedias'

Definition at line 88 of file wikipedia.py.

◆ rest_v1_summary_url

str searx.engines.wikipedia.rest_v1_summary_url = 'https://{wiki_netloc}/api/rest_v1/page/summary/{title}'

Definition at line 99 of file wikipedia.py.

◆ send_accept_language_header

bool searx.engines.wikipedia.send_accept_language_header = True

Definition at line 84 of file wikipedia.py.

◆ wiki_lc_locale_variants

dict searx.engines.wikipedia.wiki_lc_locale_variants
Initial value:
1= {
2 "zh": (
3 "zh-CN",
4 "zh-HK",
5 "zh-MO",
6 "zh-MY",
7 "zh-SG",
8 "zh-TW",
9 ),
10 "zh-classical": ("zh-classical",),
11}

Definition at line 116 of file wikipedia.py.

◆ wikipedia_article_depth

str searx.engines.wikipedia.wikipedia_article_depth = 'https://meta.wikimedia.org/wiki/Wikipedia_article_depth'

Definition at line 92 of file wikipedia.py.

◆ wikipedia_script_variants

dict searx.engines.wikipedia.wikipedia_script_variants
Initial value:
1= {
2 "zh": (
3 "zh_Hant",
4 "zh_Hans",
5 )
6}

Definition at line 135 of file wikipedia.py.