Skip to content

750 was were check #755

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

Open
wants to merge 1 commit 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
1 change: 1 addition & 0 deletions app/main/checks/presentation_checks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@
from .name_of_image_check import PresImageCaptureCheck
from .task_tracker import TaskTracker
from .overview_in_tasks import OverviewInTasks
from .was_were_check import PresWasWereCheck
31 changes: 31 additions & 0 deletions app/main/checks/presentation_checks/was_were_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import re
from ..base_check import BasePresCriterion, answer
from app.nlp.is_passive_was_were_sentence import is_passive_was_were_sentece

class PresWasWereCheck(BasePresCriterion):
label = 'Проверка на пассивные конструкции, начинающиеся с Был/Была/Было/Были, которые можно убрать без потери смысла'
description = ''
id = 'pres_was_were_check'

def __init__(self, file_info):
super().__init__(file_info)

def check(self):
detected = {}
for slide_index, slide_text in enumerate(self.file.get_text_from_slides()):
mock_slide_text = "Было проведено исследование. Было бы здорово. Как бы было здорово. Была проделана работа. Были сделаны шаги..."
sentences = re.split(r'(?<=[.!?…])\s+', mock_slide_text)
for sentence_index, sentence in enumerate(sentences):
if is_passive_was_were_sentece(sentence):
if slide_index not in detected:
detected[slide_index] = []
detected[slide_index].append(f'{sentence_index+1}: {sentence}')
if len(detected):
result_str = 'Обнаружены конструкции (Был/Была/Было/Были), которые можно удалить без потери смысла:<br><br>'
for slide_index, messages in detected.items():
result_str += f'Слайд №{slide_index+1}:<br>' + '<br>'.join(messages) + '<br><br>'
result_score = 0
else:
result_str = 'Пройдена!'
result_score = 1
return answer(result_score, result_str)
1 change: 1 addition & 0 deletions app/main/checks/report_checks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,4 @@
from .sw_section_size import SWSectionSizeCheck
from .sw_keywords_check import SWKeywordsCheck
from .task_tracker import ReportTaskTracker
from .was_were_check import ReportWasWereCheck
34 changes: 34 additions & 0 deletions app/main/checks/report_checks/was_were_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import re
from ..base_check import BaseReportCriterion, answer
from app.nlp.is_passive_was_were_sentence import is_passive_was_were_sentece

class ReportWasWereCheck(BaseReportCriterion):
label = 'Проверка на пассивные конструкции, начинающиеся с Был/Была/Было/Были, которые можно убрать без потери смысла'
description = ''
id = 'report_was_were_check'

def __init__(self, file_info):
super().__init__(file_info)

def check(self):
if self.file.page_counter() < 4:
return answer(False, 'В отчёте недостаточно страниц. Нечего проверять.')
detected = {}
for page_index, page_text in self.file.pdf_file.get_text_on_page().items():
Copy link
Contributor

Choose a reason for hiding this comment

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

Как будто бы сама обработка для слайдов и отчетов отличается по существу только контейнерами (мы достаем из слайдов или из страниц предложения), а также сообщением для детализации (или

Страница №{page_index+1}:<br>' + '<br>'.join(messages) + '<br><br>

или

'Слайд №{slide_index+1}:<br>' + '<br>'.join(messages) + '<br><br>'

Предлагаю максимум общей логики вынести в отдельную функцию в app/nlp/is_passive_was_were_sentence.py, указать ей параметрами информацию об источнике (слайды или страницы - для итогового сообщения) и поправить два критерия так, чтобы в них дублирующаяся логика заменилась на вызов этой функции

sentences = re.split(r'(?<=[.!?…])\s+', page_text)
for sentence_index, sentence in enumerate(sentences):
if is_passive_was_were_sentece(sentence):
if page_index not in detected:
detected[page_index] = []
detected[page_index].append(f'{sentence_index+1}: {sentence}')
if len(detected):
result_str = 'Обнаружены конструкции (Был/Была/Было/Были), которые можно удалить без потери смысла:<br><br>'
Copy link
Contributor

Choose a reason for hiding this comment

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

Вот эта строчка повторяется и в критерии для слайдов. Ее необходимо вынести в константу в app/nlp/is_passive_was_were_sentence.py и импортировать в обоих критериях

for page_index, messages in detected.items():
result_str += f'Страница №{page_index+1}:<br>' + '<br>'.join(messages) + '<br><br>'
print(f'Страница №{page_index+1}:<br>' + '<br>'.join(messages) + '<br><br>')
print()
result_score = 0
else:
result_str = 'Пройдена!'
result_score = 1
return answer(result_score, result_str)
26 changes: 26 additions & 0 deletions app/nlp/is_passive_was_were_sentence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import re
import pymorphy2
import string

morph = pymorphy2.MorphAnalyzer()
Copy link
Contributor

Choose a reason for hiding this comment

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

Добавьте в данном файле в виде комментария примеры хороших и плохих предложений, которые начинаются с Был*


def clean_word(word):
punct = string.punctuation.replace('-', '')
return word.translate(str.maketrans('', '', punct))

def is_passive_was_were_sentece(sentence):
first_words = re.split(r'\s+', sentence.strip(), maxsplit=2)
if len(first_words) < 2:
return False

first_word = clean_word(first_words[0])
second_word = clean_word(first_words[1])

parsed = morph.parse(first_word)[0]
if (parsed.normal_form == 'быть' and
'past' in parsed.tag and
parsed.tag.POS == 'VERB'):
second_word_parsed = morph.parse(second_word)[0]
return ('PRTS' in second_word_parsed.tag and
'pssv' in second_word_parsed.tag)
return False