AliHaider0343 commited on
Commit
ae3ff72
1 Parent(s): 4a09976

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -0
app.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import streamlit as st
3
+ from transformers import RobertaTokenizer, RobertaForSequenceClassification
4
+ import re
5
+ import string
6
+
7
+ def tokenize_sentences(sentence):
8
+ encoded_dict = tokenizer.encode_plus(
9
+ sentence,
10
+ add_special_tokens=True,
11
+ max_length=128,
12
+ padding='max_length',
13
+ truncation=True,
14
+ return_attention_mask=True,
15
+ return_tensors='pt'
16
+ )
17
+ return torch.cat([encoded_dict['input_ids']], dim=0), torch.cat([encoded_dict['attention_mask']], dim=0)
18
+
19
+
20
+
21
+ def preprocess_query(query):
22
+ query = str(query).lower()
23
+ query = query.strip()
24
+ query=query.translate(str.maketrans("", "", string.punctuation))
25
+ return query
26
+
27
+ def predict_category(sentence, threshold):
28
+ input_ids, attention_mask = tokenize_sentences(sentence)
29
+ with torch.no_grad():
30
+ outputs = categories_model(input_ids, attention_mask=attention_mask)
31
+ logits = outputs.logits
32
+ predicted_categories = torch.sigmoid(logits).squeeze().tolist()
33
+ results = dict()
34
+ for label, prediction in zip(LABEL_COLUMNS_CATEGORIES, predicted_categories):
35
+ if prediction < threshold:
36
+ continue
37
+ precentage = round(float(prediction) * 100, 2)
38
+ results[label] = precentage
39
+ return results
40
+
41
+ # Load tokenizer and model
42
+ BERT_MODEL_NAME_FOR_CATEGORIES_CLASSIFICATION = 'roberta-large'
43
+ tokenizer = RobertaTokenizer.from_pretrained(BERT_MODEL_NAME_FOR_CATEGORIES_CLASSIFICATION, do_lower_case=True)
44
+
45
+ LABEL_COLUMNS_CATEGORIES = ['AMBIENCE', 'DRINK', 'FOOD', 'GENERAL', 'RESTAURANT', 'SERVICE', 'STAFF']
46
+
47
+ categories_model = RobertaForSequenceClassification.from_pretrained(BERT_MODEL_NAME_FOR_CATEGORIES_CLASSIFICATION, num_labels=len(LABEL_COLUMNS_CATEGORIES))
48
+ categories_model.load_state_dict(torch.load('./Categories_Classification_Model_updated.pth'))
49
+ categories_model.eval()
50
+
51
+ # Streamlit App
52
+ st.title("Review/Sentence Classification")
53
+ st.write("Multilable/Multiclass Sentence classification under 7 Defined Categories. ")
54
+
55
+ sentence = st.text_input("Enter a sentence:")
56
+ threshold = st.slider("Threshold", min_value=0.0, max_value=1.0, step=0.01, value=0.5)
57
+
58
+ if sentence:
59
+ processed_sentence = preprocess_query(sentence)
60
+ results = predict_category(processed_sentence, threshold)
61
+ if len(results) > 0:
62
+ st.write("Predicted Aspects:")
63
+ table_data = [["Category", "Probability"]]
64
+ for category, percentage in results.items():
65
+ table_data.append([category, f"{percentage}%"])
66
+ st.table(table_data)
67
+ else:
68
+ st.write("No Categories above the threshold.")