Keshavp08 commited on
Commit
2ebc794
·
1 Parent(s): 3cd85d3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -41
app.py CHANGED
@@ -1,48 +1,57 @@
1
  import streamlit as st
2
- import transformers
3
  import pandas as pd
 
 
4
 
5
- from transformers import AutoTokenizer, AutoModelForSequenceClassification, TextClassificationPipeline
 
 
6
 
7
- # Load the pre-trained BERT model
8
- model_name = 'nlptown/bert-base-multilingual-uncased-sentiment'
9
- tokenizer = AutoTokenizer.from_pretrained(model_name)
10
- model = AutoModelForSequenceClassification.from_pretrained(model_name)
11
- pipeline = TextClassificationPipeline(model=model, tokenizer=tokenizer, framework='pt', task='text-classification')
12
-
13
- # Define the toxicity classification function
14
  def classify_toxicity(text):
15
- result = pipeline(text)[0]
16
- label = result['label']
17
- score = result['score']
18
- return label, score
19
-
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  # Define the Streamlit app
22
- def app():
23
- # Create a persistent DataFrame
24
- if 'results' not in st.session_state:
25
- st.session_state.results = pd.DataFrame(columns=['text', 'toxicity', 'score'])
26
-
27
- # Create a form for users to enter their text
28
- with st.form(key='text_form'):
29
- text_input = st.text_input(label='Enter your text:')
30
- submit_button = st.form_submit_button(label='Classify')
31
-
32
- # Classify the text and display the results
33
- if submit_button and text_input != '':
34
- label, score = classify_toxicity(text_input)
35
- st.write('Classification Result:')
36
- st.write(f'Text: {text_input}')
37
- st.write(f'Toxicity: {label}')
38
- st.write(f'Score: {score}')
39
-
40
- # Add the classification result to the persistent DataFrame
41
- st.session_state.results = st.session_state.results.append({'text': text_input, 'toxicity': label, 'score': score}, ignore_index=True)
42
-
43
- # Display the persistent DataFrame
44
- st.write('Classification Results:')
45
- st.write(st.session_state.results)
46
-
47
- if _name_ == '_main_':
48
- app()
 
 
1
  import streamlit as st
 
2
  import pandas as pd
3
+ import torch
4
+ from transformers import BertTokenizer, BertForSequenceClassification
5
 
6
+ # Load the pre-trained BERT model and tokenizer
7
+ model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2)
8
+ tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
9
 
10
+ # Define the classification function
 
 
 
 
 
 
11
  def classify_toxicity(text):
12
+ # Tokenize the text
13
+ input_ids = tokenizer.encode(text, add_special_tokens=True)
14
+ # Truncate or pad the text to the maximum length
15
+ max_length = 128
16
+ input_ids = input_ids[:max_length] + [0] * (max_length - len(input_ids))
17
+ # Convert the input to a PyTorch tensor
18
+ input_ids = torch.tensor(input_ids).unsqueeze(0)
19
+ # Set the model to evaluation mode
20
+ model.eval()
21
+ # Make a prediction
22
+ with torch.no_grad():
23
+ outputs = model(input_ids)
24
+ logits = outputs[0]
25
+ # Get the predicted class
26
+ predicted_class = torch.argmax(logits).item()
27
+ return predicted_class
28
 
29
  # Define the Streamlit app
30
+ def main():
31
+ # Set the app title
32
+ st.title("Toxicity Classifier")
33
+ # Create a text input for the user to enter the text to classify
34
+ text = st.text_input("Enter text to classify:")
35
+ # Create a button to perform the classification
36
+ if st.button("Classify"):
37
+ # Classify the text
38
+ predicted_class = classify_toxicity(text)
39
+ # Display the predicted class
40
+ if predicted_class == 0:
41
+ st.write("The text is not toxic.")
42
+ else:
43
+ st.write("The text is toxic.")
44
+ # Create a checkbox to allow the user to add the classification to a DataFrame
45
+ add_to_dataframe = st.checkbox("Add classification to DataFrame")
46
+ if add_to_dataframe:
47
+ # Load the existing DataFrame or create a new one if it doesn't exist
48
+ dataframe = pd.read_csv("classifications.csv") if "classifications.csv" in st.session_state else pd.DataFrame(columns=["Text", "Toxic"])
49
+ # Add the classification to the DataFrame
50
+ dataframe = dataframe.append({"Text": text, "Toxic": predicted_class}, ignore_index=True)
51
+ # Save the DataFrame to a CSV file
52
+ dataframe.to_csv("classifications.csv", index=False)
53
+ # Display the DataFrame
54
+ st.write(dataframe)
55
+
56
+ if __name__ == "__main__":
57
+ main()