public_domain_image_archive.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Public domain image archive"""
  3. from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl
  4. from json import dumps
  5. from searx.network import get
  6. from searx.utils import extr
  7. from searx.exceptions import SearxEngineAccessDeniedException, SearxEngineException
  8. THUMBNAIL_SUFFIX = "?fit=max&h=360&w=360"
  9. """
  10. Example thumbnail urls (from requests & html):
  11. - https://the-public-domain-review.imgix.net
  12. /shop/nov-2023-prints-00043.jpg
  13. ?fit=max&h=360&w=360
  14. - https://the-public-domain-review.imgix.net
  15. /collections/the-history-of-four-footed-beasts-and-serpents-1658/
  16. 8616383182_5740fa7851_o.jpg
  17. ?fit=max&h=360&w=360
  18. Example full image urls (from html)
  19. - https://the-public-domain-review.imgix.net/shop/
  20. nov-2023-prints-00043.jpg
  21. ?fit=clip&w=970&h=800&auto=format,compress
  22. - https://the-public-domain-review.imgix.net/collections/
  23. the-history-of-four-footed-beasts-and-serpents-1658/8616383182_5740fa7851_o.jpg
  24. ?fit=clip&w=310&h=800&auto=format,compress
  25. The thumbnail url from the request will be cleaned for the full image link
  26. The cleaned thumbnail url will have THUMBNAIL_SUFFIX added to them, based on the original thumbnail parameters
  27. """
  28. # about
  29. about = {
  30. "website": 'https://pdimagearchive.org',
  31. "use_official_api": False,
  32. "require_api_key": False,
  33. "results": 'JSON',
  34. }
  35. base_url = 'https://oqi2j6v4iz-dsn.algolia.net'
  36. pdia_config_url = 'https://pdimagearchive.org/_astro/config.BiNvrvzG.js'
  37. categories = ['images']
  38. page_size = 20
  39. paging = True
  40. __CACHED_API_KEY = None
  41. def _clean_url(url):
  42. parsed = urlparse(url)
  43. query = [(k, v) for (k, v) in parse_qsl(parsed.query) if k not in ['ixid', 's']]
  44. return urlunparse((parsed.scheme, parsed.netloc, parsed.path, parsed.params, urlencode(query), parsed.fragment))
  45. def _get_algolia_api_key():
  46. global __CACHED_API_KEY # pylint:disable=global-statement
  47. if __CACHED_API_KEY:
  48. return __CACHED_API_KEY
  49. resp = get(pdia_config_url)
  50. if resp.status_code != 200:
  51. raise LookupError("Failed to obtain Algolia API key for PDImageArchive")
  52. api_key = extr(resp.text, 'r="', '"', default=None)
  53. if api_key is None:
  54. raise LookupError("Couldn't obtain Algolia API key for PDImageArchive")
  55. __CACHED_API_KEY = api_key
  56. return api_key
  57. def _clear_cached_api_key():
  58. global __CACHED_API_KEY # pylint:disable=global-statement
  59. __CACHED_API_KEY = None
  60. def request(query, params):
  61. api_key = _get_algolia_api_key()
  62. args = {
  63. 'x-algolia-api-key': api_key,
  64. 'x-algolia-application-id': 'OQI2J6V4IZ',
  65. }
  66. params['url'] = f"{base_url}/1/indexes/*/queries?{urlencode(args)}"
  67. params["method"] = "POST"
  68. request_params = {
  69. "page": params["pageno"] - 1,
  70. "query": query,
  71. "highlightPostTag": "__ais-highlight__",
  72. "highlightPreTag": "__ais-highlight__",
  73. }
  74. data = {
  75. "requests": [
  76. {"indexName": "prod_all-images", "params": urlencode(request_params)},
  77. ]
  78. }
  79. params["data"] = dumps(data)
  80. # http errors are handled manually to be able to reset the api key
  81. params['raise_for_httperror'] = False
  82. return params
  83. def response(resp):
  84. results = []
  85. json_data = resp.json()
  86. if resp.status_code == 403:
  87. _clear_cached_api_key()
  88. raise SearxEngineAccessDeniedException()
  89. if resp.status_code != 200:
  90. raise SearxEngineException()
  91. if 'results' not in json_data:
  92. return []
  93. for result in json_data['results'][0]['hits']:
  94. content = []
  95. if "themes" in result:
  96. content.append("Themes: " + result['themes'])
  97. if "encompassingWork" in result:
  98. content.append("Encompassing work: " + result['encompassingWork'])
  99. content = "\n".join(content)
  100. base_image_url = result['thumbnail'].split("?")[0]
  101. results.append(
  102. {
  103. 'template': 'images.html',
  104. 'url': _clean_url(f"{about['website']}/images/{result['objectID']}"),
  105. 'img_src': _clean_url(base_image_url),
  106. 'thumbnail_src': _clean_url(base_image_url + THUMBNAIL_SUFFIX),
  107. 'title': f"{result['title'].strip()} by {result['artist']} {result.get('displayYear', '')}",
  108. 'content': content,
  109. }
  110. )
  111. return results