tineye.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """This engine implements *Tineye - reverse image search*
  3. Using TinEye, you can search by image or perform what we call a reverse image
  4. search. You can do that by uploading an image or searching by URL. You can also
  5. simply drag and drop your images to start your search. TinEye constantly crawls
  6. the web and adds images to its index. Today, the TinEye index is over 50.2
  7. billion images `[tineye.com] <https://tineye.com/how>`_.
  8. .. hint::
  9. This SearXNG engine only supports *'searching by URL'* and it does not use
  10. the official API `[api.tineye.com] <https://api.tineye.com/python/docs/>`_.
  11. """
  12. from typing import TYPE_CHECKING
  13. from urllib.parse import urlencode
  14. from datetime import datetime
  15. from flask_babel import gettext
  16. from searx.result_types import EngineResults
  17. if TYPE_CHECKING:
  18. import logging
  19. logger = logging.getLogger()
  20. about = {
  21. "website": 'https://tineye.com',
  22. "wikidata_id": 'Q2382535',
  23. "official_api_documentation": 'https://api.tineye.com/python/docs/',
  24. "use_official_api": False,
  25. "require_api_key": False,
  26. "results": 'JSON',
  27. }
  28. engine_type = 'online_url_search'
  29. """:py:obj:`searx.search.processors.online_url_search`"""
  30. categories = ['general']
  31. paging = True
  32. safesearch = False
  33. base_url = 'https://tineye.com'
  34. search_string = '/api/v1/result_json/?page={page}&{query}'
  35. FORMAT_NOT_SUPPORTED = gettext(
  36. "Could not read that image url. This may be due to an unsupported file"
  37. " format. TinEye only supports images that are JPEG, PNG, GIF, BMP, TIFF or WebP."
  38. )
  39. """TinEye error message"""
  40. NO_SIGNATURE_ERROR = gettext(
  41. "The image is too simple to find matches. TinEye requires a basic level of"
  42. " visual detail to successfully identify matches."
  43. )
  44. """TinEye error message"""
  45. DOWNLOAD_ERROR = gettext("The image could not be downloaded.")
  46. """TinEye error message"""
  47. def request(query, params):
  48. """Build TinEye HTTP request using ``search_urls`` of a :py:obj:`engine_type`."""
  49. params['raise_for_httperror'] = False
  50. if params['search_urls']['data:image']:
  51. query = params['search_urls']['data:image']
  52. elif params['search_urls']['http']:
  53. query = params['search_urls']['http']
  54. logger.debug("query URL: %s", query)
  55. query = urlencode({'url': query})
  56. # see https://github.com/TinEye/pytineye/blob/main/pytineye/api.py
  57. params['url'] = base_url + search_string.format(query=query, page=params['pageno'])
  58. params['headers'].update(
  59. {
  60. 'Connection': 'keep-alive',
  61. 'Accept-Encoding': 'gzip, defalte, br',
  62. 'Host': 'tineye.com',
  63. 'DNT': '1',
  64. 'TE': 'trailers',
  65. }
  66. )
  67. return params
  68. def parse_tineye_match(match_json):
  69. """Takes parsed JSON from the API server and turns it into a :py:obj:`dict`
  70. object.
  71. Attributes `(class Match) <https://github.com/TinEye/pytineye/blob/main/pytineye/api.py>`__
  72. - `image_url`, link to the result image.
  73. - `domain`, domain this result was found on.
  74. - `score`, a number (0 to 100) that indicates how closely the images match.
  75. - `width`, image width in pixels.
  76. - `height`, image height in pixels.
  77. - `size`, image area in pixels.
  78. - `format`, image format.
  79. - `filesize`, image size in bytes.
  80. - `overlay`, overlay URL.
  81. - `tags`, whether this match belongs to a collection or stock domain.
  82. - `backlinks`, a list of Backlink objects pointing to the original websites
  83. and image URLs. List items are instances of :py:obj:`dict`, (`Backlink
  84. <https://github.com/TinEye/pytineye/blob/main/pytineye/api.py>`__):
  85. - `url`, the image URL to the image.
  86. - `backlink`, the original website URL.
  87. - `crawl_date`, the date the image was crawled.
  88. """
  89. # HINT: there exists an alternative backlink dict in the domains list / e.g.::
  90. #
  91. # match_json['domains'][0]['backlinks']
  92. backlinks = []
  93. if "backlinks" in match_json:
  94. for backlink_json in match_json["backlinks"]:
  95. if not isinstance(backlink_json, dict):
  96. continue
  97. crawl_date = backlink_json.get("crawl_date")
  98. if crawl_date:
  99. crawl_date = datetime.strptime(crawl_date, '%Y-%m-%d')
  100. else:
  101. crawl_date = datetime.min
  102. backlinks.append(
  103. {
  104. 'url': backlink_json.get("url"),
  105. 'backlink': backlink_json.get("backlink"),
  106. 'crawl_date': crawl_date,
  107. 'image_name': backlink_json.get("image_name"),
  108. }
  109. )
  110. return {
  111. 'image_url': match_json.get("image_url"),
  112. 'domain': match_json.get("domain"),
  113. 'score': match_json.get("score"),
  114. 'width': match_json.get("width"),
  115. 'height': match_json.get("height"),
  116. 'size': match_json.get("size"),
  117. 'image_format': match_json.get("format"),
  118. 'filesize': match_json.get("filesize"),
  119. 'overlay': match_json.get("overlay"),
  120. 'tags': match_json.get("tags"),
  121. 'backlinks': backlinks,
  122. }
  123. def response(resp) -> EngineResults:
  124. """Parse HTTP response from TinEye."""
  125. results = EngineResults()
  126. # handle the 422 client side errors, and the possible 400 status code error
  127. if resp.status_code in (400, 422):
  128. json_data = resp.json()
  129. suggestions = json_data.get('suggestions', {})
  130. message = f'HTTP Status Code: {resp.status_code}'
  131. if resp.status_code == 422:
  132. s_key = suggestions.get('key', '')
  133. if s_key == "Invalid image URL":
  134. # test https://docs.searxng.org/_static/searxng-wordmark.svg
  135. message = FORMAT_NOT_SUPPORTED
  136. elif s_key == 'NO_SIGNATURE_ERROR':
  137. # test https://pngimg.com/uploads/dot/dot_PNG4.png
  138. message = NO_SIGNATURE_ERROR
  139. elif s_key == 'Download Error':
  140. # test https://notexists
  141. message = DOWNLOAD_ERROR
  142. else:
  143. logger.warning("Unknown suggestion key encountered: %s", s_key)
  144. else: # 400
  145. description = suggestions.get('description')
  146. if isinstance(description, list):
  147. message = ','.join(description)
  148. # see https://github.com/searxng/searxng/pull/1456#issuecomment-1193105023
  149. # results.add(results.types.Answer(answer=message))
  150. logger.info(message)
  151. return results
  152. # Raise for all other responses
  153. resp.raise_for_status()
  154. json_data = resp.json()
  155. for match_json in json_data['matches']:
  156. tineye_match = parse_tineye_match(match_json)
  157. if not tineye_match['backlinks']:
  158. continue
  159. backlink = tineye_match['backlinks'][0]
  160. results.append(
  161. {
  162. 'template': 'images.html',
  163. 'url': backlink['backlink'],
  164. 'thumbnail_src': tineye_match['image_url'],
  165. 'source': backlink['url'],
  166. 'title': backlink['image_name'],
  167. 'img_src': backlink['url'],
  168. 'format': tineye_match['image_format'],
  169. 'width': tineye_match['width'],
  170. 'height': tineye_match['height'],
  171. 'publishedDate': backlink['crawl_date'],
  172. }
  173. )
  174. # append number of results
  175. number_of_results = json_data.get('num_matches')
  176. if number_of_results:
  177. results.append({'number_of_results': number_of_results})
  178. return results