From c019b13f93120d101202061e4298539e2315cbd0 Mon Sep 17 00:00:00 2001 From: Iamhexi Date: Fri, 4 Oct 2024 21:02:59 +0200 Subject: [PATCH] feat(main): implement paragraph choosing --- knowledge_verificator/main.py | 25 +++++++++++++++++++++++-- knowledge_verificator/utils/string.py | 26 ++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 knowledge_verificator/utils/string.py diff --git a/knowledge_verificator/main.py b/knowledge_verificator/main.py index 1b65103..0fc67e5 100755 --- a/knowledge_verificator/main.py +++ b/knowledge_verificator/main.py @@ -7,6 +7,7 @@ from knowledge_verificator.materials import MaterialDatabase from knowledge_verificator.nli import NaturalLanguageInference, Relation from knowledge_verificator.qg import QuestionGeneration +from knowledge_verificator.utils.string import clip_text if __name__ == '__main__': @@ -61,8 +62,28 @@ continue material = material_db.materials[chosen_index] - # TODO: A user should be able to choose a paragraph. - paragraph = material.paragraphs[0] + + MAX_LENGTH_OF_CLIPPED_PARAGRAPH = 15 + console.print('Available paragraphs: ') + for i, paragraph in enumerate(material.paragraphs): + console.print( + f'{i+1} {clip_text(paragraph, MAX_LENGTH_OF_CLIPPED_PARAGRAPH)}' + ) + + console.print('Which paragraph you want to learn? ') + paragraph_choice = input() + + if not paragraph_choice.isnumeric(): + console.print(INCORRECT_CHOICE_WARNING) + continue + + chosen_index = int(paragraph_choice) - 1 + if chosen_index < 0 or chosen_index >= len(material.paragraphs): + console.print(INCORRECT_CHOICE_WARNING) + continue + + # TODO: Refactor this fragment to apply DRY principle. + paragraph = material.paragraphs[chosen_index] console.print('Learn this paragraph: ') console.print(paragraph) diff --git a/knowledge_verificator/utils/string.py b/knowledge_verificator/utils/string.py new file mode 100644 index 0000000..04d07b2 --- /dev/null +++ b/knowledge_verificator/utils/string.py @@ -0,0 +1,26 @@ +"""Module with string-related utility function.""" + + +def clip_text(text: str, max_length: int) -> str: + """ + Clip `text` if its length exceeds `max_length`. + + If the text was clipped, it has three dots `...` at the end. Otherwise, + the text is returned unchanged. + + Args: + text (str): Text to clip. + max_length (int): Maximum allowed length. It will not be exceeded. + + Returns: + str: Clipped text. + """ + if max_length <= 4: + raise ValueError( + 'Minimal reasonable value of `max_length` is 4 (one character ' + f'and three dots). Supplied value of {max_length}.' + ) + text_length = len(text) + if text_length > max_length: + return text[: max_length - 3] + '...' + return text