analyze.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import json
  2. import logging
  3. import uuid
  4. from flask import Blueprint
  5. from flask import request
  6. from db import db
  7. from db.task import Task
  8. from route.util import make_response
  9. from service.photo_analyzer import StandingPhotoAnalyzer
  10. from service.video_analyzer import *
  11. from worker.thread_pool import pool
  12. # from service.video_analyzer import BaseVideoAnalyzer, CrunchVideoAnalyzer, HighKneesVideoAnalyzer, \
  13. # PlankVideoAnalyzer, SquatVideoAnalyzer, StandingLongJumpVideoAnalyzer, JuanfuAnalyzer
  14. # from service.video.Video3DAnalyzer import Video3DAnalyzer
  15. logging.basicConfig(format='%(asctime)s - %(name)s[line:%(lineno)d] - %(levelname)s: %(message)s',
  16. level=logging.DEBUG)
  17. bp = Blueprint("analyze", __name__, url_prefix='/')
  18. def callback_generator(task_uuid):
  19. def callback(status, **kwargs):
  20. try:
  21. from app import app
  22. with app.app_context():
  23. task = Task.query.get(task_uuid)
  24. task.status = status
  25. if status == 'FINISHED':
  26. task.result = json.dumps(kwargs['result'])
  27. if status == 'ERROR':
  28. logging.error("error analyzing: ", exc_info=kwargs['error'])
  29. db.session.commit()
  30. logging.debug("calling to " + status)
  31. except Exception as e:
  32. logging.debug("nmsl", exc_info=e)
  33. return callback
  34. @bp.route("analysis", methods=['POST'])
  35. def analysis():
  36. req = request.get_json()
  37. types = {
  38. "PHOTO_STANDING": StandingPhotoAnalyzer,
  39. "VIDEO_HIGHKNEES": GaotaituiVideoAnalyzer,
  40. "VIDEO_CRUNCH": JuanfuAnalyzer,
  41. "VIDEO_STANDINGLONGJUMP": JumpVideoAnalyzer,
  42. "VIDEO_MULTIJUMP": JumpwithbothVideoAnalyzer,
  43. "VIDEO_SITANDREACH": SitforwardVideoAnalyzer,
  44. "VIDEO_RUNBACKANDFORTH": TrunaroundVideoAnalyzer,
  45. "VIDEO_TENNISTHROW": TennisthrowVideoAnalyzer,
  46. "VIDEO_BALANCEBEAM": BalancebeamVideoAnalyzer,
  47. "VIDEO_SINGLELEGSTAND": StandingVideoAnalyzer,
  48. "VIDEO_PLANK": PingbanVideoAnalyzer,
  49. "VIDEO_SQUAT": ShendunVideoAnalyzer
  50. }
  51. ana_type = types.get(req.get('type'))
  52. if ana_type is None:
  53. return make_response(400, "invalid type", {})
  54. try:
  55. ana = ana_type(req.get('data'))
  56. except Exception as e:
  57. return make_response(400, str(e), {})
  58. with __import__("app").app.app_context():
  59. task_uuid = str(uuid.uuid4())
  60. new_task = Task(task_uuid, req.get('type'))
  61. db.session.add(new_task)
  62. db.session.commit()
  63. logging.debug("task created.")
  64. pool.submit(ana.analyze, callback_generator(task_uuid))
  65. logging.debug("task submited")
  66. return make_response(201, "success", {'task_uuid': task_uuid})