ISOM5240GP4 commited on
Commit
95fe581
·
verified ·
1 Parent(s): 305441b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -11
app.py CHANGED
@@ -3,11 +3,14 @@ from transformers import pipeline, AutoModelForSequenceClassification, AutoToken
3
  import torch
4
  import numpy as np
5
 
 
6
  def analyze_email(email_body):
 
7
  spam_pipeline = pipeline("text-classification", model="cybersectony/phishing-email-detection-distilbert_v2.4.1")
8
  sentiment_model = AutoModelForSequenceClassification.from_pretrained("ISOM5240GP4/email_sentiment", num_labels=2)
9
  tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
10
 
 
11
  spam_result = spam_pipeline(email_body)
12
  spam_label = spam_result[0]["label"]
13
  spam_confidence = spam_result[0]["score"]
@@ -15,6 +18,7 @@ def analyze_email(email_body):
15
  if spam_label == "LABEL_1":
16
  return "spam", f"This is a spam email (Confidence: {spam_confidence:.2f}). No follow-up needed."
17
  else:
 
18
  inputs = tokenizer(email_body, padding=True, truncation=True, return_tensors='pt')
19
  outputs = sentiment_model(**inputs)
20
  predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
@@ -31,11 +35,14 @@ def analyze_email(email_body):
31
  f"Sentiment: {sentiment} (Confidence: {sentiment_confidence:.2f}).\n"
32
  "**Need to Follow-Up**: This email is not spam and has negative sentiment.")
33
 
 
34
  def main():
 
35
  st.title("EmailSentry")
 
36
  st.write("Aims to perform analysis on incoming emails and to determine whether there is urgency or higher priority for the company to follow-up.")
37
 
38
- # Initialize session state
39
  if "email_body" not in st.session_state:
40
  st.session_state.email_body = ""
41
  if "result" not in st.session_state:
@@ -43,7 +50,7 @@ def main():
43
  if "result_type" not in st.session_state:
44
  st.session_state.result_type = ""
45
 
46
- # Collapsible instructions
47
  with st.expander("How to Use", expanded=False):
48
  st.write("""
49
  - Type or paste an email into the text box.
@@ -52,10 +59,10 @@ def main():
52
  - Use 'Clear' to reset the input and result.
53
  """)
54
 
55
- # Text area for email input
56
  email_body = st.text_area("Email Body", value=st.session_state.email_body, height=200, key="email_input")
57
 
58
- # Sample emails (shortened snippets for button labels)
59
  sample_spam = """
60
  Subject: Urgent: Verify Your Account Now!
61
  Dear Customer,
@@ -85,7 +92,7 @@ Sarah
85
  """
86
  negative_snippet = "Subject: Issue with Recent Delivery Dear Support, I received my package today, but..."
87
 
88
- # Custom CSS for buttons and result boxes
89
  st.markdown("""
90
  <style>
91
  /* Sample buttons (smaller text) */
@@ -110,12 +117,12 @@ Sarah
110
  div.stButton > button[kind="primary"]:hover {
111
  background-color: #E74C3C;
112
  }
113
- /* Clear button (gray) */
114
  div.stButton > button[kind="secondary"][key="clear"] {
115
  background-color: #d3d3d3;
116
  color: #333333;
117
- font-size: 18px; /* Match Analyze Email size */
118
- padding: 12px 24px; /* Match Analyze Email padding */
119
  border: none;
120
  border-radius: 5px;
121
  }
@@ -147,7 +154,7 @@ Sarah
147
  # Subheading for sample buttons
148
  st.subheader("Examples")
149
 
150
- # Sample buttons (in columns)
151
  col1, col2, col3 = st.columns(3)
152
  with col1:
153
  if st.button(spam_snippet, key="spam_sample"):
@@ -168,7 +175,7 @@ Sarah
168
  st.session_state.result_type = ""
169
  st.rerun()
170
 
171
- # Analyze and Clear buttons (aligned in a row)
172
  col_analyze, col_clear = st.columns(2)
173
  with col_analyze:
174
  if st.button("Analyze Email", key="analyze", type="primary"):
@@ -187,7 +194,7 @@ Sarah
187
  st.session_state.result_type = ""
188
  st.rerun()
189
 
190
- # Display result with styled box
191
  if st.session_state.result:
192
  if st.session_state.result_type == "spam":
193
  st.markdown(f'<div class="spam-result">{st.session_state.result}</div>', unsafe_allow_html=True)
@@ -198,5 +205,6 @@ Sarah
198
  else:
199
  st.write(st.session_state.result) # For error messages
200
 
 
201
  if __name__ == "__main__":
202
  main()
 
3
  import torch
4
  import numpy as np
5
 
6
+ # Function to analyze email for spam and sentiment
7
  def analyze_email(email_body):
8
+ # Load pre-trained models for spam detection and sentiment analysis
9
  spam_pipeline = pipeline("text-classification", model="cybersectony/phishing-email-detection-distilbert_v2.4.1")
10
  sentiment_model = AutoModelForSequenceClassification.from_pretrained("ISOM5240GP4/email_sentiment", num_labels=2)
11
  tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
12
 
13
+ # Step 1: Check if email is spam
14
  spam_result = spam_pipeline(email_body)
15
  spam_label = spam_result[0]["label"]
16
  spam_confidence = spam_result[0]["score"]
 
18
  if spam_label == "LABEL_1":
19
  return "spam", f"This is a spam email (Confidence: {spam_confidence:.2f}). No follow-up needed."
20
  else:
21
+ # Step 2: Analyze sentiment for non-spam emails
22
  inputs = tokenizer(email_body, padding=True, truncation=True, return_tensors='pt')
23
  outputs = sentiment_model(**inputs)
24
  predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
 
35
  f"Sentiment: {sentiment} (Confidence: {sentiment_confidence:.2f}).\n"
36
  "**Need to Follow-Up**: This email is not spam and has negative sentiment.")
37
 
38
+ # Main application function
39
  def main():
40
+ # Set page title
41
  st.title("EmailSentry")
42
+ # Set project objective
43
  st.write("Aims to perform analysis on incoming emails and to determine whether there is urgency or higher priority for the company to follow-up.")
44
 
45
+ # Initialize session state variables
46
  if "email_body" not in st.session_state:
47
  st.session_state.email_body = ""
48
  if "result" not in st.session_state:
 
50
  if "result_type" not in st.session_state:
51
  st.session_state.result_type = ""
52
 
53
+ # Collapsible instructions section
54
  with st.expander("How to Use", expanded=False):
55
  st.write("""
56
  - Type or paste an email into the text box.
 
59
  - Use 'Clear' to reset the input and result.
60
  """)
61
 
62
+ # Input text area for email content
63
  email_body = st.text_area("Email Body", value=st.session_state.email_body, height=200, key="email_input")
64
 
65
+ # Define sample emails and their snippets for buttons
66
  sample_spam = """
67
  Subject: Urgent: Verify Your Account Now!
68
  Dear Customer,
 
92
  """
93
  negative_snippet = "Subject: Issue with Recent Delivery Dear Support, I received my package today, but..."
94
 
95
+ # Custom CSS for styling buttons and result boxes
96
  st.markdown("""
97
  <style>
98
  /* Sample buttons (smaller text) */
 
117
  div.stButton > button[kind="primary"]:hover {
118
  background-color: #E74C3C;
119
  }
120
+ /* Clear button (aligned with Analyze, gray) */
121
  div.stButton > button[kind="secondary"][key="clear"] {
122
  background-color: #d3d3d3;
123
  color: #333333;
124
+ font-size: 18px;
125
+ padding: 12px 24px;
126
  border: none;
127
  border-radius: 5px;
128
  }
 
154
  # Subheading for sample buttons
155
  st.subheader("Examples")
156
 
157
+ # Sample buttons layout (3 columns)
158
  col1, col2, col3 = st.columns(3)
159
  with col1:
160
  if st.button(spam_snippet, key="spam_sample"):
 
175
  st.session_state.result_type = ""
176
  st.rerun()
177
 
178
+ # Action buttons layout (Analyze and Clear)
179
  col_analyze, col_clear = st.columns(2)
180
  with col_analyze:
181
  if st.button("Analyze Email", key="analyze", type="primary"):
 
194
  st.session_state.result_type = ""
195
  st.rerun()
196
 
197
+ # Display analysis result in styled boxes
198
  if st.session_state.result:
199
  if st.session_state.result_type == "spam":
200
  st.markdown(f'<div class="spam-result">{st.session_state.result}</div>', unsafe_allow_html=True)
 
205
  else:
206
  st.write(st.session_state.result) # For error messages
207
 
208
+ # Run the app
209
  if __name__ == "__main__":
210
  main()