duckduckgo_definitions.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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, urlparse, urljoin
  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. if image is not None and urlparse(image).netloc == '':
  80. image = urljoin('https://duckduckgo.com', image)
  81. # urls
  82. # Official website, Wikipedia page
  83. for ddg_result in search_res.get('Results', []):
  84. firstURL = ddg_result.get('FirstURL')
  85. text = ddg_result.get('Text')
  86. if firstURL is not None and text is not None:
  87. urls.append({'title': text, 'url': firstURL})
  88. results.append({'title': heading, 'url': firstURL})
  89. # related topics
  90. for ddg_result in search_res.get('RelatedTopics', []):
  91. if 'FirstURL' in ddg_result:
  92. firstURL = ddg_result.get('FirstURL')
  93. text = ddg_result.get('Text')
  94. if not is_broken_text(text):
  95. suggestion = result_to_text(text,
  96. ddg_result.get('Result'))
  97. if suggestion != heading and suggestion is not None:
  98. results.append({'suggestion': suggestion})
  99. elif 'Topics' in ddg_result:
  100. suggestions = []
  101. relatedTopics.append({'name': ddg_result.get('Name', ''),
  102. 'suggestions': suggestions})
  103. for topic_result in ddg_result.get('Topics', []):
  104. suggestion = result_to_text(topic_result.get('Text'),
  105. topic_result.get('Result'))
  106. if suggestion != heading and suggestion is not None:
  107. suggestions.append(suggestion)
  108. # abstract
  109. abstractURL = search_res.get('AbstractURL', '')
  110. if abstractURL != '':
  111. # add as result ? problem always in english
  112. infobox_id = abstractURL
  113. urls.append({'title': search_res.get('AbstractSource'),
  114. 'url': abstractURL,
  115. 'official': True})
  116. results.append({'url': abstractURL,
  117. 'title': heading})
  118. # definition
  119. definitionURL = search_res.get('DefinitionURL', '')
  120. if definitionURL != '':
  121. # add as result ? as answer ? problem always in english
  122. infobox_id = definitionURL
  123. urls.append({'title': search_res.get('DefinitionSource'),
  124. 'url': definitionURL})
  125. # to merge with wikidata's infobox
  126. if infobox_id:
  127. infobox_id = replace_http_by_https(infobox_id)
  128. # attributes
  129. # some will be converted to urls
  130. if 'Infobox' in search_res:
  131. infobox = search_res.get('Infobox')
  132. if 'content' in infobox:
  133. osm_zoom = 17
  134. coordinates = None
  135. for info in infobox.get('content'):
  136. data_type = info.get('data_type')
  137. data_label = info.get('label')
  138. data_value = info.get('value')
  139. # Workaround: ddg may return a double quote
  140. if data_value == '""':
  141. continue
  142. # Is it an external URL ?
  143. # * imdb_id / facebook_profile / youtube_channel / youtube_video / twitter_profile
  144. # * instagram_profile / rotten_tomatoes / spotify_artist_id / itunes_artist_id / soundcloud_id
  145. # * netflix_id
  146. external_url = get_external_url(data_type, data_value)
  147. if external_url is not None:
  148. urls.append({'title': data_label,
  149. 'url': external_url})
  150. elif data_type in ['instance', 'wiki_maps_trigger', 'google_play_artist_id']:
  151. # ignore instance: Wikidata value from "Instance Of" (Qxxxx)
  152. # ignore wiki_maps_trigger: reference to a javascript
  153. # ignore google_play_artist_id: service shutdown
  154. pass
  155. elif data_type == 'string' and data_label == 'Website':
  156. # There is already an URL for the website
  157. pass
  158. elif data_type == 'area':
  159. attributes.append({'label': data_label,
  160. 'value': area_to_str(data_value),
  161. 'entity': 'P2046'})
  162. osm_zoom = area_to_osm_zoom(data_value.get('amount'))
  163. elif data_type == 'coordinates':
  164. if data_value.get('globe') == 'http://www.wikidata.org/entity/Q2':
  165. # coordinate on Earth
  166. # get the zoom information from the area
  167. coordinates = info
  168. else:
  169. # coordinate NOT on Earth
  170. attributes.append({'label': data_label,
  171. 'value': data_value,
  172. 'entity': 'P625'})
  173. elif data_type == 'string':
  174. attributes.append({'label': data_label,
  175. 'value': data_value})
  176. if coordinates:
  177. data_label = coordinates.get('label')
  178. data_value = coordinates.get('value')
  179. latitude = data_value.get('latitude')
  180. longitude = data_value.get('longitude')
  181. url = get_earth_coordinates_url(latitude, longitude, osm_zoom)
  182. urls.append({'title': 'OpenStreetMap',
  183. 'url': url,
  184. 'entity': 'P625'})
  185. if len(heading) > 0:
  186. # TODO get infobox.meta.value where .label='article_title'
  187. if image is None and len(attributes) == 0 and len(urls) == 1 and\
  188. len(relatedTopics) == 0 and len(content) == 0:
  189. results.append({'url': urls[0]['url'],
  190. 'title': heading,
  191. 'content': content})
  192. else:
  193. results.append({'infobox': heading,
  194. 'id': infobox_id,
  195. 'content': content,
  196. 'img_src': image,
  197. 'attributes': attributes,
  198. 'urls': urls,
  199. 'relatedTopics': relatedTopics})
  200. return results
  201. def unit_to_str(unit):
  202. for prefix in WIKIDATA_PREFIX:
  203. if unit.startswith(prefix):
  204. wikidata_entity = unit[len(prefix):]
  205. return WIKIDATA_UNITS.get(wikidata_entity, unit)
  206. return unit
  207. def area_to_str(area):
  208. """parse {'unit': 'http://www.wikidata.org/entity/Q712226', 'amount': '+20.99'}"""
  209. unit = unit_to_str(area.get('unit'))
  210. if unit is not None:
  211. try:
  212. amount = float(area.get('amount'))
  213. return '{} {}'.format(amount, unit)
  214. except ValueError:
  215. pass
  216. return '{} {}'.format(area.get('amount', ''), area.get('unit', ''))