.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
google_images.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""This is the implementation of the Google Images engine using the internal
3Google API used by the Google Go Android app.
4
5This internal API offer results in
6
7- JSON (``_fmt:json``)
8- Protobuf_ (``_fmt:pb``)
9- Protobuf_ compressed? (``_fmt:pc``)
10- HTML (``_fmt:html``)
11- Protobuf_ encoded in JSON (``_fmt:jspb``).
12
13.. _Protobuf: https://en.wikipedia.org/wiki/Protocol_Buffers
14"""
15
16from typing import TYPE_CHECKING
17
18from urllib.parse import urlencode
19from json import loads
20
21from searx.engines.google import fetch_traits # pylint: disable=unused-import
22from searx.engines.google import (
23 get_google_info,
24 time_range_dict,
25 detect_google_sorry,
26)
27
28if TYPE_CHECKING:
29 import logging
30 from searx.enginelib.traits import EngineTraits
31
32 logger: logging.Logger
33 traits: EngineTraits
34
35
36# about
37about = {
38 "website": 'https://images.google.com',
39 "wikidata_id": 'Q521550',
40 "official_api_documentation": 'https://developers.google.com/custom-search',
41 "use_official_api": False,
42 "require_api_key": False,
43 "results": 'JSON',
44}
45
46# engine dependent config
47categories = ['images', 'web']
48paging = True
49max_page = 50
50time_range_support = True
51safesearch = True
52send_accept_language_header = True
53
54filter_mapping = {0: 'images', 1: 'active', 2: 'active'}
55
56
57def request(query, params):
58 """Google-Image search request"""
59
60 google_info = get_google_info(params, traits)
61
62 query_url = (
63 'https://'
64 + google_info['subdomain']
65 + '/search'
66 + '?'
67 + urlencode({'q': query, 'tbm': "isch", **google_info['params'], 'asearch': 'isch'})
68 # don't urlencode this because wildly different AND bad results
69 # pagination uses Zero-based numbering
70 + f'&async=_fmt:json,p:1,ijn:{params["pageno"] - 1}'
71 )
72
73 if params['time_range'] in time_range_dict:
74 query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
75 if params['safesearch']:
76 query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
77 params['url'] = query_url
78 params['cookies'] = google_info['cookies']
79 params['headers'].update(google_info['headers'])
80 # this ua will allow getting ~50 results instead of 10. #1641
81 params['headers']['User-Agent'] = (
82 'NSTN/3.60.474802233.release Dalvik/2.1.0 (Linux; U; Android 12;' f' {google_info.get("country", "US")}) gzip'
83 )
84
85 return params
86
87
88def response(resp):
89 """Get response from google's search request"""
90 results = []
91
92 detect_google_sorry(resp)
93
94 json_start = resp.text.find('{"ischj":')
95 json_data = loads(resp.text[json_start:])
96
97 for item in json_data["ischj"].get("metadata", []):
98 result_item = {
99 'url': item["result"]["referrer_url"],
100 'title': item["result"]["page_title"],
101 'content': item["text_in_grid"]["snippet"],
102 'source': item["result"]["site_title"],
103 'resolution': f'{item["original_image"]["width"]} x {item["original_image"]["height"]}',
104 'img_src': item["original_image"]["url"],
105 'thumbnail_src': item["thumbnail"]["url"],
106 'template': 'images.html',
107 }
108
109 author = item["result"].get('iptc', {}).get('creator')
110 if author:
111 result_item['author'] = ', '.join(author)
112
113 copyright_notice = item["result"].get('iptc', {}).get('copyright_notice')
114 if copyright_notice:
115 result_item['source'] += ' | ' + copyright_notice
116
117 freshness_date = item["result"].get("freshness_date")
118 if freshness_date:
119 result_item['source'] += ' | ' + freshness_date
120
121 file_size = item.get('gsa', {}).get('file_size')
122 if file_size:
123 result_item['source'] += ' (%s)' % file_size
124
125 results.append(result_item)
126
127 return results