update_engine_descriptions.py 7.2 KB

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