File size: 1,563 Bytes
667fe9d
 
85ac990
 
 
667fe9d
 
85ac990
667fe9d
2c1f9dd
 
85ac990
7b9e59d
667fe9d
85ac990
667fe9d
 
85ac990
 
 
667fe9d
 
85ac990
7b9e59d
85ac990
 
 
 
 
 
667fe9d
 
85ac990
 
 
2c1f9dd
667fe9d
85ac990
 
 
 
 
667fe9d
 
85ac990
 
b42b884
85ac990
 
b42b884
 
 
 
 
 
 
2c1f9dd
85ac990
667fe9d
 
b42b884
85ac990
 
667fe9d
 
85ac990
 
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from __future__ import annotations

import os
from functools import lru_cache
from typing import TYPE_CHECKING

import gradio as gr
import joblib

from app.model import infer_model

if TYPE_CHECKING:
    from sklearn.base import BaseEstimator

__all__ = ["launch_gui"]


POSITIVE_LABEL = "Positive 😊"
NEUTRAL_LABEL = "Neutral 😐"
NEGATIVE_LABEL = "Negative 😀"


@lru_cache(maxsize=1)
def load_model() -> BaseEstimator:
    """Load the trained model and cache it."""
    model_path = os.environ.get("MODEL_PATH", None)
    if model_path is None:
        msg = "MODEL_PATH environment variable not set"
        raise ValueError(msg)
    return joblib.load(model_path)


def sentiment_analysis(text: str) -> str:
    """Perform sentiment analysis on the provided text."""
    model = load_model()
    prediction = infer_model(model, [text])[0]

    if prediction == 0:
        return NEGATIVE_LABEL
    if prediction == 1:
        return POSITIVE_LABEL
    return NEUTRAL_LABEL


demo = gr.Interface(
    fn=sentiment_analysis,
    inputs=gr.Textbox(lines=10, label="Enter text here"),
    outputs="label",
    title="Sentiment Analysis",
    description="Predict the sentiment of a given text.",
    examples=[
        ["I love the weather today!"],
        ["You are a terrible person."],
        ["The movie we watched was boring."],
        ["This website is amazing!"],
    ],
    allow_flagging=False,
)


def launch_gui(share: bool) -> None:
    """Launch the Gradio GUI."""
    demo.launch(share=share)


if __name__ == "__main__":
    demo.launch()