-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.py
174 lines (143 loc) · 6.42 KB
/
main.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
from fastapi import FastAPI, File, Request
from functions.ImageDetectorV1 import detectorV1
from functions.ImageDetectorV2 import detectorV2
from functions.newassignmentV1 import new_assignmentV1
from functions.newassignmentV2 import new_assignmentV2
from fastapistats import Stats
import json
import os
from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler
from fastapi.responses import RedirectResponse
import uuid
app = FastAPI()
update = Stats.update_stats
# THese 2 functions help count if objects were detected for the dashboard
@app.get('/countobjectdetected', response_class=RedirectResponse)
@update(name='Detected')
def objectdetected():
return RedirectResponse("https://two-trick-pony-nl-dashboard-photoscavenger-dashboard-jvqrac.streamlitapp.com/")
@app.get('/countobjectnotdetected', response_class=RedirectResponse)
@update(name='NotDetected')
def objectnotdetected():
return RedirectResponse("https://two-trick-pony-nl-dashboard-photoscavenger-dashboard-jvqrac.streamlitapp.com/")
@app.get('/', response_class=RedirectResponse)
@update(name='Homepage')
def read_root(request: Request):
print("redirect to dashboard")
return RedirectResponse("https://two-trick-pony-nl-dashboard-photoscavenger-dashboard-jvqrac.streamlitapp.com/")
@app.get('/exampleresponse')
@update(name='ExampleResponse')
def exampleresponse():
return {'Searchedfor:': 'boat',
'Wasfound': 'NO',
'OtherObjectsDetected': ['person',
'person',
'person',
'person',
'bicycle',
'motorbike',
'bicycle',
'motorbike',
'bicycle'],
'Processed_FileName': 'scanned_image54e46fb8-93f8-43ad-a8ec-99eb83f260af.jpg',
'file_url': 'image54e46fb8-93f8-43ad-a8ec-99eb83f260af.jpg',
'listofobjectsWithConfidence':
[{'person': 100},
{'person': 100},
{'person': 100},
{'person': 100},
{'bicycle': 97},
{'motorbike': 91},
{'bicycle': 75},
{'motorbike': 48},
{'bicycle': 28}]}
# This endpoint triggers for this API call: 127.0.0.1:8000/uploadfile/cat.
# Add a image to your call in the body, and set a expected object in the URL.
# The function then runs the AI model to see if the picture contains the expected object
@app.post('/uploadfile/{expectedobject}')
@update(name='uploadfileV1') # if the name kwarg is not passed it will default to the function name
async def UploadImage(expectedobject, file: bytes = File(...)):
uniqueid = str(uuid.uuid4())
with open('image'+uniqueid+'.jpg', 'wb') as image:
rawimage = 'image'+uniqueid+'.jpg'
os.chdir('static')
image.write(file)
image.close()
os.chdir('..')
results = detectorV1(rawimage, expectedobject)
objectfound = results[1]
otherobjectsdetected = results[2]
listofobjectsWithConfidence = results[3]
filename = results[0]
# remove uploaded image
os.remove(rawimage)
return {'Searchedfor:': expectedobject, 'Wasfound': objectfound, 'OtherObjectsDetected': otherobjectsdetected, 'Processed_FileName': filename, 'file_url': rawimage, 'listofobjectsWithConfidence': listofobjectsWithConfidence}
@app.post("/v2/uploadfile/{expectedobject}")
@update(name='uploadfileV2')
async def UploadImageV2(expectedobject, file: bytes = File(...)):
# Receiving the image the image
uniqueid = str(uuid.uuid4())
with open('image'+uniqueid+'.jpg', 'wb') as image:
# Saving te raw image
rawimage = 'image'+uniqueid+'.jpg'
image.write(file)
# Calling the detector
results = detectorV2(rawimage, expectedobject)
# Parsing the different results
objectfound = results[1]
print(objectfound)
if objectfound == 'NO':
await objectnotdetected()
else:
await objectdetected()
filename = results[0]
otherobjectsdetected = results[2]
# Removing the image uploaded so we don't store any data
os.remove(rawimage)
return {'Searchedfor:': expectedobject, 'Wasfound': objectfound, 'OtherObjectsDetected': otherobjectsdetected, 'Processed_FileName': filename}
@app.get('/newassignment/{score}')
@update(name='NewAssignmentV1') # if the name kwarg is not passed it will default to the function name
def new_assignment(score: int):
assignment = new_assignmentV1(score)
return assignment
@app.get('/v2/newassignment/{score}')
@update(name='NewAssignmentV2') # if the name kwarg is not passed it will default to the function name
def new_assignment_v2(score: int):
assignment = new_assignmentV2(score)
return assignment
@app.get('/healthcheck')
@update(name='Healthcheck by AWS')
def healthcheck():
return 'Server is up'
@app.get('/get_long_term_data/')
def get_long_term_data():
with open('statshistoric.json', 'r+') as payload:
payload = json.load(payload)
return payload
def daily_analytics_update():
# Get the current days stats and add a timestamp
with open('stats.json', 'r+') as data:
new_data = json.load(data)
date = {'timestamp': datetime.today().strftime('%Y-%m-%d %H:%M')}
new_data.update(date)
with open('statshistoric.json', 'r+') as file:
# First we load existing data into a dict.
file_data = json.load(file)
# Join new_data with file_data inside emp_details
file_data["LongtermData"].append(new_data)
# Sets file's current position at offset.
file.seek(0)
# convert back to json.
json.dump(file_data, file, indent=4)
# reset the daily json to 0
for i in new_data:
new_data[i] = 0
with open("stats.json", "w") as f:
json.dump(new_data, f, indent=4)
# This schedular runs every hour making a snapshot of the stats.json
# file and stores in in the longermdata file
scheduler = BackgroundScheduler()
scheduler.add_job(daily_analytics_update, 'interval', hours=48)
scheduler.start()
daily_analytics_update()