File size: 1,186 Bytes
391bd16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from __future__ import annotations

from abc import ABC, abstractmethod
from typing import TYPE_CHECKING

import joblib

if TYPE_CHECKING:
    from pathlib import Path

    from sklearn.pipeline import Pipeline


class Model(ABC):
    """Base class for all models"""

    @property
    @abstractmethod
    def pipeline(self) -> Pipeline:
        """Pipeline used for the model"""
        ...

    @property
    @abstractmethod
    def description(self) -> str:
        """Description of the architecture"""
        ...

    @abstractmethod
    def _predict(self, text: str) -> int:
        """Predict the sentiment of the given text"""
        ...

    @staticmethod
    def from_file(path: Path) -> Model:
        """Load the model from the given file"""
        return joblib.load(path)

    def to_file(self, path: Path) -> None:
        """Save the model to the given file"""
        joblib.dump(self, path)

    def predict(self, text: str) -> int:
        """Perform sentiment analysis on the given text"""
        return self._predict(text)

    def train(self, x: list[str], y: list[int]) -> None:
        """Train the model on the given data"""
        self.pipeline.fit(x, y)