tineye.py 7.2 KB

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