forked from MrHiraiwa/LineBotForGPTPlus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vision.py
73 lines (58 loc) · 2.68 KB
/
vision.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from flask import Blueprint, request, redirect, jsonify
import requests
import base64
import os
vision = Blueprint('vision', __name__)
GOOGLE_API_KEY = os.environ.get('GOOGLE_API_KEY') # API key should be stored in environment variables
def analyze_image(image_bytes):
api_url = "https://vision.googleapis.com/v1/images:annotate?key=" + GOOGLE_API_KEY
base64_image = base64.b64encode(image_bytes).decode("utf-8")
request_body = {
"requests": [
{
"image": {
"content": base64_image
},
"features": [
{ "type": "LABEL_DETECTION" },
{ "type": "TEXT_DETECTION" },
{ "type": "LANDMARK_DETECTION" },
{ "type": "FACE_DETECTION" },
{ "type": "OBJECT_LOCALIZATION" },
{ "type": "DOCUMENT_TEXT_DETECTION" }
]
}
]
}
response = requests.post(api_url, json=request_body)
return response.json()
def vision_results_to_string(vision_results):
result_string = ""
result = vision_results['responses'][0]
label_annotations = result.get('labelAnnotations', [])
text_annotations = result.get('textAnnotations', [])
landmark_annotations = result.get('landmarkAnnotations', [])
face_annotations = result.get('faceAnnotations', [])
object_annotations = result.get('localizedObjectAnnotations', [])
result_string += "Labels: " + ', '.join([ann['description'] for ann in label_annotations]) if label_annotations else "None"
result_string += "\nText: " + ', '.join([ann['description'] for ann in text_annotations]) if text_annotations else "None"
result_string += "\nLandmarks: " + ', '.join([ann['description'] for ann in landmark_annotations]) if landmark_annotations else "None"
result_string += "\nFaces: " + str(len(face_annotations))
result_string += "\nObjects: " + ', '.join([ann['name'] for ann in object_annotations]) if object_annotations else "None"
return result_string
import requests
def get_image(image_url, line_access_token):
headers = {
"Content-Type": "application/json; charset=UTF-8",
"Authorization": f"Bearer {line_access_token}",
}
response = requests.get(image_url, headers=headers)
return response.content
from linebot import LineBotApi
def vision_api(message_id, CHANNEL_ACCESS_TOKEN):
line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)
message_content = line_bot_api.get_message_content(message_id)
image = message_content.content
vision_results = analyze_image(image)
vision_results = vision_results_to_string(vision_results)
return vision_results