update_engine_descriptions.py 11 KB

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