update_engine_descriptions.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. #!/usr/bin/env python
  2. # SPDX-License-Identifier: AGPL-3.0-or-later
  3. import json
  4. from urllib.parse import urlparse
  5. from os.path import join
  6. from lxml.html import fromstring
  7. from langdetect import detect_langs
  8. from langdetect.lang_detect_exception import LangDetectException
  9. from searx.engines import wikidata, set_loggers
  10. from searx.utils import extract_text, match_language
  11. from searx.locales import LOCALE_NAMES
  12. from searx import searx_dir
  13. from searx.utils import gen_useragent
  14. import searx.search
  15. import searx.network
  16. set_loggers(wikidata, 'wikidata')
  17. SPARQL_WIKIPEDIA_ARTICLE = """
  18. SELECT DISTINCT ?item ?name
  19. WHERE {
  20. hint:Query hint:optimizer "None".
  21. VALUES ?item { %IDS% }
  22. ?article schema:about ?item ;
  23. schema:inLanguage ?lang ;
  24. schema:name ?name ;
  25. schema:isPartOf [ wikibase:wikiGroup "wikipedia" ] .
  26. FILTER(?lang in (%LANGUAGES_SPARQL%)) .
  27. FILTER (!CONTAINS(?name, ':')) .
  28. }
  29. """
  30. SPARQL_DESCRIPTION = """
  31. SELECT DISTINCT ?item ?itemDescription
  32. WHERE {
  33. VALUES ?item { %IDS% }
  34. ?item schema:description ?itemDescription .
  35. FILTER (lang(?itemDescription) in (%LANGUAGES_SPARQL%))
  36. }
  37. ORDER BY ?itemLang
  38. """
  39. NOT_A_DESCRIPTION = [
  40. 'web site',
  41. 'site web',
  42. 'komputa serĉilo',
  43. 'interreta serĉilo',
  44. 'bilaketa motor',
  45. 'web search engine',
  46. 'wikimedia täpsustuslehekülg',
  47. ]
  48. SKIP_ENGINE_SOURCE = [
  49. # fmt: off
  50. ('gitlab', 'wikidata') # descriptions are about wikipedia disambiguation pages
  51. # fmt: on
  52. ]
  53. LANGUAGES = LOCALE_NAMES.keys()
  54. WIKIPEDIA_LANGUAGES = {'language': 'wikipedia_language'}
  55. LANGUAGES_SPARQL = ''
  56. IDS = None
  57. descriptions = {}
  58. wd_to_engine_name = {}
  59. def normalize_description(description):
  60. for c in [chr(c) for c in range(0, 31)]:
  61. description = description.replace(c, ' ')
  62. description = ' '.join(description.strip().split())
  63. return description
  64. def update_description(engine_name, lang, description, source, replace=True):
  65. if not isinstance(description, str):
  66. return
  67. description = normalize_description(description)
  68. if description.lower() == engine_name.lower():
  69. return
  70. if description.lower() in NOT_A_DESCRIPTION:
  71. return
  72. if (engine_name, source) in SKIP_ENGINE_SOURCE:
  73. return
  74. if ' ' not in description:
  75. # skip unique word description (like "website")
  76. return
  77. if replace or lang not in descriptions[engine_name]:
  78. descriptions[engine_name][lang] = [description, source]
  79. def get_wikipedia_summary(lang, pageid):
  80. params = {
  81. 'language': lang.replace('_','-'),
  82. 'headers': {}
  83. }
  84. searx.engines.engines['wikipedia'].request(pageid, params)
  85. try:
  86. response = searx.network.get(params['url'], headers=params['headers'], timeout=10)
  87. response.raise_for_status()
  88. api_result = json.loads(response.text)
  89. return api_result.get('extract')
  90. except:
  91. return None
  92. def detect_language(text):
  93. try:
  94. r = detect_langs(str(text)) # pylint: disable=E1101
  95. except LangDetectException:
  96. return None
  97. if len(r) > 0 and r[0].prob > 0.95:
  98. return r[0].lang
  99. return None
  100. def get_website_description(url, lang1, lang2=None):
  101. headers = {
  102. 'User-Agent': gen_useragent(),
  103. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  104. 'DNT': '1',
  105. 'Upgrade-Insecure-Requests': '1',
  106. 'Sec-GPC': '1',
  107. 'Cache-Control': 'max-age=0',
  108. }
  109. if lang1 is not None:
  110. lang_list = [lang1]
  111. if lang2 is not None:
  112. lang_list.append(lang2)
  113. headers['Accept-Language'] = f'{",".join(lang_list)};q=0.8'
  114. try:
  115. response = searx.network.get(url, headers=headers, timeout=10)
  116. response.raise_for_status()
  117. except Exception:
  118. return (None, None)
  119. try:
  120. html = fromstring(response.text)
  121. except ValueError:
  122. html = fromstring(response.content)
  123. description = extract_text(html.xpath('/html/head/meta[@name="description"]/@content'))
  124. if not description:
  125. description = extract_text(html.xpath('/html/head/meta[@property="og:description"]/@content'))
  126. if not description:
  127. description = extract_text(html.xpath('/html/head/title'))
  128. lang = extract_text(html.xpath('/html/@lang'))
  129. if lang is None and len(lang1) > 0:
  130. lang = lang1
  131. lang = detect_language(description) or lang or 'en'
  132. lang = lang.split('_')[0]
  133. lang = lang.split('-')[0]
  134. return (lang, description)
  135. def initialize():
  136. global IDS, WIKIPEDIA_LANGUAGES, LANGUAGES_SPARQL
  137. searx.search.initialize()
  138. wikipedia_engine = searx.engines.engines['wikipedia']
  139. WIKIPEDIA_LANGUAGES = {
  140. language: wikipedia_engine.url_lang(language.replace('_', '-'))
  141. for language in LANGUAGES
  142. }
  143. WIKIPEDIA_LANGUAGES['nb_NO'] = 'no'
  144. LANGUAGES_SPARQL = ', '.join(f"'{l}'" for l in set(WIKIPEDIA_LANGUAGES.values()))
  145. for engine_name, engine in searx.engines.engines.items():
  146. descriptions[engine_name] = {}
  147. wikidata_id = getattr(engine, "about", {}).get('wikidata_id')
  148. if wikidata_id is not None:
  149. wd_to_engine_name.setdefault(wikidata_id, set()).add(engine_name)
  150. IDS = ' '.join(list(map(lambda wd_id: 'wd:' + wd_id, wd_to_engine_name.keys())))
  151. def fetch_wikidata_descriptions():
  152. searx.network.set_timeout_for_thread(60)
  153. result = wikidata.send_wikidata_query(
  154. SPARQL_DESCRIPTION
  155. .replace('%IDS%', IDS)
  156. .replace('%LANGUAGES_SPARQL%', LANGUAGES_SPARQL)
  157. )
  158. if result is not None:
  159. for binding in result['results']['bindings']:
  160. wikidata_id = binding['item']['value'].replace('http://www.wikidata.org/entity/', '')
  161. wikidata_lang = binding['itemDescription']['xml:lang']
  162. description = binding['itemDescription']['value']
  163. for engine_name in wd_to_engine_name[wikidata_id]:
  164. for lang in LANGUAGES:
  165. if WIKIPEDIA_LANGUAGES[lang] == wikidata_lang:
  166. update_description(engine_name, lang, description, 'wikidata')
  167. def fetch_wikipedia_descriptions():
  168. result = wikidata.send_wikidata_query(
  169. SPARQL_WIKIPEDIA_ARTICLE
  170. .replace('%IDS%', IDS)
  171. .replace('%LANGUAGES_SPARQL%', LANGUAGES_SPARQL)
  172. )
  173. if result is not None:
  174. for binding in result['results']['bindings']:
  175. wikidata_id = binding['item']['value'].replace('http://www.wikidata.org/entity/', '')
  176. wikidata_lang = binding['name']['xml:lang']
  177. pageid = binding['name']['value']
  178. for engine_name in wd_to_engine_name[wikidata_id]:
  179. for lang in LANGUAGES:
  180. if WIKIPEDIA_LANGUAGES[lang] == wikidata_lang:
  181. description = get_wikipedia_summary(lang, pageid)
  182. update_description(engine_name, lang, description, 'wikipedia')
  183. def normalize_url(url):
  184. url = url.replace('{language}', 'en')
  185. url = urlparse(url)._replace(path='/', params='', query='', fragment='').geturl()
  186. url = url.replace('https://api.', 'https://')
  187. return url
  188. def fetch_website_description(engine_name, website):
  189. default_lang, default_description = get_website_description(website, None, None)
  190. if default_lang is None or default_description is None:
  191. # the front page can't be fetched: skip this engine
  192. return
  193. wikipedia_languages_r = { V: K for K, V in WIKIPEDIA_LANGUAGES.items() }
  194. languages = ['en', 'es', 'pt', 'ru', 'tr', 'fr']
  195. languages = languages + [ l for l in LANGUAGES if l not in languages]
  196. previous_matched_lang = None
  197. previous_count = 0
  198. for lang in languages:
  199. if lang not in descriptions[engine_name]:
  200. fetched_lang, desc = get_website_description(website, lang, WIKIPEDIA_LANGUAGES[lang])
  201. if fetched_lang is None or desc is None:
  202. continue
  203. matched_lang = match_language(fetched_lang, LANGUAGES, fallback=None)
  204. if matched_lang is None:
  205. fetched_wikipedia_lang = match_language(fetched_lang, WIKIPEDIA_LANGUAGES.values(), fallback=None)
  206. matched_lang = wikipedia_languages_r.get(fetched_wikipedia_lang)
  207. if matched_lang is not None:
  208. update_description(engine_name, matched_lang, desc, website, replace=False)
  209. # check if desc changed with the different lang values
  210. if matched_lang == previous_matched_lang:
  211. previous_count += 1
  212. if previous_count == 6:
  213. # the website has returned the same description for 6 different languages in Accept-Language header
  214. # stop now
  215. break
  216. else:
  217. previous_matched_lang = matched_lang
  218. previous_count = 0
  219. def fetch_website_descriptions():
  220. for engine_name, engine in searx.engines.engines.items():
  221. website = getattr(engine, "about", {}).get('website')
  222. if website is None and hasattr(engine, "search_url"):
  223. website = normalize_url(getattr(engine, "search_url"))
  224. if website is None and hasattr(engine, "base_url"):
  225. website = normalize_url(getattr(engine, "base_url"))
  226. if website is not None:
  227. fetch_website_description(engine_name, website)
  228. def get_engine_descriptions_filename():
  229. return join(join(searx_dir, "data"), "engine_descriptions.json")
  230. def get_output():
  231. """
  232. From descriptions[engine][language] = [description, source]
  233. To
  234. * output[language][engine] = description_and_source
  235. * description_and_source can be:
  236. * [description, source]
  237. * description (if source = "wikipedia")
  238. * [f"engine:lang", "ref"] (reference to another existing description)
  239. """
  240. output = {
  241. locale: {} for locale in LOCALE_NAMES
  242. }
  243. seen_descriptions = {}
  244. for engine_name, lang_descriptions in descriptions.items():
  245. for language, description in lang_descriptions.items():
  246. if description[0] in seen_descriptions:
  247. ref = seen_descriptions[description[0]]
  248. description = [f'{ref[0]}:{ref[1]}', 'ref']
  249. else:
  250. seen_descriptions[description[0]] = (engine_name, language)
  251. if description[1] == 'wikipedia':
  252. description = description[0]
  253. output.setdefault(language, {}).setdefault(engine_name, description)
  254. return output
  255. def main():
  256. initialize()
  257. print('Fetching wikidata descriptions')
  258. fetch_wikidata_descriptions()
  259. print('Fetching wikipedia descriptions')
  260. fetch_wikipedia_descriptions()
  261. print('Fetching website descriptions')
  262. fetch_website_descriptions()
  263. output = get_output()
  264. with open(get_engine_descriptions_filename(), 'w', encoding='utf8') as f:
  265. f.write(json.dumps(output, indent=1, separators=(',', ':'), ensure_ascii=False))
  266. if __name__ == "__main__":
  267. main()