import gradio as gr import transformers import torch from transformers import BertModel, BertTokenizer, AdamW, get_linear_schedule_with_warmup from torch import nn, optim from torch.utils.data import Dataset, DataLoader import pickle class_names = ['left', 'neutral', 'right'] PRE_TRAINED_MODEL_NAME = 'bert-base-uncased' tokenizer = BertTokenizer.from_pretrained(PRE_TRAINED_MODEL_NAME) MAX_LEN = 256 bert_model = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME) class SentimentClassifier(nn.Module): def __init__(self, n_classes): super(SentimentClassifier, self).__init__() self.bert = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME) self.drop = nn.Dropout(p=0.4) self.out = nn.Linear(self.bert.config.hidden_size, n_classes) def forward(self, input_ids, attention_mask): _, pooled_output = self.bert( input_ids=input_ids, attention_mask=attention_mask, return_dict=False ) output = self.drop(pooled_output) return self.out(output) model = SentimentClassifier(len(class_names)) model2 = torch.load("model_BERT_2", map_location=torch.device('cpu')) def result_final(new_article): encoded_review = tokenizer.encode_plus( review_text, max_length=MAX_LEN, add_special_tokens=True, return_token_type_ids=False, padding="max_length", truncation=True, return_attention_mask=True, return_tensors='pt', ) input_ids = encoded_review['input_ids'].to(device) attention_mask = encoded_review['attention_mask'].to(device) output = model2(input_ids, attention_mask) _, prediction = torch.max(output, dim=1) return class_names[prediction] iface = gr.Interface(fn = result_final, inputs = "text", outputs = ["text"], title = "News Bias Classifer") iface.launch()