wikipedia.py 11 KB

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