wolframalpha_api.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Wolfram|Alpha (Science)
  3. """
  4. from urllib.parse import urlencode
  5. from lxml import etree
  6. # about
  7. about = {
  8. "website": 'https://www.wolframalpha.com',
  9. "wikidata_id": 'Q207006',
  10. "official_api_documentation": 'https://products.wolframalpha.com/api/',
  11. "use_official_api": True,
  12. "require_api_key": False,
  13. "results": 'XML',
  14. }
  15. # search-url
  16. search_url = 'https://api.wolframalpha.com/v2/query?appid={api_key}&{query}'
  17. site_url = 'https://www.wolframalpha.com/input/?{query}'
  18. api_key = '' # defined in settings.yml
  19. # xpath variables
  20. failure_xpath = '/queryresult[attribute::success="false"]'
  21. input_xpath = '//pod[starts-with(attribute::id, "Input")]/subpod/plaintext'
  22. pods_xpath = '//pod'
  23. subpods_xpath = './subpod'
  24. pod_primary_xpath = './@primary'
  25. pod_id_xpath = './@id'
  26. pod_title_xpath = './@title'
  27. plaintext_xpath = './plaintext'
  28. image_xpath = './img'
  29. img_src_xpath = './@src'
  30. img_alt_xpath = './@alt'
  31. # pods to display as image in infobox
  32. # this pods do return a plaintext, but they look better and are more useful as images
  33. image_pods = {'VisualRepresentation', 'Illustration'}
  34. # do search-request
  35. def request(query, params):
  36. params['url'] = search_url.format(query=urlencode({'input': query}), api_key=api_key)
  37. params['headers']['Referer'] = site_url.format(query=urlencode({'i': query}))
  38. return params
  39. # replace private user area characters to make text legible
  40. def replace_pua_chars(text):
  41. pua_chars = {
  42. '\uf522': '\u2192', # right arrow
  43. '\uf7b1': '\u2115', # set of natural numbers
  44. '\uf7b4': '\u211a', # set of rational numbers
  45. '\uf7b5': '\u211d', # set of real numbers
  46. '\uf7bd': '\u2124', # set of integer numbers
  47. '\uf74c': 'd', # differential
  48. '\uf74d': '\u212f', # euler's number
  49. '\uf74e': 'i', # imaginary number
  50. '\uf7d9': '=',
  51. } # equals sign
  52. for k, v in pua_chars.items():
  53. text = text.replace(k, v)
  54. return text
  55. # get response from search-request
  56. def response(resp):
  57. results = []
  58. search_results = etree.XML(resp.content)
  59. # return empty array if there are no results
  60. if search_results.xpath(failure_xpath):
  61. return []
  62. try:
  63. infobox_title = search_results.xpath(input_xpath)[0].text
  64. except: # pylint: disable=bare-except
  65. infobox_title = ""
  66. pods = search_results.xpath(pods_xpath)
  67. result_chunks = []
  68. result_content = ""
  69. for pod in pods:
  70. pod_id = pod.xpath(pod_id_xpath)[0]
  71. pod_title = pod.xpath(pod_title_xpath)[0]
  72. pod_is_result = pod.xpath(pod_primary_xpath)
  73. subpods = pod.xpath(subpods_xpath)
  74. if not subpods:
  75. continue
  76. # Appends either a text or an image, depending on which one is more suitable
  77. for subpod in subpods:
  78. content = subpod.xpath(plaintext_xpath)[0].text
  79. image = subpod.xpath(image_xpath)
  80. if content and pod_id not in image_pods:
  81. if pod_is_result or not result_content:
  82. if pod_id != "Input":
  83. result_content = "%s: %s" % (pod_title, content)
  84. # if no input pod was found, title is first plaintext pod
  85. if not infobox_title:
  86. infobox_title = content
  87. content = replace_pua_chars(content)
  88. result_chunks.append({'label': pod_title, 'value': content})
  89. elif image:
  90. result_chunks.append(
  91. {
  92. 'label': pod_title,
  93. 'image': {'src': image[0].xpath(img_src_xpath)[0], 'alt': image[0].xpath(img_alt_xpath)[0]},
  94. }
  95. )
  96. if not result_chunks:
  97. return []
  98. title = "Wolfram Alpha (%s)" % infobox_title
  99. # append infobox
  100. results.append(
  101. {
  102. 'infobox': infobox_title,
  103. 'attributes': result_chunks,
  104. 'urls': [{'title': 'Wolfram|Alpha', 'url': resp.request.headers['Referer']}],
  105. }
  106. )
  107. # append link to site
  108. results.append({'url': resp.request.headers['Referer'], 'title': title, 'content': result_content})
  109. return results