|
import torch |
|
import streamlit as st |
|
from transformers import RobertaTokenizer, RobertaForSequenceClassification |
|
import re |
|
import string |
|
|
|
def tokenize_sentences(sentence): |
|
encoded_dict = tokenizer.encode_plus( |
|
sentence, |
|
add_special_tokens=True, |
|
max_length=128, |
|
padding='max_length', |
|
truncation=True, |
|
return_attention_mask=True, |
|
return_tensors='pt' |
|
) |
|
return torch.cat([encoded_dict['input_ids']], dim=0), torch.cat([encoded_dict['attention_mask']], dim=0) |
|
|
|
|
|
|
|
def preprocess_query(query): |
|
query = str(query).lower() |
|
query = query.strip() |
|
query=query.translate(str.maketrans("", "", string.punctuation)) |
|
return query |
|
|
|
def predict_category(sentence, threshold): |
|
input_ids, attention_mask = tokenize_sentences(sentence) |
|
with torch.no_grad(): |
|
outputs = categories_model(input_ids, attention_mask=attention_mask) |
|
logits = outputs.logits |
|
predicted_categories = torch.sigmoid(logits).squeeze().tolist() |
|
results = dict() |
|
for label, prediction in zip(LABEL_COLUMNS_CATEGORIES, predicted_categories): |
|
if prediction < threshold: |
|
continue |
|
precentage = round(float(prediction) * 100, 2) |
|
results[label] = precentage |
|
return results |
|
|
|
|
|
BERT_MODEL_NAME_FOR_CATEGORIES_CLASSIFICATION = 'roberta-large' |
|
tokenizer = RobertaTokenizer.from_pretrained(BERT_MODEL_NAME_FOR_CATEGORIES_CLASSIFICATION, do_lower_case=True) |
|
|
|
LABEL_COLUMNS_CATEGORIES = ['AMBIENCE', 'DRINK', 'FOOD', 'GENERAL', 'RESTAURANT', 'SERVICE', 'STAFF'] |
|
|
|
categories_model = RobertaForSequenceClassification.from_pretrained(BERT_MODEL_NAME_FOR_CATEGORIES_CLASSIFICATION, num_labels=len(LABEL_COLUMNS_CATEGORIES)) |
|
categories_model.load_state_dict(torch.load('./Categories_Classification_Model_updated.pth',map_location=torch.device('cpu') )) |
|
categories_model.eval() |
|
|
|
|
|
st.title("Review/Sentence Classification") |
|
st.write("Multilable/Multiclass Sentence classification under 7 Defined Categories. ") |
|
|
|
sentence = st.text_input("Enter a sentence:") |
|
threshold = st.slider("Threshold", min_value=0.0, max_value=1.0, step=0.01, value=0.5) |
|
|
|
if sentence: |
|
processed_sentence = preprocess_query(sentence) |
|
results = predict_category(processed_sentence, threshold) |
|
if len(results) > 0: |
|
st.write("Predicted Aspects:") |
|
table_data = [["Category", "Probability"]] |
|
for category, percentage in results.items(): |
|
table_data.append([category, f"{percentage}%"]) |
|
st.table(table_data) |
|
else: |
|
st.write("No Categories above the threshold.") |