Advertisement
qq88

Untitled

Mar 16th, 2020
369
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.34 KB | None | 0 0
  1. import aiohttp
  2. import asyncio
  3. import uvicorn
  4. from fastai import *
  5. from fastai.vision import *
  6. from io import BytesIO
  7. from starlette.applications import Starlette
  8. from starlette.middleware.cors import CORSMiddleware
  9. from starlette.responses import HTMLResponse, JSONResponse
  10. from starlette.staticfiles import StaticFiles
  11.  
  12. export_file_url = 'https://www.dropbox.com/s/6bgq8t6yextloqp/export.pkl?raw=1'
  13. export_file_name = 'export.pkl'
  14.  
  15. classes = ['black', 'grizzly', 'teddys']
  16. path = Path(__file__).parent
  17.  
  18. app = Starlette()
  19. app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_headers=['X-Requested-With', 'Content-Type'])
  20. app.mount('/static', StaticFiles(directory='app/static'))
  21.  
  22.  
  23. async def download_file(url, dest):
  24.     if dest.exists(): return
  25.     async with aiohttp.ClientSession() as session:
  26.         async with session.get(url) as response:
  27.             data = await response.read()
  28.             with open(dest, 'wb') as f:
  29.                 f.write(data)
  30.  
  31.  
  32. async def setup_learner():
  33.     await download_file(export_file_url, path / export_file_name)
  34.     try:
  35.         learn = load_learner(path, export_file_name)
  36.         return learn
  37.     except RuntimeError as e:
  38.         if len(e.args) > 0 and 'CPU-only machine' in e.args[0]:
  39.             print(e)
  40.             message = "\n\nThis model was trained with an old version of fastai and will not work in a CPU environment.\n\nPlease update the fastai library in your training environment and export your model again.\n\nSee instructions for 'Returning to work' at https://course.fast.ai."
  41.             raise RuntimeError(message)
  42.         else:
  43.             raise
  44.  
  45.  
  46. loop = asyncio.get_event_loop()
  47. tasks = [asyncio.ensure_future(setup_learner())]
  48. learn = loop.run_until_complete(asyncio.gather(*tasks))[0]
  49. loop.close()
  50.  
  51.  
  52. @app.route('/')
  53. async def homepage(request):
  54.     html_file = path / 'view' / 'index.html'
  55.     return HTMLResponse(html_file.open().read())
  56.  
  57.  
  58. @app.route('/analyze', methods=['POST'])
  59. async def analyze(request):
  60.     img_data = await request.form()
  61.     img_bytes = await (img_data['file'].read())
  62.     img = open_image(BytesIO(img_bytes))
  63.     prediction = learn.predict(img)[0]
  64.     return JSONResponse({'result': str(prediction)})
  65.  
  66.  
  67. if __name__ == '__main__':
  68.     if 'serve' in sys.argv:
  69.         uvicorn.run(app=app, host='0.0.0.0', port=5000, log_level="info")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement