duckduckgo_definitions.py 5.3 KB

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