def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('token', type=str, required=True)
        parser.add_argument('keyword', type=str, required=True)
        args = parser.parse_args()

        keyword = args['keyword']
        token = args['token']

        #check user isLogin
        if tokenValidator(token):
            resp = []
            try:
                if (keyword == ''):
                    db = sql()
                    db.cursor.execute(
                        f"select * from RPA where `top_version` = 'Y'")
                    result = db.cursor.fetchall()
                else:
                    db = sql()
                    db.cursor.execute(
                        f"select * from RPA where `top_version` = 'Y' AND match (`description`, `name`) against ('{keyword}' in BOOLEAN MODE) > 0.001"
                    )
                    result = db.cursor.fetchall()
                logging.info(result)
                data = [list(a) for a in result]
                for item in data:
                    db = sql()
                    db.cursor.execute(
                        f"select * from user where `user_id`='{item[0]}'")
                    result = db.cursor.fetchone()
                    respItem = {
                        'RPAID': item[3],
                        'RPADescription': item[5],
                        'RPAName': item[6],
                        'userName': result[1],
                        'projectID': item[1]
                    }
                    resp.append(respItem)
                return {
                    "status": "success",
                    "msg": "",
                    "data": {
                        'rpaList': resp
                    }
                }, 200
            except Exception as e:
                logging.debug(f"[getRPA] error: {e}")
                return {"status": "error", "msg": f"{e}", "data": {}}, 200
                db.conn.rollback()
            finally:
                db.conn.close()
        else:
            return {
                "status": "error",
                "msg": "user did not login",
                "data": {}
            }, 401
    def randomIndexGenerator(self):
        try:
            if self.filetype == '.csv':
                data=pd.read_csv(self.filepath)
            # elif self.filetype == '.xls' or self.filetype == 'xlsx':
            #     data=pd.read_excel(self.filepath, index_col=0)
            else:
                raise Exception("[fileChecker] file format error")
            db=sql()
            db.cursor.execute(f"delete from score where `course_id` = '{self.courseID}'")
            db.conn.commit()

            # check column in csv
            studentIDList=data[' 學號']
            
            uidList = []
            for studentID in studentIDList:
                uid=str(uuid.uuid1())
                while uid in uidList:
                    uid=str(uuid.uuid1())
                uidList.append(uid)
                tempList = studentIDList
                index = tempList[tempList == studentID].index
                tempList = tempList.drop(index)
                try:
                    db=sql()
                    for ID in tempList:
                        db.cursor.execute(f"insert into score (`course_id`,`judge_id`,`student_id`) values ('{self.courseID}','{studentID}','{ID}');")
                    db.conn.commit()

                except Exception as e:
                    raise Exception(f'[fileChecker]{e}')
                    db.conn.rollback()
                finally:
                    db.conn.close()


            data['StudentUID'] = uidList

            if self.filetype == '.csv':
                data.to_csv(self.filepath)
            # elif self.filetype == '.xls' or self.filetype == '.xlsx':
            #     data.to_excel(self.filepath)

        except Exception as e:
            db=sql()
            db.cursor.execute(f"delete from score where `course_id` = '{self.courseID}'")
            db.conn.commit()
            raise Exception(f'[fileChecker]{e}')
        return True
Beispiel #3
0
 def post(self):
     try:
         parser=reqparse.RequestParser()
         parser.add_argument('token',type=str,required=True)
         parser.add_argument('modelUid',type=str,required=True)
         args=parser.parse_args()
         if not tokenValidator(args['token']):
             return {"status":"error","msg":"token error","data":{}},401
         args.pop('token')
         logging.info(f'[API_deleteModel] args:{args}')
         mid=args['modelUid']
         _,modelFid,_,_,_,status,_,_=getModelInfo(mid)[0]
         if status=='train':
             return {"status":"error","msg":f"model {mid} is still training. Can't delete","data":{}},400
         try:
             shutil.rmtree(os.path.join(param.modelpath,mid))
         except FileNotFoundError:
             pass
         try:
             db=sql()
             db.cursor.execute(f"delete from `models` where `mid`='{mid}';")
             numOfresult=db.cursor.execute(f"select * from `models` where (`fid`='{modelFid}' and (`status`='train' or `status`='success'));")
             if numOfresult==0:
                 unlockFile(modelFid)
             db.conn.commit()
         except Exception as e:
             db.conn.rollback()
             raise e
         finally:
             db.conn.close()
         return {"status":"success","msg":"","data":{}},200
     except Exception as e:
         logging.error(f"[API_deleteModel]{traceback.format_exc()}")
         return {"status":"error","msg":str(traceback.format_exc()),"data":{}},400
Beispiel #4
0
 def purgeImg(self):
     try:
         logging.info(
             f'[PurgeImg] Purging img before {date.today()-timedelta(days=2)}'
         )
         db = sql()
         db.cursor.execute(
             f"select * from plottedImgs where createdTime<'{date.today()-timedelta(days=2)}'"
         )
         data = db.cursor.fetchall()
         data = [list(a) for a in data]
         removedId = []
         for d in data:
             id = d[0]
             path = d[1]
             try:
                 os.remove(path)
             except Exception as e:
                 logging.error(f'[PurgeImg] ID:{id}, Path:{path} Error:{e}')
             db.cursor.execute(f"delete from plottedImgs where `id`='{id}'")
         db.conn.commit()
     except Exception as e:
         db.conn.rollback()
         logging.error(f'[PurgeImg] {e}')
     finally:
         db.conn.close()
Beispiel #5
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('password', type=str, required=True)
        parser.add_argument('token', type=str,required=True)
        args = parser.parse_args()
        logging.info(f'[ForgetPasswordVerify] {args}')

        md5 = hashlib.md5()
        md5.update(args['password'].encode("utf-8"))
        password = md5.hexdigest()

        try:
            data= userPasswordToken().userPasswordTokenValidator(args['token'])
            logging.info(data)
            if data != False:
                db=sql()
                db.cursor.execute(f"update user set `user_password`='{password}' where `user_id`='{data['sub']}'")
                db.conn.commit()
                return {"status":"success","msg":"","data":{"user":data['sub']}},200
            else:
                return {"status":"error","msg":"verify error","data":{}},400
        except Exception as e:
            logging.error(f'[ForgetPasswordVerify] {e}')
            return {"status":"error","msg":f"{e}","data":{}},400
            db.conn.rollback()
        finally:
            db.conn.close()
Beispiel #6
0
 def delete(self, projectID, token):
     try:
         db = sql()
         db.cursor.execute(
             f"select model_index from model where `project_id`='{projectID}'"
         )
         result = db.cursor.fetchall()
         modelIndexList = [a[0] for a in result]
         for modelIndex in modelIndexList:
             db.cursor.execute(
                 f"select * from model where `model_index`='{modelIndex}'")
             result = db.cursor.fetchone()
             if (result[1] != None):
                 form = {'modelUid': result[1], 'token': token}
                 response = requests.post(coreApi.DeleteModel, data=form)
                 responseObj = response.json()
                 if responseObj["status"] == "success":
                     db.cursor.execute(
                         f"delete from model where `model_index` = '{modelIndex}'"
                     )
                     db.conn.commit()
                 else:
                     return False
             else:
                 db.cursor.execute(
                     f"delete from model where `model_index` = '{modelIndex}'"
                 )
                 db.conn.commit()
         return True
     except Exception as e:
         logging.error(str(e))
         db.conn.rollback()
         return False
     finally:
         db.conn.close()
Beispiel #7
0
 def convert(self):
     try:
         im = Image.fromarray(self.img)
         im.save(f'{self.params.imgpath}/{self.imgId}.png')
         self.imgWH = Image.open(
             f'{self.params.imgpath}/{self.imgId}.png').size
         td = date.today()
         db = sql()
         db.cursor.execute(
             f"INSERT INTO `incore`.`plottedImgs` (`id`, `path`, `width`, `height`, `createdTime`) VALUES ('{self.imgId}', '{self.params.imgpath}/{self.imgId}.png', '{self.imgWH[0]}', '{self.imgWH[1]}', '{td.year}-{td.month}-{td.day}');"
         )
         db.conn.commit()
         self.bokeh_fig.image_url(url=[
             f"http://{self.params.host}:{self.params.port}/viz/getimg?uid={self.imgId}&action=get"
         ],
                                  x=0,
                                  y=0,
                                  w=self.imgWH[0],
                                  h=self.imgWH[1],
                                  anchor='bottom_left')
         script, div = components(self.bokeh_fig, wrap_script=False)
         self.component = ({"div": div, "script": script})
     except Exception as e:
         raise Exception(f'[convert] {e}')
     finally:
         db.conn.close()
Beispiel #8
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('projectID', type=str, required=True)
        parser.add_argument('token', type=str, required=True)
        args = parser.parse_args()
        logging.debug(f"[GetFileList] args: {args}")

        projectID = args['projectID']
        token = args['token']

        #check user isLogin
        if tokenValidator(token):

            resp = []
            try:
                db = sql()
                db.cursor.execute(
                    f"select * from file where `project_id`='{projectID}'")
                result = db.cursor.fetchall()
                data = [list(a) for a in result]
                for item in data:
                    form = {'fileUids': json.dumps([item[0]]), 'token': token}
                    logging.info(f'form:{form}')
                    response = requests.post(coreApi.GetFileStatus, data=form)
                    responseObj = response.json()
                    if responseObj["status"] == 'success':
                        respItem = {
                            'fileID': item[0],
                            'fileName': item[1][:(item[1].rfind("."))],
                            'fileType': item[1][(item[1].rfind(".") + 1):],
                            'fileStatus': responseObj["data"]["status"][0]
                        }
                        db.cursor.execute(
                            f"select Count(*) from model where `file_id`='{item[0]}'"
                        )
                        result = db.cursor.fetchall()
                        if result[0][0] > 0:
                            respItem['fileStatus'] = 1
                        resp.append(respItem)
            except Exception as e:
                logging.error(str(e))
                db.conn.rollback()
            finally:
                db.conn.close()
            logging.debug(f"[GetFileList] resp: {resp}")
            return {
                "status": "success",
                "msg": "",
                "data": {
                    'fileList': resp
                }
            }, 200

        else:
            return {
                "status": "error",
                "msg": "user did not login",
                "data": {}
            }, 401
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('projectID', type=str, required=True)
        parser.add_argument('token', type=str, required=True)
        args = parser.parse_args()
        logging.debug(f"[DeleteProject] args: {args}")

        projectID = args['projectID']

        #check user isLogin
        if tokenValidator(args['token']):

            try:
                db = sql()
                db.cursor.execute(
                    f"select `file_id` from file where `project_id`='{projectID}'"
                )
                result = db.cursor.fetchall()
                fileIDList = [a[0] for a in result]
                for fileID in fileIDList:
                    form = {'fileUid': fileID, 'token': args['token']}
                    response = requests.post(coreApi.DeleteFile, data=form)
                    responseObj = response.json()
                    if responseObj["status"] == "success":
                        db.cursor.execute(
                            f"delete from file where `file_id` = '{fileID}'")
                        db.conn.commit()
                        continue
                    else:
                        return responseObj, 400

                if deleteModelByProject.delete(projectID,
                                               args['token']) != True:
                    return {
                        "status": "error",
                        "msg": "delete project error",
                        "data": {}
                    }, 400

                db.cursor.execute(
                    f"delete from project where `project_id` = '{projectID}'")
                db.conn.commit()
                logging.info(f"[DeleteProject] OK with project id {projectID}")
                return {"status": "success", "msg": "", "data": {}}, 200

            except Exception as e:
                db.conn.rollback()
                logging.error(e)
                return {"status": "error", "msg": f"{e}", "data": {}}, 400
            finally:
                db.conn.close()

        else:
            return {
                "status": "error",
                "msg": "user did not login",
                "data": {}
            }, 401
Beispiel #10
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('file', type=FileStorage, location='files',required=True)
        parser.add_argument('userID',type=str,required=True)
        parser.add_argument('projectID',type=str,required=True)
        parser.add_argument('token',type=str,required=True)
        args = parser.parse_args()
        logging.debug(f"[ImportRPA] args: {args}")
        file = args['file']
        userID=args['userID']
        projectID=args['projectID']
        token = args['token']

        #check user isLogin
        if tokenValidator(token):
            #check filetype
            filename=file.filename
            filetype=filename[filename.rfind("."):]
            logging.debug(f"[ImportRPA] File type:{filetype}")
            if filetype != '.json':
                return {"status":"error","msg":"file type error","data":{}},400
            
            uid = RPAUidGenerator().uid
            savedPath=param.RPAFilepath +'\\'+ uid + '.json'
            try:
                file.save(savedPath)
            except Exception as e:
                return {"status":"error","msg":f"file error:{e}","data":{}},400

            try:
                fileChecker(savedPath).check()
            except Exception as e:
                return {"status":"error","msg":str(e),"data":{}},400

            try:
                db=sql()
                db.cursor.execute(f"select MAX(version) from RPA where `project_id`='{projectID}'")
                result,  = db.cursor.fetchone()
                if result == None:
                    version = 1
                    
                else:
                    version = result + 1
                    db.cursor.execute(f"update RPA set `top_version`='N' where `user_id` = '{userID}' and `project_id` = '{projectID}'")
                    db.conn.commit()
                db.cursor.execute(f"insert into RPA (`user_id`,`project_id`, `version`, `RPA_id`, `top_version`, `name`, `description`) values ('{userID}','{projectID}','{version}','{uid}','Y', '', '');")
                db.conn.commit()
                return {"status":"success","msg":"","data":{"RPAID":uid}},201
            except Exception as e:
                logging.debug(f"[ImportRPA] error: {e}")
                db.conn.rollback()
                return {"status":"error","msg":"","data":{}},400
            finally:
                db.conn.close()
        else:
            return {"status":"error","msg":"user did not login","data":{}},401
Beispiel #11
0
    def post(self):
        '''
        @ type: num/cv/nlp
        @ file: a file
        @ tokenstr: keypair1
        @ tokenint: keypair2
        '''
        parser = reqparse.RequestParser()
        parser.add_argument('fileUid', type=str, required=True)
        parser.add_argument('token', type=str, required=True)
        args = parser.parse_args()
        fid = args['fileUid']
        token = args['token']

        #check token
        if not tokenValidator(token):
            return {"status": "error", "msg": "token error", "data": {}}, 401
        try:
            fileInfo = getFileInfo(fid)
        except Exception as e:
            logging.error(f'[Delfile]{e}')
            return {'status': 'error', 'msg': str(e), 'data': {}}, 400

        fileInfo = fileInfo[0]

        if fileInfo[3] == 1:
            logging.warning(f'[API_DelFile] file {fid} in use')
            return {
                "status": "error",
                "msg": "The file is in-used",
                "data": {}
            }, 400

        filePath = fileInfo[2]
        dataType = fileInfo[1]
        actionFile = fileInfo[5]
        if dataType == 'cv':
            shutil.rmtree(filePath)
        else:
            os.remove(filePath)
        if actionFile:
            os.remove(actionFile)

        try:
            db = sql()
            db.cursor.execute(f"delete from files where fid='{fid}'")
            db.conn.commit()
        except Exception as e:
            logging.error(f"[API_DelFile] {e}")
        finally:
            db.conn.close()

        logging.info(f"[API_DelFile] OK with file uid {fid}")
        return {"status": "success", "msg": "", "data": {}}, 201
Beispiel #12
0
def unlockFile(fid):
    try:
        db = sql()
        db.cursor.execute(
            f"UPDATE files SET `inuse` = '0' WHERE (`fid` = '{fid}');")
        db.conn.commit()
    except Exception as e:
        raise Exception(f'[unlockFile]{e}')
        db.rollback()
    finally:
        db.conn.close()
Beispiel #13
0
 def saveimg(self):
     try:
         self.mat_plt.savefig(f'{self.params.imgpath}/{self.imgId}.png', dpi=300,bbox_inches='tight')
         self.imgWH=Image.open(f'{self.params.imgpath}/{self.imgId}.png').size
         td=date.today()
         db=sql()
         db.cursor.execute(f"INSERT INTO `incore`.`plottedImgs` (`id`, `path`, `width`, `height`, `createdTime`) VALUES ('{self.imgId}', '{self.params.imgpath}/{self.imgId}.png', '{self.imgWH[0]}', '{self.imgWH[1]}', '{td.year}-{td.month}-{td.day}');")
         db.conn.commit()
     except Exception as e:
         raise Exception(f'[saveImg] {e}')
     finally:
         db.conn.close()
Beispiel #14
0
    def post(self):
        try:
            parser = reqparse.RequestParser()
            parser.add_argument('account', type=str, required=True)
            parser.add_argument('password', type=str, required=True)
            # parser.add_argument('user',type=str,required=True)
            args = parser.parse_args()

            md5 = hashlib.md5()
            md5.update(args['password'].encode("utf-8"))

            password = md5.hexdigest()
            try:
                db = sql()
                db.cursor.execute(
                    f"select * from user where `user_account`='{args['account']}' AND `user_password`='{password}'"
                )
                result = db.cursor.fetchone()

                try:
                    if result != None:
                        data = {'userID': result[0], 'userName': result[1]}
                        token = tokenGenerator(data)
                        return {
                            "status": "success",
                            "msg": "",
                            "data": {
                                "userID": f'{result[0]}',
                                "userName": f'{result[1]}',
                                'userRole': f'{result[5]}',
                                "token": f'{token}'
                            }
                        }
                    else:
                        return {
                            "status": "error",
                            "msg": "user don't exist"
                        }, 400
                except Exception as e:
                    logging.info(str(e))

            except Exception as e:
                db.conn.rollback()
            finally:
                db.conn.close()

        except Exception as e:
            return {
                "status": "error",
                "msg": f"login error:{e}",
                "data": {}
            }, 400
Beispiel #15
0
def getModelInfo(mid):
    try:
        db = sql()
        db.cursor.execute(f"select * from models where `mid`='{mid}'")
        data = db.cursor.fetchall()
        data = [[tt for tt in t] for t in data]
        if len(data) == 0:
            raise Exception(f'[getModelInfo] model {mid} not found')
        return data
    except Exception as e:
        raise Exception(f'[getModelInfo]{e}')
    finally:
        db.conn.close()
Beispiel #16
0
    def post(self):
        fName = '[AddCourse]'
        parser = reqparse.RequestParser()
        parser.add_argument('courseName', type=str, required=True)
        parser.add_argument('courseYear', type=str, required=True)
        parser.add_argument('jobName', type=str, required=True)
        parser.add_argument('deadline', type=str, required=True)
        parser.add_argument('token', type=str, required=True)
        args = parser.parse_args()

        courseName = args['courseName']
        courseYear = args['courseYear']
        jobName = args['jobName']
        deadline = args['deadline']
        token = args['token']

        #check user isLogin
        if tokenValidator(token):
            args.pop('token')
            logging.debug(f"[AddCourse] args: {args}")

            #generate course UID and save
            uid = courseIndexGenerator().uid
            logging.debug(f'[AddCourse] course UID:{uid}')

            try:
                db = sql()
                db.cursor.execute(
                    f"insert into course (`course_id`,`course_name`,`course_year`,`course_jobName`,`course_deadline`) values ('{uid}','{courseName}','{courseYear}','{jobName}','{deadline}');"
                )
                db.conn.commit()
                return {
                    "status": "success",
                    "msg": "",
                    "data": {
                        "courseID": uid
                    }
                }, 201

            except Exception as e:
                logging.error(str(e))
                return {"status": "error", "msg": str(e), "data": {}}, 400
            finally:
                db.conn.close()

        else:
            return {
                "status": "error",
                "msg": "user did not login",
                "data": {}
            }, 401
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('token', type=str, required=True)
        parser.add_argument('modelIndex', type=str, required=True)
        parser.add_argument('fileID', type=str, required=True)
        parser.add_argument('label', type=str)
        args = parser.parse_args()
        logging.debug(f"[DoModelTest] args: {args}")

        modelIndex = args['modelIndex']
        token = args['token']
        fileID = args['fileID']
        label = args['label']

        if label == None:
            label = ''

        #check user isLogin
        if tokenValidator(token):
            try:
                db = sql()
                db.cursor.execute(
                    f"select * from model where `model_index`='{modelIndex}'")
                result = db.cursor.fetchone()
                if (result[1] != None):
                    form = {
                        'modelUid': result[1],
                        'fileUid': fileID,
                        'label': label,
                        'token': token
                    }
                    resp = requests.post(coreApi.DoModelTest, data=form)
                    response = resp.json()
                    return response, 200
                else:
                    return {
                        "status": "error",
                        "msg": "model id or file id not found",
                        "data": {}
                    }, 500
            except Exception as e:
                logging.error(str(e))
                db.conn.rollback()
            finally:
                db.conn.close()
        else:
            return {
                "status": "error",
                "msg": "user did not login",
                "data": {}
            }, 401
Beispiel #18
0
def changeModelStatus(mid, status):
    statusList = ['train', 'fail', 'success']
    if status not in statusList:
        raise Exception("[changeModelStatus] invalid status")
    try:
        db = sql()
        db.cursor.execute(
            f"update models set `status` = '{status}' where `mid`='{mid}'")
        db.conn.commit()
    except Exception as e:
        db.conn.rollback()
        raise Exception(f"[changeModelStatus] {e}")
    finally:
        db.conn.close()
Beispiel #19
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('modelIndex', type=str, required=True)
        parser.add_argument('token', type=str, required=True)
        args = parser.parse_args()
        logging.debug(f"[DeleteModel] args: {args}")

        modelIndex = args['modelIndex']
        token = args['token']

        #check user isLogin
        if tokenValidator(args['token']):
            try:
                db = sql()
                db.cursor.execute(
                    f"select * from model where `model_index`='{modelIndex}'")
                result = db.cursor.fetchone()
                if result[1] != None:
                    status, resp = ModelService().deleteModel(result[1], token)
                    if (status):
                        return {
                            "status": "success",
                            "msg": "",
                            "data": {}
                        }, 200
                    else:
                        return resp
                else:
                    db.cursor.execute(
                        f"delete from model where `model_index` = '{modelIndex}'"
                    )
                    db.conn.commit()
                    logging.info(f"[DeleteModel] OK with file id {modelIndex}")
                    return {
                        "status": "success",
                        "msg": "can not find model",
                        "data": {}
                    }, 200

            except Exception as e:
                logging.error(str(e))
                return {"status": "error", "msg": f"{e}", "data": {}}, 500

        else:
            return {
                "status": "error",
                "msg": "user did not login",
                "data": {}
            }, 401
Beispiel #20
0
    def post(self):
        fName = '[ModifyCourse]'
        parser = reqparse.RequestParser()
        parser.add_argument('courseID', type=str, required=True)
        parser.add_argument('courseName', type=str, required=True)
        parser.add_argument('courseYear', type=str, required=True)
        parser.add_argument('jobName', type=str, required=True)
        parser.add_argument('deadline', type=str, required=True)
        parser.add_argument('token', type=str, required=True)
        args = parser.parse_args()

        courseID = args['courseID']
        courseName = args['courseName']
        courseYear = args['courseYear']
        jobName = args['jobName']
        deadline = args['deadline']
        token = args['token']

        #check user isLogin
        if tokenValidator(token):
            args.pop('token')
            logging.debug(f"[ModifyCourse] args: {args}")

            try:
                db = sql()
                db.cursor.execute(
                    f"update course set `course_name`='{courseName}', `course_year`='{courseYear}', `course_jobName`='{jobName}', `course_deadline`='{deadline}' where `course_id`='{courseID}'"
                )
                db.conn.commit()
                return {
                    "status": "success",
                    "msg": "",
                    "data": {
                        "courseID": courseID
                    }
                }, 200

            except Exception as e:
                logging.error(str(e))
                return {"status": "error", "msg": str(e), "data": {}}, 400
            finally:
                db.conn.close()

        else:
            return {
                "status": "error",
                "msg": "user did not login",
                "data": {}
            }, 401
Beispiel #21
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('fileID', type=str, required=True)
        parser.add_argument('action', type=str, required=True)
        parser.add_argument('fileNameAfterProcessing', type=str, required=True)
        parser.add_argument('userID', type=str, required=True)
        parser.add_argument('projectID', type=str, required=True)
        parser.add_argument('token', type=str, required=True)
        args = parser.parse_args()
        logging.debug(f"[DoPreprocess] args: {args}")

        fileID = args['fileID']
        action = args['action']
        token = args['token']
        fileNameAfterProcessing = args['fileNameAfterProcessing']
        userID = args['userID']
        projectID = args['projectID']

        #check user isLogin
        if tokenValidator(token):
            response = AnalyticService().doPreprocess(token, fileID, action)

            if response["status"] == "success":
                try:
                    newFileID = response["data"]["fileUid"]
                    db = sql()
                    db.cursor.execute(
                        f"insert into file (`file_id`,`file_name`,`user_id`,`project_id`) values ('{newFileID}','{fileNameAfterProcessing}','{userID}','{projectID}');"
                    )
                    db.conn.commit()
                    logging.info(
                        f"[DoPreprocess] OK with file uid {newFileID}")
                    return response
                except Exception as e:
                    db.conn.rollback()
                    logging.error(str(e))
                finally:
                    db.conn.close()

            else:
                return response
            return response
        else:
            return {
                "status": "error",
                "msg": "user did not login",
                "data": {}
            }, 401
 def sendLineMessage(self, status):
     db = sql()
     db.cursor.execute(
         f"select * from user where `user_id`='{self.userID}'")
     result = db.cursor.fetchone()
     lineID = result[6]
     db.cursor.execute(f"select * from RPA where `RPA_id`='{self.RPAID}'")
     result = db.cursor.fetchone()
     RPAName = result[6]
     if (lineID == None):
         return
     else:
         form = {'lineID': lineID, 'status': status, 'projectName': RPAName}
         logging.info(f'{form}')
         resp = requests.post('https://140.112.26.135:8005/sendMessage',
                              data=form)
         logging.info(f'{resp}')
Beispiel #23
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('projectID', type=str, required=True)
        parser.add_argument('token', type=str, required=True)
        args = parser.parse_args()
        logging.debug(f"[GetProjectInfo] args: {args}")

        projectID = args['projectID']

        #check user isLogin
        if tokenValidator(args['token']):

            resp = []
            try:
                db = sql()
                db.cursor.execute(
                    f"select * from project where `project_id`='{projectID}'")
                result = db.cursor.fetchone()
                respItem = {
                    'projectName': result[2],
                    'projectType': result[3],
                    'dataType': result[4]
                }
            except Exception as e:
                db.conn.rollback()
                return {
                    "status": "error",
                    "msg": "project not found",
                    "data": {}
                }, 200
            finally:
                db.conn.close()
            return {
                "status": "success",
                "msg": "",
                "data": {
                    'project': respItem
                }
            }, 200

        else:
            return {
                "status": "error",
                "msg": "user did not login",
                "data": {}
            }, 401
Beispiel #24
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('userID', type=str, required=True)
        parser.add_argument('token', type=str, required=True)
        args = parser.parse_args()
        logging.debug(f"[GetProject] args: {args}")

        userID = args['userID']

        #check user isLogin
        if tokenValidator(args['token']):

            resp = []
            try:
                db = sql()
                db.cursor.execute(
                    f"select * from project where `user_id`='{userID}'")
                result = db.cursor.fetchall()
                data = [list(a) for a in result]
                for item in data:
                    respItem = {
                        'projectID': item[0],
                        'projectName': item[2],
                        'projectType': item[3],
                        'dataType': item[4]
                    }
                    resp.append(respItem)
            except Exception as e:
                db.conn.rollback()
            finally:
                db.conn.close()
            logging.debug(f"[GetProject] resp: {resp}")
            return {
                "status": "success",
                "msg": "",
                "data": {
                    'projectList': resp
                }
            }, 200

        else:
            return {
                "status": "error",
                "msg": "user did not login",
                "data": {}
            }, 401
    def studentDataChecker(self):
        try:
            if self.filetype == '.csv':
                data=pd.read_csv(self.filepath)
            # elif self.filetype == '.xls' or self.filetype == 'xlsx':
            #     data=pd.read_excel(self.filepath, index_col=0)

            # check column in csv
            cols=data.columns.tolist()
            if not(' 學號' in cols and ' 電子郵件' in cols):
                raise Exception("[fileChecker] file do not contain 學號 or 電子郵件")
        except Exception as e:
            db=sql()
            db.cursor.execute(f"delete from score where `course_id` = '{self.courseID}'")
            db.conn.commit()
            os.remove(self.filepath)
            raise Exception(f'[fileChecker]{e}')
        return True
Beispiel #26
0
def handle_message(event):
    try:
        db = sql()
        db.cursor.execute(
            f"select * from user where `user_email`='{event.message.text}'")
        result = db.cursor.fetchone()
        if (result == None):
            line_bot_api.reply_message(
                event.reply_token, TextSendMessage(text="查無此Email, 請重新確認!"))
        else:
            db.cursor.execute(
                f"update user set `user_line`='{event.source.user_id}' where `user_id`='{result[0]}'"
            )
            db.conn.commit()
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text="綁定成功!"))
    except Exception as e:
        db.conn.rollback()
Beispiel #27
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('projectName', type=str, required=True)
        parser.add_argument('projectType',type=str,required=True)
        parser.add_argument('dataType',type=str,required=True)
        parser.add_argument('userID',type=str,required=True)
        parser.add_argument('token',type=str,required=True)
        args = parser.parse_args()
        logging.debug(f"[AddProject] args: {args}")

        projectName = args['projectName']
        projectType = args['projectType']
        dataType = args['dataType']
        userID = args['userID']

        #check user isLogin
        if tokenValidator(args['token']):

            projectTypeList=param.projectTypeList
            #check project type
            if args['projectType'] not in projectTypeList:
                return {"status":"error","msg":"project type not supported","data":{}},400

            
            dataTypeList=param.dataFileTypeList
            #check data type
            if dataType not in dataTypeList:
                return {"status":"error","msg":"data type not supported","data":{}},400

            uid = projectUidGenerator().uid
            try:
                db=sql()
                db.cursor.execute(f"insert into project (`project_id`,`user_id`,`project_name`,`project_type`,`data_type`) values ('{uid}','{userID}','{projectName}','{projectType}','{dataType}');")
                db.conn.commit()
            except Exception as e:
                db.conn.rollback()
            finally:
                db.conn.close()
            logging.info(f"[AddProject] OK with project id {uid}")
            return {"status":"success","msg":"","data":{"projectID":uid}},201


        else:
            return {"status":"error","msg":"user did not login","data":{}},401
Beispiel #28
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('projectID', type=str, required=True)
        parser.add_argument('token', type=str, required=True)
        args = parser.parse_args()
        logging.debug(f"[GetAnalyticsAlgoByProject] args: {args}")
        projectID = args['projectID']
        token = args['token']

        #check user isLogin
        if tokenValidator(token):
            try:
                db = sql()
                db.cursor.execute(
                    f"select * from project where `project_id`='{projectID}'")
                result = db.cursor.fetchone()
                if result != None:
                    form = {"dataType": result[4], "projectType": result[3]}
                    resp = requests.get(coreApi.GetAnalyticAlgo, data=form)
                    response = resp.json()
                    logging.warn(f'response {response}')
                    if response['status'] == 'success':
                        return response, 200
                    else:
                        return response, 400
                else:
                    return {
                        "status": "error",
                        "msg": 'Project not found',
                        "data": {}
                    }, 400

            except Exception as e:
                logging.error(str(e))
                return {"status": "error", "msg": f'{e}', "data": {}}, 400
                db.conn.rollback()
            finally:
                db.conn.close()
        else:
            return {
                "status": "error",
                "msg": "user did not login",
                "data": {}
            }, 401
Beispiel #29
0
 def get(self):
     try:
         parser = reqparse.RequestParser()
         parser.add_argument('uid', type=str, required=True)
         parser.add_argument('action', type=str, required=True)
         args = parser.parse_args()
         logging.debug(f"[API_getImg] args: {args}")
         uid = args['uid']
         action = args['action']
         db = sql()
         db.cursor.execute(
             f"select `path` from plottedImgs where id='{uid}'")
         info = db.cursor.fetchall()
         info = [[tt for tt in t] for t in info]
         if len(info) == 0:
             abort(404)
         logging.debug(f"[API_getImg] SQL: {info}")
         path = info[0][0]
         file = open(path, 'rb')
         data = file.read()
         response = make_response(data)
         response.headers['Access-Control-Allow-Origin'] = '*'
         response.headers[
             'Access-Control-Allow-Methods'] = 'OPTIONS,HEAD,GET,POST'
         response.headers[
             'Access-Control-Allow-Headers'] = 'x-requested-with'
         if action == 'download':
             response.headers[
                 'Content-Type'] = 'application/octet-stream; charset=utf-8'
             response.headers[
                 'Content-Disposition'] = 'attachment; filename=visualize.png'
         elif action == 'get':
             pass
         else:
             return {
                 "status": "error",
                 "msg": "action is not valid",
                 "data": {}
             }, 400
     except Exception as e:
         logging.error(f'[API_getImg] {e}')
         return {"status": "error", "msg": str(e), "data": {}}, 400
     return response
Beispiel #30
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('token', type=str, required=True)
        args = parser.parse_args()
        logging.debug(f"[GetCourse] args: {args}")

        #check user isLogin
        if tokenValidator(args['token']):

            resp = []
            try:
                db = sql()
                db.cursor.execute(f"select * from course")
                result = db.cursor.fetchall()
                data = [list(a) for a in result]
                for item in data:
                    respItem = {
                        'courseID': item[0],
                        'courseName': item[1],
                        'courseYear': item[2],
                        'jobName': item[3],
                        'deadline': item[4]
                    }
                    resp.append(respItem)
            except Exception as e:
                db.conn.rollback()
            finally:
                db.conn.close()
            logging.debug(f"[GetCourse] resp: {resp}")
            return {
                "status": "success",
                "msg": "",
                "data": {
                    'courseList': resp
                }
            }, 200

        else:
            return {
                "status": "error",
                "msg": "user did not login",
                "data": {}
            }, 401