Akhil Koduri commited on
Commit
6315870
·
verified ·
1 Parent(s): d2abc66

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -43
app.py CHANGED
@@ -1,65 +1,68 @@
1
  import streamlit as st
2
  import pandas as pd
3
  import fitz # PyMuPDF
4
- import docx
5
- from transformers import BertTokenizer, BertForSequenceClassification
6
- import torch
7
- from io import StringIO
8
 
9
- # Load pre-trained model and tokenizer
10
- model_name = "google/bert-base-uncased"
11
- tokenizer = BertTokenizer.from_pretrained(model_name)
12
- model = BertForSequenceClassification.from_pretrained(model_name, num_labels=2)
13
 
14
- # Custom labels for classification
15
  labels = {
16
- 0: "Negative",
17
- 1: "Positive"
18
  }
19
 
20
- # Function to classify text
21
- def classify_text(text):
22
- inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
23
- outputs = model(**inputs)
24
- logits = outputs.logits
25
- probabilities = torch.softmax(logits, dim=-1)
26
- confidence_score, predicted_class = torch.max(probabilities, dim=-1)
27
- confidence_score = confidence_score.item()
28
- predicted_class = predicted_class.item()
29
-
30
- label = labels[predicted_class]
31
-
32
  # Streamlit app
33
  st.title("BERT Text Classification")
34
- st.write("This app classifies text using a pre-trained BERT model.")
35
 
36
  # Input text area
37
  input_text = st.text_area("Enter text to classify")
38
 
39
- # Classification and display
40
- if st.button("Classify") and input_text:
41
- label, score = classify_text(input_text)
42
- st.write(f"Predicted Class: {label}")
43
- st.write(f"Confidence: {score:.4f}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  # File upload section
46
  st.write("Upload a file for classification:")
47
- uploaded_file = st.file_uploader("Choose a file", type=["csv", "pdf", "txt", "doc", "docx", "xlsx"])
48
 
49
  if uploaded_file is not None:
50
- file_type = uploaded_file.type
51
- if file_type == "text/csv":
52
  df = pd.read_csv(uploaded_file)
53
- elif file_type == "application/pdf":
 
 
 
 
 
 
 
 
54
  with fitz.open(stream=uploaded_file.read(), filetype="pdf") as doc:
55
- text = "".join(page.get_text() for page in doc)
56
- elif file_type == "text/plain":
57
- text = uploaded_file.getvalue().decode("utf-8")
58
- elif file_type in ["application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/msword"]:
59
- doc = docx.Document(uploaded_file)
60
- text = "\n".join(para.text for para in doc.paragraphs)
61
 
62
- if 'text' in locals():
63
- label, score = classify_text(text)
64
- st.write(f"Predicted Class for {file_type}: {label}")
65
- st.write(f"Confidence: {score:.4f}")
 
1
  import streamlit as st
2
  import pandas as pd
3
  import fitz # PyMuPDF
4
+ from transformers import pipeline
 
 
 
5
 
6
+ # Load pre-trained model and tokenizer from Hugging Face
7
+ model_name = "google-bert/bert-base-uncased"
8
+ pipe = pipeline("text-classification", model=model_name)
 
9
 
10
+ # Custom labels for your classification task
11
  labels = {
12
+ "LABEL_0": "Negative",
13
+ "LABEL_1": "Positive"
14
  }
15
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  # Streamlit app
17
  st.title("BERT Text Classification")
18
+ st.write("This app uses a pre-trained BERT model to classify text into positive or negative sentiment.")
19
 
20
  # Input text area
21
  input_text = st.text_area("Enter text to classify")
22
 
23
+ def classify_text(text):
24
+ result = pipe(text)[0]
25
+ label = labels.get(result['label'], result['label'])
26
+ score = result['score']
27
+
28
+ # Adjust classification based on score
29
+ if score < 0.75:
30
+ label = "Negative"
31
+
32
+ return label, score
33
+
34
+ if st.button("Classify"):
35
+ if input_text:
36
+ # Perform classification
37
+ label, score = classify_text(input_text)
38
+ st.write(f"**Predicted Class:** {label}")
39
+ st.write(f"**Confidence:** {score:.4f}")
40
+ else:
41
+ st.write("Please enter some text to classify.")
42
 
43
  # File upload section
44
  st.write("Upload a file for classification:")
45
+ uploaded_file = st.file_uploader("Choose a file", type=["csv", "pdf"])
46
 
47
  if uploaded_file is not None:
48
+ if uploaded_file.type == "text/csv":
49
+ # Process CSV file
50
  df = pd.read_csv(uploaded_file)
51
+ if 'text' not in df.columns:
52
+ st.write("The CSV file must contain a 'text' column.")
53
+ else:
54
+ df['Prediction'] = df['text'].apply(lambda x: classify_text(x)[0])
55
+ df['Confidence'] = df['text'].apply(lambda x: classify_text(x)[1])
56
+ st.write(df)
57
+
58
+ elif uploaded_file.type == "application/pdf":
59
+ # Process PDF file
60
  with fitz.open(stream=uploaded_file.read(), filetype="pdf") as doc:
61
+ text = ""
62
+ for page in doc:
63
+ text += page.get_text()
 
 
 
64
 
65
+ # Perform classification
66
+ label, score = classify_text(text)
67
+ st.write(f"**Predicted Class for PDF:** {label}")
68
+ st.write(f"**Confidence:** {score:.4f}")