models.py 14.9 KB
Newer Older
1
"""Models for dealing with text data, both in the database and in the application itself."""
2
from typing import Dict, List
3
from enum import Enum
4
import typing
5
from mcserver.config import Config
6
from mcserver.models_auto import TExercise, Corpus, TCorpus, Exercise, TLearningResult, LearningResult
7
from openapi.openapi_server.models import SolutionElement, Solution, Link, NodeMC, TextComplexity, AnnisResponse, \
8
    GraphData, StaticExercise, FileType, FrequencyItem, Phenomenon
9 10

AnnisResponse = AnnisResponse
11 12
FileType = FileType
FrequencyItem = FrequencyItem
13 14
GraphData = GraphData
LinkMC = Link
15
NodeMC = NodeMC
16
Phenomenon = Phenomenon
17
SolutionElement = SolutionElement
18
StaticExercise = StaticExercise
19 20 21 22 23 24 25 26 27
TextComplexity = TextComplexity


def make_solution_element_from_salt_id(salt_id: str) -> SolutionElement:
    """Extracts necessary information from a SALT ID string to create a solution element."""
    salt_parts: List[str] = salt_id.split("#")[-1].split("tok")
    sentence_id = int(salt_parts[0].replace("sent", ""))
    token_id = int(salt_parts[1].replace("tok", ""))
    return SolutionElement(content="", salt_id=salt_id, sentence_id=sentence_id, token_id=token_id)
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80


class Case(Enum):
    nominative = 0
    genitive = 1
    dative = 2
    accusative = 3
    ablative = 4
    vocative = 5
    locative = 6


class CitationLevel(Enum):
    """Citation level values for a single corpus."""
    book = "Book"
    chapter = "Chapter"
    default = "default"
    letter = "Letter"
    section = "Section"
    sentence = "Sentence"
    unit = "Unit"


class Dependency(Enum):
    adjectivalClause = 0
    adjectivalModifier = 1
    adverbialClauseModifier = 2
    adverbialModifier = 3
    appositionalModifier = 4
    auxiliary = 5
    caseMarking = 6
    classifier = 7
    clausalComplement = 8
    conjunct = 9
    coordinatingConjunction = 10
    copula = 11
    determiner = 12
    discourseElement = 13
    dislocated = 14
    expletive = 15
    goesWith = 16
    list = 17
    marker = 18
    multiwordExpression = 19
    nominalModifier = 20
    numericModifier = 21
    object = 22
    oblique = 23
    orphan = 24
    parataxis = 25
    punctuation = 26
    root = 27
    subject = 28
81 82
    unspecified = 29
    vocative = 30
83 84 85 86 87 88 89 90 91


class ExerciseType(Enum):
    cloze = "ddwtos"
    kwic = "kwic"
    markWords = "markWords"
    matching = "matching"


92 93
class Feats(Enum):
    Case = "case"
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159


class Language(Enum):
    German = "de"
    English = "en"


class Lemma(Enum):
    xxx = "xxx"


class MimeType(Enum):
    docx = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    pdf = "application/pdf"
    xml = "text/xml"


class ObjectType(Enum):
    Activity = "Activity"
    Agent = "Agent"


class PartOfSpeech(Enum):
    adjective = 1
    adverb = 2
    auxiliary = 3
    conjunction = 4
    interjection = 5
    noun = 6
    numeral = 7
    other = 8
    particle = 9
    preposition = 10
    pronoun = 11
    properNoun = 12
    punctuation = 13
    symbol = 14
    verb = 15


class ResourceType(Enum):
    """Resource types for the UpdateInfo table in the database.

    Each updatable entity has its own resource type value."""
    cts_data = 1
    exercise_list = 2
    file_api_clean = 3


class TextComplexityMeasure(Enum):
    all = 1


class UdPipeInputFormat(Enum):
    tokenize = 1
    conllu = 2
    horizontal = 3


class VocabularyCorpus(Enum):
    agldt = Config.VOCABULARY_AGLDT_FILE_NAME
    bws = Config.VOCABULARY_BWS_FILE_NAME
    proiel = Config.VOCABULARY_PROIEL_FILE_NAME
    viva = Config.VOCABULARY_VIVA_FILE_NAME


160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
class CorpusMC:
    """Keep this synchronized with the implementation in models_auto!

    It is replicated here because the Open-Alchemy package does not correctly assign default values for optional
    parameters."""

    @classmethod
    def from_dict(cls,
                  source_urn: str,
                  author: str = "Anonymus",
                  cid: typing.Optional[int] = None,
                  citation_level_1: str = "default",
                  citation_level_2: str = "default",
                  citation_level_3: str = "default",
                  title: str = "Anonymus",
                  ) -> TCorpus:
        # ignore CID (corpus ID) because it is going to be generated automatically
        return Corpus.from_dict(
            source_urn=source_urn, author=author, citation_level_1=citation_level_1,
            citation_level_2=citation_level_2, citation_level_3=citation_level_3, title=title)


class ExerciseMC:
    """Keep this synchronized with the implementation in models_auto!

    It is replicated here because the Open-Alchemy package does not correctly assign default values for optional
    parameters."""

    @classmethod
    def from_dict(cls,
                  eid: str,
                  last_access_time: float,
                  correct_feedback: str = "",
                  general_feedback: str = "",
                  incorrect_feedback: str = "",
                  instructions: str = "",
                  partially_correct_feedback: str = "",
                  search_values: str = "[]",
                  work_author: str = "",
                  work_title: str = "",
                  conll: str = "",
                  exercise_type: str = "",
                  exercise_type_translation: str = "",
                  language: str = "de",
                  solutions: str = "[]",
                  text_complexity: float = 0,
                  urn: str = "",
                  ) -> TExercise:
        return Exercise.from_dict(
            eid=eid, last_access_time=last_access_time, correct_feedback=correct_feedback,
            general_feedback=general_feedback, incorrect_feedback=incorrect_feedback,
            instructions=instructions, partially_correct_feedback=partially_correct_feedback,
            search_values=search_values, work_author=work_author, work_title=work_title,
            conll=conll, exercise_type=exercise_type, exercise_type_translation=exercise_type_translation,
            language=language, solutions=solutions, text_complexity=text_complexity, urn=urn)


class LearningResultMC:
    """Keep this synchronized with the implementation in models_auto!

    It is replicated here because the Open-Alchemy package does not correctly assign default values for optional
    parameters."""

    @classmethod
    def from_dict(cls,
                  completion: bool,
                  correct_responses_pattern: str,
                  created_time: float,
                  object_definition_description: str,
                  response: str,
                  score_max: int,
                  score_min: int,
                  score_raw: int,
                  success: bool,
                  actor_account_name: str = "",
                  actor_object_type: str = "",
                  category_id: str = "",
                  category_object_type: str = "",
                  choices: str = "[]",
                  duration: str = "PT0S",
                  extensions: str = "{}",
                  interaction_type: str = "",
                  object_definition_type: str = "",
                  object_object_type: str = "",
                  score_scaled: float = 0,
                  verb_display: str = "",
                  verb_id: str = "",
                  ) -> TLearningResult:
        return LearningResult.from_dict(
            completion=completion, correct_responses_pattern=correct_responses_pattern, created_time=created_time,
            object_definition_description=object_definition_description, response=response, score_max=score_max,
            score_min=score_min, score_raw=score_raw, success=success, actor_account_name=actor_account_name,
            actor_object_type=actor_object_type, category_id=category_id, category_object_type=category_object_type,
            choices=choices, duration=duration, extensions=extensions, interaction_type=interaction_type,
            object_definition_type=object_definition_type, object_object_type=object_object_type,
            score_scaled=score_scaled, verb_display=verb_display, verb_id=verb_id)


class Account:
    def __init__(self, json_dict: dict):
        self.name: str = json_dict["name"]


class Actor:
    def __init__(self, json_dict: dict):
        self.account: Account = Account(json_dict["account"])
        self.object_type: ObjectType = ObjectType(json_dict["objectType"])

    def serialize(self) -> dict:
        return dict(account=self.account.__dict__, objectType=self.object_type.value)
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391


class Category:
    def __init__(self, json_dict: dict):
        self.id: str = json_dict["id"]
        self.object_type: ObjectType = ObjectType(json_dict["objectType"])

    def serialize(self) -> dict:
        return dict(id=self.id, objectType=self.object_type.value)


class Choice:
    def __init__(self, json_dict: dict):
        self.description: Description = Description(json_dict["description"])
        self.id: str = json_dict["id"]

    def serialize(self) -> dict:
        return dict(description={"en-US": self.description.en_us}, id=self.id)


class Description:
    def __init__(self, json_dict: dict):
        self.en_us: str = json_dict["en-US"]


class Display:
    def __init__(self, json_dict: dict):
        self.en_us: str = json_dict["en-US"]


class Verb:
    def __init__(self, json_dict: dict):
        self.id: str = json_dict["id"]
        self.display: Display = Display(json_dict["display"])

    def serialize(self) -> dict:
        return dict(id=self.id, display={"en-US": self.display.en_us})


class Definition:
    def __init__(self, json_dict: dict):
        self.choices: List[Choice] = [Choice(x) for x in json_dict.get("choices", [])]
        self.correct_responses_pattern: List[str] = json_dict["correctResponsesPattern"]
        self.description: Description = Description(json_dict["description"])
        self.extensions: Dict[str, object] = json_dict["extensions"]
        self.interaction_type: str = json_dict["interactionType"]
        self.type: str = json_dict["type"]

    def serialize(self) -> dict:
        return dict(extensions=self.extensions, description=self.description.__dict__, type=self.type,
                    interactionType=self.interaction_type, correctResponsesPattern=self.correct_responses_pattern,
                    choices=[x.serialize() for x in self.choices])


class Object:
    def __init__(self, json_dict: dict):
        self.definition: Definition = Definition(json_dict["definition"])
        self.object_type: ObjectType = ObjectType(json_dict["objectType"])

    def serialize(self) -> dict:
        return dict(objectType=self.object_type.value, definition=self.definition.serialize())


class ContextActivities:
    def __init__(self, json_dict: dict):
        self.category: List[Category] = [Category(x) for x in json_dict["category"]]

    def serialize(self) -> dict:
        return dict(category=[x.serialize() for x in self.category])


class Context:
    def __init__(self, json_dict: dict):
        self.context_activities: ContextActivities = ContextActivities(json_dict["contextActivities"])

    def serialize(self) -> dict:
        return dict(contextActivities=self.context_activities.serialize())


class Score:
    def __init__(self, json_dict: dict):
        self.max: int = json_dict["max"]
        self.min: int = json_dict["min"]
        self.raw: int = json_dict["raw"]
        self.scaled: float = json_dict["scaled"]


class Result:
    def __init__(self, json_dict: dict):
        self.completion: bool = json_dict["completion"]
        self.duration: str = json_dict["duration"]
        self.response: str = json_dict["response"]
        self.score: Score = Score(json_dict["score"])
        self.success: bool = json_dict.get("success", self.score.raw == self.score.max)

    def serialize(self) -> dict:
        return dict(completion=self.completion, success=self.success, duration=self.duration, response=self.response,
                    score=self.score.__dict__)


class XapiStatement:
    def __init__(self, json_dict: dict):
        self.actor: Actor = Actor(json_dict["actor"])
        self.context: Context = Context(json_dict["context"])
        self.object: Object = Object(json_dict["object"])
        self.result: Result = Result(json_dict["result"])
        self.verb: Verb = Verb(json_dict["verb"])

    def serialize(self) -> dict:
        return dict(actor=self.actor.serialize(), verb=self.verb.serialize(), object=self.object.serialize(),
                    context=self.context.serialize(), result=self.result.serialize())


class ExerciseData:
    """Model for exercise data. Holds textual annotations as a graph"""
    graph: GraphData
    solutions: List[Solution]
    uri: str

    def __init__(self, graph: GraphData = None, uri: str = None, solutions: List[Solution] = None,
                 json_dict: dict = None):
        if json_dict is not None:
392
            self.graph = GraphData.from_dict(json_dict["graph"])
393
            self.uri = json_dict["uri"]
394
            self.solutions = [Solution.from_dict(solution_dict) for solution_dict in json_dict["solutions"]]
395 396 397 398 399 400
        else:
            self.graph = graph
            self.solutions = [] if solutions is None else solutions
            self.uri = uri

    def serialize(self) -> dict:
401
        ret_val: dict = {"solutions": [x.to_dict() for x in self.solutions],
402
                         "graph": dict(multigraph=self.graph.multigraph, directed=self.graph.directed,
403 404
                                       graph=self.graph.graph, nodes=[x.to_dict() for x in self.graph.nodes],
                                       links=[x.to_dict() for x in self.graph.links]), "uri": self.uri}
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
        return ret_val


class DownloadableFile:
    id: str
    file_name: str
    file_path: str
    file_type: FileType

    def __init__(self, file_id: str, file_name: str, file_type: FileType, file_path: str):
        self.id = file_id
        self.file_type = file_type
        self.file_name = file_name
        self.file_path = file_path


class Citation:
    level: CitationLevel
    label: str
    value: int

    def __init__(self, level: CitationLevel, label: str, value: int):
        self.level = level
        self.label = label
        self.value = value


class BaseTextPart:
    citation: Citation
    text_value: str

    def __init__(self, citation: Citation, text_value: str = ""):
        self.citation = citation
        self.text_value = text_value


class TextPart(BaseTextPart):
    sub_text_parts = None

    def __init__(self, citation: Citation, text_value: str = "", sub_text_parts=None):
        self.sub_text_parts: List[TextPart] = [] if sub_text_parts is None else sub_text_parts
        super().__init__(citation=citation, text_value=text_value)


class CustomCorpus:
    corpus: Corpus
    file_path: str
    text_parts: List[TextPart]

    def __init__(self, corpus: Corpus, file_path: str, text_parts: List[TextPart] = None):
        self.corpus = corpus
        self.file_path = file_path
        self.text_parts: List[TextPart] = [] if text_parts is None else text_parts


class Sentence:
    def __init__(self, id: int, matching_degree: int):
        self.id = id
        self.matching_degree = matching_degree