update_engine_descriptions.py 11 KB

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