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

Implement the basic backend with API #14

Merged
merged 15 commits into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from 7 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
6 changes: 6 additions & 0 deletions config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
mode: BACKEND
logging_level: DEBUG
production_mode: false
learning_materials: ./learning_assets
experiment_implementation: ./tests/model
experiment_results: ./tests/model/results
48 changes: 48 additions & 0 deletions knowledge_verificator/backend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""Module with the backend defining available endpoints."""

from typing import Any, Union

from fastapi import FastAPI


endpoints = FastAPI()


def format_response(data: Any = '', successful: bool = True) -> dict:
Iamhexi marked this conversation as resolved.
Show resolved Hide resolved
"""Format a response to a request to a single format."""
Iamhexi marked this conversation as resolved.
Show resolved Hide resolved
if successful:
Iamhexi marked this conversation as resolved.
Show resolved Hide resolved
message = 'Success'
else:
message = 'Failure'
return {'data': data, 'message': message}


@endpoints.get('/materials')
def get_materials():
"""Get all learning materials."""
Iamhexi marked this conversation as resolved.
Show resolved Hide resolved
# return materials.materials()
return format_response(successful=True)


@endpoints.get('/materials/{material_id}')
def get_material(material_id: int, q: Union[str, None] = None):
"""
Get a specific learning material.

Args:
material_id (int): ID of a material to retrieve.
q (Union[str, None], optional): Query to find a material if
Iamhexi marked this conversation as resolved.
Show resolved Hide resolved
`material_id` is not known. Defaults to None.

Returns:
dict: Response with status of a request
Iamhexi marked this conversation as resolved.
Show resolved Hide resolved
status and a learning material if request was processed correctly.
"""
data = {'material_id': material_id, 'query': q}
return format_response(data=data, successful=True)


@endpoints.delete('/materials/{material_id}')
def delete_material(material_id: int):
"""Delete a learning material with the supplied `material_id`."""
Iamhexi marked this conversation as resolved.
Show resolved Hide resolved
return format_response(data=str(material_id), successful=False)
Iamhexi marked this conversation as resolved.
Show resolved Hide resolved
135 changes: 135 additions & 0 deletions knowledge_verificator/command_line.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
"""Module with an interactive command-line interface."""

from rich.text import Text

from knowledge_verificator.io_handler import logger, console, config
from knowledge_verificator.answer_chooser import AnswerChooser
from knowledge_verificator.materials import MaterialDatabase
from knowledge_verificator.nli import NaturalLanguageInference, Relation
from knowledge_verificator.qg import QuestionGeneration
from knowledge_verificator.utils.menu import choose_from_menu


def display_feedback(relation: Relation, chosen_answer: str) -> None:
"""
Display feedback to a terminal.

Args:
relation (Relation): Relation between a reference answer and the
Iamhexi marked this conversation as resolved.
Show resolved Hide resolved
answer provided by a user. Either they are consistent, not
consistent or they are independent claims.
chosen_answer (str): An answer provided by a user.
"""
match relation:
case Relation.ENTAILMENT:
feedback = 'correct'
style = 'green'
case Relation.CONTRADICTION:
feedback = f'wrong. Correct answer is {chosen_answer}'
style = 'red'
case Relation.NEUTRAL:
feedback = 'not directly associated with the posed question'
style = 'yellow'

feedback_text = Text(f'Your answer is {feedback}.', style=style)
console.print(feedback_text)


def run_cli_mode():
"""
Run an interactive command-line interface.

Raises:
ValueError:
"""
qg_module = QuestionGeneration()
chooser = AnswerChooser()
Iamhexi marked this conversation as resolved.
Show resolved Hide resolved
nli_module = NaturalLanguageInference()

while True:
options = ['knowledge database', 'my own paragraph']
user_choice = choose_from_menu(
menu_elements=options, plural_name='options'
)

match user_choice:
case 'knowledge database':
try:
material_db = MaterialDatabase(config.learning_materials)
except FileNotFoundError:
console.print(
f'In the `{config.learning_materials}` there is no database. '
'Try using your own materials.'
)
continue

if not material_db.materials:
console.print(
'The knowledge database exists but is empty. '
'Try using your own materials.'
)
continue

material = choose_from_menu(
material_db.materials,
plural_name='materials',
attribute_to_show='title',
)

if material is None:
continue

paragraph = str(
choose_from_menu(material.paragraphs, 'paragraphs')
)

if paragraph is None:
Iamhexi marked this conversation as resolved.
Show resolved Hide resolved
continue

console.print('Learn this paragraph: ')
console.print(paragraph)
console.print()
input('Press ENTER when ready.')

case 'my own paragraph':
console.print('Enter a paragraph you would like to learn: ')
paragraph = input().strip()

case _:
console.print('Unrecognised option, try again!')

logger.debug('Loaded the following paragraph:\n %s', paragraph)

chosen_answer = chooser.choose_answer(paragraph=paragraph)
if not chosen_answer:
logger.error(
Iamhexi marked this conversation as resolved.
Show resolved Hide resolved
'The supplied paragraph is either too short or too general. '
'Please, try providing a longer or more specific paragraph.'
)
continue

console.clear()

logger.debug(
'The `%s` has been chosen as the answer, based on which question '
'will be generated.',
chosen_answer,
)

question_with_context = qg_module.generate(
answer=chosen_answer, context=paragraph
)
question = question_with_context['question']
logger.debug(
'Question Generation module has supplied the question: %s', question
)

console.print(
f'\nAnswer the question with full sentence. {question} \nYour answer: '
)
user_answer = input().strip()
relation = nli_module.infer_relation(
premise=paragraph, hypothesis=user_answer
)

display_feedback(relation=relation, chosen_answer=chosen_answer)
Iamhexi marked this conversation as resolved.
Show resolved Hide resolved
42 changes: 17 additions & 25 deletions knowledge_verificator/io_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,58 +3,50 @@
an instance of `rich` console, and an instance of a preconfigured `Logger`.
"""

import logging

from argparse import ArgumentParser
from logging import Logger
from rich.console import Console
from rich.logging import RichHandler

from knowledge_verificator.utils.configuration_parser import ConfigurationParser


def get_argument_parser() -> ArgumentParser:
"""
Provide an instance of the CLI arguments paraser.
Provide an instance of the CLI arguments parser.

Returns:
ArgumentParser: Configured instance of argument parser.
"""
arg_parser = ArgumentParser(
prog='knowledge_verificator',
description='The system of knowledge verificator facilitating self-study.',
)

arg_parser.add_argument(
'-d',
'--debug',
action='store_true',
default=False,
'-c',
'--config',
default='config.yaml',
action='store',
help=(
'Turn on a debug mode, which shows all logs including those from '
'`debug` and `info` levels.'
'Path to a YAML configuration file that contain configuration '
'of the system.'
),
)

arg_parser.add_argument(
'-e',
'--experiments',
action='store_true',
default=False,
help='Run experiments instead of running an interactive mode.',
)

return arg_parser


console = Console()
logger = Logger('main_logger')

logging_handler = RichHandler(rich_tracebacks=True)
_logging_handler = RichHandler(rich_tracebacks=True)

parser = get_argument_parser()
args = parser.parse_args()
_parser = get_argument_parser()
args = _parser.parse_args()

LOGGING_LEVEL = logging.WARNING
if args.debug:
LOGGING_LEVEL = logging.DEBUG
_configuratioParser = ConfigurationParser(configuration_file=args.config)
config = _configuratioParser.parse_configuration()

logging_handler.setLevel(LOGGING_LEVEL)
logger.addHandler(logging_handler)
_logging_handler.setLevel(config.logging_level)
logger.addHandler(_logging_handler)
Loading
Loading