duckduckgo_definitions.py 9.4 KB

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