Ejemplo n.º 1
0
 def post(self):
     ret = json.dumps({'status': 0, 'content': 'OK'})
     db = Mydb()
     try:
         info = self.request.protocol + "://" + self.request.host + ", method=" + self.request.method + ", access url=" + self.request.uri
         logger.info(info)
         body = self.request.body_arguments
         Args = [
             self_argument('username', True, helpinfo='Miss username'),
             self_argument('password', True, helpinfo='Miss password'),
         ]
         s, vals = DataIsValid(Args, body)
         if s:
             raise Exception(vals)
         username = vals['username']
         password = vals['password']
         if not (username or password):
             raise Exception('no password or username')
         sql = "SELECT * FROM user WHERE username='******' and password='******'" % (username, password)
         s, f = db.get(sql)
         if f:
             raise Exception("The user is exist!")
         else:
             sql = "INSERT INTO user VALUES (%s, %s)"
             s, f = db.modify(sql, [username, password])
             if s:
                 raise Exception(f)
             ret = json.dumps({'status': 0, 'content': 'OK'})
     except Exception, e:
         logger.error(str(e))
         ret = json.dumps({'status': '-110', 'content': str(e)})
Ejemplo n.º 2
0
 def post(self):
     ret = json.dumps({'status': 0, 'content': 'OK'})
     db = Mydb()
     try:
         info = self.request.protocol + "://" + self.request.host + ", method=" + self.request.method + ", access url=" + self.request.uri
         logger.info(info)
         body = self.request.body_arguments
         Args = [
             self_argument('username', required=True, helpinfo="miss user name"),
             self_argument('title', required=True, helpinfo="miss topic title"),
             self_argument('content', required=True, helpinfo="miss topic content"),
         ]
         s, vals = DataIsValid(Args, body)
         if s:
             raise Exception(vals)
         username = vals['username']
         if not(username):
             raise Exception("No username, Maybe not login")
         sql_str = "SELECT * FROM user WHERE username='******'" % (username)
         s, f = db.get(sql_str)
         if s or not(f):
             raise Exception("No this user")
         title = vals['title']
         if len(title) > 100:
             raise Exception("title has too many words")
         content = vals['content']
         if len(content) < 100:
             abstract = content
         else:
             abstract = content[:100]
         date = get_ct()
         sql_str = "INSERT INTO topic VALUES (NULL, %s, %s, %s, %s, %s)"
         data = [username, title, content, abstract, date]
         s, f = db.modify(sql_str, data)
         if s:
            raise Exception(f)
     except Exception, e:
         logger.error(str(e))
         ret = json.dumps({'status': '-120', 'content': str(e)})
Ejemplo n.º 3
0
 def post(self):
     ret = json.dumps({'status': 0, 'content': 'OK'})
     db = Mydb()
     try:
         info = self.request.protocol + "://" + self.request.host + ", method=" + self.request.method + ", access url=" + self.request.uri
         logger.info(info)
         body = self.request.body_arguments
         Args = [
             self_argument('username', required=True, helpinfo="miss user name"),
             self_argument('topic_id', required=True, helpinfo="miss topic id"),
             self_argument('content', required=True, helpinfo="miss comment content"),
         ]
         s, vals = DataIsValid(Args, body)
         if s:
             raise Exception(vals)
         username = vals['username']
         if not(username):
             raise Exception("No username, Maybe not login")
         sql_str = "SELECT * FROM user WHERE username='******'" % (username)
         s, f = db.get(sql_str)
         if s or not(f):
             raise Exception("No this user")
         date = get_ct()
         content = vals['content']
         topic_id = vals['topic_id']
         sql_str = "SELECT * FROM topic WHERE topic_id=%s" % (topic_id)
         s, f= db.get(sql_str)
         if s or not(f):
             raise Exception("No this topic")
         sql_str = "INSERT INTO comment VALUES (NULL, %s, %s, %s, %s)"
         data = [username, topic_id, content, date]
         s, f = db.modify(sql_str, data)
         if s:
             raise Exception(f)
     except Exception, e:
         logger.error(str(e))
         ret = json.dumps({'status': '-120', 'content': str(e)})
Ejemplo n.º 4
0
class tag_submit(restful.Resource):
    def __init__(self):
        self.ret = {
            "status": 0,
            "message": ""
        }
        self.db = Mydb()

    def post(self):
        #判断post的值是否正确
        try:
            arguments = [
                Arg('tag', type=str, required=True, help='Miss tag'),
                Arg('domain', type=str, required=False, help='Miss domain', default=""),
                Arg('project', type=str, required=True, help='Miss project'),
                Arg('role', type=str, required=True, help='Miss role'),
                Arg('comment', type=str, required=True, help='Miss comment'),
                Arg('commit_time', type=str, required=True, help='Miss commit_time'),
                Arg('commit_user', type=str, required=True, help='Miss commit_user'),
                Arg('download_url', type=str, required=True, help='Miss download_url'),
                Arg('config_url', type=str, required=True, help='Miss config_url'),
                Arg('is_ready', type=str, required=False, help='Miss is_ready', default=""),
                Arg('branch', type=str, required=True, help='Miss is_ready'),
            ]
            args = get_parser(arguments).parse_args()
            tag_tag = args['tag']
            tag_domain = args['domain']
            tag_project = args['project']
            tag_role = args['role']
            tag_comment = args['comment']
            tag_commit_time = args['commit_time']
            tag_commit_user = args['commit_user']
            tag_download_url = args['download_url']
            tag_config_url = args['config_url']
            tag_is_ready = args['is_ready']
            tag_branch = args['branch']
            #判断此tag值是否已经存在
            sql_str = 'SELECT tag FROM tag WHERE tag="%s" and project="%s" and role="%s" and branch="%s"' % (
                        tag_tag, tag_project, tag_role, tag_branch)
            exist_tag, f = self.db.get(sql_str)
            if exist_tag:
                raise Exception("this tag is exist")
            ISOTIMEFORMAT = '%Y-%m-%d %H:%M:%S'
            try:
                #将提交时间的字符转转化成datetime格式
                tag_commit_time = datetime.datetime.strptime(tag_commit_time, ISOTIMEFORMAT)
            except Exception, e:
                raise Exception(str(e))
            print tag_commit_time
            sql_str = 'INSERT INTO tag (tag, domain, project, role, comment, commit_time, commit_user, config_url, download_url, is_ready, branch) ' \
                      'VALUES ("%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s");' % (
                tag_tag, tag_domain, tag_project, tag_role, tag_comment, tag_commit_time, tag_commit_user, tag_config_url, tag_download_url, tag_is_ready, tag_branch)
            s, f = self.db.modify(sql_str)
            if s:
                logger.error(f)
                raise Exception(str(f))
            self.ret['message'] = "OK"
            logger.info('insert a tag info: %s', self.ret["message"])
        except Exception, e:
            logger.error(str(e))
            self.ret["status"] = -400
            self.ret["message"] = str(e)
Ejemplo n.º 5
0
    def post(self):
        ret = {'status': 0, 'message': 'OK'}
        db = Mydb()
        try:
            upfilepath = ''
            ivecfile = ''
            upload_path = config_get('wavdir', 'sre')
            dependent_threshold = float(
                config_get('dependent-threshold', 'sre'))
            independent_threshold = float(
                config_get('independent-threshold', 'sre'))
            if not os.path.exists(upload_path):
                os.makedirs(upload_path)
            logger.info('upload path is ' + upload_path)
            ivec_path = config_get('ivectordir', 'sre')
            validframes = int(config_get('validframes', 'sre'))
            if not os.path.exists(ivec_path):
                os.makedirs(ivec_path)
            logger.info('ivec path is ' + ivec_path)
            info = self.request.protocol + '://' + self.request.host + ', method=' + self.request.method + ', access url=' + self.request.uri
            logger.info(info)
            body = self.request.body_arguments
            Args = [
                self_argument('UserId', required=True,
                              helpinfo='miss user id'),
                self_argument('IsSelf',
                              required=True,
                              helpinfo='miss isself symbol'),
                self_argument('TextRelevance',
                              required=True,
                              helpinfo='miss text relevance symbol')
            ]
            s, vals = DataIsValid(Args, body)
            if s:
                raise Exception(vals)
            userid = vals['UserId']
            isself = vals['IsSelf']
            text_relevance = vals['TextRelevance']
            isself_symbol = False
            if isself == 'yes':
                isself_symbol = True
            elif isself != 'no':
                logger.warning('isself param maybe wrong:' + isself)
            text_relevance_symbol = False
            if text_relevance == 'yes':
                text_relevance_symbol = True
            elif text_relevance != 'no':
                logger.warning('text_relevance param maybe wrong:' +
                               text_relevance)
            logger.info('userid is ' + userid)
            if not (userid):
                raise Exception('No user id')
            res, userinfo = db.get('SELECT * FROM user WHERE userid="%s"' %
                                   (userid))
            if res != 0:
                raise Exception('cannot find user: %s information.' % (userid))
            if len(userinfo) > 0:
                latest_info = sorted(userinfo,
                                     key=lambda x: int(x['timeid']),
                                     reverse=True)[0]
            else:
                raise Exception('%s\'s userinfo is empty' % (userid))
            logger.info('query user %s info:%s' % (userid, str(latest_info)))
            file_metas = self.request.files['UploadFile']
            wav_uuid = uuid.uuid1()
            logger.info('generate uuid:' + str(wav_uuid))
            wavpath = upload_path + '/' + userid
            if not os.path.exists(wavpath):
                os.makedirs(wavpath)
            for meta in file_metas:
                filename = meta['filename']
                upfilepath = wavpath.rstrip('/') + '/' + str(
                    wav_uuid) + '_' + str(isself_symbol) + '_' + filename
                with open(upfilepath, 'wb') as up:
                    up.write(meta['body'])
                    up.close()
                    break
            ivecfile_path = ivec_path.rstrip('/') + '/' + userid + '/'
            if not os.path.exists(ivecfile_path):
                os.makedirs(ivecfile_path)
            ivecfile = ivecfile_path.rstrip('/') + '/' + str(
                wav_uuid) + '.ivec'
            ubm = get_ubm()
            sre_compute = CpuCompute()
            #use str function is to avoid string encode error
            if not sre_compute.Compute(ubm, str(upfilepath), str(ivecfile),
                                       int(validframes)):
                raise Exception('compute ivector failed')
            sre_score = ScorePLDA()
            mean = get_mean()
            if not mean:
                raise Exception('ubm is not inited')
            #use str function is to avoid string encode error
            score = float(
                sre_score.score_plda(ubm.ubm, str(latest_info['ivecpath']),
                                     str(ivecfile), str(mean)))
            res, _ = db.modify(
                'INSERT INTO valid (userid, wavpath, ivecpath, isself, score) values ("%s", "%s", "%s", %s, %f);'
                % (userid, upfilepath, ivecfile, isself_symbol, score))
            if res != 0:
                raise Exception('insert record into user error')
            threshold = 0
            if text_relevance_symbol:
                threshold = dependent_threshold
                ret['message'] = 'Text-dependent valid function, '
            else:
                threshold = independent_threshold
                ret['message'] = 'Text-independent valid function, '
            if score > threshold:
                ret['message'] += 'you are in person, threshold is ' + str(
                    threshold)
            else:
                ret['message'] += 'you are not in person, threshold is ' + str(
                    threshold)
            ret['message'] += ', score is %f' % (score)

        except Exception, e:
            logger.error(str(e))
            ret = {'status': -1, 'message': str(e)}
            if os.path.isfile(upfilepath):
                os.remove(upfilepath)
            if os.path.isfile(ivecfile):
                os.remove(ivecfile)
Ejemplo n.º 6
0
    def post(self):
        ret = {'status': 0, 'message': 'OK'}
        db = Mydb()
        try:
            upfilepath = ''
            ivecfile = ''
            upload_path = config_get('wavdir', 'sre')
            if not os.path.exists(upload_path):
                os.makedirs(upload_path)
            logger.info('upload path is ' + upload_path)
            ivec_path = config_get('ivectordir', 'sre')
            validframes = int(config_get('validframes', 'sre'))
            if not os.path.exists(ivec_path):
                os.makedirs(ivec_path)
            logger.info('ivec path is ' + ivec_path)
            info = self.request.protocol + '://' + self.request.host + ', method=' + self.request.method + ', access url=' + self.request.uri
            logger.info(info)
            body = self.request.body_arguments
            Args = [
                self_argument('UserId', required=True, helpinfo='miss user id')
            ]
            s, vals = DataIsValid(Args, body)
            if s:
                raise Exception(vals)
            userid = vals['UserId']
            logger.info('userid is ' + userid)
            if not (userid):
                raise Exception('No user id')
            file_metas = self.request.files['UploadFile']
            wav_uuid = uuid.uuid1()
            logger.info('generate uuid:' + str(wav_uuid))
            wavpath = upload_path + '/' + userid
            if not os.path.exists(wavpath):
                os.makedirs(wavpath)
            for meta in file_metas:
                filename = meta['filename']
                upfilepath = wavpath.rstrip('/') + '/' + str(
                    wav_uuid) + '_' + filename
                with open(upfilepath, 'wb') as up:
                    up.write(meta['body'])
                    up.close()
                    break
            ivecfile_path = ivec_path.rstrip('/') + '/' + userid + '/'
            if not os.path.exists(ivecfile_path):
                os.makedirs(ivecfile_path)
            ivecfile = ivecfile_path.rstrip('/') + '/' + str(
                wav_uuid) + '.ivec'
            ubm = get_ubm()
            sre_compute = CpuCompute()
            #use str function is to avoid string encode error
            if not sre_compute.Compute(ubm, str(upfilepath), str(ivecfile),
                                       int(validframes)):
                raise Exception('compute ivector failed')
            res, userinfo = db.get('SELECT * FROM user WHERE userid="%s";' %
                                   (userid))
            if len(userinfo) > 0:
                logger.warning(
                    'the user %s was enrolled, verification just use latest ivector'
                    % (userid))
            sql_command = 'INSERT INTO user (userid, wavpath, ivecpath) values ("%s", "%s", "%s");' % (
                userid, upfilepath, ivecfile)

            res, _ = db.modify(sql_command)
            if res != 0:
                raise Exception('insert record into user error')
        except Exception, e:
            logger.error(str(e))
            ret = {'status': -1, 'message': str(e)}
            if os.path.isfile(upfilepath):
                os.remove(upfilepath)
            if os.path.isfile(ivecfile):
                os.remove(ivecfile)