update_engine_descriptions.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. #!/usr/bin/env python
  2. import json
  3. from urllib.parse import urlparse
  4. from os.path import join
  5. from lxml.html import fromstring
  6. from langdetect import detect_langs
  7. from langdetect.lang_detect_exception import LangDetectException
  8. from searx.engines import wikidata, set_loggers
  9. from searx.utils import extract_text, match_language
  10. from searx.locales import LOCALE_NAMES
  11. from searx import searx_dir
  12. from searx.utils import gen_useragent
  13. import searx.search
  14. import searx.network
  15. set_loggers(wikidata, 'wikidata')
  16. SPARQL_WIKIPEDIA_ARTICLE = """
  17. SELECT DISTINCT ?item ?name
  18. WHERE {
  19. hint:Query hint:optimizer "None".
  20. VALUES ?item { %IDS% }
  21. ?article schema:about ?item ;
  22. schema:inLanguage ?lang ;
  23. schema:name ?name ;
  24. schema:isPartOf [ wikibase:wikiGroup "wikipedia" ] .
  25. FILTER(?lang in (%LANGUAGES_SPARQL%)) .
  26. FILTER (!CONTAINS(?name, ':')) .
  27. }
  28. """
  29. SPARQL_DESCRIPTION = """
  30. SELECT DISTINCT ?item ?itemDescription
  31. WHERE {
  32. VALUES ?item { %IDS% }
  33. ?item schema:description ?itemDescription .
  34. FILTER (lang(?itemDescription) in (%LANGUAGES_SPARQL%))
  35. }
  36. ORDER BY ?itemLang
  37. """
  38. NOT_A_DESCRIPTION = [
  39. 'web site',
  40. 'site web',
  41. 'komputa serĉilo',
  42. 'interreta serĉilo',
  43. 'bilaketa motor',
  44. 'web search engine',
  45. 'wikimedia täpsustuslehekülg',
  46. ]
  47. SKIP_ENGINE_SOURCE = [
  48. ('gitlab', 'wikidata') # descriptions are about wikipedia disambiguation pages
  49. ]
  50. LANGUAGES = LOCALE_NAMES.keys()
  51. WIKIPEDIA_LANGUAGES = {'language': 'wikipedia_language'}
  52. LANGUAGES_SPARQL = ''
  53. IDS = None
  54. descriptions = {}
  55. wd_to_engine_name = {}
  56. def normalize_description(description):
  57. for c in [chr(c) for c in range(0, 31)]:
  58. description = description.replace(c, ' ')
  59. description = ' '.join(description.strip().split())
  60. return description
  61. def update_description(engine_name, lang, description, source, replace=True):
  62. if not isinstance(description, str):
  63. return
  64. description = normalize_description(description)
  65. if description.lower() == engine_name.lower():
  66. return
  67. if description.lower() in NOT_A_DESCRIPTION:
  68. return
  69. if (engine_name, source) in SKIP_ENGINE_SOURCE:
  70. return
  71. if ' ' not in description:
  72. # skip unique word description (like "website")
  73. return
  74. if replace or lang not in descriptions[engine_name]:
  75. descriptions[engine_name][lang] = [description, source]
  76. def get_wikipedia_summary(lang, pageid):
  77. params = {
  78. 'language': lang.replace('_','-'),
  79. 'headers': {}
  80. }
  81. searx.engines.engines['wikipedia'].request(pageid, params)
  82. try:
  83. response = searx.network.get(params['url'], headers=params['headers'], timeout=10)
  84. response.raise_for_status()
  85. api_result = json.loads(response.text)
  86. return api_result.get('extract')
  87. except:
  88. return None
  89. def detect_language(text):
  90. try:
  91. r = detect_langs(str(text)) # pylint: disable=E1101
  92. except LangDetectException:
  93. return None
  94. if len(r) > 0 and r[0].prob > 0.95:
  95. return r[0].lang
  96. return None
  97. def get_website_description(url, lang1, lang2=None):
  98. headers = {
  99. 'User-Agent': gen_useragent(),
  100. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  101. 'DNT': '1',
  102. 'Upgrade-Insecure-Requests': '1',
  103. 'Sec-GPC': '1',
  104. 'Cache-Control': 'max-age=0',
  105. }
  106. if lang1 is not None:
  107. lang_list = [lang1]
  108. if lang2 is not None:
  109. lang_list.append(lang2)
  110. headers['Accept-Language'] = f'{",".join(lang_list)};q=0.8'
  111. try:
  112. response = searx.network.get(url, headers=headers, timeout=10)
  113. response.raise_for_status()
  114. except Exception:
  115. return (None, None)
  116. try:
  117. html = fromstring(response.text)
  118. except ValueError:
  119. html = fromstring(response.content)
  120. description = extract_text(html.xpath('/html/head/meta[@name="description"]/@content'))
  121. if not description:
  122. description = extract_text(html.xpath('/html/head/meta[@property="og:description"]/@content'))
  123. if not description:
  124. description = extract_text(html.xpath('/html/head/title'))
  125. lang = extract_text(html.xpath('/html/@lang'))
  126. if lang is None and len(lang1) > 0:
  127. lang = lang1
  128. lang = detect_language(description) or lang or 'en'
  129. lang = lang.split('_')[0]
  130. lang = lang.split('-')[0]
  131. return (lang, description)
  132. def initialize():
  133. global IDS, WIKIPEDIA_LANGUAGES, LANGUAGES_SPARQL
  134. searx.search.initialize()
  135. wikipedia_engine = searx.engines.engines['wikipedia']
  136. WIKIPEDIA_LANGUAGES = {
  137. language: wikipedia_engine.url_lang(language.replace('_', '-'))
  138. for language in LANGUAGES
  139. }
  140. WIKIPEDIA_LANGUAGES['nb_NO'] = 'no'
  141. LANGUAGES_SPARQL = ', '.join(f"'{l}'" for l in set(WIKIPEDIA_LANGUAGES.values()))
  142. for engine_name, engine in searx.engines.engines.items():
  143. descriptions[engine_name] = {}
  144. wikidata_id = getattr(engine, "about", {}).get('wikidata_id')
  145. if wikidata_id is not None:
  146. wd_to_engine_name.setdefault(wikidata_id, set()).add(engine_name)
  147. IDS = ' '.join(list(map(lambda wd_id: 'wd:' + wd_id, wd_to_engine_name.keys())))
  148. def fetch_wikidata_descriptions():
  149. searx.network.set_timeout_for_thread(60)
  150. result = wikidata.send_wikidata_query(
  151. SPARQL_DESCRIPTION
  152. .replace('%IDS%', IDS)
  153. .replace('%LANGUAGES_SPARQL%', LANGUAGES_SPARQL)
  154. )
  155. if result is not None:
  156. for binding in result['results']['bindings']:
  157. wikidata_id = binding['item']['value'].replace('http://www.wikidata.org/entity/', '')
  158. wikidata_lang = binding['itemDescription']['xml:lang']
  159. description = binding['itemDescription']['value']
  160. for engine_name in wd_to_engine_name[wikidata_id]:
  161. for lang in LANGUAGES:
  162. if WIKIPEDIA_LANGUAGES[lang] == wikidata_lang:
  163. update_description(engine_name, lang, description, 'wikidata')
  164. def fetch_wikipedia_descriptions():
  165. result = wikidata.send_wikidata_query(
  166. SPARQL_WIKIPEDIA_ARTICLE
  167. .replace('%IDS%', IDS)
  168. .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 = {
  238. locale: {} for locale in LOCALE_NAMES
  239. }
  240. seen_descriptions = {}
  241. for engine_name, lang_descriptions in descriptions.items():
  242. for language, description in lang_descriptions.items():
  243. if description[0] in seen_descriptions:
  244. ref = seen_descriptions[description[0]]
  245. description = [f'{ref[0]}:{ref[1]}', 'ref']
  246. else:
  247. seen_descriptions[description[0]] = (engine_name, language)
  248. if description[1] == 'wikipedia':
  249. description = description[0]
  250. output.setdefault(language, {}).setdefault(engine_name, description)
  251. return output
  252. def main():
  253. initialize()
  254. print('Fetching wikidata descriptions')
  255. fetch_wikidata_descriptions()
  256. print('Fetching wikipedia descriptions')
  257. fetch_wikipedia_descriptions()
  258. print('Fetching website descriptions')
  259. fetch_website_descriptions()
  260. output = get_output()
  261. with open(get_engine_descriptions_filename(), 'w', encoding='utf8') as f:
  262. f.write(json.dumps(output, indent=1, separators=(',', ':'), ensure_ascii=False))
  263. if __name__ == "__main__":
  264. main()