File size: 2,618 Bytes
ae3ff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6682ca
ae3ff72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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

# Load tokenizer and model
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()

# Streamlit App
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.")