def wxbt_init_question(openid: str): """ 生成一个current记录, 返回current对象本身 所有current记录到同一个用户上([email protected], user_id: 5dfa0c005e3dd462f4755877) 另外创建字段记录其openid """ current_test = BtCurrentTestModel() current_test.user_id = WxBtConfig.wx_user_id current_test.openid = openid current_test.test_start_time = datetime.datetime.utcnow() current_test.questions = {} xuanzeti = QuestionModel.objects(index=WxBtConfig.xuanzeti_index).first() i = 1 for t in xuanzeti.questions: tmp = { "type": 4, "content": t['text'], "options": [{ "key": a, "value": b } for a, b in t['options'].items()], "index": i } current_test.questions.update({str(i): tmp}) i += 1 q1 = QuestionModel.objects(index=WxBtConfig.q8_index).first() q2 = QuestionModel.objects(index=WxBtConfig.q9_index).first() q = q1 _upload_url = wxbt_gen_upload_url(openid, i) _upload_url = 'audio/0-bt-christmas2019/8.m4a' q_current = CurrentQuestionEmbed(q_id=str(q.id), q_type=q.q_type, q_text=q.text, wav_upload_url=_upload_url, file_location='BOS', status='url_fetched') current_test.questions.update({str(i): q_current}) q.update(inc__used_times=1) # update i += 1 q = q2 _upload_url = wxbt_gen_upload_url(openid, i) _upload_url = 'audio/0-bt-christmas2019/9.m4a' q_current = CurrentQuestionEmbed(q_id=str(q.id), q_type=q.q_type, q_text=q.text, wav_upload_url=_upload_url, file_location='BOS', status='url_fetched') current_test.questions.update({str(i): q_current}) q.update(inc__used_times=1) # update i += 1 # save current_test.save() return current_test
def admin_get_question(): question_index = int(request.form.get("questionId")) # todo: change api and param name questions = QuestionModel.objects(index=question_index) if len(questions) == 0: resp = {"needDisplay": True, "tip": "没有此题号"} return jsonify(errors.error(resp)) question = questions[0] if question["q_type"] != 2: resp = {"needDisplay": True, "tip": "暂时只支持题型2"} return jsonify(errors.error(resp)) # 生成测试 test = CurrentTestModel() test.user_id = str(current_user.id) test.test_start_time = datetime.datetime.utcnow() q_current = CurrentQuestionEmbed(q_id=str(question.id), q_type=question.q_type, q_text=question.text, wav_upload_url='', wav_temp_url='') test.questions = {"1": q_current} test.save() # 保存test id # print("[DEBUG] save test id in session when admin get question, test id: %s" % test.id.__str__()) current_app.logger.debug("save test id in session when admin get question, test id: %s" % test.id.__str__()) session["test_id"] = test.id.__str__() # wrap question context = {"questionType": question.q_type, "questionNumber": 1, "questionLimitTime": ExamConfig.question_limit_time[question.q_type], "lastQuestion": True, "readLimitTime": ExamConfig.question_prepare_time[question.q_type], "questionInfo": QuestionConfig.question_type_tip[question.q_type], "questionContent": question.text } return jsonify(errors.success(json.dumps(context)))
def get_score_of_specific_questions(index): """获取某题目的成绩情况 :param index: 题号ID :return: 该问题的成绩情况 """ current_app.logger.info('get_score_of_specific_questions ' + index) cur_question = QuestionModel.objects(index=index).first() if not cur_question: return jsonify(errors.Score_criteria_not_exist) all_answers = AnalysisModel.objects(question_num=index).order_by('date') if len(all_answers) == 0: return jsonify(errors.Score_no_data) mapper = DateMapper() result_by_date = __generate_result_from_dict( mapper.map_answers(all_answers), 'date') result_all = [] for answer in all_answers: result_all.append( _generate_total_score(answer['score_key'], answer['score_detail'])) return jsonify( errors.success({ 'resultByDate': result_by_date, 'allResult': result_all }))
def start_auto_optimize(): question_num = request.form.get("questionNum") settings = json.loads(request.form.get("settings")) print("start_auto_optimize: questionNum: " + str(question_num)) print(settings) # 重新计算某道题目所有人的击中向量 question = QuestionModel.objects(index=question_num).first() if not question: return jsonify(errors.Question_not_exist) analysis = Analysis() analysis.re_analysis(question) # 根据击中向量优化参数 analysis_list = AnalysisModel.objects(question_num=question_num).order_by( 'score_key') # !!!从低到高排序 if len(analysis_list) == 0: return jsonify(errors.success(OptimizeConfig.EMPTY_SCORE_DATA)) key_hit_mat = [] for a in analysis_list: key_hit_mat.append(a['key_hits']) detail_hit_mat = [] analysis_list = analysis_list.order_by('score_detail') # !!!从低到高排序 for a in analysis_list: detail_hits = reduce(lambda x, y: x + y, a['detail_hits']) detail_hit_mat.append(detail_hits) algorithm = GradientDescent( ) if settings['algorithm'] == 'gradient' else NormalEquation() key_y = algorithm.get_gaussian_array(settings['keyMean'], settings['keySigma'], len(key_hit_mat)) detail_y = algorithm.get_gaussian_array(settings['detailMean'], settings['detailSigma'], len(detail_hit_mat)) settings[ 'theta'] = question['weights']['key'] if settings['reuse'] else None # 调用优化方法 key_theta, key_j = algorithm.optimize_param(key_hit_mat, key_y, settings) detail_theta, detail_j = algorithm.optimize_param(detail_hit_mat, detail_y, settings) # 存储优化结果 question['weights']['key'] = key_theta question['weights']['detail'] = detail_theta question['last_optimize_time'] = datetime.datetime.utcnow() question['auto_optimized'] = True question.save() # 存储cost optimize = OptimizeModel() optimize['question_num'] = question_num optimize['wordbase'] = question['wordbase'] optimize['weights'] = question['weights'] optimize['key_history_cost'] = key_j optimize['detail_history_cost'] = detail_j optimize['complete_time'] = datetime.datetime.utcnow() optimize['finish'] = True optimize.save() return jsonify(errors.success())
def collect_history_to_analysis(): """将 current 表中新出现的已评分分析的题目搬运到 analysis """ print('[collect_history_to_analysis] start') history_list = HistoryTestModel.objects() for question in QuestionModel.objects(q_type=2).order_by('index'): collect(question, history_list) print('[collect_history_to_analysis] end')
def get_weight_data(): question_num = request.args.get("questionNum") print("get_weight_data: questionNum: " + str(question_num)) question = QuestionModel.objects(index=question_num).first() if not question: return jsonify(errors.Question_not_exist) data = __question2weight(question) data['allHitTimes'] = len(AnalysisModel.objects(question_num=question_num)) # return jsonify(errors.success(mock_data.weight_data)) print(errors.success(data)) return jsonify(errors.success(data))
def get_cached_questions(q_type): key = 'cached_questions:type_%s' % q_type all_qs_bytes = redis_client.get(key) if all_qs_bytes: return pickle.loads(all_qs_bytes) d = {'q_type': q_type, 'index': {'$lte': 10000}} questions = QuestionModel.objects(__raw__=d).order_by( 'used_times') # 按使用次数倒序获得questions cached_qs = [] for q in questions: cached_qs.append(q) redis_client.set(key, pickle.dumps(cached_qs), ex=7200, nx=True) return cached_qs
def post(self): ''' 질문 검색 ''' uuid = request.json['uuid'] Quest = QuestionModel.objects(uuid=uuid).first() name = QuestionModel.objects(uuid=uuid).first() Num = 0 append_Dict = dict() QNA_LIST = list() if Quest is None: abort(406) for q in Quest['question']: QNA_LIST.append(( Quest['question'][q]['question'], Quest['question'][q]['answer'] )) Str = { 'title': str(name['name']), 'list': { } } while True: if not QNA_LIST: break else: append_Dict[Num] = {'question': QNA_LIST[0][0], 'answer': QNA_LIST[0][1]} del QNA_LIST[0] Num += 1 Str['list'] = dict(append_Dict) return jsonify(Str)
def update_weight(): question_num = request.form.get('questionNum') weight = json.loads(request.form.get("weight")) print("update_weight: questionNum: " + str(question_num)) print(weight) question = QuestionModel.objects(index=question_num).first() if not question: return jsonify(errors.Question_not_exist) question['weights']['key'] = weight['keyWeight'] question['weights']['detail'] = weight['detailWeight'] question['last_optimize_time'] = datetime.datetime.utcnow() question.save() # return jsonify(errors.success(mock_data.weight_data)) return jsonify(errors.success(__question2weight(question)))
def post(self): user_id = get_jwt_identity() uuid = request.json['uuid'] user = UserModel.objects(id=user_id).first() if user is None: abort(406) quest_uuid = QuestionModel.objects(uuid=uuid).first() if not quest_uuid['name'] == user_id: abort(409) pass
def post(self): ''' 문제 테이블 생성 및 수정 ''' user_identity = get_jwt_identity() quest_uuid = request.json['uuid'] quest_name = request.json['title'] quest_list = request.json['list'] find = QuestionModel.objects(uuid=quest_uuid).first() user = UserModel.objects(id=user_identity).first() if user is None: abort(406) if find is None: quest = {} for a in quest_list: quest[a] = { 'question': quest_list[str(a)]['q'], 'answer': quest_list[str(a)]['a'] } QuestionModel( gar=quest_uuid, uuid=quest_uuid, name=quest_name, user=user_identity, question=quest, ).save() else: quest = {} for a in quest_list: quest[a] = { 'question': quest_list[str(a)]['q'], 'answer': quest_list[str(a)]['a'] } find.update(question=quest) return {'uuid': quest_uuid}, 201
def post(self): ''' 유저 검색 ''' Num = 0 append_Dict = dict() uuid_name_List = list() search_user = request.json['search_id'] user = UserModel.objects(id=search_user).first() QList = QuestionModel.objects(user=search_user).all() if user is None: abort(406) for q in QList: uuid_name_List.append((q['uuid'], q['name'])) Str = { 'user': { 'id': user['id'], 'name': user['name'] }, 'workbook' : { } } while True: if not uuid_name_List: break else: append_Dict[Num] = {'name': uuid_name_List[0][1], 'uuid': uuid_name_List[0][0]} del uuid_name_List[0] Num += 1 Str['workbook'] = dict(append_Dict) return jsonify(Str)
def admin_get_result(): current_app.logger.info("admin_get_result: user_name: " + session.get("user_name", "NO USER")) current_test_id = session.get("test_id") tests = CurrentTestModel.objects(id=current_test_id) if len(tests) == 0: current_app.logger.error("upload_file ERROR: No Tests!, test_id: %s" % current_test_id) return jsonify(errors.Exam_not_exist) questions = tests[0]['questions'] if len(questions) == 0: current_app.logger.error("upload_file ERROR: No Questions!, test_id: %s" % current_test_id) return jsonify(errors.Exam_not_exist) question = questions.get("1") if question['status'] == 'finished': score = question["score"] raw_question = QuestionModel.objects(id=question.q_id)[0] context = {"main": score["main"], "detail": score["detail"], "total": score["main"] * 0.7 + score["detail"] * 0.3, "rcgText": question["feature"]["rcg_text"], "text": question["q_text"], "rcgKeyWords": question["feature"]["keywords"], "keyWords": raw_question["wordbase"]["keywords"], "rcgMainWords": question["feature"]["mainwords"], "mainWords": raw_question["wordbase"]["mainwords"], "rcgDetailWords": question["feature"]["detailwords"], "detailWords": raw_question["wordbase"]["detailwords"] } result = json.dumps({"status": "Success", "result": context}) elif question['status'] not in ['none', 'url_fetched', 'handling']: return jsonify(errors.Audio_process_failed) else: result = json.dumps({"status": "InProcess"}) return jsonify(errors.success(result))
def question_type4_test(): q = QuestionModel.objects(index=10001).first() print(q) print(q.questions)