ynp3 commited on
Commit
48fa517
·
1 Parent(s): fadd033

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -53
app.py CHANGED
@@ -1,68 +1,58 @@
1
  import streamlit as st
2
  import pandas as pd
3
  from transformers import BertTokenizer, BertForSequenceClassification
4
- import torch
5
 
6
  # Load pre-trained BERT model and tokenizer
7
- MODEL_PATH = "bert-base-uncased"
8
- tokenizer = BertTokenizer.from_pretrained(MODEL_PATH)
9
- model = BertForSequenceClassification.from_pretrained(MODEL_PATH)
10
  model.eval()
11
 
12
- # Create DataFrame to store classification results
13
- df = pd.DataFrame(columns=["Text", "Toxic", "Obscene", "Insult", "Identity Hate", "Threat", "Severe Toxic"])
14
-
15
  def classify_text(text):
16
- # Tokenize input text
17
- encoded_input = tokenizer.encode_plus(
18
- text,
19
- max_length=512,
20
- padding='max_length',
21
- truncation=True,
22
- return_tensors='pt'
23
- )
24
- input_ids = encoded_input['input_ids']
25
- attention_mask = encoded_input['attention_mask']
26
-
27
- # Predict toxicity using pre-trained BERT model
28
- with torch.no_grad():
29
- outputs = model(input_ids, attention_mask)
30
- logits = outputs.logits
31
- probabilities = torch.softmax(logits, dim=1)
32
- toxic_prob = probabilities[0][1].item()
33
- obscene_prob = probabilities[0][2].item()
34
- insult_prob = probabilities[0][3].item()
35
- identity_hate_prob = probabilities[0][4].item()
36
- threat_prob = probabilities[0][5].item()
37
- severe_toxic_prob = probabilities[0][6].item()
38
-
39
- # Return predicted probabilities
40
- return toxic_prob, obscene_prob, insult_prob, identity_hate_prob, threat_prob, severe_toxic_prob
41
 
42
- # Streamlit app
43
  def main():
44
  st.title("Toxicity Classification App")
45
- text = st.text_area("Enter text to classify", height=200)
46
  if st.button("Classify"):
47
- if text.strip() == "":
48
- st.warning("Please enter some text.")
49
- else:
50
- toxic_prob, obscene_prob, insult_prob, identity_hate_prob, threat_prob, severe_toxic_prob = classify_text(text)
51
- st.write("Toxicity probabilities:")
52
- st.write("Toxic:", toxic_prob)
53
- st.write("Obscene:", obscene_prob)
54
- st.write("Insult:", insult_prob)
55
- st.write("Identity Hate:", identity_hate_prob)
56
- st.write("Threat:", threat_prob)
57
- st.write("Severe Toxic:", severe_toxic_prob)
58
-
59
- if st.button("Add to DataFrame"):
60
- df.loc[len(df)] = [text, toxic_prob, obscene_prob, insult_prob, identity_hate_prob, threat_prob, severe_toxic_prob]
61
- st.success("Classification results added to DataFrame.")
62
-
63
- # Display DataFrame with classification results
64
- st.subheader("Classification Results")
65
- st.dataframe(df)
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  if __name__ == "__main__":
68
  main()
 
1
  import streamlit as st
2
  import pandas as pd
3
  from transformers import BertTokenizer, BertForSequenceClassification
 
4
 
5
  # Load pre-trained BERT model and tokenizer
6
+ tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
7
+ model = BertForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=6)
8
+ model.load_state_dict(torch.load('path_to_pretrained_model.pth', map_location=torch.device('cpu'))) # Load pre-trained model weights
9
  model.eval()
10
 
11
+ # Define function for classification
 
 
12
  def classify_text(text):
13
+ inputs = tokenizer(text, padding=True, truncation=True, return_tensors="pt")
14
+ outputs = model(**inputs)
15
+ logits = outputs.logits
16
+ probabilities = torch.sigmoid(logits)
17
+ return probabilities
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
+ # Create Streamlit app
20
  def main():
21
  st.title("Toxicity Classification App")
22
+ text_input = st.text_area("Enter text for classification:", "")
23
  if st.button("Classify"):
24
+ probabilities = classify_text(text_input)
25
+ toxic = probabilities[0][0].item()
26
+ obscene = probabilities[0][1].item()
27
+ insult = probabilities[0][2].item()
28
+ identity_hate = probabilities[0][3].item()
29
+ threat = probabilities[0][4].item()
30
+ severe_toxic = probabilities[0][5].item()
31
+
32
+ st.write("### Classification Results:")
33
+ st.write("Toxic: {:.2%}".format(toxic))
34
+ st.write("Obscene: {:.2%}".format(obscene))
35
+ st.write("Insult: {:.2%}".format(insult))
36
+ st.write("Identity Hate: {:.2%}".format(identity_hate))
37
+ st.write("Threat: {:.2%}".format(threat))
38
+ st.write("Severe Toxic: {:.2%}".format(severe_toxic))
39
+
40
+ # Add results to persistent DataFrame
41
+ result = {
42
+ 'Text': text_input,
43
+ 'Toxic': toxic,
44
+ 'Obscene': obscene,
45
+ 'Insult': insult,
46
+ 'Identity Hate': identity_hate,
47
+ 'Threat': threat,
48
+ 'Severe Toxic': severe_toxic
49
+ }
50
+ df = pd.DataFrame(result, index=[0])
51
+ if 'classified_df' not in st.session_state:
52
+ st.session_state.classified_df = pd.DataFrame(columns=['Text', 'Toxic', 'Obscene', 'Insult', 'Identity Hate', 'Threat', 'Severe Toxic'])
53
+ st.session_state.classified_df = st.session_state.classified_df.append(df, ignore_index=True)
54
+ st.write("### Classified Data:")
55
+ st.write(st.session_state.classified_df)
56
 
57
  if __name__ == "__main__":
58
  main()