duckduckgo_definitions.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """DuckDuckGo (Instant Answer API)
  4. """
  5. import json
  6. from urllib.parse import urlencode, urlparse, urljoin
  7. from lxml import html
  8. from searx.data import WIKIDATA_UNITS
  9. from searx.engines.duckduckgo import language_aliases
  10. from searx.engines.duckduckgo import ( # pylint: disable=unused-import
  11. _fetch_supported_languages,
  12. supported_languages_url,
  13. )
  14. from searx.utils import extract_text, html_to_text, match_language, get_string_replaces_function
  15. from searx.external_urls import get_external_url, get_earth_coordinates_url, area_to_osm_zoom
  16. # about
  17. about = {
  18. "website": 'https://duckduckgo.com/',
  19. "wikidata_id": 'Q12805',
  20. "official_api_documentation": 'https://duckduckgo.com/api',
  21. "use_official_api": True,
  22. "require_api_key": False,
  23. "results": 'JSON',
  24. }
  25. URL = 'https://api.duckduckgo.com/' + '?{query}&format=json&pretty=0&no_redirect=1&d=1'
  26. WIKIDATA_PREFIX = ['http://www.wikidata.org/entity/', 'https://www.wikidata.org/entity/']
  27. replace_http_by_https = get_string_replaces_function({'http:': 'https:'})
  28. def is_broken_text(text):
  29. """duckduckgo may return something like "<a href="xxxx">http://somewhere Related website<a/>"
  30. The href URL is broken, the "Related website" may contains some HTML.
  31. The best solution seems to ignore these results.
  32. """
  33. return text.startswith('http') and ' ' in text
  34. def result_to_text(text, htmlResult):
  35. # TODO : remove result ending with "Meaning" or "Category" # pylint: disable=fixme
  36. result = None
  37. dom = html.fromstring(htmlResult)
  38. a = dom.xpath('//a')
  39. if len(a) >= 1:
  40. result = extract_text(a[0])
  41. else:
  42. result = text
  43. if not is_broken_text(result):
  44. return result
  45. return None
  46. def request(query, params):
  47. params['url'] = URL.format(query=urlencode({'q': query}))
  48. language = match_language(params['language'], supported_languages, language_aliases)
  49. language = language.split('-')[0]
  50. params['headers']['Accept-Language'] = language
  51. return params
  52. def response(resp):
  53. # pylint: disable=too-many-locals, too-many-branches, too-many-statements
  54. results = []
  55. search_res = json.loads(resp.text)
  56. # search_res.get('Entity') possible values (not exhaustive) :
  57. # * continent / country / department / location / waterfall
  58. # * actor / musician / artist
  59. # * book / performing art / film / television / media franchise / concert tour / playwright
  60. # * prepared food
  61. # * website / software / os / programming language / file format / software engineer
  62. # * compagny
  63. content = ''
  64. heading = search_res.get('Heading', '')
  65. attributes = []
  66. urls = []
  67. infobox_id = None
  68. relatedTopics = []
  69. # add answer if there is one
  70. answer = search_res.get('Answer', '')
  71. if answer:
  72. logger.debug('AnswerType="%s" Answer="%s"', search_res.get('AnswerType'), answer)
  73. if search_res.get('AnswerType') not in ['calc', 'ip']:
  74. results.append({'answer': html_to_text(answer)})
  75. # add infobox
  76. if 'Definition' in search_res:
  77. content = content + search_res.get('Definition', '')
  78. if 'Abstract' in search_res:
  79. content = content + search_res.get('Abstract', '')
  80. # image
  81. image = search_res.get('Image')
  82. image = None if image == '' else image
  83. if image is not None and urlparse(image).netloc == '':
  84. image = urljoin('https://duckduckgo.com', image)
  85. # urls
  86. # Official website, Wikipedia page
  87. for ddg_result in search_res.get('Results', []):
  88. firstURL = ddg_result.get('FirstURL')
  89. text = ddg_result.get('Text')
  90. if firstURL is not None and text is not None:
  91. urls.append({'title': text, 'url': firstURL})
  92. results.append({'title': heading, 'url': firstURL})
  93. # related topics
  94. for ddg_result in search_res.get('RelatedTopics', []):
  95. if 'FirstURL' in ddg_result:
  96. firstURL = ddg_result.get('FirstURL')
  97. text = ddg_result.get('Text')
  98. if not is_broken_text(text):
  99. suggestion = result_to_text(text, ddg_result.get('Result'))
  100. if suggestion != heading and suggestion is not None:
  101. results.append({'suggestion': suggestion})
  102. elif 'Topics' in ddg_result:
  103. suggestions = []
  104. relatedTopics.append({'name': ddg_result.get('Name', ''), 'suggestions': suggestions})
  105. for topic_result in ddg_result.get('Topics', []):
  106. suggestion = result_to_text(topic_result.get('Text'), topic_result.get('Result'))
  107. if suggestion != heading and suggestion is not None:
  108. suggestions.append(suggestion)
  109. # abstract
  110. abstractURL = search_res.get('AbstractURL', '')
  111. if abstractURL != '':
  112. # add as result ? problem always in english
  113. infobox_id = abstractURL
  114. urls.append({'title': search_res.get('AbstractSource'), 'url': abstractURL, 'official': True})
  115. results.append({'url': abstractURL, 'title': heading})
  116. # definition
  117. definitionURL = search_res.get('DefinitionURL', '')
  118. if definitionURL != '':
  119. # add as result ? as answer ? problem always in english
  120. infobox_id = definitionURL
  121. urls.append({'title': search_res.get('DefinitionSource'), 'url': definitionURL})
  122. # to merge with wikidata's infobox
  123. if infobox_id:
  124. infobox_id = replace_http_by_https(infobox_id)
  125. # attributes
  126. # some will be converted to urls
  127. if 'Infobox' in search_res:
  128. infobox = search_res.get('Infobox')
  129. if 'content' in infobox:
  130. osm_zoom = 17
  131. coordinates = None
  132. for info in infobox.get('content'):
  133. data_type = info.get('data_type')
  134. data_label = info.get('label')
  135. data_value = info.get('value')
  136. # Workaround: ddg may return a double quote
  137. if data_value == '""':
  138. continue
  139. # Is it an external URL ?
  140. # * imdb_id / facebook_profile / youtube_channel / youtube_video / twitter_profile
  141. # * instagram_profile / rotten_tomatoes / spotify_artist_id / itunes_artist_id / soundcloud_id
  142. # * netflix_id
  143. external_url = get_external_url(data_type, data_value)
  144. if external_url is not None:
  145. urls.append({'title': data_label, 'url': external_url})
  146. elif data_type in ['instance', 'wiki_maps_trigger', 'google_play_artist_id']:
  147. # ignore instance: Wikidata value from "Instance Of" (Qxxxx)
  148. # ignore wiki_maps_trigger: reference to a javascript
  149. # ignore google_play_artist_id: service shutdown
  150. pass
  151. elif data_type == 'string' and data_label == 'Website':
  152. # There is already an URL for the website
  153. pass
  154. elif data_type == 'area':
  155. attributes.append({'label': data_label, 'value': area_to_str(data_value), 'entity': 'P2046'})
  156. osm_zoom = area_to_osm_zoom(data_value.get('amount'))
  157. elif data_type == 'coordinates':
  158. if data_value.get('globe') == 'http://www.wikidata.org/entity/Q2':
  159. # coordinate on Earth
  160. # get the zoom information from the area
  161. coordinates = info
  162. else:
  163. # coordinate NOT on Earth
  164. attributes.append({'label': data_label, 'value': data_value, 'entity': 'P625'})
  165. elif data_type == 'string':
  166. attributes.append({'label': data_label, 'value': data_value})
  167. if coordinates:
  168. data_label = coordinates.get('label')
  169. data_value = coordinates.get('value')
  170. latitude = data_value.get('latitude')
  171. longitude = data_value.get('longitude')
  172. url = get_earth_coordinates_url(latitude, longitude, osm_zoom)
  173. urls.append({'title': 'OpenStreetMap', 'url': url, 'entity': 'P625'})
  174. if len(heading) > 0:
  175. # TODO get infobox.meta.value where .label='article_title' # pylint: disable=fixme
  176. if image is None and len(attributes) == 0 and len(urls) == 1 and len(relatedTopics) == 0 and len(content) == 0:
  177. results.append({'url': urls[0]['url'], 'title': heading, 'content': content})
  178. else:
  179. results.append(
  180. {
  181. 'infobox': heading,
  182. 'id': infobox_id,
  183. 'content': content,
  184. 'img_src': image,
  185. 'attributes': attributes,
  186. 'urls': urls,
  187. 'relatedTopics': relatedTopics,
  188. }
  189. )
  190. return results
  191. def unit_to_str(unit):
  192. for prefix in WIKIDATA_PREFIX:
  193. if unit.startswith(prefix):
  194. wikidata_entity = unit[len(prefix) :]
  195. return WIKIDATA_UNITS.get(wikidata_entity, unit)
  196. return unit
  197. def area_to_str(area):
  198. """parse {'unit': 'http://www.wikidata.org/entity/Q712226', 'amount': '+20.99'}"""
  199. unit = unit_to_str(area.get('unit'))
  200. if unit is not None:
  201. try:
  202. amount = float(area.get('amount'))
  203. return '{} {}'.format(amount, unit)
  204. except ValueError:
  205. pass
  206. return '{} {}'.format(area.get('amount', ''), area.get('unit', ''))