-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcat_detector.py
executable file
·128 lines (95 loc) · 2.66 KB
/
cat_detector.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#!/usr/bin/env python3
import requests
import json
import os
import io
import base64
from PIL import Image
import sys
home=os.getenv("HOME")
API_KEY=(open(home+"/.aws/API_KEY", "r").read().strip())
API_URL=(open(home+"/.aws/API_URL", "r").read().strip())
def customJSON(obj):
d = obj.__dict__
for x in d:
dx = d[x]
if(type(dx) is int):
continue
if(type(dx) is str):
continue
if(type(dx) is list):
for i in range(0, len(dx)):
dx[i] = customJSON(dx[i])
continue
if(dx is None):
continue
d[x] = customJSON(d[x])
print("custom=", d[x])
return d
class ImageRequest:
imageBytes=None
imageURL=None
confidence=0
bucketFilename=None
bucketFolder=None
def __init__(self, bytes, confidence):
self.confidence=confidence
self.imageBytes=bytes
def readImage(filename):
file=open(filename, "rb")
data=file.read()
data = resizeImage(data)
encoded=base64.b64encode(data).decode()
return encoded
def isImage(filename):
if(filename.endswith("png")):
return True
elif(filename.endswith("jpeg")):
return True
elif(filename.endswith("jpg")):
return True
def resizeImage(image):
im = Image.open(io.BytesIO(image))
size = [1024,1024]
w,h = im.size
if(w < size[0]):
size[0] = w
if(h < size[1]):
size[1] = h
im.thumbnail(size, Image.ANTIALIAS)
imgByteArr = io.BytesIO()
im.save(imgByteArr, format='PNG')
imgByteArr = imgByteArr.getvalue()
return imgByteArr
def process(filename):
results = []
if(os.path.isfile(filename)):
if(not isImage(filename)):
return None
data = readImage(filename)
request = ImageRequest(data, 50)
headers = {"accept":"application/json","Content-Type":"application/json", "x-api-key":API_KEY}
payload=json.dumps(customJSON(request))
response = requests.post(API_URL, headers=headers, data=payload)
loaded = json.loads(response.content)
print(loaded)
elif(os.path.isdir(filename)):
for file in os.listdir(filename):
out = process(filename+"/"+file)
if(not out is None):
results.append(out)
else:
print("Error: File not found:"+filename)
return None
return results
def main():
print("url="+API_URL)
print("key="+API_KEY)
if(len(sys.argv) > 1):
location=sys.argv[1]
else:
location=input("Please give a location::")
if(location is None or location == ""):
return
process(location)
main()