-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
54 lines (44 loc) · 1.88 KB
/
Copy pathserver.py
File metadata and controls
54 lines (44 loc) · 1.88 KB
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
from starlette.applications import Starlette
from starlette.responses import HTMLResponse, JSONResponse
from starlette.staticfiles import StaticFiles
from starlette.middleware.cors import CORSMiddleware
import uvicorn, aiohttp, asyncio
from io import BytesIO
from fastai import *
from fastai.vision import *
model_file_url ='https://drive.google.com/uc?export=download&id=1dXLSSh8XPLS5DP-DeCJpZuIXbflXOCzj'
model_file_name = 'model'
classes = ['mask', 'no_mask']
path = Path(__file__).parent
app = Starlette()
app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_headers=['X-Requested-With', 'Content-Type'])
app.mount('/static', StaticFiles(directory='app/static'))
async def download_file(url, dest):
if dest.exists(): return
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
data = await response.read()
with open(dest, 'wb') as f: f.write(data)
async def setup_learner():
await download_file(model_file_url, path/'models'/f'{model_file_name}.pth')
data_bunch = ImageDataBunch.single_from_classes(path, classes,
ds_tfms=get_transforms(), size=224).normalize(imagenet_stats)
learn = cnn_learner(data_bunch, models.resnet34, pretrained=False)
learn.load(model_file_name)
return learn
loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(setup_learner())]
learn = loop.run_until_complete(asyncio.gather(*tasks))[0]
loop.close()
@app.route('/')
def index(request):
html = path/'view'/'index.html'
return HTMLResponse(html.open().read())
@app.route('/analyze', methods=['POST'])
async def analyze(request):
data = await request.form()
img_bytes = await (data['file'].read())
img = open_image(BytesIO(img_bytes))
return JSONResponse({'result': str(learn.predict(img)[0])})
if __name__ == '__main__':
if 'serve' in sys.argv: uvicorn.run(app, host='0.0.0.0', port=8080)