duckduckgo_definitions.py 10 KB

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