Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,103 +1,88 @@
|
|
| 1 |
-
# Import required
|
|
|
|
| 2 |
import pandas as pd
|
| 3 |
-
import numpy as np
|
| 4 |
import torch
|
| 5 |
-
from
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
#
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
# Load pre-trained
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
train_data = TensorDataset(train_seq, train_mask, train_y)
|
| 36 |
-
train_sampler = RandomSampler(train_data)
|
| 37 |
-
train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=batch_size)
|
| 38 |
-
|
| 39 |
-
val_data = TensorDataset(val_seq, val_mask, val_y)
|
| 40 |
-
val_sampler = SequentialSampler(val_data)
|
| 41 |
-
val_dataloader = DataLoader(val_data, sampler=val_sampler, batch_size=batch_size)
|
| 42 |
-
|
| 43 |
-
# Load pre-trained BERT model and add a classification head
|
| 44 |
-
model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=6)
|
| 45 |
-
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 46 |
-
model.to(device)
|
| 47 |
-
|
| 48 |
-
# Set optimizer and learning rate
|
| 49 |
-
optimizer = AdamW(model.parameters(), lr=2e-5)
|
| 50 |
-
|
| 51 |
-
# Fine-tune the model on the training set
|
| 52 |
-
epochs = 2
|
| 53 |
-
for epoch in range(epochs):
|
| 54 |
-
model.train()
|
| 55 |
-
total_loss = 0
|
| 56 |
-
for batch in train_dataloader:
|
| 57 |
-
batch_seq = batch[0].to(device)
|
| 58 |
-
batch_mask = batch[1].to(device)
|
| 59 |
-
batch_y = batch[2].to(device)
|
| 60 |
-
model.zero_grad()
|
| 61 |
-
outputs = model(batch_seq, attention_mask=batch_mask, labels=batch_y)
|
| 62 |
-
loss = outputs[0]
|
| 63 |
-
total_loss += loss.item()
|
| 64 |
-
loss.backward()
|
| 65 |
-
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 66 |
-
optimizer.step()
|
| 67 |
-
avg_train_loss = total_loss / len(train_dataloader)
|
| 68 |
-
print("Epoch:", epoch+1, "Training Loss:", avg_train_loss)
|
| 69 |
-
|
| 70 |
-
# Evaluate model performance on validation
|
| 71 |
-
# Evaluate model performance on validation
|
| 72 |
-
model.eval()
|
| 73 |
-
total_val_accuracy = 0
|
| 74 |
-
total_val_f1 = 0
|
| 75 |
with torch.no_grad():
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Import required packages
|
| 2 |
+
import streamlit as st
|
| 3 |
import pandas as pd
|
|
|
|
| 4 |
import torch
|
| 5 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification
|
| 6 |
+
|
| 7 |
+
# Define model paths
|
| 8 |
+
MODEL_MAP = {
|
| 9 |
+
'BERT': 'bert-base-uncased',
|
| 10 |
+
'RoBERTa': 'roberta-base',
|
| 11 |
+
'DistilBERT': 'distilbert-base-uncased'
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
# Define label columns
|
| 15 |
+
LABEL_COLS = ['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate']
|
| 16 |
+
|
| 17 |
+
# Load pre-trained model and tokenizer
|
| 18 |
+
@st.cache_resource
|
| 19 |
+
def load_model(model_name):
|
| 20 |
+
path = "finetuned_model.pt"
|
| 21 |
+
model = torch.load(path)
|
| 22 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_MAP[model_name])
|
| 23 |
+
return model, tokenizer
|
| 24 |
+
|
| 25 |
+
# Classify text using pre-trained model
|
| 26 |
+
def classify_text(model, tokenizer, text):
|
| 27 |
+
inputs = tokenizer.encode_plus(
|
| 28 |
+
text,
|
| 29 |
+
add_special_tokens=True,
|
| 30 |
+
max_length=512,
|
| 31 |
+
padding='max_length',
|
| 32 |
+
return_tensors='pt',
|
| 33 |
+
truncation=True
|
| 34 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
with torch.no_grad():
|
| 36 |
+
logits = model(inputs['input_ids'],inputs['attention_mask'])[0]
|
| 37 |
+
probabilities = torch.softmax(logits, dim=1)[0]
|
| 38 |
+
pred_class = torch.argmax(probabilities, dim=0)
|
| 39 |
+
return LABEL_COLS[pred_class], round(probabilities[0].tolist(),2)
|
| 40 |
+
|
| 41 |
+
# Define Streamlit app layout
|
| 42 |
+
def app():
|
| 43 |
+
st.title('Classifier App')
|
| 44 |
+
model_options = list(MODEL_MAP.keys())
|
| 45 |
+
model_name = st.sidebar.selectbox('Select model', model_options)
|
| 46 |
+
st.sidebar.write('You selected:', model_name)
|
| 47 |
+
model, tokenizer = load_model(model_name)
|
| 48 |
+
|
| 49 |
+
# Input text to classify
|
| 50 |
+
st.subheader('Enter your text below:')
|
| 51 |
+
text_input = st.text_area(label='', height=100, max_chars=500)
|
| 52 |
+
|
| 53 |
+
# Classify text and display results
|
| 54 |
+
if st.button('Classify'):
|
| 55 |
+
if not text_input:
|
| 56 |
+
st.write('Please enter some text')
|
| 57 |
+
else:
|
| 58 |
+
class_label, class_prob = classify_text(model, tokenizer, text_input)
|
| 59 |
+
st.subheader('Result')
|
| 60 |
+
st.write('Input Text:', text_input)
|
| 61 |
+
st.write('Highest Toxicity Class:', class_label)
|
| 62 |
+
st.write('Probability:', class_prob)
|
| 63 |
+
|
| 64 |
+
# Display classification results
|
| 65 |
+
st.subheader('Classification Results')
|
| 66 |
+
if 'classification_results' not in st.session_state:
|
| 67 |
+
st.session_state.classification_results = pd.DataFrame(columns=['text', 'toxicity_class', 'probability'])
|
| 68 |
+
if st.button('Add to Results'):
|
| 69 |
+
if not text_input:
|
| 70 |
+
st.write('Please enter some text')
|
| 71 |
+
else:
|
| 72 |
+
class_label, class_prob = classify_text(model, tokenizer, text_input)
|
| 73 |
+
st.session_state.classification_results = st.session_state.classification_results.append({
|
| 74 |
+
'text': text_input,
|
| 75 |
+
'toxicity_class': class_label,
|
| 76 |
+
'probability': class_prob
|
| 77 |
+
}, ignore_index=True)
|
| 78 |
+
|
| 79 |
+
# Display saved classification results
|
| 80 |
+
if not st.session_state.classification_results.empty:
|
| 81 |
+
st.write(st.session_state.classification_results)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
|