wolframalpha_api.py 4.1 KB

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