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