Exemple #1
0
def live_stats(request):
    strings = {
        'CN': {
            'ERR_LIVE': '载入谱面信息失败...',
            'SUCCESS': '成功获取谱面详细信息',
            'ERR_NONAJAX': '服务器接收请求不是AJAX'
        },
        'EN': {
            'ERR_LIVE': 'Failed to load live notes...',
            'SUCCESS': 'Successfully fetched detailed live stats',
            'ERR_NONAJAX': 'The request is not AJAX'
        }
    }
    lang = request.POST.get('lang', 'EN')
    if request.is_ajax():
        song_list, diff, PR = eval(
            request.POST['song_list']
        ), request.POST['difficulty'], request.POST['perfect_rate']
        user_info = 'User Information: {0} from {1} advanced simulation page\n'.format(
            str(get_client_ip(request)), lang)
        user_info += 'View Live Info: {0} {1}'.format(song_list, diff)
        print(user_info)

        try:
            live = MFLive(song_list,
                          diff,
                          local_dir=settings.BASE_DIR + '/static/live_json/',
                          perfect_rate=float(PR))
            live_stats = html_view(live, lang=lang).data.replace(
                'http:', '').replace('https:', '')
            print('Successfully loaded live.')
        except:
            print('Failed to load live.')
            message = {'complete': False, 'msg': strings[lang]['ERR_LIVE']}
            return JsonResponse(message)

        message = {
            'complete': True,
            'live_stats': live_stats,
            'msg': '{0} {1} {2}'.format(strings[lang]['SUCCESS'], song_list,
                                        diff)
        }
    else:
        message = {'complete': False, 'msg': strings[lang]['ERR_NONAJAX']}
    return JsonResponse(message)
Exemple #2
0
def old_UI(request):
    counter, _ = Counter.objects.get_or_create()
    count = counter.TeamCount
    result, live, live_info, timing, output_file = '', '', '', '', llatb.config.html_template.format(
        '')
    if 'group' in request.POST and 'attribute' in request.POST and 'difficulty' in request.POST:
        group_sel, attr_sel, diff_sel = request.POST['group'], request.POST[
            'attribute'], request.POST['difficulty']
        df_live = live_basic_data[live_basic_data.apply(
            lambda x: x.group == group_sel and x.attr == attr_sel and x.
            diff_level == diff_sel,
            axis=1)]
        group = '\n'.join([
            '<option value="{0}" {1}>{0}</option>'.format(
                x, 'selected' * (x == group_sel)) for x in ["μ's", 'Aqours']
        ])
        attr = '\n'.join([
            '<option value="{0}" {1}>{0}</option>'.format(
                x, 'selected' * (x == attr_sel))
            for x in ['Smile', 'Pure', 'Cool']
        ])
        diff = '\n'.join([
            '<option value="{0}" {1}>{0}</option>'.format(
                x, 'selected' * (x == diff_sel))
            for x in ['Easy', 'Normal', 'Hard', 'Expert', 'Master']
        ])
        PR = request.POST['perfect_rate']
        perfect_rate = '<input name="perfect_rate" type="number" min="0.01" max="1" step="0.01" value="{0}" />'.format(
            PR)
        if 'live' in request.POST and request.POST['live'] in df_live[
                'name'].values:
            try:
                live_sel = request.POST['live']
                live = '\n'.join([
                    '<option value="{0}" {1}>{0}</option>'.format(
                        x['name'], 'selected' * (x['name'] == live_sel))
                    for i, x in df_live.iterrows()
                ])
                try:
                    live_obj = Live(live_sel,
                                    diff_sel,
                                    local_dir=settings.BASE_DIR +
                                    '/static/live_json/',
                                    perfect_rate=float(PR))
                except:
                    url = live_basic_data[live_basic_data.apply(
                        lambda x: x['name'] == live_sel and x['diff_level'
                                                              ] == diff_sel,
                        axis=1)].iloc[0]['file_dir']
                    print(live_sel, diff_sel, 'not exists, download from', url)
                    opener = urllib.request.URLopener()
                    opener.addheader('User-Agent', 'whatever')
                    opener.retrieve(
                        url, settings.BASE_DIR + '/static/live_json/' +
                        url.split('/')[-1])
                    live_obj = Live(live_sel, diff_sel, perfect_rate=float(PR))
                live_info = html_view(live_obj, lang='CN').data
            except:
                print('Did not find live', live_sel, diff_sel)
                result += 'Did not find live {0} {1}'.format(
                    live_sel, diff_sel)
        else:
            try:
                live = '\n'.join([
                    '<option value="{0}">{0}</option>'.format(x['name'])
                    for i, x in df_live.iterrows()
                ])
                live_sel = 'Default {0} {1}'.format(group_sel, attr_sel)
                live_obj = DefaultLive(live_sel,
                                       diff_sel,
                                       perfect_rate=float(PR))
            except:
                print('Did not find live', live_sel, diff_sel)
                result += 'Did not find live {0} {1}'.format(
                    live_sel, diff_sel)

        score_up, skill_up = float(request.POST.get('score_up', 0)), float(
            request.POST.get('skill_up', 0))
        boost = '\n'.join([
            '<input type="checkbox" name="{0}" value=0.1 {1}> {2}'.format(
                name, 'checked' * (value > 0), string) for name, value, string
            in zip(['score_up', 'skill_up'], [score_up, skill_up],
                   ['得分+10%', '技能+10%'])
        ])
        is_gem_unlimited = bool(request.POST.get('unlimited_gem', 0))
        unlimited_gem = '<input type="checkbox" name="unlimited_gem" value=1 {0}> {1}'.format(
            'checked' * is_gem_unlimited, '宝石无限')
        profile = '<textarea name="profile" cols="80" rows="20">{0}</textarea>'.format(
            request.POST['profile'])
        extra_cond_sel = 'default' if 'extra_cond' not in request.POST else request.POST[
            'extra_cond']
        extra_cond = '\n'.join([
            '<option value="{0}" {1}>{2}</option>'.format(
                x, 'selected' * (x == extra_cond_sel), s) for x, s in
            zip(['default', 'max_level_bond', 'idolized', 'ultimate'],
                ['维持当前状态', '当前状态满级满绊', '贴纸觉醒满级满绊', '觉醒满槽满技能'])
        ])

        user_info = 'User IP Address: {0}\n'.format(str(
            get_client_ip(request)))
        user_info += 'Live Info: {0} {1} {2} {3}, P Rate={4}\n'.format(
            request.POST.get('live', 'NO_LIVE'), group_sel, attr_sel, diff_sel,
            PR)
        user_info += 'ScoreUp={0}, SkillUp={1}, GemUnlimited={2}, ExtraCond={3}'.format(
            score_up, skill_up, is_gem_unlimited, extra_cond_sel)
        print(user_info)

        try:
            if 'calculate' in request.POST:
                json_str = request.POST['profile']
                # try:
                start_time = time.time()
                if 'detail' in json_str:
                    user_profile = GameData(json_str,
                                            file_type='pll',
                                            string_input=True)
                else:
                    user_profile = GameData(json_str,
                                            file_type='ieb',
                                            string_input=True)
                if extra_cond_sel == 'max_level_bond':
                    for i, card in user_profile.raw_card.items():
                        card.idolize(idolized=card.idolized, reset_slot=False)
                elif extra_cond_sel == 'idolized':
                    for i, card in user_profile.raw_card.items():
                        card.idolize(idolized=True, reset_slot=False)
                elif extra_cond_sel == 'ultimate':
                    for i, card in user_profile.raw_card.items():
                        card.idolize(idolized=True)
                        card.slot_num = card.max_slot_num
                        if card.skill is not None:
                            card.skill.level = 8
                if is_gem_unlimited:
                    for x in list(user_profile.owned_gem.keys()):
                        user_profile.owned_gem[x] = 9
                else:
                    for x in ['Smile', 'Pure', 'Cool']:
                        user_profile.owned_gem[x + ' Kiss'] = 9

                print('Finished loading user profile')
                opt = {
                    'score_up_bonus': score_up,
                    'skill_up_bonus': skill_up,
                    'guest_cskill': None
                }
                tb = TeamBuilder(live_obj, user_profile, opt=opt)
                tb.build_team(K=12,
                              method='1-suboptimal',
                              alloc_method='DC' if is_gem_unlimited else 'DP')
                elapsed_time = time.time() - start_time

                output_files_template = '''
				</table><table border="1" class="dataframe">
			  	<tbody>
			  		<tr>
				      <td>LL Helper 队伍信息sd文件</td>
				      <td>SIFStats 队伍Json文件</td>
			  		</tr>
				    <tr>
				      <td><textarea name="LLHelper" cols="80" rows="10">{0}</textarea></td>
				      <td><textarea name="SIFState" cols="80" rows="10">{1}</textarea></td>
				    </tr>
				</tbody>
				</table>
			  	'''
                timing += 'Computation takes {0:.2f} seconds. <br/>'.format(
                    elapsed_time)
                result += tb.view_result(show_cost=True, lang='CN').data
                output_file += output_files_template.format(
                    tb.best_team.to_LLHelper(None), tb.best_team.to_ieb(None))

                count += 1
                counter.TeamCount = count
                counter.save()
        except:
            print('Invalid User input', json_str)
    else:
        group = '\n'.join([
            '<option value="{0}">{0}</option>'.format(x)
            for x in ["μ's", 'Aqours']
        ])
        attr = '\n'.join([
            '<option value="{0}">{0}</option>'.format(x)
            for x in ['Smile', 'Pure', 'Cool']
        ])
        diff = '\n'.join([
            '<option value="{0}">{0}</option>'.format(x)
            for x in ['Easy', 'Normal', 'Hard', 'Expert', 'Master']
        ])
        boost = '\n'.join([
            '<input type="checkbox" name="{0}" value=0.1> {1}'.format(
                name, string) for name, string in zip(['score_up', 'skill_up'],
                                                      ['得分+10%', '技能+10%'])
        ])
        profile = '<textarea name="profile" cols="80" rows="20"></textarea>'
        unlimited_gem = '<input type="checkbox" name="unlimited_gem" value=1> 宝石无限'
        extra_cond = '\n'.join([
            '<option value="{0}">{1}</option>'.format(x, s) for x, s in
            zip(['default', 'max_level_bond', 'idolized', 'ultimate'],
                ['维持当前状态', '当前状态满级满绊', '贴纸觉醒满级满绊', '觉醒满槽满技能'])
        ])
        perfect_rate = '<input name="perfect_rate" type="number" min="0.01" max="1" step="0.01" value="0.95" />'
    return HttpResponse(
        html_template.substitute(author_memo=author_memo.format(count),
                                 live=live,
                                 group=group,
                                 attr=attr,
                                 diff=diff,
                                 boost=boost,
                                 perfect_rate=perfect_rate,
                                 profile=profile,
                                 extra_cond=extra_cond,
                                 unlimited_gem=unlimited_gem,
                                 live_info=live_info,
                                 timing=timing,
                                 result=result,
                                 output_file=output_file))
Exemple #3
0
def calculate(request):
	strings = {
		'CN': {
			'DEFAULT': '默认谱面',
			'ERR_LIVE': '载入谱面信息失败...',
			'ERR_PROFILE': '载入用户卡组信息失败...',
			'ERR_EXCOND': '应用附加条件失败...',
			'ERR_SOLVE': '求解最佳卡组失败,请检查该色是否有13张卡',
			'ERR_EXPORT': '导出文件失败...',
			'IMCOMPLETE': '由于服务器响应时间限制,返回算法中断前最优结果,算法完成度 {0}/{1},请尝试<button id="recalculate" class="w3-green w3-hover-yellow roundBtn" style="height:25px" onclick="calculate(true)"><b>继续未完成计算</b></button>。<br>可能是你的宝石太少了,您也可以尝试开启无限宝石看你需要哪些并抓紧时间收集。',
			'SUCCESS': '#{0} 组队成功,共耗时{1:.2f}秒',
			'ERR_NONAJAX': '服务器接收请求不是AJAX'
		},
		'EN': {
			'DEFAULT': 'Default',
			'ERR_LIVE': 'Failed to load live notes...',
			'ERR_PROFILE': 'Failed to read user profile...',
			'ERR_EXCOND': 'Failed to apply extra condition...',
			'ERR_SOLVE': 'Failed to solve optimal team, please check whether there are at least 13 cards have current attribute',
			'ERR_EXPORT': 'Failed to export result into other formats...',
			'IMCOMPLETE': 'Due to server response time limit, algorithm terminated with progress {0}/{1}, please try to <button id="recalculate" class="w3-green w3-hover-yellow roundBtn" style="height:25px" onclick="calculate(true)"><b>continue</b></button> the computation.',
			'SUCCESS': '#{0} Team builded, used {1:.2f} secs',
			'ERR_NONAJAX': 'The request is not AJAX'
		}
	}
	lang = request.POST.get('lang', 'EN')
	if request.is_ajax():
		start_time = time.time()
		song_list, PR = eval(request.POST['song_list']), float(request.POST['perfect_rate'])
		group, attr, diff = [request.POST[x] for x in ['group', 'attribute', 'difficulty']]
		score_up, skill_up = float(request.POST.get('score_up',0)), float(request.POST.get('skill_up',0))
		unlimit_gem, extra_cond, json_str = bool(request.POST['unlimit_gem']=='true'), request.POST['extra_cond'], request.POST['user_profile']
		is_sm, is_random = bool(request.POST.get('is_sm', 'false')=='true'), bool(request.POST.get('is_random', 'false')=='true')
		pin_index = [int(x) for x in json.loads(request.POST.get('pin_index', '[]'))]
		exclude_index = [int(x) for x in json.loads(request.POST.get('exclude_index', '[]'))]
		next_cskill_index, prev_max_cskill_index = int(request.POST.get('next_cskill_index', 0)), int(request.POST.get('prev_max_cskill_index', 0))

		user_info  = 'User Information: {0} from {1} team building page\n'.format(str(get_client_ip(request)), lang)
		if not is_sm:
			user_info += 'Live Info: {0} {1} {2} {3}, P Rate={4}, {5}/{6} pinned cards\n'.format(song_list, group, attr, diff, PR, len(pin_index), len(exclude_index))
		else:
			user_info += 'Live Info: {5} {0} {1} {2} {3}, P Rate={4}, {6}/{7} pinned cards\n'.format(song_list, group, attr, diff, PR, 'SM'+' random'*is_random, len(pin_index), len(exclude_index))
		user_info += 'ScoreUp={0}, SkillUp={1}, GemUnlimited={2}, ExtraCond={3}, start from case {4}, previous best case is at {5}'.format(score_up, skill_up, unlimit_gem, extra_cond, next_cskill_index, prev_max_cskill_index)
		print(user_info)

		# Load live
		try:
			if strings[lang]['DEFAULT'] not in song_list[0] and not is_sm:
				live = MFLive(song_list, diff, local_dir=settings.BASE_DIR+'/static/live_json/', perfect_rate=PR)
				live_stats, note_list = html_view(live, lang=lang).data, json.dumps(live.web_note_list)
			elif is_sm:
				live = SMLive(song_list, diff, local_dir=settings.BASE_DIR+'/static/live_json/', perfect_rate=PR, is_random=is_random)
				live_stats, note_list = 'NA', '{}'
			else:
				song_name = song_list[0].replace(strings[lang]['DEFAULT'], 'Default')
				live = DefaultLive(song_name, diff, perfect_rate=PR)
				live_stats, note_list = 'NA', '{}'
			print('Successfully loaded live.')
		except:
			print('Failed to load live.')
			message = {'complete':False, 'msg':strings[lang]['ERR_LIVE']}
			return JsonResponse(message)
		# Load user profile
		try:
			if 'detail' in json_str:
				user_profile = GameData(json_str, file_type='pll', string_input=True)
			else:
				user_profile = GameData(json_str, file_type='ieb', string_input=True)
			print('Successfully loaded user profile.')
		except:
			print('Failed to load user profile.')
			message = {'complete':False, 'msg':strings[lang]['ERR_PROFILE']}
			return JsonResponse(message)
		# Solve for optimal team
		try:
			guest_center = request.POST.get('guest_center', 'None')
			guest_cskill = None if guest_center == 'None' else CenterSkill.fromStr(guest_center)
			if guest_cskill != None: print('Guest skill specified to be', str(guest_cskill))
			opt = {'score_up_bonus':score_up, 'skill_up_bonus':skill_up, 'guest_cskill':guest_cskill}
			tb = TeamBuilder(live, user_profile, opt=opt, unlimited_SIS=unlimit_gem, extra_cond=extra_cond)
			
			# Choose alloc method wisely
			_, (num_calc, num_total, prev_max_cskill_index) = tb.build_team(K=12, method='1-suboptimal', alloc_method='auto', time_limit=24, pin_index=pin_index, exclude_index=exclude_index, next_cskill_index=next_cskill_index, prev_max_cskill_index=prev_max_cskill_index)
			result = ''
			if num_calc < num_total:
				result += '<p style="text-align:center; color:red"><b>{0}</b></p>'.format(strings[lang]['IMCOMPLETE'].format(num_calc, num_total))
			result += tb.view_result(show_cost=True, lang=lang).data.replace('http:','').replace('https:','')
		except:
			print('Failed to compute optimal team.')
			message = {'complete':False, 'msg':strings[lang]['ERR_SOLVE']}
			return JsonResponse(message)
		# Covert result to LL Helper and SIFStats
		try:
			sd_file, ieb_file = tb.best_team.to_LLHelper(None), tb.best_team.to_ieb(None)
			simul_base_info = json.dumps(tb.best_team.prepare_simulation(opt))
		except:
			print('Failed to export file.')
			message = {'complete':False, 'msg':strings[lang]['ERR_EXPORT']}
			return JsonResponse(message)
		elapsed_time = time.time() - start_time

		counter, _ = Counter.objects.get_or_create()
		counter.TeamCount += 1
		counter.save()
		print('This is the {0}-th built team, computation takes {1:.2f} seconds'.format(counter.TeamCount, elapsed_time))
		message = {
			'complete': True,
			'counter': counter.TeamCount,
			'sd_file': sd_file,
			'ieb_file': ieb_file,
			'live_stats': live_stats,
			'result': result,
			'note_list': note_list,
			'simul_base_info': simul_base_info,
			'next_cskill_index': num_calc+1,
			'prev_max_cskill_index': prev_max_cskill_index,
			'msg': strings[lang]['SUCCESS'].format(counter.TeamCount, elapsed_time)
		}
	else:
		message = {'complete':False, 'msg':strings[lang]['ERR_NONAJAX']}
	return JsonResponse(message)
Exemple #4
0
def filter_cards(request):
	strings = {
		'CN': {
			'DEFAULT': '默认谱面',
			'ERR_LIVE': '载入谱面信息失败...',
			'ERR_PROFILE': '载入用户卡组信息失败...',
			'ERR_EXCOND': '应用附加条件失败...',
			'ERR_TIER': '计算卡牌强度天梯失败...',
			'SUCCESS': '成功筛选卡牌',
			'ERR_NONAJAX': '服务器接收请求不是AJAX'
		},
		'EN': {
			'DEFAULT': 'Default',
			'ERR_LIVE': 'Failed to load live notes...',
			'ERR_PROFILE': 'Failed to read user profile...',
			'ERR_EXCOND': 'Failed to apply extra condition...',
			'ERR_TIER': 'Failed to compute card strength tier...',
			'SUCCESS': 'Successfully filter the cards',
			'ERR_NONAJAX': 'The request is not AJAX'
		}
	}

	lang = request.POST.get('lang', 'EN')
	if request.is_ajax():
		start_time = time.time()
		song_list, PR = eval(request.POST['song_list']), float(request.POST['perfect_rate'])
		group, attr, diff = [request.POST[x] for x in ['group', 'attribute', 'difficulty']]
		score_up, skill_up = float(request.POST.get('score_up',0)), float(request.POST.get('skill_up',0))
		extra_cond, json_str = request.POST['extra_cond'], request.POST['user_profile']
		is_sm, is_random = bool(request.POST.get('is_sm', 'false')=='true'), bool(request.POST.get('is_random', 'false')=='true')

		user_info  = 'User Information: {0} from {1} card filtering page\n'.format(str(get_client_ip(request)), lang)
		if not is_sm:
			user_info += 'Live Info: {0} {1} {2} {3}, P Rate={4}\n'.format(song_list, group, attr, diff, PR)
		else:
			user_info += 'Live Info: {5} {0} {1} {2} {3}, P Rate={4}\n'.format(song_list, group, attr, diff, PR, 'SM'+' random'*is_random)
		user_info += 'ScoreUp={0}, SkillUp={1}, ExtraCond={2}'.format(score_up, skill_up, extra_cond)
		print(user_info)

		# Load live
		try:
			if strings[lang]['DEFAULT'] not in song_list[0] and not is_sm:
				live = MFLive(song_list, diff, local_dir=settings.BASE_DIR+'/static/live_json/', perfect_rate=PR)
				live_stats, note_list = html_view(live, lang=lang).data, json.dumps(live.web_note_list)
			elif is_sm:
				live = SMLive(song_list, diff, local_dir=settings.BASE_DIR+'/static/live_json/', perfect_rate=PR, is_random=is_random)
				live_stats, note_list = 'NA', '{}'
			else:
				song_name = song_list[0].replace(strings[lang]['DEFAULT'], 'Default')
				live = DefaultLive(song_name, diff, perfect_rate=PR)
				live_stats, note_list = 'NA', '{}'
			print('Successfully loaded live.')
		except:
			print('Failed to load live.')
			message = {'complete':False, 'msg':strings[lang]['ERR_LIVE']}
			return JsonResponse(message)
		# Load user profile
		try:
			if 'detail' in json_str:
				user_profile = GameData(json_str, file_type='pll', string_input=True)
			else:
				user_profile = GameData(json_str, file_type='ieb', string_input=True)
			print('Successfully loaded user profile.')
		except:
			print('Failed to load user profile.')
			message = {'complete':False, 'msg':strings[lang]['ERR_PROFILE']}
			return JsonResponse(message)
		# Modify user profile
		try:
			guest_center = request.POST.get('guest_center', 'None')
			guest_cskill = None if guest_center == 'None' else CenterSkill.fromStr(guest_center)
			if guest_cskill != None: print('Guest skill specified to be', str(guest_cskill))
			opt = {'score_up_bonus':score_up, 'skill_up_bonus':skill_up, 'guest_cskill':guest_cskill}
			tb = TeamBuilder(live, user_profile, opt=opt, extra_cond=extra_cond)
			result = {k:v.data.replace('http:','').replace('https:','') for k, v in tb.show_rough_strength().items()}
		except:
			print('Failed to filter cards.')
			message = {'complete':False, 'msg':strings[lang]['ERR_TIER']}
			return JsonResponse(message)

		message = {
			'complete': True,
			'result': result,
			'msg': strings[lang]['SUCCESS']
		}
	else:
		message = {'complete':False, 'msg':strings[lang]['ERR_NONAJAX']}
	return JsonResponse(message)