tineye.py 7.3 KB

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