duckduckgo_definitions.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import json
  2. from lxml import html
  3. from re import compile
  4. from searx.engines.xpath import extract_text
  5. from searx.engines.duckduckgo import _fetch_supported_languages, supported_languages_url
  6. from searx.url_utils import urlencode
  7. from searx.utils import html_to_text
  8. url = 'https://api.duckduckgo.com/'\
  9. + '?{query}&format=json&pretty=0&no_redirect=1&d=1'
  10. http_regex = compile(r'^http:')
  11. def result_to_text(url, text, htmlResult):
  12. # TODO : remove result ending with "Meaning" or "Category"
  13. dom = html.fromstring(htmlResult)
  14. a = dom.xpath('//a')
  15. if len(a) >= 1:
  16. return extract_text(a[0])
  17. else:
  18. return text
  19. def request(query, params):
  20. params['url'] = url.format(query=urlencode({'q': query}))
  21. params['headers']['Accept-Language'] = params['language'].split('-')[0]
  22. return params
  23. def response(resp):
  24. results = []
  25. search_res = json.loads(resp.text)
  26. content = ''
  27. heading = search_res.get('Heading', '')
  28. attributes = []
  29. urls = []
  30. infobox_id = None
  31. relatedTopics = []
  32. # add answer if there is one
  33. answer = search_res.get('Answer', '')
  34. if answer != '':
  35. results.append({'answer': html_to_text(answer)})
  36. # add infobox
  37. if 'Definition' in search_res:
  38. content = content + search_res.get('Definition', '')
  39. if 'Abstract' in search_res:
  40. content = content + search_res.get('Abstract', '')
  41. # image
  42. image = search_res.get('Image', '')
  43. image = None if image == '' else image
  44. # attributes
  45. if 'Infobox' in search_res:
  46. infobox = search_res.get('Infobox', None)
  47. if 'content' in infobox:
  48. for info in infobox.get('content'):
  49. attributes.append({'label': info.get('label'),
  50. 'value': info.get('value')})
  51. # urls
  52. for ddg_result in search_res.get('Results', []):
  53. if 'FirstURL' in ddg_result:
  54. firstURL = ddg_result.get('FirstURL', '')
  55. text = ddg_result.get('Text', '')
  56. urls.append({'title': text, 'url': firstURL})
  57. results.append({'title': heading, 'url': firstURL})
  58. # related topics
  59. for ddg_result in search_res.get('RelatedTopics', []):
  60. if 'FirstURL' in ddg_result:
  61. suggestion = result_to_text(ddg_result.get('FirstURL', None),
  62. ddg_result.get('Text', None),
  63. ddg_result.get('Result', None))
  64. if suggestion != heading:
  65. results.append({'suggestion': suggestion})
  66. elif 'Topics' in ddg_result:
  67. suggestions = []
  68. relatedTopics.append({'name': ddg_result.get('Name', ''),
  69. 'suggestions': suggestions})
  70. for topic_result in ddg_result.get('Topics', []):
  71. suggestion = result_to_text(topic_result.get('FirstURL', None),
  72. topic_result.get('Text', None),
  73. topic_result.get('Result', None))
  74. if suggestion != heading:
  75. suggestions.append(suggestion)
  76. # abstract
  77. abstractURL = search_res.get('AbstractURL', '')
  78. if abstractURL != '':
  79. # add as result ? problem always in english
  80. infobox_id = abstractURL
  81. urls.append({'title': search_res.get('AbstractSource'),
  82. 'url': abstractURL})
  83. # definition
  84. definitionURL = search_res.get('DefinitionURL', '')
  85. if definitionURL != '':
  86. # add as result ? as answer ? problem always in english
  87. infobox_id = definitionURL
  88. urls.append({'title': search_res.get('DefinitionSource'),
  89. 'url': definitionURL})
  90. # to merge with wikidata's infobox
  91. if infobox_id:
  92. infobox_id = http_regex.sub('https:', infobox_id)
  93. # entity
  94. entity = search_res.get('Entity', None)
  95. # TODO continent / country / department / location / waterfall /
  96. # mountain range :
  97. # link to map search, get weather, near by locations
  98. # TODO musician : link to music search
  99. # TODO concert tour : ??
  100. # TODO film / actor / television / media franchise :
  101. # links to IMDB / rottentomatoes (or scrap result)
  102. # TODO music : link tu musicbrainz / last.fm
  103. # TODO book : ??
  104. # TODO artist / playwright : ??
  105. # TODO compagny : ??
  106. # TODO software / os : ??
  107. # TODO software engineer : ??
  108. # TODO prepared food : ??
  109. # TODO website : ??
  110. # TODO performing art : ??
  111. # TODO prepared food : ??
  112. # TODO programming language : ??
  113. # TODO file format : ??
  114. if len(heading) > 0:
  115. # TODO get infobox.meta.value where .label='article_title'
  116. if image is None and len(attributes) == 0 and len(urls) == 1 and\
  117. len(relatedTopics) == 0 and len(content) == 0:
  118. results.append({
  119. 'url': urls[0]['url'],
  120. 'title': heading,
  121. 'content': content
  122. })
  123. else:
  124. results.append({
  125. 'infobox': heading,
  126. 'id': infobox_id,
  127. 'entity': entity,
  128. 'content': content,
  129. 'img_src': image,
  130. 'attributes': attributes,
  131. 'urls': urls,
  132. 'relatedTopics': relatedTopics
  133. })
  134. return results