Browse Source

fix import and refactor.

lyc8503 4 years ago
parent
commit
76d6b4b935

+ 6 - 3
backend_refactor/app.py

@@ -1,10 +1,13 @@
 import logging
+
 from flask import Flask
-import route.upload, route.analyze, route.result
-from config import VERSION_PREFIX, MAX_CONTENT_LENGTH, MYSQL_URI
-from route.util import make_response
 
+import route.analyze
+import route.result
+import route.upload
+from config import VERSION_PREFIX, MAX_CONTENT_LENGTH, MYSQL_URI
 from db import db
+from route.util import make_response
 
 app = Flask(__name__)
 app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH

+ 1 - 1
backend_refactor/db/__init__.py

@@ -1,3 +1,3 @@
 from flask_sqlalchemy import SQLAlchemy
 
-db = SQLAlchemy()
+db = SQLAlchemy()

+ 10 - 8
backend_refactor/db/task.py

@@ -1,18 +1,20 @@
-from db import db
 import time
 
+from db import db
+
+
 class Task(db.Model):
     uuid = db.Column(db.String(64), primary_key=True)
-    type = db.Column(db.Enum('PHOTO_STANDING', 'VIDEO_HIGHKNEES', 
-        'VIDEO_CRUNCH', 'VIDEO_STANDINGLONGJUMP', 'VIDEO_MULTIJUMP', 
-        'VIDEO_SITANDREACH', 'VIDEO_RUNBACKANDFORTH', 
-        'VIDEO_TENNISTHROW', 'VIDEO_BALANCEBEAM', 
-        'VIDEO_SINGLELEGSTAND', 'VIDEO_PLANK', 'VIDEO_SQUAT'))
+    type = db.Column(db.Enum('PHOTO_STANDING', 'VIDEO_HIGHKNEES',
+                             'VIDEO_CRUNCH', 'VIDEO_STANDINGLONGJUMP', 'VIDEO_MULTIJUMP',
+                             'VIDEO_SITANDREACH', 'VIDEO_RUNBACKANDFORTH',
+                             'VIDEO_TENNISTHROW', 'VIDEO_BALANCEBEAM',
+                             'VIDEO_SINGLELEGSTAND', 'VIDEO_PLANK', 'VIDEO_SQUAT'))
     create_time = db.Column(db.BigInteger)
-    status = db.Column(db.Enum('QUEUEING','RUNNING','FINISHED','ERROR'))
+    status = db.Column(db.Enum('QUEUEING', 'RUNNING', 'FINISHED', 'ERROR'))
     result = db.Column(db.String(8192))
 
-    def __init__(self, uuid, type, create_time = time.time() * 1000, status='QUEUEING', result='{}'):
+    def __init__(self, uuid, type, create_time=time.time() * 1000, status='QUEUEING', result='{}'):
         self.uuid = uuid
         self.type = type
         self.create_time = create_time

+ 6 - 0
backend_refactor/gunicorn.conf.py

@@ -162,6 +162,7 @@ access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"
 
 proc_name = None
 
+
 #
 # Server hooks
 #
@@ -183,15 +184,19 @@ proc_name = None
 def post_fork(server, worker):
     server.log.info("Worker spawned (pid: %s)", worker.pid)
 
+
 def pre_fork(server, worker):
     pass
 
+
 def pre_exec(server):
     server.log.info("Forked child, re-executing.")
 
+
 def when_ready(server):
     server.log.info("Server is ready. Spawning workers")
 
+
 def worker_int(worker):
     worker.log.info("worker received INT or QUIT signal")
 
@@ -209,5 +214,6 @@ def worker_int(worker):
                 code.append("  %s" % (line.strip()))
     worker.log.debug("\n".join(code))
 
+
 def worker_abort(worker):
     worker.log.info("worker received SIGABRT signal")

+ 0 - 0
backend_refactor/pool/__init__.py


+ 0 - 2
backend_refactor/pool/thread_pool.py

@@ -1,5 +1,3 @@
 from concurrent.futures import ThreadPoolExecutor
 
 pool = ThreadPoolExecutor()
-
-

+ 1 - 2
backend_refactor/route/analyze.py

@@ -1,5 +1,4 @@
 import json
-import logging
 import uuid
 
 from flask import Blueprint
@@ -7,10 +6,10 @@ from flask import request
 
 from db import db
 from db.task import Task
+from pool.thread_pool import pool
 from route.util import make_response
 from service.photo_analyzer import StandingPhotoAnalyzer
 from service.video_analyzer import *
-from worker.thread_pool import pool
 
 # from service.video_analyzer import BaseVideoAnalyzer, CrunchVideoAnalyzer, HighKneesVideoAnalyzer, \
 # PlankVideoAnalyzer, SquatVideoAnalyzer, StandingLongJumpVideoAnalyzer, JuanfuAnalyzer

+ 5 - 4
backend_refactor/route/result.py

@@ -1,9 +1,10 @@
 import json
+import uuid
 
 from flask import Blueprint
-from route.util import make_response
+
 from db.task import Task
-import uuid
+from route.util import make_response
 
 bp = Blueprint("result", __name__, url_prefix='/')
 
@@ -18,7 +19,8 @@ def get_result(task_uuid):
     status = task.status
 
     if status == 'FINISHED':
-        return make_response(200, "success", {"task_uuid": task.uuid, "type": task.type, "result": json.loads(task.result)})
+        return make_response(200, "success",
+                             {"task_uuid": task.uuid, "type": task.type, "result": json.loads(task.result)})
     elif status == 'QUEUEING':
         return make_response(200, "queueing", {"task_uuid": task.uuid, "type": task.type})
     elif status == 'RUNNING':
@@ -27,4 +29,3 @@ def get_result(task_uuid):
         return make_response(200, "error", {"task_uuid": task.uuid, "type": task.type})
     else:
         assert 0.1 + 0.2 == 0.3, "what do u mean?"
-    

+ 1 - 2
backend_refactor/route/upload.py

@@ -1,13 +1,12 @@
 import logging
 import uuid
 
+from PIL import Image
 from flask import request, Blueprint
 
 from config import UPLOAD_DIR
 from route.util import make_response
 
-from PIL import Image
-
 bp = Blueprint("upload", __name__, url_prefix='/')
 
 

+ 0 - 1
backend_refactor/service/ai/photo/standing_photo.py

@@ -327,4 +327,3 @@ def analyse_npy_side(npy_side, height):
         result.append("膝盖角度分析:下肢膝盖超伸角度为{}度".format(round(knee_angle_r, 2)))
     result.append(knee_forward_risk_level)
     return result
-

+ 1 - 3
backend_refactor/service/ai/util/__init__.py

@@ -6,6 +6,4 @@ Created on Tue Apr 28 18:47:14 2020
 @author: joe
 """
 
-
-
-#__all__ = ["torch_openpose", "util", "model"]
+# __all__ = ["torch_openpose", "util", "model"]

+ 1 - 1
backend_refactor/service/ai/util/body.py

@@ -212,7 +212,7 @@ if __name__ == "__main__":
     body_estimation = Body('../model/body_pose_model.pth')
 
     test_image = '../images/ski.jpg'
-    #test_image='.。/capture_image/capture_image3.png'
+    # test_image='.。/capture_image/capture_image3.png'
     oriImg = cv2.imread(test_image)  # B,G,R order
     candidate, subset = body_estimation(oriImg)
     canvas = util.draw_bodypose(oriImg, candidate, subset)

+ 2 - 1
backend_refactor/service/ai/util/breakout25.py

@@ -5,9 +5,10 @@ Created on Tue Apr 28 15:13:51 2020
 
 @author: joe
 """
-import numpy as np
 import math
 
+import numpy as np
+
 jointpairs = [[1, 0], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 8], [8, 9], [9, 10], [10, 11], [8, 12],
               [12, 13], [13, 14], [0, 15], [0, 16] \
     , [15, 17], [16, 18], [11, 24], [11, 22], [14, 21], [14, 19], [22, 23], [19, 20]]

+ 4 - 3
backend_refactor/service/ai/util/torch_openpose.py

@@ -1,12 +1,13 @@
+import logging
+import math
+
 import cv2
 import numpy as np
-import math
-from scipy.ndimage.filters import gaussian_filter
 import torch
+from scipy.ndimage.filters import gaussian_filter
 
 from service.ai.util import util
 from service.ai.util.model import bodypose_model, bodypose_25_model
-import logging
 
 model_coco = 'model/body_coco.pth'
 model_body25 = 'model/body_25.pth'

+ 27 - 25
backend_refactor/service/ai/util/util.py

@@ -1,26 +1,27 @@
-import numpy as np
 import math
+
 import cv2
+import numpy as np
 
 
 # draw the body keypoint and lims
-def draw_bodypose(img, poses,model_type = 'coco'):
+def draw_bodypose(img, poses, model_type='coco'):
     stickwidth = 4
-    
+
     limbSeq = [[1, 2], [1, 5], [2, 3], [3, 4], [5, 6], [6, 7], [1, 8], [8, 9], \
-                   [9, 10], [1, 11], [11, 12], [12, 13], [1, 0], [0, 14], [14, 16], \
-                   [0, 15], [15, 17]]
+               [9, 10], [1, 11], [11, 12], [12, 13], [1, 0], [0, 14], [14, 16], \
+               [0, 15], [15, 17]]
     njoint = 18
-    if model_type == 'body_25':    
-        limbSeq = [[1,0],[1,2],[2,3],[3,4],[1,5],[5,6],[6,7],[1,8],[8,9],[9,10],\
-                            [10,11],[8,12],[12,13],[13,14],[0,15],[0,16],[15,17],[16,18],\
-                                [11,24],[11,22],[14,21],[14,19],[22,23],[19,20]]
+    if model_type == 'body_25':
+        limbSeq = [[1, 0], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 8], [8, 9], [9, 10], \
+                   [10, 11], [8, 12], [12, 13], [13, 14], [0, 15], [0, 16], [15, 17], [16, 18], \
+                   [11, 24], [11, 22], [14, 21], [14, 19], [22, 23], [19, 20]]
         njoint = 25
 
     colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], \
               [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], \
-              [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85], [255,255,0], [255,255,85], [255,255,170],\
-                  [255,255,255],[170,255,255],[85,255,255],[0,255,255]]
+              [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85], [255, 255, 0], [255, 255, 85], [255, 255, 170], \
+              [255, 255, 255], [170, 255, 255], [85, 255, 255], [0, 255, 255]]
     for i in range(njoint):
         for n in range(len(poses)):
             pose = poses[n][i]
@@ -28,16 +29,16 @@ def draw_bodypose(img, poses,model_type = 'coco'):
                 continue
             x, y = pose[:2]
             cv2.circle(img, (int(x), int(y)), 4, colors[i], thickness=-1)
-    
+
     for pose in poses:
-        for limb,color in zip(limbSeq,colors):
+        for limb, color in zip(limbSeq, colors):
             p1 = pose[limb[0]]
             p2 = pose[limb[1]]
-            if p1[2] <=0 or p2[2] <= 0:
+            if p1[2] <= 0 or p2[2] <= 0:
                 continue
             cur_canvas = img.copy()
-            X = [p1[1],p2[1]]
-            Y = [p1[0],p2[0]]
+            X = [p1[1], p2[1]]
+            Y = [p1[0], p2[0]]
             mX = np.mean(X)
             mY = np.mean(Y)
             length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
@@ -45,27 +46,28 @@ def draw_bodypose(img, poses,model_type = 'coco'):
             polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
             cv2.fillConvexPoly(cur_canvas, polygon, color)
             img = cv2.addWeighted(img, 0.4, cur_canvas, 0.6, 0)
-   
+
     return img
 
+
 def padRightDownCorner(img, stride, padValue):
     h = img.shape[0]
     w = img.shape[1]
 
     pad = 4 * [None]
-    pad[0] = 0 # up
-    pad[1] = 0 # left
-    pad[2] = 0 if (h % stride == 0) else stride - (h % stride) # down
-    pad[3] = 0 if (w % stride == 0) else stride - (w % stride) # right
+    pad[0] = 0  # up
+    pad[1] = 0  # left
+    pad[2] = 0 if (h % stride == 0) else stride - (h % stride)  # down
+    pad[3] = 0 if (w % stride == 0) else stride - (w % stride)  # right
 
     img_padded = img
-    pad_up = np.tile(img_padded[0:1, :, :]*0 + padValue, (pad[0], 1, 1))
+    pad_up = np.tile(img_padded[0:1, :, :] * 0 + padValue, (pad[0], 1, 1))
     img_padded = np.concatenate((pad_up, img_padded), axis=0)
-    pad_left = np.tile(img_padded[:, 0:1, :]*0 + padValue, (1, pad[1], 1))
+    pad_left = np.tile(img_padded[:, 0:1, :] * 0 + padValue, (1, pad[1], 1))
     img_padded = np.concatenate((pad_left, img_padded), axis=1)
-    pad_down = np.tile(img_padded[-2:-1, :, :]*0 + padValue, (pad[2], 1, 1))
+    pad_down = np.tile(img_padded[-2:-1, :, :] * 0 + padValue, (pad[2], 1, 1))
     img_padded = np.concatenate((img_padded, pad_down), axis=0)
-    pad_right = np.tile(img_padded[:, -2:-1, :]*0 + padValue, (1, pad[3], 1))
+    pad_right = np.tile(img_padded[:, -2:-1, :] * 0 + padValue, (1, pad[3], 1))
     img_padded = np.concatenate((img_padded, pad_right), axis=1)
 
     return img_padded, pad

+ 0 - 1
backend_refactor/service/ai/video/inner_analyze.py

@@ -1,4 +1,3 @@
-import logging
 import math
 
 

+ 0 - 1
backend_refactor/service/ai/video/video_score/balancebeam.py

@@ -47,7 +47,6 @@ def cal_second_score(list):
     return sum_score
 
 
-
 def cal_balancebeam(result):
     result_ig = result
     re = {}

+ 0 - 1
backend_refactor/service/ai/video/video_score/juanfu.py

@@ -1,4 +1,3 @@
-
 def ignore_data_juanfu(result):
     result_ig = result
     k = "0"

+ 2 - 2
backend_refactor/service/ai/video/video_score/jump.py

@@ -143,11 +143,11 @@ def cal_jump(result):
         if int(index) <= int(highest_ankle_index):
             continue
         else:
-            if float(result[str(int(index) - 1)]["leg_heigh"]) <= float(result[index]["leg_heigh"]) or float(result[index]["leg_heigh"])>float(lowest_ankle_height):
+            if float(result[str(int(index) - 1)]["leg_heigh"]) <= float(result[index]["leg_heigh"]) or float(
+                    result[index]["leg_heigh"]) > float(lowest_ankle_height):
                 lowest_ankle_height = float(result[index]["leg_heigh"])
                 lowest_ankle_index = index
 
-
     result_ig = is_zero(result_ig, lowest_ankle_index)
 
     fifth_score = cal_ratio(result_ig[lowest_ankle_index]["hip_right_angle"], 85) * 20 + cal_ratio(

+ 1 - 1
backend_refactor/service/ai/video/video_score/sitforward.py

@@ -38,7 +38,7 @@ def cal_sitforward(result):
     highest_weist_index = 0
 
     for index in result:
-        if float(result[index]["wrist_x"]) < float(highest_wrist_x) and float(result[index]["wrist_x"])!=0:
+        if float(result[index]["wrist_x"]) < float(highest_wrist_x) and float(result[index]["wrist_x"]) != 0:
             highest_wrist_x = result[index]["wrist_x"]
             highest_weist_index = index
     is_zero(result_ig, highest_weist_index)

+ 0 - 1
backend_refactor/service/ai/video/video_score/tennisthrow.py

@@ -119,7 +119,6 @@ def cal_tennisthrow(result):
     re["1"]["farrest_distance"] = farrest_distance
     re["1"]["first_score"] = first_score
 
-
     re["3"] = result_ig[highest_wrist_index]
     re["3"]["highest_wrist_index"] = highest_wrist_index
     re["3"]["highest_wrist"] = highest_wrist

+ 0 - 1
backend_refactor/service/ai/video/video_score/turnaround.py

@@ -78,7 +78,6 @@ def check_zero(result_ig, index):
     return index
 
 
-
 # 10-meter turnaround
 def cal_turnaround(result):
     result_ig = result

+ 3 - 1
backend_refactor/service/photo_analyzer.py

@@ -1,6 +1,8 @@
+import copy
 from typing import Callable
+
 import cv2
-import copy
+
 from config import UPLOAD_DIR
 from service.ai.photo.standing_photo import *
 from service.ai.util import torch_openpose

+ 3 - 4
backend_refactor/service/video_analyzer.py

@@ -1,10 +1,11 @@
+import logging
 import os.path
 import pickle
 from typing import Callable
-from config import UPLOAD_DIR
+
 import cv2
-import logging
 
+from config import UPLOAD_DIR
 from service.ai.util.torch_openpose import torch_openpose
 from service.ai.util.util import draw_bodypose
 from service.ai.video.classify.gaotaitui import classify_gaotaitui
@@ -93,8 +94,6 @@ class BaseVideoAnalyzer:
             raise e
 
 
-
-
 class JumpVideoAnalyzer(BaseVideoAnalyzer):
     def _do_analyze(self):
         self.results = {k: analyse_npy_side_jump(v) for k, v in self.results.items()}