update_engine_descriptions.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. #!/usr/bin/env python
  2. # lint: pylint
  3. # SPDX-License-Identifier: AGPL-3.0-or-later
  4. """Fetch website description from websites and from
  5. :origin:`searx/engines/wikidata.py` engine.
  6. Output file: :origin:`searx/data/engine_descriptions.json`.
  7. """
  8. # pylint: disable=invalid-name, global-statement
  9. import json
  10. from urllib.parse import urlparse
  11. from os.path import join
  12. from lxml.html import fromstring
  13. from searx.engines import wikidata, set_loggers
  14. from searx.utils import extract_text, searx_useragent
  15. from searx.locales import LOCALE_NAMES, locales_initialize, match_locale
  16. from searx import searx_dir
  17. from searx.utils import gen_useragent, detect_language
  18. import searx.search
  19. import searx.network
  20. from searx.data import data_dir
  21. DATA_FILE = data_dir / 'engine_descriptions.json'
  22. set_loggers(wikidata, 'wikidata')
  23. locales_initialize()
  24. # you can run the query in https://query.wikidata.org
  25. # replace %IDS% by Wikidata entities separated by spaces with the prefix wd:
  26. # for example wd:Q182496 wd:Q1540899
  27. # replace %LANGUAGES_SPARQL% by languages
  28. SPARQL_WIKIPEDIA_ARTICLE = """
  29. SELECT DISTINCT ?item ?name ?article ?lang
  30. WHERE {
  31. hint:Query hint:optimizer "None".
  32. VALUES ?item { %IDS% }
  33. ?article schema:about ?item ;
  34. schema:inLanguage ?lang ;
  35. schema:name ?name ;
  36. schema:isPartOf [ wikibase:wikiGroup "wikipedia" ] .
  37. FILTER(?lang in (%LANGUAGES_SPARQL%)) .
  38. FILTER (!CONTAINS(?name, ':')) .
  39. }
  40. ORDER BY ?item ?lang
  41. """
  42. SPARQL_DESCRIPTION = """
  43. SELECT DISTINCT ?item ?itemDescription
  44. WHERE {
  45. VALUES ?item { %IDS% }
  46. ?item schema:description ?itemDescription .
  47. FILTER (lang(?itemDescription) in (%LANGUAGES_SPARQL%))
  48. }
  49. ORDER BY ?itemLang
  50. """
  51. NOT_A_DESCRIPTION = [
  52. 'web site',
  53. 'site web',
  54. 'komputa serĉilo',
  55. 'interreta serĉilo',
  56. 'bilaketa motor',
  57. 'web search engine',
  58. 'wikimedia täpsustuslehekülg',
  59. ]
  60. SKIP_ENGINE_SOURCE = [
  61. # fmt: off
  62. ('gitlab', 'wikidata')
  63. # descriptions are about wikipedia disambiguation pages
  64. # fmt: on
  65. ]
  66. WIKIPEDIA_LANGUAGES = {}
  67. LANGUAGES_SPARQL = ''
  68. IDS = None
  69. WIKIPEDIA_LANGUAGE_VARIANTS = {'zh_Hant': 'zh-tw'}
  70. descriptions = {}
  71. wd_to_engine_name = {}
  72. def normalize_description(description):
  73. for c in [chr(c) for c in range(0, 31)]:
  74. description = description.replace(c, ' ')
  75. description = ' '.join(description.strip().split())
  76. return description
  77. def update_description(engine_name, lang, description, source, replace=True):
  78. if not isinstance(description, str):
  79. return
  80. description = normalize_description(description)
  81. if description.lower() == engine_name.lower():
  82. return
  83. if description.lower() in NOT_A_DESCRIPTION:
  84. return
  85. if (engine_name, source) in SKIP_ENGINE_SOURCE:
  86. return
  87. if ' ' not in description:
  88. # skip unique word description (like "website")
  89. return
  90. if replace or lang not in descriptions[engine_name]:
  91. descriptions[engine_name][lang] = [description, source]
  92. def get_wikipedia_summary(wikipedia_url, searxng_locale):
  93. # get the REST API URL from the HTML URL
  94. # Headers
  95. headers = {'User-Agent': searx_useragent()}
  96. if searxng_locale in WIKIPEDIA_LANGUAGE_VARIANTS:
  97. headers['Accept-Language'] = WIKIPEDIA_LANGUAGE_VARIANTS.get(searxng_locale)
  98. # URL path : from HTML URL to REST API URL
  99. parsed_url = urlparse(wikipedia_url)
  100. # remove the /wiki/ prefix
  101. article_name = parsed_url.path.split('/wiki/')[1]
  102. # article_name is already encoded but not the / which is required for the REST API call
  103. encoded_article_name = article_name.replace('/', '%2F')
  104. path = '/api/rest_v1/page/summary/' + encoded_article_name
  105. wikipedia_rest_url = parsed_url._replace(path=path).geturl()
  106. try:
  107. response = searx.network.get(wikipedia_rest_url, headers=headers, timeout=10)
  108. response.raise_for_status()
  109. except Exception as e: # pylint: disable=broad-except
  110. print(" ", wikipedia_url, e)
  111. return None
  112. api_result = json.loads(response.text)
  113. return api_result.get('extract')
  114. def get_website_description(url, lang1, lang2=None):
  115. headers = {
  116. 'User-Agent': gen_useragent(),
  117. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  118. 'DNT': '1',
  119. 'Upgrade-Insecure-Requests': '1',
  120. 'Sec-GPC': '1',
  121. 'Cache-Control': 'max-age=0',
  122. }
  123. if lang1 is not None:
  124. lang_list = [lang1]
  125. if lang2 is not None:
  126. lang_list.append(lang2)
  127. headers['Accept-Language'] = f'{",".join(lang_list)};q=0.8'
  128. try:
  129. response = searx.network.get(url, headers=headers, timeout=10)
  130. response.raise_for_status()
  131. except Exception: # pylint: disable=broad-except
  132. return (None, None)
  133. try:
  134. html = fromstring(response.text)
  135. except ValueError:
  136. html = fromstring(response.content)
  137. description = extract_text(html.xpath('/html/head/meta[@name="description"]/@content'))
  138. if not description:
  139. description = extract_text(html.xpath('/html/head/meta[@property="og:description"]/@content'))
  140. if not description:
  141. description = extract_text(html.xpath('/html/head/title'))
  142. lang = extract_text(html.xpath('/html/@lang'))
  143. if lang is None and len(lang1) > 0:
  144. lang = lang1
  145. lang = detect_language(description) or lang or 'en'
  146. lang = lang.split('_')[0]
  147. lang = lang.split('-')[0]
  148. return (lang, description)
  149. def initialize():
  150. global IDS, LANGUAGES_SPARQL
  151. searx.search.initialize()
  152. wikipedia_engine = searx.engines.engines['wikipedia']
  153. locale2lang = {'nl-BE': 'nl'}
  154. for sxng_ui_lang in LOCALE_NAMES:
  155. sxng_ui_alias = locale2lang.get(sxng_ui_lang, sxng_ui_lang)
  156. wiki_lang = None
  157. if sxng_ui_alias in wikipedia_engine.traits.custom['WIKIPEDIA_LANGUAGES']:
  158. wiki_lang = sxng_ui_alias
  159. if not wiki_lang:
  160. wiki_lang = wikipedia_engine.traits.get_language(sxng_ui_alias)
  161. if not wiki_lang:
  162. print(f"WIKIPEDIA_LANGUAGES missing {sxng_ui_lang}")
  163. continue
  164. WIKIPEDIA_LANGUAGES[sxng_ui_lang] = wiki_lang
  165. LANGUAGES_SPARQL = ', '.join(f"'{l}'" for l in set(WIKIPEDIA_LANGUAGES.values()))
  166. for engine_name, engine in searx.engines.engines.items():
  167. descriptions[engine_name] = {}
  168. wikidata_id = getattr(engine, "about", {}).get('wikidata_id')
  169. if wikidata_id is not None:
  170. wd_to_engine_name.setdefault(wikidata_id, set()).add(engine_name)
  171. IDS = ' '.join(list(map(lambda wd_id: 'wd:' + wd_id, wd_to_engine_name.keys())))
  172. def fetch_wikidata_descriptions():
  173. print('Fetching wikidata descriptions')
  174. searx.network.set_timeout_for_thread(60)
  175. result = wikidata.send_wikidata_query(
  176. SPARQL_DESCRIPTION.replace('%IDS%', IDS).replace('%LANGUAGES_SPARQL%', LANGUAGES_SPARQL)
  177. )
  178. if result is not None:
  179. for binding in result['results']['bindings']:
  180. wikidata_id = binding['item']['value'].replace('http://www.wikidata.org/entity/', '')
  181. wikidata_lang = binding['itemDescription']['xml:lang']
  182. desc = binding['itemDescription']['value']
  183. for engine_name in wd_to_engine_name[wikidata_id]:
  184. for searxng_locale in LOCALE_NAMES:
  185. if WIKIPEDIA_LANGUAGES[searxng_locale] != wikidata_lang:
  186. continue
  187. print(
  188. f" engine: {engine_name:20} / wikidata_lang: {wikidata_lang:5}",
  189. f"/ len(wikidata_desc): {len(desc)}",
  190. )
  191. update_description(engine_name, searxng_locale, desc, 'wikidata')
  192. def fetch_wikipedia_descriptions():
  193. print('Fetching wikipedia descriptions')
  194. result = wikidata.send_wikidata_query(
  195. SPARQL_WIKIPEDIA_ARTICLE.replace('%IDS%', IDS).replace('%LANGUAGES_SPARQL%', LANGUAGES_SPARQL)
  196. )
  197. if result is not None:
  198. for binding in result['results']['bindings']:
  199. wikidata_id = binding['item']['value'].replace('http://www.wikidata.org/entity/', '')
  200. wikidata_lang = binding['name']['xml:lang']
  201. wikipedia_url = binding['article']['value'] # for example the URL https://de.wikipedia.org/wiki/PubMed
  202. for engine_name in wd_to_engine_name[wikidata_id]:
  203. for searxng_locale in LOCALE_NAMES:
  204. if WIKIPEDIA_LANGUAGES[searxng_locale] != wikidata_lang:
  205. continue
  206. desc = get_wikipedia_summary(wikipedia_url, searxng_locale)
  207. if not desc:
  208. continue
  209. print(
  210. f" engine: {engine_name:20} / wikidata_lang: {wikidata_lang:5}",
  211. f"/ len(wikipedia_desc): {len(desc)}",
  212. )
  213. update_description(engine_name, searxng_locale, desc, 'wikipedia')
  214. def normalize_url(url):
  215. url = url.replace('{language}', 'en')
  216. url = urlparse(url)._replace(path='/', params='', query='', fragment='').geturl()
  217. url = url.replace('https://api.', 'https://')
  218. return url
  219. def fetch_website_description(engine_name, website):
  220. print(f"- fetch website descr: {engine_name} / {website}")
  221. default_lang, default_description = get_website_description(website, None, None)
  222. if default_lang is None or default_description is None:
  223. # the front page can't be fetched: skip this engine
  224. return
  225. # to specify an order in where the most common languages are in front of the
  226. # language list ..
  227. languages = ['en', 'es', 'pt', 'ru', 'tr', 'fr']
  228. languages = languages + [l for l in LOCALE_NAMES if l not in languages]
  229. previous_matched_lang = None
  230. previous_count = 0
  231. for lang in languages:
  232. if lang in descriptions[engine_name]:
  233. continue
  234. fetched_lang, desc = get_website_description(website, lang, WIKIPEDIA_LANGUAGES[lang])
  235. if fetched_lang is None or desc is None:
  236. continue
  237. # check if desc changed with the different lang values
  238. if fetched_lang == previous_matched_lang:
  239. previous_count += 1
  240. if previous_count == 6:
  241. # the website has returned the same description for 6 different languages in Accept-Language header
  242. # stop now
  243. break
  244. else:
  245. previous_matched_lang = fetched_lang
  246. previous_count = 0
  247. # Don't trust in the value of fetched_lang, some websites return
  248. # for some inappropriate values, by example bing-images::
  249. #
  250. # requested lang: zh-Hans-CN / fetched lang: ceb / desc: 查看根据您的兴趣量身定制的提要
  251. #
  252. # The lang ceb is "Cebuano" but the description is given in zh-Hans-CN
  253. print(
  254. f" engine: {engine_name:20} / requested lang:{lang:7}"
  255. f" / fetched lang: {fetched_lang:7} / len(desc): {len(desc)}"
  256. )
  257. matched_lang = match_locale(fetched_lang, LOCALE_NAMES.keys(), fallback=lang)
  258. update_description(engine_name, matched_lang, desc, website, replace=False)
  259. def fetch_website_descriptions():
  260. print('Fetching website descriptions')
  261. for engine_name, engine in searx.engines.engines.items():
  262. website = getattr(engine, "about", {}).get('website')
  263. if website is None and hasattr(engine, "search_url"):
  264. website = normalize_url(getattr(engine, "search_url"))
  265. if website is None and hasattr(engine, "base_url"):
  266. website = normalize_url(getattr(engine, "base_url"))
  267. if website is not None:
  268. fetch_website_description(engine_name, website)
  269. def get_engine_descriptions_filename():
  270. return join(join(searx_dir, "data"), "engine_descriptions.json")
  271. def get_output():
  272. """
  273. From descriptions[engine][language] = [description, source]
  274. To
  275. * output[language][engine] = description_and_source
  276. * description_and_source can be:
  277. * [description, source]
  278. * description (if source = "wikipedia")
  279. * [f"engine:lang", "ref"] (reference to another existing description)
  280. """
  281. output = {locale: {} for locale in LOCALE_NAMES}
  282. seen_descriptions = {}
  283. for engine_name, lang_descriptions in descriptions.items():
  284. for language, description in lang_descriptions.items():
  285. if description[0] in seen_descriptions:
  286. ref = seen_descriptions[description[0]]
  287. description = [f'{ref[0]}:{ref[1]}', 'ref']
  288. else:
  289. seen_descriptions[description[0]] = (engine_name, language)
  290. if description[1] == 'wikipedia':
  291. description = description[0]
  292. output.setdefault(language, {}).setdefault(engine_name, description)
  293. return output
  294. def main():
  295. initialize()
  296. fetch_wikidata_descriptions()
  297. fetch_wikipedia_descriptions()
  298. fetch_website_descriptions()
  299. output = get_output()
  300. with DATA_FILE.open('w', encoding='utf8') as f:
  301. f.write(json.dumps(output, indent=1, separators=(',', ':'), sort_keys=True, ensure_ascii=False))
  302. if __name__ == "__main__":
  303. main()