abdull4h commited on
Commit
a9c27e2
·
verified ·
1 Parent(s): 8ffe607

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +113 -95
app.py CHANGED
@@ -1,5 +1,6 @@
1
  import gradio as gr
2
  from transformers import pipeline
 
3
 
4
  # Initialize pipelines
5
  ocr = pipeline("image-to-text", model="microsoft/trocr-base-printed")
@@ -10,12 +11,10 @@ SUSPICIOUS_PHRASES = [
10
  "urgent", "immediately", "password", "account locked", "wire transfer",
11
  "bank verification", "click here", "verification code", "credit card",
12
  "suspended", "login now", "reset your password", "act now", "unusual activity",
13
- "security alert", "confirm your identity", "gift card", "lottery winner",
14
- "inheritance", "tax refund", "payment pending"
15
  ]
16
 
17
  def extract_text_from_image(image):
18
- """Extract text from uploaded image using OCR."""
19
  if image is None:
20
  return ""
21
  try:
@@ -25,9 +24,8 @@ def extract_text_from_image(image):
25
  return f"Error processing image: {str(e)}"
26
 
27
  def analyze_text(text):
28
- """Analyze text for phishing indicators."""
29
  if not text.strip():
30
- return "No text to analyze.", "", gr.update(visible=False)
31
 
32
  # Zero-shot Classification
33
  candidate_labels = ["Phishing Email", "Legitimate Email"]
@@ -36,155 +34,176 @@ def analyze_text(text):
36
  label = result["labels"][0]
37
  confidence = result["scores"][0]
38
 
39
- # Determine alert level and color
40
  if label == "Phishing Email":
41
  if confidence > 0.8:
42
  alert_html = """
43
- <div style="padding: 15px; background-color: #ffebee; border-left: 6px solid #f44336; margin-bottom: 15px;">
44
- <h3 style="color: #d32f2f; margin: 0;">⚠️ High Risk - Likely Phishing Attempt</h3>
 
 
 
 
45
  </div>
46
  """
47
  else:
48
  alert_html = """
49
- <div style="padding: 15px; background-color: #fff3e0; border-left: 6px solid #ff9800; margin-bottom: 15px;">
50
- <h3 style="color: #f57c00; margin: 0;">⚠️ Medium Risk - Suspicious Content Detected</h3>
 
 
 
 
51
  </div>
52
  """
53
  else:
54
  alert_html = """
55
- <div style="padding: 15px; background-color: #e8f5e9; border-left: 6px solid #4caf50; margin-bottom: 15px;">
56
- <h3 style="color: #2e7d32; margin: 0;">✅ Low Risk - Likely Legitimate</h3>
 
 
 
 
57
  </div>
58
  """
59
 
60
- # Keyword Analysis
61
  found_phrases = []
62
  text_lower = text.lower()
63
  for phrase in SUSPICIOUS_PHRASES:
64
  if phrase in text_lower:
65
  found_phrases.append(phrase)
66
 
67
- # Generate Detailed Report
68
  report = [
69
- f"### Analysis Results",
70
- f"**Confidence Score:** {confidence:.1%}",
71
- f"**Classification:** {label}",
72
- "\n### Detected Indicators"
 
 
 
 
 
 
73
  ]
74
 
75
  if found_phrases:
76
- report.append("🚩 **Suspicious elements found:**")
 
 
 
 
77
  for phrase in found_phrases:
78
- report.append(f"- Found '{phrase}'")
 
79
  else:
80
- report.append(" No common suspicious phrases detected.")
81
 
82
- report.append("\n### Recommendation")
83
  if confidence > 0.9:
84
- report.append("🔴 **High confidence in classification - exercise extreme caution!**")
85
  elif confidence > 0.7:
86
- report.append("🟡 **Moderate confidence - review carefully and verify sender.**")
87
  else:
88
- report.append("🟢 **Low confidence - but always remain vigilant.**")
89
-
 
90
  return alert_html, "\n".join(report), gr.update(visible=True)
91
 
92
  def process_input(text_input, image_input):
93
- """Process either text input or image input."""
94
- # If text is provided, use it directly
95
  if text_input.strip():
96
  return analyze_text(text_input)
97
 
98
- # If image is provided, extract text first
99
  if image_input is not None:
100
  extracted_text = extract_text_from_image(image_input)
101
  if extracted_text.strip():
102
  return analyze_text(extracted_text)
103
  return (
104
- """<div style="padding: 15px; background-color: #fff3e0; border-left: 6px solid #ff9800; margin-bottom: 15px;">
105
- <h3 style="color: #f57c00; margin: 0;">⚠️ OCR Processing Error</h3>
106
  </div>""",
107
  "Could not extract text from image. Please ensure the image contains clear, readable text.",
108
  gr.update(visible=False)
109
  )
110
 
111
- return (
112
- "",
113
- "Please provide either text or an image to analyze.",
114
- gr.update(visible=False)
115
- )
116
 
117
  # Custom theme
118
  custom_theme = gr.themes.Soft().set(
119
- body_background_fill='*background-1',
120
- block_background_fill='*background-2',
121
- block_label_background_fill='*background-3',
122
- input_background_fill='*background-2',
123
- button_primary_background_fill='*primary-500',
124
- button_primary_text_color='white',
125
  )
126
 
127
- # Create Gradio interface with tabs
128
- with gr.Blocks(theme=custom_theme) as demo:
129
- gr.Markdown("""
130
- # 📧 AI Phishing Detector
131
- ### Analyze emails and messages for potential phishing attempts
132
- Upload a screenshot or paste text to check for suspicious content
 
 
 
 
 
 
 
133
  """)
134
 
135
- with gr.Row():
136
- with gr.Column(scale=1):
137
- gr.Markdown("""
138
- ### How to Use
139
- 1. Either paste message text or upload a screenshot
140
- 2. Click 'Analyze' to check for phishing indicators
141
- 3. Review the detailed analysis results
142
-
143
- ℹ️ This tool uses AI to detect:
144
- - Suspicious language patterns
145
- - Common phishing phrases
146
- - Urgency indicators
147
- - Security threat language
 
 
 
 
 
 
 
148
  """)
 
 
 
 
 
 
 
 
 
149
 
150
- with gr.Column(scale=2):
151
- with gr.Tab("✏️ Text Input"):
152
- text_input = gr.Textbox(
153
- lines=8,
154
- label="Message Text",
155
- placeholder="Paste email or message content here...",
156
- elem_id="text_input"
157
- )
158
-
159
- with gr.Tab("📷 Screenshot Upload"):
160
- image_input = gr.Image(
161
- label="Upload Screenshot",
162
- type="pil",
163
- elem_id="image_input"
164
- )
165
-
166
- analyze_button = gr.Button("🔍 Analyze", variant="primary", size="lg")
167
-
168
- with gr.Row():
169
- with gr.Column():
170
- alert_html = gr.HTML(label="Alert")
171
- analysis = gr.Markdown(label="Detailed Analysis")
172
-
173
- with gr.Accordion("ℹ️ About this tool", open=False):
174
- gr.Markdown("""
175
- This tool uses advanced AI models to analyze messages for potential phishing attempts:
176
- - OCR technology to extract text from screenshots
177
- - Zero-shot classification for pattern detection
178
- - Keyword analysis for suspicious content
179
-
180
- **Disclaimer:** This is an educational demo. Always verify suspicious messages with your IT department.
181
- """)
182
 
183
  # Examples
184
  examples = [
185
  ["Subject: URGENT - Account Security Alert\n\nDear User,\n\nWe detected unusual activity in your account. Click here immediately to verify your identity and reset your password. If you don't respond within 24 hours, your account will be suspended.\n\nBank Security Team", None],
186
  ["Subject: Team Meeting Tomorrow\n\nHi everyone,\n\nJust a reminder that we have our weekly team meeting tomorrow at 10 AM in the main conference room. Please bring your project updates.\n\nBest regards,\nSarah", None],
187
  ]
 
188
  gr.Examples(
189
  examples=examples,
190
  inputs=[text_input, image_input],
@@ -193,11 +212,10 @@ with gr.Blocks(theme=custom_theme) as demo:
193
  cache_examples=True
194
  )
195
 
196
- # Set up event handler
197
  analyze_button.click(
198
  fn=process_input,
199
  inputs=[text_input, image_input],
200
- outputs=[alert_html, analysis]
201
  )
202
 
203
  # Launch the app
 
1
  import gradio as gr
2
  from transformers import pipeline
3
+ import numpy as np
4
 
5
  # Initialize pipelines
6
  ocr = pipeline("image-to-text", model="microsoft/trocr-base-printed")
 
11
  "urgent", "immediately", "password", "account locked", "wire transfer",
12
  "bank verification", "click here", "verification code", "credit card",
13
  "suspended", "login now", "reset your password", "act now", "unusual activity",
14
+ "security alert", "confirm your identity", "gift card", "lottery winner"
 
15
  ]
16
 
17
  def extract_text_from_image(image):
 
18
  if image is None:
19
  return ""
20
  try:
 
24
  return f"Error processing image: {str(e)}"
25
 
26
  def analyze_text(text):
 
27
  if not text.strip():
28
+ return "", "", gr.update(visible=False)
29
 
30
  # Zero-shot Classification
31
  candidate_labels = ["Phishing Email", "Legitimate Email"]
 
34
  label = result["labels"][0]
35
  confidence = result["scores"][0]
36
 
37
+ # Determine risk level and styling
38
  if label == "Phishing Email":
39
  if confidence > 0.8:
40
  alert_html = """
41
+ <div style="padding: 20px; background: linear-gradient(to right, #ffebee, #ffcdd2);
42
+ border-radius: 12px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin-bottom: 20px;">
43
+ <div style="display: flex; align-items: center; gap: 12px;">
44
+ <span style="font-size: 24px;">⚠️</span>
45
+ <h3 style="color: #c62828; margin: 0; font-size: 18px;">High Risk Detected - Likely Phishing Attempt</h3>
46
+ </div>
47
  </div>
48
  """
49
  else:
50
  alert_html = """
51
+ <div style="padding: 20px; background: linear-gradient(to right, #fff3e0, #ffe0b2);
52
+ border-radius: 12px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin-bottom: 20px;">
53
+ <div style="display: flex; align-items: center; gap: 12px;">
54
+ <span style="font-size: 24px;">⚡</span>
55
+ <h3 style="color: #ef6c00; margin: 0; font-size: 18px;">Medium Risk - Suspicious Content Detected</h3>
56
+ </div>
57
  </div>
58
  """
59
  else:
60
  alert_html = """
61
+ <div style="padding: 20px; background: linear-gradient(to right, #e8f5e9, #c8e6c9);
62
+ border-radius: 12px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin-bottom: 20px;">
63
+ <div style="display: flex; align-items: center; gap: 12px;">
64
+ <span style="font-size: 24px;">✅</span>
65
+ <h3 style="color: #2e7d32; margin: 0; font-size: 18px;">Low Risk - Likely Legitimate</h3>
66
+ </div>
67
  </div>
68
  """
69
 
70
+ # Find suspicious phrases
71
  found_phrases = []
72
  text_lower = text.lower()
73
  for phrase in SUSPICIOUS_PHRASES:
74
  if phrase in text_lower:
75
  found_phrases.append(phrase)
76
 
77
+ # Generate detailed analysis report with modern styling
78
  report = [
79
+ "<div style='background: white; padding: 24px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05);'>",
80
+ "<h3 style='color: #1a237e; margin-top: 0;'>Analysis Details</h3>",
81
+ f"<div style='display: flex; gap: 20px; margin-bottom: 20px;'>",
82
+ f"<div style='flex: 1; padding: 16px; background: #f5f5f5; border-radius: 8px;'>",
83
+ f"<strong>Confidence Score:</strong> {confidence:.1%}",
84
+ "</div>",
85
+ f"<div style='flex: 1; padding: 16px; background: #f5f5f5; border-radius: 8px;'>",
86
+ f"<strong>Classification:</strong> {label}",
87
+ "</div>",
88
+ "</div>"
89
  ]
90
 
91
  if found_phrases:
92
+ report.extend([
93
+ "<div style='margin-top: 20px;'>",
94
+ "<h4 style='color: #d32f2f;'>🚩 Suspicious Elements Detected:</h4>",
95
+ "<ul style='list-style-type: none; padding-left: 0;'>"
96
+ ])
97
  for phrase in found_phrases:
98
+ report.append(f"<li style='margin-bottom: 8px; padding: 8px 12px; background: #ffebee; border-radius: 6px;'>Found: '{phrase}'</li>")
99
+ report.append("</ul></div>")
100
  else:
101
+ report.append("<p style='color: #2e7d32;'>✅ No common suspicious phrases detected.</p>")
102
 
103
+ report.append("<div style='margin-top: 20px; padding: 16px; background: #e3f2fd; border-radius: 8px;'>")
104
  if confidence > 0.9:
105
+ report.append("<p style='margin: 0;'><strong>🔴 High confidence in classification - exercise extreme caution!</strong></p>")
106
  elif confidence > 0.7:
107
+ report.append("<p style='margin: 0;'><strong>🟡 Moderate confidence - review carefully and verify sender.</strong></p>")
108
  else:
109
+ report.append("<p style='margin: 0;'><strong>🟢 Low confidence - but always remain vigilant.</strong></p>")
110
+ report.append("</div></div>")
111
+
112
  return alert_html, "\n".join(report), gr.update(visible=True)
113
 
114
  def process_input(text_input, image_input):
 
 
115
  if text_input.strip():
116
  return analyze_text(text_input)
117
 
 
118
  if image_input is not None:
119
  extracted_text = extract_text_from_image(image_input)
120
  if extracted_text.strip():
121
  return analyze_text(extracted_text)
122
  return (
123
+ """<div style="padding: 20px; background: #fff3e0; border-radius: 12px; margin-bottom: 20px;">
124
+ <h3 style="color: #ef6c00; margin: 0;">⚠️ OCR Processing Error</h3>
125
  </div>""",
126
  "Could not extract text from image. Please ensure the image contains clear, readable text.",
127
  gr.update(visible=False)
128
  )
129
 
130
+ return "", "Please provide either text or an image to analyze.", gr.update(visible=False)
 
 
 
 
131
 
132
  # Custom theme
133
  custom_theme = gr.themes.Soft().set(
134
+ body_background_fill="#f8f9fa",
135
+ block_background_fill="white",
136
+ block_label_background_fill="*background-3",
137
+ input_background_fill="white",
138
+ button_primary_background_fill="#1a237e",
139
+ button_primary_text_color="white",
140
  )
141
 
142
+ # Create Gradio interface with modern design
143
+ with gr.Blocks(theme=custom_theme, css="""
144
+ .container { max-width: 1000px; margin: auto; }
145
+ .header { text-align: center; margin-bottom: 2rem; }
146
+ .tool-description { max-width: 800px; margin: 0 auto 2rem auto; }
147
+ .input-section { margin-bottom: 2rem; }
148
+ .analysis-section { margin-top: 2rem; }
149
+ """) as demo:
150
+ gr.HTML("""
151
+ <div class="header">
152
+ <h1 style="color: #1a237e; font-size: 2.5rem; margin-bottom: 1rem;">🛡️ AI Phishing Guard</h1>
153
+ <p style="color: #555; font-size: 1.2rem;">Protect yourself from phishing attempts with AI-powered analysis</p>
154
+ </div>
155
  """)
156
 
157
+ with gr.Row(equal_height=True):
158
+ with gr.Column():
159
+ gr.HTML("""
160
+ <div class="tool-description">
161
+ <h3 style="color: #1a237e;">How to Use</h3>
162
+ <ol style="color: #555; line-height: 1.6;">
163
+ <li>Either paste message text or upload a screenshot</li>
164
+ <li>Click 'Analyze' to check for phishing indicators</li>
165
+ <li>Review the detailed analysis results</li>
166
+ </ol>
167
+ <div style="background: #e3f2fd; padding: 16px; border-radius: 8px; margin-top: 1rem;">
168
+ <h4 style="color: #1a237e; margin-top: 0;">This tool detects:</h4>
169
+ <ul style="color: #555; margin-bottom: 0;">
170
+ <li>Suspicious language patterns</li>
171
+ <li>Common phishing phrases</li>
172
+ <li>Urgency indicators</li>
173
+ <li>Security threat language</li>
174
+ </ul>
175
+ </div>
176
+ </div>
177
  """)
178
+
179
+ with gr.Tabs():
180
+ with gr.TabItem("✏️ Text Input"):
181
+ text_input = gr.Textbox(
182
+ lines=8,
183
+ label="Message Text",
184
+ placeholder="Paste email or message content here...",
185
+ elem_id="text_input"
186
+ )
187
 
188
+ with gr.TabItem("📷 Screenshot Upload"):
189
+ image_input = gr.Image(
190
+ label="Upload Screenshot",
191
+ type="pil",
192
+ elem_id="image_input"
193
+ )
194
+
195
+ analyze_button = gr.Button("🔍 Analyze", variant="primary", size="lg")
196
+
197
+ with gr.Column(visible=True) as output_col:
198
+ alert_html = gr.HTML()
199
+ analysis = gr.HTML()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
 
201
  # Examples
202
  examples = [
203
  ["Subject: URGENT - Account Security Alert\n\nDear User,\n\nWe detected unusual activity in your account. Click here immediately to verify your identity and reset your password. If you don't respond within 24 hours, your account will be suspended.\n\nBank Security Team", None],
204
  ["Subject: Team Meeting Tomorrow\n\nHi everyone,\n\nJust a reminder that we have our weekly team meeting tomorrow at 10 AM in the main conference room. Please bring your project updates.\n\nBest regards,\nSarah", None],
205
  ]
206
+
207
  gr.Examples(
208
  examples=examples,
209
  inputs=[text_input, image_input],
 
212
  cache_examples=True
213
  )
214
 
 
215
  analyze_button.click(
216
  fn=process_input,
217
  inputs=[text_input, image_input],
218
+ outputs=[alert_html, analysis, output_col]
219
  )
220
 
221
  # Launch the app