duckduckgo_definitions.py 9.6 KB

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