Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Probator stub #632

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions ajax/annot_proba.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php
require_once('../lib/header_ajax.php');
require_once('../lib/lib_annot.php');

if (!is_logged()) {
return;
}


try {
$result['status'] = 1;
$result_answers = json_decode($_POST['answers']);
$answers = array();
foreach($result_answers as $answ){
$sample_id = $answ[0];
$answer_id = $answ[1];
$moderator_answer_id = 0; // No_answer or DB corrupt

// TODO save my answer

$res = sql_query("SELECT `answer` FROM `morph_annot_moderated_samples` WHERE `sample_id` = $sample_id");

if ($r = sql_fetch_array($res))
$moderator_answer_id = (int)$r['answer'];

$answers[] = array($sample_id, $answer_id, $moderator_answer_id);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь или странные отступы, или логическая ошибка. Где заканчивается foreach?

$result['answers'] = $answers;
}
catch (Exception $e) {
$result['status'] = 0;
$result['error'] = 1;
}
log_timing(true);
die(json_encode($result));
?>
10 changes: 9 additions & 1 deletion lib/lib_annot.php
Original file line number Diff line number Diff line change
Expand Up @@ -999,12 +999,19 @@ function get_available_tasks($user_id, $only_editable=false, $limit=0, $random=f
// memorize pool types with manual and complexity
$types_with_manual = array();
$type2complexity = array();
$res = sql_query("SELECT type_id, doc_link, complexity FROM morph_annot_pool_types WHERE doc_link != '' OR complexity > 0");
$type_has_samples = array();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не очень понятное название переменной. Я бы назвал как-то типа $type_has_finished_pools

$res = sql_query("SELECT `type_id`, `doc_link`, `complexity`
, (SELECT COUNT(*) AS `pool_count` FROM `morph_annot_pools` AS `p`
WHERE `p`.`pool_type` = `morph_annot_pool_types`.`type_id` AND `p`.`status` = ".MA_POOLS_STATUS_ARCHIVED.") AS `archieved_pools_count`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/archieved/archived/, пожалуйста. и ниже тоже.

FROM `morph_annot_pool_types`
WHERE `doc_link` != '' OR `complexity` > 0");
while ($r = sql_fetch_array($res)) {
if ($r['doc_link'])
$types_with_manual[] = $r['type_id'];
if ($r['complexity'] > 0)
$type2complexity[$r['type_id']] = $r['complexity'];
if ($r['archieved_pools_count'] > 0)
$type_has_samples[] = $r['type_id'];
}
// get all pools by status
$res = sql_query("SELECT pool_id, pool_name, status, pool_type FROM morph_annot_pools p LEFT JOIN morph_annot_pool_types t ON (p.pool_type = t.type_id) WHERE status = ".MA_POOLS_STATUS_IN_PROGRESS." $order_string $limit_string");
Expand Down Expand Up @@ -1105,6 +1112,7 @@ function get_available_tasks($user_id, $only_editable=false, $limit=0, $random=f
}
$tasks[$group_id]['has_manual'] = in_array($group_id, $types_with_manual);
$tasks[$group_id]['complexity'] = isset($type2complexity[$group_id]) ? $type2complexity[$group_id] : 0;
$tasks[$group_id]['has_samples'] = in_array($group_id, $type_has_samples);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Аналогично, has_samples слабо намекает, что это на самом деле такое

$tasks[$group_id]['name'] = preg_replace('/\s+#\d+\s*$/', '', $v['pools'][0]['name']);
$tasks[$group_id]['is_hot'] = in_array($group_id, $hot_types);
}
Expand Down
60 changes: 60 additions & 0 deletions pool-probator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php
require('lib/header.php');
require_once('lib/lib_xml.php');
require_once('lib/lib_annot.php');

if (!isset($_GET['pool_type']))
throw new UnexpectedValueException('Wrong pool_type');

$pool_size = 5;

if ($t = get_proba_packet((int)$_GET['pool_type'], $pool_size)) {
$smarty->assign('packet', $t);
$smarty->display('qa/morph_annot_proba.tpl');
}

function get_proba_packet($pool_type, $size) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Похоже на копипасту из get_annotation_packet(), не надо так

global $config;

$res = sql_query("SELECT `pool_type`.`doc_link`, `pool_type`.`gram_descr`, COUNT(*) AS `pool_count`
FROM `morph_annot_pools` AS `pool`
INNER JOIN `morph_annot_pool_types` AS `pool_type` ON `pool`.`pool_type` = `pool_type`.`type_id`
WHERE `pool`.`pool_type` = $pool_type AND `pool`.`status` = ".MA_POOLS_STATUS_ARCHIVED." ");
$r = sql_fetch_array($res);
if ((int)$r['pool_count'] == 0)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем каст к инту?

throw new UnexpectedValueException("No archieved pools for pool_type=$pool_type");

$packet = array(
'pool_type' => $pool_type,
'has_manual' => (bool)$r['doc_link'],
'gram_descr' => explode('@', $r['gram_descr'])
);

$res = sql_query("SELECT `sample`.`sample_id`, `sample`.`pool_id`, `pool`.`revision`
FROM `morph_annot_samples` AS `sample`
INNER JOIN `morph_annot_pools` AS `pool` ON `pool`.`pool_id` = `sample`.`pool_id`
WHERE `pool`.`pool_type` = $pool_type AND `pool`.`status` = ".MA_POOLS_STATUS_ARCHIVED."
ORDER BY RAND()
LIMIT $size");

if (!sql_num_rows($res))
throw new Exception("No samples for pool_type=$pool_type");

$gram_descr = array();
while ($r = sql_fetch_array($res)) {
$r1 = sql_fetch_array(sql_query("SELECT tf_id, rev_text FROM tf_revisions WHERE tf_id = (SELECT tf_id FROM morph_annot_samples WHERE sample_id = ".$r['sample_id']." LIMIT 1) AND rev_id <= ".$r['revision']." ORDER BY rev_id DESC LIMIT 1"));
$instance = get_context_for_word($r1['tf_id'], $config['misc']['morph_annot_user_context_size']);
$arr = xml2ary($r1['rev_text']);
$parses = get_morph_vars($arr['tfr']['_c']['v'], $gram_descr);
$lemmata = array();
foreach ($parses as $p) {
$lemmata[] = $p['lemma_text'];
}
$instance['lemmata'] = implode(', ', array_unique($lemmata));
$instance['sample_id'] = $r['sample_id'];
$packet['instances'][] = $instance;
}
return $packet;
}
log_timing();
?>
154 changes: 154 additions & 0 deletions templates/qa/morph_annot_proba.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
{* Smarty *}
{extends file='common.tpl'}
{*block name=before_content}{if $game_is_on == 1}{include file="qa/game_status.tpl"}{/if}{/block*}
{block name=content}
{literal}
<style type="text/css">
.correct {background-color:green;}
.incorrect {background-color:red;}
</style>
<script type="text/javascript">
$(document).ready(function() {
$('div.alert').hide();
$('.ma_instance button').click(function(event) {
$('button.ma_show_results').addClass('disabled');
var $btn = $(event.target);
$btn.closest('div').find('button').attr('disabled', 'disabled').removeClass('chosen');
$btn.addClass('chosen');

$btn.closest('div').fadeTo('slow', 0.5).removeClass('ma_not_ready').addClass('ma_ready');
//perhaps all the instances are clicked
var flag = 1;
$('div.ma_instance').each(function(i, el) {
if (!$(el).hasClass('ma_ready'))
flag = 0;
});
if (flag) $('button.ma_show_results').removeClass('disabled');

$btn.closest('div').find('button').removeAttr('disabled');
});
$('a.expand').click(function(event) {
var $btn = $(event.target);
$.post('ajax/get_context.php', {'tf_id':$(this).attr('rel'), 'dir':$(this).attr('rev')}, function(res) {
var s = '';
for (var i = 0; i < res.context.length; ++i) {
s += ' ' + res.context[i];
};
if ($btn.attr('rev') == -1) {
$btn.closest('div').prepend(s);
$btn.remove();
}
else {
$btn.closest('div').append(s);
$btn.remove();
}

});
event.preventDefault();
});
$('button.ma_show_results').click(function() {
if($(this).hasClass('disabled')) {
$first_notready = $('.ma_not_ready').eq(0);
$('html').scrollTop($first_notready.offset().top)
}
else {
ShowResults();
}
});

function ShowResults(){
var answers = new Array();
$('div.ma_instance').each(function(i, el) {
var sample_id = Number($(el).attr('rel'));
var answer_id = GetMyAnswer(sample_id);
answers.push(new Array(sample_id, answer_id));
});

$.post('ajax/annot_proba.php', {answers: JSON.stringify(answers)}, function(res){
if (res.status == 1) {
CalculateResults(res.answers);
} else
alert('Что-то пошло не так. Попробуйте перезагрузить страницу.')
});

}

function CalculateResults(answers)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это же будет перенесено в бэкенд, правда?

{
var samples_total = answers.length;
var samples_rejected = 0;
var samples_agree = 0;
for(var k=0; k<samples_total; k++) {
var sample_id = answers[k][0];
var answer_id = answers[k][1];
var moderator_answer_id = answers[k][2];
if ( answer_id == moderator_answer_id)
samples_agree++;
else
samples_rejected++;
if ( answer_id == moderator_answer_id)
$('#a_' + sample_id).addClass('correct');
else
$('#a_' + sample_id).addClass('incorrect');
}
var text = 'Всего примеров: ' + samples_total + ' Вы пропустили примеров: ' + samples_rejected + ' Ответов совпало с правильным: = ' + samples_agree;
$('div.alert').show();
$("div.alert").text(text);
}

function GetMyAnswer(sample_id)
{
if ($('button#b_' + sample_id + '_99').hasClass('chosen'))
return 99;
var result = -1;
$("button[rel='" + sample_id+"']").each(function(i, el) {
var button_id = $(el).attr('rev');
if ($('button#b_' + sample_id + '_' + button_id).hasClass('chosen')){
result = button_id;
}
});
return Number(result);
}

});
</script>
</script>
{/literal}
<br>
<ul class="breadcrumb">
<li><a href="{$web_prefix}/pool-probator.php?pool_type={$packet.pool_type}">Пробная разметка</a> <span class="divider">/</span></li>
<li class="active">{$packet.gram_descr|implode:" &mdash; "}</li>
</ul>
<div class="ma_annot_top_block clearfix">
{if $packet.has_manual}<div class="pull-right">
<a class="btn btn-primary" href="manual.php?pool_type={$packet.pool_type}" target="_blank"><i class="icon-info-sign icon-white"></i> Инструкция по разметке</a>
</div>{/if}
<div class="ma_thanx_block">
Попробуйте проставить свои ответы в этих примерах, взятых из давно размеченных пулов. Если вы не уверены, пропускайте пример.
<br>Эти задания не идут вам в статистику, просто можете проверить свои силы.
</div>
</div>
{foreach from=$packet.instances item=instance}
<div class='ma_instance ma_not_ready' rel='{$instance.sample_id}' rev='{$instance.sample_id}'>
<div class="ma_instance_words">
{if $instance.has_left_context}<a class='expand' href="#" rel='{$instance.has_left_context}' rev='-1'>...</a>{/if}
{foreach from=$instance.context item=word name=x}
{if $smarty.foreach.x.index == $instance.mainword}
<b class='ma_instance_word' title='{$instance.lemmata}'>{$word|htmlspecialchars}</b>
{else}
{$word|htmlspecialchars}
{/if}
{/foreach}
{if $instance.has_right_context}<a class='expand' href="#" rel='{$instance.has_right_context}' rev='1'>...</a>{/if}
</div>
{foreach from=$packet.gram_descr item=var name=x}
<button rev='{$smarty.foreach.x.index + 1}' rel="{$instance.sample_id}" id="b_{$instance.sample_id}_{$smarty.foreach.x.index + 1}" class="btn">{$var|htmlspecialchars}</button>
{/foreach}
<button rev='99' id="b_{$instance.sample_id}_99" class='btn other'>Другое</button>
<button rev='-1' class='btn reject btn-danger'>Пропустить</button>
<div class="btn answer_helper" id="a_{$instance.sample_id}">ответ</div>
</div>
{/foreach}
<button class='btn btn-primary btn-large ma_show_results disabled'>Узнать свою статистику!</button>
<div class="alert" ></div>
{/block}
1 change: 1 addition & 0 deletions templates/qa/tasks.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
</td>
<td class="ma_type_help">{if $type.has_manual}<a href="manual.php?pool_type={$key}" class="" title="инструкция по разметке">инструкция</a>{/if}</td>
<td class="">{if isset($type.random_id)}<a href="?act=annot&amp;pool_id={$type.random_id}" class="btn">Взять на разметку</a>{/if}</td>
<td class="">{if $type.has_samples}<a href="pool-probator.php?pool_type={$key}" class="btn">Попробовать тестовые задания</a>{/if}</td>
</tr>
<tr class="ma_type_pools" style="display: none;" id="pools_{$key}">
<td colspan="3">
Expand Down