File size: 2,398 Bytes
a1b658b
 
230b305
5cc287d
a1b658b
 
5cc287d
635ba57
7ce2ced
 
44dda57
 
61336fa
635ba57
5cc287d
635ba57
 
5cc287d
358197a
5cc287d
a3ea6a6
a1b658b
5cc287d
 
a1b658b
230b305
5cc287d
 
 
 
a1b658b
7ce2ced
a1b658b
7ce2ced
7687d77
7ce2ced
 
 
 
 
 
4b4aa45
7ce2ced
 
4b4aa45
61336fa
 
 
7ce2ced
44dda57
a1b658b
 
 
 
 
 
ad3c02f
a1b658b
 
 
3d4e13e
 
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
import gradio as gr
import numpy as np
from transformers import pipeline
from model import DepressionClassifier
import hopsworks
import joblib
import torch
from huggingface_hub import hf_hub_download
import transformers
from transformers import BertModel, BertTokenizer
from PIL import Image
import requests
import io

class_names = ['Not Depressed', 'Depressed']
pt_file = hf_hub_download(repo_id="liangc40/sentimental_analysis", filename="model.pt")

model = DepressionClassifier(len(class_names), 'bert-base-cased')
model.load_state_dict(torch.load(pt_file, map_location=torch.device('cpu')))
model.eval()
#pipe = pipeline(model="liangc40/sentimental_analysis")

#project = hopsworks.login(project='liangc40')
#fs = project.get_feature_store()


#mr = project.get_model_registry()
#model = mr.get_model("sentimental_analysis_model", version=1)
#model_dir = model.download()
#model = joblib.load(model_dir + "/sentimental_analysis_model.pkl")


def analyse(text):
    #text = "I'm depressed"
    #model = model.to('cpu')
    tokenizer = BertTokenizer.from_pretrained('bert-base-cased')
    encoding = tokenizer.encode_plus(text, max_length=32, add_special_tokens=True, # Add '[CLS]' and '[SEP]'
                                     return_token_type_ids=False,
                                     pad_to_max_length=True,
                                     return_attention_mask=True,
                                     return_tensors='pt')

    outputs = model(input_ids = encoding['input_ids'], attention_mask = encoding['attention_mask'])
    _, preds = torch.max(outputs, dim=1)
    face_url = "https://raw.githubusercontent.com/liangc40/ID2223_Sentimental_Analysis_Project/main/Image/"+ str(preds) + ".png"
    r = requests.get(face_url, stream=True)
    img = Image.open(io.BytesIO(r.content))
    #img = Image.open(requests.get(face_url, stream=True).raw)
    #print(preds)
    return img

with gr.Blocks() as demo:
    gr.Markdown("<h1><center>Sentiment Analysis with Fine-tuned BERT Model")

    inputs_text=gr.Textbox(placeholder='Type your text for which you want know the sentiment', label='Text')
    text_button = gr.Button('Analyse Sentiment')
    output_text_sentiment = gr.Textbox(placeholder='Sentiment of the text.', label='Sentiment')
    text_button.click(analyse, inputs = inputs_text, outputs = output_text_sentiment)

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