update_engine_descriptions.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. #!/usr/bin/env python
  2. import sys
  3. import json
  4. from urllib.parse import quote, urlparse
  5. import detect_language
  6. from lxml.html import fromstring
  7. from searx.engines.wikidata import send_wikidata_query
  8. from searx.utils import extract_text
  9. import searx
  10. import searx.search
  11. import searx.poolrequests
  12. SPARQL_WIKIPEDIA_ARTICLE = """
  13. SELECT DISTINCT ?item ?name
  14. WHERE {
  15. VALUES ?item { %IDS% }
  16. ?article schema:about ?item ;
  17. schema:inLanguage ?lang ;
  18. schema:name ?name ;
  19. schema:isPartOf [ wikibase:wikiGroup "wikipedia" ] .
  20. FILTER(?lang in (%LANGUAGES_SPARQL%)) .
  21. FILTER (!CONTAINS(?name, ':')) .
  22. }
  23. """
  24. SPARQL_DESCRIPTION = """
  25. SELECT DISTINCT ?item ?itemDescription
  26. WHERE {
  27. VALUES ?item { %IDS% }
  28. ?item schema:description ?itemDescription .
  29. FILTER (lang(?itemDescription) in (%LANGUAGES_SPARQL%))
  30. }
  31. ORDER BY ?itemLang
  32. """
  33. LANGUAGES = searx.settings['locales'].keys()
  34. LANGUAGES_SPARQL = ', '.join(set(map(lambda l: repr(l.split('_')[0]), LANGUAGES)))
  35. IDS = None
  36. descriptions = {}
  37. wd_to_engine_name = {}
  38. def normalize_description(description):
  39. for c in [chr(c) for c in range(0, 31)]:
  40. description = description.replace(c, ' ')
  41. description = ' '.join(description.strip().split())
  42. return description
  43. def update_description(engine_name, lang, description, source, replace=True):
  44. if replace or lang not in descriptions[engine_name]:
  45. descriptions[engine_name][lang] = [normalize_description(description), source]
  46. def get_wikipedia_summary(language, pageid):
  47. search_url = 'https://{language}.wikipedia.org/api/rest_v1/page/summary/{title}'
  48. url = search_url.format(title=quote(pageid), language=language)
  49. try:
  50. response = searx.poolrequests.get(url)
  51. response.raise_for_status()
  52. api_result = json.loads(response.text)
  53. return api_result.get('extract')
  54. except:
  55. return None
  56. def detect_language(text):
  57. r = cld3.get_language(str(text)) # pylint: disable=E1101
  58. if r is not None and r.probability >= 0.98 and r.is_reliable:
  59. return r.language
  60. return None
  61. def get_website_description(url, lang1, lang2=None):
  62. headers = {
  63. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0',
  64. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  65. 'DNT': '1',
  66. 'Upgrade-Insecure-Requests': '1',
  67. 'Sec-GPC': '1',
  68. 'Cache-Control': 'max-age=0',
  69. }
  70. if lang1 is not None:
  71. lang_list = [lang1]
  72. if lang2 is not None:
  73. lang_list.append(lang2)
  74. headers['Accept-Language'] = f'{",".join(lang_list)};q=0.8'
  75. try:
  76. response = searx.poolrequests.get(url, headers=headers, timeout=10)
  77. response.raise_for_status()
  78. except Exception:
  79. return (None, None)
  80. try:
  81. html = fromstring(response.text)
  82. except ValueError:
  83. html = fromstring(response.content)
  84. description = extract_text(html.xpath('/html/head/meta[@name="description"]/@content'))
  85. if not description:
  86. description = extract_text(html.xpath('/html/head/meta[@property="og:description"]/@content'))
  87. if not description:
  88. description = extract_text(html.xpath('/html/head/title'))
  89. lang = extract_text(html.xpath('/html/@lang'))
  90. if lang is None and len(lang1) > 0:
  91. lang = lang1
  92. lang = detect_language(description) or lang or 'en'
  93. lang = lang.split('_')[0]
  94. lang = lang.split('-')[0]
  95. return (lang, description)
  96. def initialize():
  97. global descriptions, wd_to_engine_name, IDS
  98. searx.search.initialize()
  99. for engine_name, engine in searx.engines.engines.items():
  100. descriptions[engine_name] = {}
  101. wikidata_id = getattr(engine, "about", {}).get('wikidata_id')
  102. if wikidata_id is not None:
  103. wd_to_engine_name.setdefault(wikidata_id, set()).add(engine_name)
  104. IDS = ' '.join(list(map(lambda wd_id: 'wd:' + wd_id, wd_to_engine_name.keys())))
  105. def fetch_wikidata_descriptions():
  106. global IDS
  107. result = send_wikidata_query(SPARQL_DESCRIPTION
  108. .replace('%IDS%', IDS)
  109. .replace('%LANGUAGES_SPARQL%', LANGUAGES_SPARQL))
  110. if result is not None:
  111. for binding in result['results']['bindings']:
  112. wikidata_id = binding['item']['value'].replace('http://www.wikidata.org/entity/', '')
  113. lang = binding['itemDescription']['xml:lang']
  114. description = binding['itemDescription']['value']
  115. if ' ' in description: # skip unique word description (like "website")
  116. for engine_name in wd_to_engine_name[wikidata_id]:
  117. update_description(engine_name, lang, description, 'wikidata')
  118. def fetch_wikipedia_descriptions():
  119. global IDS
  120. result = send_wikidata_query(SPARQL_WIKIPEDIA_ARTICLE
  121. .replace('%IDS%', IDS)
  122. .replace('%LANGUAGES_SPARQL%', LANGUAGES_SPARQL))
  123. if result is not None:
  124. for binding in result['results']['bindings']:
  125. wikidata_id = binding['item']['value'].replace('http://www.wikidata.org/entity/', '')
  126. lang = binding['name']['xml:lang']
  127. pageid = binding['name']['value']
  128. description = get_wikipedia_summary(lang, pageid)
  129. if description is not None and ' ' in description:
  130. for engine_name in wd_to_engine_name[wikidata_id]:
  131. update_description(engine_name, lang, description, 'wikipedia')
  132. def normalize_url(url):
  133. url = url.replace('{language}', 'en')
  134. url = urlparse(url)._replace(path='/', params='', query='', fragment='').geturl()
  135. url = url.replace('https://api.', 'https://')
  136. return url
  137. def fetch_website_description(engine_name, website):
  138. default_lang, default_description = get_website_description(website, None, None)
  139. if default_lang is None or default_description is None:
  140. return
  141. if default_lang not in descriptions[engine_name]:
  142. descriptions[engine_name][default_lang] = [normalize_description(default_description), website]
  143. for request_lang in ('en-US', 'es-US', 'fr-FR', 'zh', 'ja', 'ru', 'ar', 'ko'):
  144. if request_lang.split('-')[0] not in descriptions[engine_name]:
  145. lang, desc = get_website_description(website, request_lang, request_lang.split('-')[0])
  146. if desc is not None and desc != default_description:
  147. update_description(engine_name, lang, desc, website, replace=False)
  148. else:
  149. break
  150. def fetch_website_descriptions():
  151. for engine_name, engine in searx.engines.engines.items():
  152. website = getattr(engine, "about", {}).get('website')
  153. if website is None:
  154. website = normalize_url(getattr(engine, "search_url"))
  155. if website is None:
  156. website = normalize_url(getattr(engine, "base_url"))
  157. if website is not None:
  158. fetch_website_description(engine_name, website)
  159. def main():
  160. initialize()
  161. fetch_wikidata_descriptions()
  162. fetch_wikipedia_descriptions()
  163. fetch_website_descriptions()
  164. sys.stdout.write(json.dumps(descriptions, indent=1, separators=(',', ':'), ensure_ascii=False))
  165. if __name__ == "__main__":
  166. main()