Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
mxrch
GitHub Repository: mxrch/GHunt
Path: blob/master/ghunt/apis/vision.py
253 views
1
from ghunt.objects.base import GHuntCreds
2
from ghunt.errors import *
3
import ghunt.globals as gb
4
from ghunt.objects.apis import GAPI, EndpointConfig
5
from ghunt.parsers.vision import VisionFaceDetection
6
7
import httpx
8
9
from typing import *
10
import inspect
11
import json
12
13
14
class VisionHttp(GAPI):
15
def __init__(self, creds: GHuntCreds, headers: Dict[str, str] = {}):
16
super().__init__()
17
18
if not headers:
19
headers = gb.config.headers
20
21
base_headers = {
22
"X-Origin": "https://explorer.apis.google.com"
23
}
24
25
headers = {**headers, **base_headers}
26
27
self.hostname = "content-vision.googleapis.com"
28
self.scheme = "https"
29
30
self._load_api(creds, headers)
31
32
async def detect_faces(self, as_client: httpx.AsyncClient, image_url: str = "", image_content: str = "",
33
data_template="default") -> Tuple[bool, bool, VisionFaceDetection]:
34
endpoint = EndpointConfig(
35
name = inspect.currentframe().f_code.co_name,
36
verb = "POST",
37
data_type = "json", # json, data or None
38
authentication_mode = None, # sapisidhash, cookies_only, oauth or None
39
require_key = "apis_explorer", # key name, or None
40
key_origin = "https://content-vision.googleapis.com"
41
)
42
self._load_endpoint(endpoint)
43
44
base_url = "/v1/images:annotate"
45
46
# image_url can cause errors with vision_api, so we prefer using image_content
47
# See => https://cloud.google.com/vision/docs/detecting-faces?#detect_faces_in_a_remote_image
48
49
data_templates = {
50
"default": {
51
"requests":[
52
{
53
"features": [
54
{
55
"maxResults":100,
56
"type":"FACE_DETECTION"
57
}
58
],
59
"image": {}
60
}
61
]
62
}
63
}
64
65
if not data_templates.get(data_template):
66
raise GHuntParamsTemplateError(f"The asked template {data_template} for the endpoint {endpoint.name} wasn't recognized by GHunt.")
67
68
# Inputs checks
69
if image_url and image_content:
70
raise GHuntParamsInputError("[Vision API faces detection] image_url and image_content can't be both put at the same time.")
71
elif not image_url and not image_content:
72
raise GHuntParamsInputError("[Vision API faces detection] Please choose at least one parameter between image_url and image_content.")
73
74
if data_template == "default":
75
if image_url:
76
data_templates["default"]["requests"][0]["image"] = {
77
"source": {
78
"imageUri": image_url
79
}
80
}
81
elif image_content:
82
data_templates["default"]["requests"][0]["image"] = {
83
"content": image_content
84
}
85
86
data = data_templates[data_template]
87
req = await self._query(endpoint.name, as_client, base_url, data=data)
88
89
rate_limited = req.status_code == 429 # API Explorer sometimes rate-limit because they set their DefaultRequestsPerMinutePerProject to 1800
90
91
vision_face_detection = VisionFaceDetection()
92
if rate_limited:
93
return rate_limited, False, vision_face_detection
94
95
# Parsing
96
data = json.loads(req.text)
97
if not data["responses"][0]:
98
return rate_limited, False, vision_face_detection
99
100
vision_data = data["responses"][0]
101
vision_face_detection._scrape(vision_data)
102
103
return rate_limited, True, vision_face_detection
104