public_domain_image_archive.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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. pdia_base_url = 'https://pdimagearchive.org'
  36. pdia_config_start = "/_astro/InfiniteSearch."
  37. pdia_config_end = ".js"
  38. categories = ['images']
  39. page_size = 20
  40. paging = True
  41. __CACHED_API_URL = None
  42. def _clean_url(url):
  43. parsed = urlparse(url)
  44. query = [(k, v) for (k, v) in parse_qsl(parsed.query) if k not in ['ixid', 's']]
  45. return urlunparse((parsed.scheme, parsed.netloc, parsed.path, parsed.params, urlencode(query), parsed.fragment))
  46. def _get_algolia_api_url():
  47. global __CACHED_API_URL # pylint:disable=global-statement
  48. if __CACHED_API_URL:
  49. return __CACHED_API_URL
  50. # fake request to extract api url
  51. resp = get(f"{pdia_base_url}/search/?q=")
  52. if resp.status_code != 200:
  53. raise LookupError("Failed to fetch config location (and as such the API url) for PDImageArchive")
  54. pdia_config_filepart = extr(resp.text, pdia_config_start, pdia_config_end)
  55. pdia_config_url = pdia_base_url + pdia_config_start + pdia_config_filepart + pdia_config_end
  56. resp = get(pdia_config_url)
  57. if resp.status_code != 200:
  58. raise LookupError("Failed to obtain AWS api url for PDImageArchive")
  59. api_url = extr(resp.text, 'const r="', '"', default=None)
  60. if api_url is None:
  61. raise LookupError("Couldn't obtain AWS api url for PDImageArchive")
  62. __CACHED_API_URL = api_url
  63. return api_url
  64. def _clear_cached_api_url():
  65. global __CACHED_API_URL # pylint:disable=global-statement
  66. __CACHED_API_URL = None
  67. def request(query, params):
  68. params['url'] = _get_algolia_api_url()
  69. params['method'] = 'POST'
  70. request_data = {
  71. 'page': params['pageno'] - 1,
  72. 'query': query,
  73. 'hitsPerPage': page_size,
  74. 'indexName': 'prod_all-images',
  75. }
  76. params['headers'] = {'Content-Type': 'application/json'}
  77. params['data'] = dumps(request_data)
  78. # http errors are handled manually to be able to reset the api url
  79. params['raise_for_httperror'] = False
  80. return params
  81. def response(resp):
  82. results = []
  83. json_data = resp.json()
  84. if resp.status_code == 403:
  85. _clear_cached_api_url()
  86. raise SearxEngineAccessDeniedException()
  87. if resp.status_code != 200:
  88. raise SearxEngineException()
  89. if 'results' not in json_data:
  90. return []
  91. for result in json_data['results'][0]['hits']:
  92. content = []
  93. if result.get("themes"):
  94. content.append("Themes: " + result['themes'])
  95. if result.get("encompassingWork"):
  96. content.append("Encompassing work: " + result['encompassingWork'])
  97. base_image_url = result['thumbnail'].split("?")[0]
  98. results.append(
  99. {
  100. 'template': 'images.html',
  101. 'url': _clean_url(f"{about['website']}/images/{result['objectID']}"),
  102. 'img_src': _clean_url(base_image_url),
  103. 'thumbnail_src': _clean_url(base_image_url + THUMBNAIL_SUFFIX),
  104. 'title': f"{result['title'].strip()} by {result['artist']} {result.get('displayYear', '')}",
  105. 'content': "\n".join(content),
  106. }
  107. )
  108. return results