-
Notifications
You must be signed in to change notification settings - Fork 1
/
food.py
43 lines (32 loc) · 1.2 KB
/
food.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import os
import json
from google.cloud import vision
from google.oauth2 import service_account
credentials = os.getenv("VISION_API_CREDENTIALS", "")
print("hi")
print(credentials)
info = json.loads(credentials)
client = vision.ImageAnnotatorClient(
credentials=service_account.Credentials.from_service_account_info(info)
)
class FoodException(Exception):
def __init__(self, message):
super().__init__(message)
def food(data: bytes) -> tuple:
"""Detects if an image contains food.
Returns a tuple with the first item a boolean (whether it has food)
and the second item a dict mapping detected labels to scores.
Based on the example remote label classification on Google Cloud Docs.
"""
image = vision.Image(content=data)
response = client.label_detection(image=image, max_results=10)
labels = {
label.description.lower(): label.score for label in response.label_annotations
}
if response.error.message:
raise FoodException(
"{}\nFor more info on error messages, check: https://cloud.google.com/apis/design/errors".format(
response.error.message
)
)
return (labels.get("food", 0) >= 0.70, labels)