wikipedia.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """This module implements the Wikipedia engine. Some of this implementations
  3. are shared by other engines:
  4. - :ref:`wikidata engine`
  5. The list of supported languages is :py:obj:`fetched <fetch_wikimedia_traits>` from
  6. the article linked by :py:obj:`list_of_wikipedias`.
  7. Unlike traditional search engines, wikipedia does not support one Wikipedia for
  8. all languages, but there is one Wikipedia for each supported language. Some of
  9. these Wikipedias have a LanguageConverter_ enabled
  10. (:py:obj:`rest_v1_summary_url`).
  11. A LanguageConverter_ (LC) is a system based on language variants that
  12. automatically converts the content of a page into a different variant. A variant
  13. is mostly the same language in a different script.
  14. - `Wikipedias in multiple writing systems`_
  15. - `Automatic conversion between traditional and simplified Chinese characters`_
  16. PR-2554_:
  17. The Wikipedia link returned by the API is still the same in all cases
  18. (`https://zh.wikipedia.org/wiki/出租車`_) but if your browser's
  19. ``Accept-Language`` is set to any of ``zh``, ``zh-CN``, ``zh-TW``, ``zh-HK``
  20. or .. Wikipedia's LC automatically returns the desired script in their
  21. web-page.
  22. - You can test the API here: https://reqbin.com/gesg2kvx
  23. .. _https://zh.wikipedia.org/wiki/出租車:
  24. https://zh.wikipedia.org/wiki/%E5%87%BA%E7%A7%9F%E8%BB%8A
  25. To support Wikipedia's LanguageConverter_, a SearXNG request to Wikipedia uses
  26. :py:obj:`get_wiki_params` and :py:obj:`wiki_lc_locale_variants' in the
  27. :py:obj:`fetch_wikimedia_traits` function.
  28. To test in SearXNG, query for ``!wp 出租車`` with each of the available Chinese
  29. options:
  30. - ``!wp 出租車 :zh`` should show 出租車
  31. - ``!wp 出租車 :zh-CN`` should show 出租车
  32. - ``!wp 出租車 :zh-TW`` should show 計程車
  33. - ``!wp 出租車 :zh-HK`` should show 的士
  34. - ``!wp 出租車 :zh-SG`` should show 德士
  35. .. _LanguageConverter:
  36. https://www.mediawiki.org/wiki/Writing_systems#LanguageConverter
  37. .. _Wikipedias in multiple writing systems:
  38. https://meta.wikimedia.org/wiki/Wikipedias_in_multiple_writing_systems
  39. .. _Automatic conversion between traditional and simplified Chinese characters:
  40. https://en.wikipedia.org/wiki/Chinese_Wikipedia#Automatic_conversion_between_traditional_and_simplified_Chinese_characters
  41. .. _PR-2554: https://github.com/searx/searx/pull/2554
  42. """
  43. import urllib.parse
  44. import babel
  45. from lxml import html
  46. from searx import utils
  47. from searx import network as _network
  48. from searx import locales
  49. from searx.enginelib.traits import EngineTraits
  50. traits: EngineTraits
  51. # about
  52. about = {
  53. "website": 'https://www.wikipedia.org/',
  54. "wikidata_id": 'Q52',
  55. "official_api_documentation": 'https://en.wikipedia.org/api/',
  56. "use_official_api": True,
  57. "require_api_key": False,
  58. "results": 'JSON',
  59. }
  60. display_type = ["infobox"]
  61. """A list of display types composed from ``infobox`` and ``list``. The latter
  62. one will add a hit to the result list. The first one will show a hit in the
  63. info box. Both values can be set, or one of the two can be set."""
  64. send_accept_language_header = True
  65. """The HTTP ``Accept-Language`` header is needed for wikis where
  66. LanguageConverter_ is enabled."""
  67. list_of_wikipedias = 'https://meta.wikimedia.org/wiki/List_of_Wikipedias'
  68. """`List of all wikipedias <https://meta.wikimedia.org/wiki/List_of_Wikipedias>`_
  69. """
  70. wikipedia_article_depth = 'https://meta.wikimedia.org/wiki/Wikipedia_article_depth'
  71. """The *editing depth* of Wikipedia is one of several possible rough indicators
  72. of the encyclopedia's collaborative quality, showing how frequently its articles
  73. are updated. The measurement of depth was introduced after some limitations of
  74. the classic measurement of article count were realized.
  75. """
  76. rest_v1_summary_url = 'https://{wiki_netloc}/api/rest_v1/page/summary/{title}'
  77. """
  78. `wikipedia rest_v1 summary API`_:
  79. The summary response includes an extract of the first paragraph of the page in
  80. plain text and HTML as well as the type of page. This is useful for page
  81. previews (fka. Hovercards, aka. Popups) on the web and link previews in the
  82. apps.
  83. HTTP ``Accept-Language`` header (:py:obj:`send_accept_language_header`):
  84. The desired language variant code for wikis where LanguageConverter_ is
  85. enabled.
  86. .. _wikipedia rest_v1 summary API:
  87. https://en.wikipedia.org/api/rest_v1/#/Page%20content/get_page_summary__title_
  88. """
  89. wiki_lc_locale_variants = {
  90. "zh": (
  91. "zh-CN",
  92. "zh-HK",
  93. "zh-MO",
  94. "zh-MY",
  95. "zh-SG",
  96. "zh-TW",
  97. ),
  98. "zh-classical": ("zh-classical",),
  99. }
  100. """Mapping rule of the LanguageConverter_ to map a language and its variants to
  101. a Locale (used in the HTTP ``Accept-Language`` header). For example see `LC
  102. Chinese`_.
  103. .. _LC Chinese:
  104. https://meta.wikimedia.org/wiki/Wikipedias_in_multiple_writing_systems#Chinese
  105. """
  106. wikipedia_script_variants = {
  107. "zh": (
  108. "zh_Hant",
  109. "zh_Hans",
  110. )
  111. }
  112. def get_wiki_params(sxng_locale, eng_traits):
  113. """Returns the Wikipedia language tag and the netloc that fits to the
  114. ``sxng_locale``. To support LanguageConverter_ this function rates a locale
  115. (region) higher than a language (compare :py:obj:`wiki_lc_locale_variants`).
  116. """
  117. eng_tag = eng_traits.get_region(sxng_locale, eng_traits.get_language(sxng_locale, 'en'))
  118. wiki_netloc = eng_traits.custom['wiki_netloc'].get(eng_tag, 'en.wikipedia.org')
  119. return eng_tag, wiki_netloc
  120. def request(query, params):
  121. """Assemble a request (`wikipedia rest_v1 summary API`_)."""
  122. if query.islower():
  123. query = query.title()
  124. _eng_tag, wiki_netloc = get_wiki_params(params['searxng_locale'], traits)
  125. title = urllib.parse.quote(query)
  126. params['url'] = rest_v1_summary_url.format(wiki_netloc=wiki_netloc, title=title)
  127. params['raise_for_httperror'] = False
  128. params['soft_max_redirects'] = 2
  129. return params
  130. # get response from search-request
  131. def response(resp):
  132. results = []
  133. if resp.status_code == 404:
  134. return []
  135. if resp.status_code == 400:
  136. try:
  137. api_result = resp.json()
  138. except Exception: # pylint: disable=broad-except
  139. pass
  140. else:
  141. if (
  142. api_result['type'] == 'https://mediawiki.org/wiki/HyperSwitch/errors/bad_request'
  143. and api_result['detail'] == 'title-invalid-characters'
  144. ):
  145. return []
  146. _network.raise_for_httperror(resp)
  147. api_result = resp.json()
  148. title = utils.html_to_text(api_result.get('titles', {}).get('display') or api_result.get('title'))
  149. wikipedia_link = api_result['content_urls']['desktop']['page']
  150. if "list" in display_type or api_result.get('type') != 'standard':
  151. # show item in the result list if 'list' is in the display options or it
  152. # is a item that can't be displayed in a infobox.
  153. results.append({'url': wikipedia_link, 'title': title, 'content': api_result.get('description', '')})
  154. if "infobox" in display_type:
  155. if api_result.get('type') == 'standard':
  156. results.append(
  157. {
  158. 'infobox': title,
  159. 'id': wikipedia_link,
  160. 'content': api_result.get('extract', ''),
  161. 'img_src': api_result.get('thumbnail', {}).get('source'),
  162. 'urls': [{'title': 'Wikipedia', 'url': wikipedia_link}],
  163. }
  164. )
  165. return results
  166. # Nonstandard language codes
  167. #
  168. # These Wikipedias use language codes that do not conform to the ISO 639
  169. # standard (which is how wiki subdomains are chosen nowadays).
  170. lang_map = locales.LOCALE_BEST_MATCH.copy()
  171. lang_map.update(
  172. {
  173. 'be-tarask': 'bel',
  174. 'ak': 'aka',
  175. 'als': 'gsw',
  176. 'bat-smg': 'sgs',
  177. 'cbk-zam': 'cbk',
  178. 'fiu-vro': 'vro',
  179. 'map-bms': 'map',
  180. 'no': 'nb-NO',
  181. 'nrm': 'nrf',
  182. 'roa-rup': 'rup',
  183. 'nds-nl': 'nds',
  184. #'simple: – invented code used for the Simple English Wikipedia (not the official IETF code en-simple)
  185. 'zh-min-nan': 'nan',
  186. 'zh-yue': 'yue',
  187. 'an': 'arg',
  188. }
  189. )
  190. def fetch_traits(engine_traits: EngineTraits):
  191. fetch_wikimedia_traits(engine_traits)
  192. print("WIKIPEDIA_LANGUAGES: %s" % len(engine_traits.custom['WIKIPEDIA_LANGUAGES']))
  193. def fetch_wikimedia_traits(engine_traits: EngineTraits):
  194. """Fetch languages from Wikipedia. Not all languages from the
  195. :py:obj:`list_of_wikipedias` are supported by SearXNG locales, only those
  196. known from :py:obj:`searx.locales.LOCALE_NAMES` or those with a minimal
  197. :py:obj:`editing depth <wikipedia_article_depth>`.
  198. The location of the Wikipedia address of a language is mapped in a
  199. :py:obj:`custom field <searx.enginelib.traits.EngineTraits.custom>`
  200. (``wiki_netloc``). Here is a reduced example:
  201. .. code:: python
  202. traits.custom['wiki_netloc'] = {
  203. "en": "en.wikipedia.org",
  204. ..
  205. "gsw": "als.wikipedia.org",
  206. ..
  207. "zh": "zh.wikipedia.org",
  208. "zh-classical": "zh-classical.wikipedia.org"
  209. }
  210. """
  211. # pylint: disable=too-many-branches
  212. engine_traits.custom['wiki_netloc'] = {}
  213. engine_traits.custom['WIKIPEDIA_LANGUAGES'] = []
  214. # insert alias to map from a script or region to a wikipedia variant
  215. for eng_tag, sxng_tag_list in wikipedia_script_variants.items():
  216. for sxng_tag in sxng_tag_list:
  217. engine_traits.languages[sxng_tag] = eng_tag
  218. for eng_tag, sxng_tag_list in wiki_lc_locale_variants.items():
  219. for sxng_tag in sxng_tag_list:
  220. engine_traits.regions[sxng_tag] = eng_tag
  221. resp = _network.get(list_of_wikipedias)
  222. if not resp.ok:
  223. print("ERROR: response from Wikipedia is not OK.")
  224. dom = html.fromstring(resp.text)
  225. for row in dom.xpath('//table[contains(@class,"sortable")]//tbody/tr'):
  226. cols = row.xpath('./td')
  227. if not cols:
  228. continue
  229. cols = [c.text_content().strip() for c in cols]
  230. depth = float(cols[11].replace('-', '0').replace(',', ''))
  231. articles = int(cols[4].replace(',', '').replace(',', ''))
  232. eng_tag = cols[3]
  233. wiki_url = row.xpath('./td[4]/a/@href')[0]
  234. wiki_url = urllib.parse.urlparse(wiki_url)
  235. try:
  236. sxng_tag = locales.language_tag(babel.Locale.parse(lang_map.get(eng_tag, eng_tag), sep='-'))
  237. except babel.UnknownLocaleError:
  238. # print("ERROR: %s [%s] is unknown by babel" % (cols[0], eng_tag))
  239. continue
  240. finally:
  241. engine_traits.custom['WIKIPEDIA_LANGUAGES'].append(eng_tag)
  242. if sxng_tag not in locales.LOCALE_NAMES:
  243. if articles < 10000:
  244. # exclude languages with too few articles
  245. continue
  246. if int(depth) < 20:
  247. # Rough indicator of a Wikipedia’s quality, showing how
  248. # frequently its articles are updated.
  249. continue
  250. conflict = engine_traits.languages.get(sxng_tag)
  251. if conflict:
  252. if conflict != eng_tag:
  253. print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_tag))
  254. continue
  255. engine_traits.languages[sxng_tag] = eng_tag
  256. engine_traits.custom['wiki_netloc'][eng_tag] = wiki_url.netloc
  257. engine_traits.custom['WIKIPEDIA_LANGUAGES'].sort()