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

451 message about point #457

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
13 changes: 12 additions & 1 deletion app/db/db_types.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from bson import ObjectId
from flask_login import UserMixin

from main.check_packs import BASE_PACKS, BaseCriterionPack, DEFAULT_TYPE_INFO, DEFAULT_REPORT_TYPE_INFO
from main.check_packs import BASE_PACKS, BaseCriterionPack, DEFAULT_TYPE_INFO, DEFAULT_REPORT_TYPE_INFO, POINT_LEVELS

class Packable:
def __init__(self, dictionary):
Expand Down Expand Up @@ -104,6 +104,7 @@ def __init__(self, dictionary=None):
self.is_failed = dictionary.get('is_failed', None)
self.is_ended = dictionary.get('is_ended', True)
self.is_passed = dictionary.get('is_passed', int(self.score) == 1)
self.point_levels = self.get_point_levels()

def calc_score(self):
# check after implementation criterion pack
Expand Down Expand Up @@ -145,3 +146,13 @@ def none_to_false(x):
is_ended = none_to_true(self.is_ended) # None for old checks => True, True->True, False->False
is_failed = none_to_false(self.is_failed) # None for old checks => False, True->True, False->False
return {'is_ended': is_ended, 'is_failed': is_failed}

def get_point_levels(self):

Choose a reason for hiding this comment

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

функция иногда возвращает None не лучше ли поднимать исключение?

try:
for key in POINT_LEVELS:
value = POINT_LEVELS[key]
if value[0] < self.score < value[1]:
point_levels = key
return point_levels
except TypeError:
return None
2 changes: 1 addition & 1 deletion app/main/check_packs/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .base_criterion_pack import BaseCriterionPack
from .pack_config import BASE_PACKS, DEFAULT_TYPE, DEFAULT_TYPE_INFO, DEFAULT_PRES_TYPE_INFO, DEFAULT_REPORT_TYPE_INFO, \
REPORT_TYPES, BASE_PRES_CRITERION, BASE_REPORT_CRITERION
REPORT_TYPES, POINT_LEVELS, BASE_PRES_CRITERION, BASE_REPORT_CRITERION
from .utils import init_criterions
6 changes: 4 additions & 2 deletions app/main/check_packs/base_criterion_pack.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@

class BaseCriterionPack:

def __init__(self, raw_criterions, file_type, min_score=1.0, name=None, **kwargs):
def __init__(self, raw_criterions, file_type, point_levels, min_score=1, name=None, **kwargs):
self.file_type = file_type
self.name = name if name else self.__class__.__name__
self.raw_criterions = raw_criterions
self.criterions = []
self.min_score = min_score # min score to pass
self.point_levels = point_levels

def init(self, file_info):
# create criterion objects, ignore errors - validation was performed earlier
Expand Down Expand Up @@ -50,7 +51,8 @@ def to_json(self):
'name': self.name,
'raw_criterions': self.raw_criterions,
'file_type': self.file_type,
'min_score': self.min_score
'min_score': self.min_score,
'point_levels': self.point_levels,
}

@staticmethod
Expand Down
10 changes: 8 additions & 2 deletions app/main/check_packs/pack_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,16 @@
DEFAULT_REPORT_TYPE_INFO = {'type': 'report', 'report_type': REPORT_TYPES[1]}
DEFAULT_PRES_TYPE_INFO = {'type': 'pres'}
DEFAULT_TYPE_INFO = DEFAULT_PRES_TYPE_INFO
POINT_LEVELS = {"message1": [0.4, 0.6],
'Message2': [0.6, 0.7],
'Вы набрали необходимый минимум для дальнейшего допуска на защиту ВКР с оценкой "Допущен с рекомендацией значительно снизить оценку". Однако, мы рекомендуем вам продолжить исправления презентации для получения максимального балла. Это повысит ваш допуск до уровня "Допущен".': [0.7, 0.8],
'Вы набрали необходимый минимум для дальнейшего допуска на защиту ВКР с оценкой "Допущен с рекомендацией снизить оценку". Однако, мы рекомендуем вам продолжить исправления презентации для получения максимального балла. Это повысит ваш допуск до уровня "Допущен".': [0.8, 0.998],
'Уровень Вашего допуска "Допущен"': [0.999, 1.01]
}

BASE_PACKS = {
'pres': BaseCriterionPack(BASE_PRES_CRITERION, DEFAULT_PRES_TYPE_INFO, min_score=1.0,
'pres': BaseCriterionPack(BASE_PRES_CRITERION, DEFAULT_PRES_TYPE_INFO, point_levels=POINT_LEVELS, min_score=1.0,
name="BasePresentationCriterionPack"),
'report': BaseCriterionPack(BASE_REPORT_CRITERION, DEFAULT_REPORT_TYPE_INFO, min_score=1.0,
'report': BaseCriterionPack(BASE_REPORT_CRITERION, DEFAULT_REPORT_TYPE_INFO, point_levels=POINT_LEVELS, min_score=1.0,
name="BaseReportCriterionPack")
}
8 changes: 5 additions & 3 deletions app/servants/pre_luncher.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import logging

from db.db_methods import add_user, get_user, get_client, edit_user, save_criteria_pack
from main.check_packs.pack_config import BASE_PACKS, DEFAULT_REPORT_TYPE_INFO
from main.check_packs.pack_config import BASE_PACKS, DEFAULT_REPORT_TYPE_INFO, DEFAULT_PRES_TYPE_INFO

from pymongo.errors import ConnectionFailure
from server import ALLOWED_EXTENSIONS
Expand Down Expand Up @@ -36,8 +36,10 @@ def init(app, debug):
user.is_admin = True
edit_user(user)

user.file_type = DEFAULT_REPORT_TYPE_INFO
file_type = DEFAULT_REPORT_TYPE_INFO['type']
# user.file_type = DEFAULT_REPORT_TYPE_INFO
user.file_type = DEFAULT_PRES_TYPE_INFO
# file_type = DEFAULT_REPORT_TYPE_INFO['type']
file_type = DEFAULT_PRES_TYPE_INFO['type']
user.criteria = BASE_PACKS[file_type].name
user.formats = list(ALLOWED_EXTENSIONS.get(file_type))
user.two_files = True
Expand Down
6 changes: 5 additions & 1 deletion app/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,7 @@ def criteria_pack(name):
if not pack:
abort(404)
pack['raw_criterions'] = json.dumps(pack['raw_criterions'], indent=4, ensure_ascii=False)
pack['point_levels'] = json.dumps(pack['point_levels'], indent=4, ensure_ascii=False)
return render_template('./criteria_pack.html', pack=pack, name=current_user.name, navi_upload=True)


Expand All @@ -377,6 +378,7 @@ def api_criteria_pack():
file_type = form_data.get('file_type')
report_type = form_data.get('report_type')
min_score = float(form_data.get('min_score', '1'))
point_levels = form_data.get('point_levels')
# weak validation
try:
raw_criterions = json.loads(raw_criterions)
Expand All @@ -387,6 +389,7 @@ def api_criteria_pack():
raw_criterions = raw_criterions if type(raw_criterions) is list else None
file_type = file_type if file_type in BASE_PACKS.keys() else None
min_score = min_score if min_score and (0 <= min_score <= 1) else None
point_levels = json.loads(point_levels) if point_levels else None
if not (raw_criterions and file_type and min_score):
msg = f"Конфигурация набора критериев должна содержать список критериев (непустой список в формате JSON)," \
f"тип файла (один из {list(BASE_PACKS.keys())})," \
Expand All @@ -407,7 +410,8 @@ def api_criteria_pack():
'name': pack_name,
'raw_criterions': raw_criterions,
'file_type': file_type_info,
'min_score': min_score
'min_score': min_score,
'point_levels': point_levels
})
return {'data': f"Набор '{pack_name}' сохранен", 'time': datetime.now()}, 200

Expand Down
22 changes: 16 additions & 6 deletions app/templates/criteria_pack.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

{% if not (pack is defined) %}
{% set pack = {'name': '', 'file_type': 'report', 'min_score': '1',
'raw_criterions': "[[\"criterion_name\", \"criterion_params_as_dict\"]]"} %}
'raw_criterions': "[[\"criterion_name\", \"criterion_params_as_dict\"]]", 'point_levels': ""} %}
{% endif %}
{% block main %}
<div class="header row">{% include "header.html" %}</div>
Expand Down Expand Up @@ -45,14 +45,24 @@
required>
</label><br>
<label>
Список критериев набора (однажды тут будет подробнейшая <a
href="https://github.com/moevm/document_insight_system/issues/351">инструкция</a>)<br>
# укажите здесь конфигурацию набора в формате JSON<br>
<li>Список критериев набора (однажды тут будет подробнейшая <a
href="https://github.com/moevm/mse_auto_checking_slides_vaganov/issues/351">инструкция</a>)<br>
<li>Сообщения пользователям при достижении определенных уровней баллов <br>
# укажите здесь конфигурацию набора критериев и сообщений об уровне допуска в формате JSON<br>

</label><br>
<button id="btn_tab1">Набор критериев</button>
<button id="btn_tab2">Конфигурация point_levels</button>
<div id="tab1" class="tab" style="display: block">
<textarea id="raw_criterions" rows=10 cols=80
required>{{ pack['raw_criterions'] }}</textarea>
</label><br>
</div>
<div id="tab2" class="tab">
<textarea id="point_levels" rows=10 cols=80
required>{{ pack['point_levels'] }}</textarea>
</div>
<input id="pack_submit_button" value="Сохранить" type="submit">
</form>
</div>
</div>
{% endblock %}
{% endblock %}
9 changes: 8 additions & 1 deletion app/templates/results.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
{# Accepts: header dependicies, results, id, filename #}


{% extends "root.html" %}

{% block title %}Результаты проверки{% endblock %}
Expand All @@ -18,6 +17,14 @@ <h3 id="results_title" class="texteous ins">
Результат проверки: {{ "" if results.correct() else "не" }} пройдена! <!-- threshold? -->
</h3>
{% endif %}
<div>
{% if results.point_levels %}
<h6 id="results_message" class="col text-left">
<b>{{ results.point_levels }}</b>
</h6>
<p>
{% endif %}
</div>
{% else %}
<h4 id="results_title" class="texteous ins">
<i>Производится проверка файла, страница перезагрузится автоматически. Примерное время: {{ avg_process_time }} сек.</i>
Expand Down
25 changes: 23 additions & 2 deletions assets/scripts/criterion_pack.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ const RAW_CRITERION_VALIDATION_ERRORS = {
'not_json': 'Строка не является JSON-строкой',
}

$("#btn_tab1").click(function(){
openTab('tab1');
});
$("#btn_tab2").click(function(){
openTab('tab2');
});

$("#file_type").change(function () {
switch ($(this).val()) {
case "pres": {
Expand Down Expand Up @@ -43,6 +50,7 @@ pack_form.submit((e) => {
fd.append('report_type', $("#report_type").val());
fd.append('min_score', $("#min_score").val());
fd.append('raw_criterions', raw_criterions_str);
fd.append('point_levels', $("#point_levels").val());
fetch(`/api/criterion_pack`, {method: "POST", body: fd})
.then(response => {
if (response.status === 200) {
Expand All @@ -69,7 +77,20 @@ function verifyRawCriterions(text) {
JSON.parse(text);
return 0;
} catch (e) {
console.log(text, e)
console.log(text, e);
return 1;
}
}
}

function openTab(tabName) {
var i, tabs;
tabs = document.getElementsByClassName("tab");
for (i = 0; i < tabs.length; i++) {
tabs[i].style.display = "none";
}
document.getElementById(tabName).style.display = "block";
}

window.onload = function() {
openTab('tab1');
};
4 changes: 4 additions & 0 deletions assets/styles/criteria.css
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,7 @@
box-sizing: border-box;
border-radius: 4px;
}

.tab {
display: none;
}
18 changes: 17 additions & 1 deletion db_versioning/versions.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,21 @@ def update_database(cls, collections, prev_version):
raise Exception(f'Неподдерживаемый переход с версии {prev_version}')


class Version41(Version):
VERSION_NAME = '4.1'
CHANGES = 'В коллекции criteria_pack и checks добавлен атрибут point_levels'

@classmethod
def update_database(cls, collections, prev_version):
if prev_version in (Version31.VERSION_NAME,):
collections['criteria_pack'].update_many({}, {
'$set': {'point_levels': {}}})
collections['checks'].update_many({}, {
'$set': {'point_levels': {}}})
else:
raise Exception(f'Неподдерживаемый переход с версии {prev_version}')


VERSIONS = {
'1.0': Version10,
'1.1': Version11,
Expand All @@ -296,8 +311,9 @@ def update_database(cls, collections, prev_version):
'2.2': Version22,
'3.0': Version30,
'3.1': Version31,
'4.1': Version41,
}
LAST_VERSION = '3.1'
LAST_VERSION = '4.1'

for _, ver in VERSIONS.items():
print(ver.to_dict())
Loading