false_positive / app.py
Ajay1311's picture
Update app.py
0dcd077 verified
import os
import logging
import gradio as gr
import numpy as np
import matplotlib.pyplot as plt
from transformers import pipeline
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import time
logging.basicConfig(filename='phishing_urls.log', level=logging.INFO, format='%(asctime)s - %(message)s')
model = pipeline('text-classification', model="Ajay1311/phish")
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 465 # Try 465 for SSL if 587 fails
SENDER_EMAIL = "pukumar2003@gmail.com"
SENDER_PASSWORD = "qwaw bfdb xdlt qyup"
RECIPIENT_EMAIL = "pukumar2003@gmail.com"
IS_HUGGINGFACE_SPACES = "false".lower() == "true"
def send_email_via_gmail(subject, body, use_ssl=False):
"""Function to send email via Gmail SMTP server with retries."""
if IS_HUGGINGFACE_SPACES:
logging.warning("Email sending disabled in Hugging Face Spaces due to SMTP restrictions.")
return "Email sending disabled in Hugging Face Spaces due to network restrictions."
message = MIMEMultipart()
message["From"] = SENDER_EMAIL
message["To"] = RECIPIENT_EMAIL
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))
max_retries = 3
retry_delay = 5 # seconds
timeout = 10 # seconds
port = 465 if use_ssl else SMTP_PORT
for attempt in range(max_retries):
try:
if use_ssl:
with smtplib.SMTP_SSL(SMTP_SERVER, port, timeout=timeout) as server:
server.login(SENDER_EMAIL, SENDER_PASSWORD)
server.sendmail(SENDER_EMAIL, RECIPIENT_EMAIL, message.as_string())
else:
with smtplib.SMTP(SMTP_SERVER, port, timeout=timeout) as server:
server.starttls()
server.login(SENDER_EMAIL, SENDER_PASSWORD)
server.sendmail(SENDER_EMAIL, RECIPIENT_EMAIL, message.as_string())
logging.info(f"Email sent successfully via port {port}")
return "Phishing report email sent successfully!"
except (smtplib.SMTPException, OSError) as e:
logging.error(f"Failed to send email via port {port} (attempt {attempt + 1}/{max_retries}): {e}")
if attempt < max_retries - 1:
time.sleep(retry_delay)
continue
return f"Failed to send email: {e}"
def log_phishing(url_or_text):
"""Log phishing URLs or content into a log file."""
logging.info(f"Phishing detected: {url_or_text}")
def create_speedometer_chart(confidence, is_phishing):
"""Generate speedometer chart showing confidence of phishing detection."""
fig, ax = plt.subplots(figsize=(6, 3), subplot_kw={'projection': 'polar'})
confidence_pct = confidence * 100
theta = np.linspace(np.pi, 0, 100)
ax.plot(theta, [1]*100, color='lightgray', linewidth=15, alpha=0.3)
angle = np.pi * (1 - (confidence_pct / 100))
ax.plot([np.pi, angle], [0, 1], color='red' if is_phishing else 'green', linewidth=4)
ax.fill_between(theta, 0, 1, where=(theta >= angle), color='red' if is_phishing else 'green', alpha=0.25)
ax.set_rticks([])
ax.set_xticks([])
ax.set_yticklabels([])
ax.set_facecolor("white")
ax.spines['polar'].set_visible(False)
ax.set_ylim(0, 1.1)
label = f"{'PHISHING' if is_phishing else 'BENIGN'}\n{confidence_pct:.1f}%"
ax.text(0, -0.2, label, ha='center', va='center', fontsize=14, fontweight='bold', color='black')
return fig
def analyze_phishing(text):
"""Function to analyze if text contains phishing content and perform actions accordingly."""
if not text.strip():
return "No input provided.", None, "Please enter valid email or URL content for analysis."
result = model(text)
label = result[0]['label']
score = result[0]['score']
is_phishing = label.lower() == 'phishing'
chart = create_speedometer_chart(score, is_phishing)
if is_phishing:
analysis = f"""
⚠️ **Phishing Likely Detected**
The provided input has characteristics associated with phishing content.
**Confidence:** {score*100:.1f}%
**Indicators of phishing may include:**
- Suspicious or misspelled URLs
- Requests for personal credentials
- Unusual urgency or threats
- Unexpected attachments or links
**Recommendation:** Do not interact with the content until verified by your IT or security team.
"""
# Try sending email with port 587, fallback to 465
email_result = send_email_via_gmail("Phishing Detected", f"Phishing detected with confidence {score*100:.1f}%: {text}")
if "Failed to send email" in email_result:
email_result = send_email_via_gmail("Phishing Detected", f"Phishing detected with confidence {score*100:.1f}%: {text}", use_ssl=True)
log_phishing(text)
analysis += f"\n**Email Notification:** {email_result}"
else:
analysis = f"""
✅ **No Threat Detected**
The content appears legitimate based on the current model.
**Confidence:** {score*100:.1f}%
**General Safety Tips:**
- Avoid clicking unknown links
- Be cautious with personal data
- Always confirm requests from unknown senders
**Recommendation:** Proceed with standard caution.
"""
return f"{'Phishing Detected' if is_phishing else 'Content Safe'} (Confidence: {score*100:.1f}%)", chart, analysis
def open_awareness_page():
"""Return HTML to open the CyberSwaRaksha awareness page in a new tab."""
return """
<script>
window.open('https://pukumars2003.github.io/CyberSwaRaksha/', '_blank');
</script>
<p>Opening CyberSwaRaksha awareness page...</p>
"""
theme = gr.themes.Soft(primary_hue="blue", secondary_hue="gray").set(
button_primary_background_fill="*primary_600",
button_primary_text_color="white",
block_label_background_fill="*neutral_100",
block_title_text_color="*primary_600",
)
with gr.Blocks(theme=theme, css="""
.container { max-width: 800px; margin: 0 auto; }
.header { text-align: center; margin-bottom: 20px; }
.header h1 { color: #1f2937; font-size: 2.2rem; }
.header p { color: #4b5563; font-size: 1rem; }
.footer { text-align: center; margin-top: 40px; font-size: 0.9rem; color: #6b7280; }
.result-box { font-size: 1.1rem; font-weight: bold; text-align: center; }
""") as demo:
with gr.Column(elem_classes="container"):
gr.HTML("""<div class="header"><h1>Cyber Swa Raksha</h1><p>Protect From Phishing By Yourself</p></div>""")
with gr.Group():
input_text = gr.Textbox(
placeholder="Enter email content, message, or suspicious URL...",
lines=4,
label="Input Text"
)
with gr.Row():
analyze_btn = gr.Button("Analyze", variant="primary")
awareness_btn = gr.Button("Cyber Safety Tips", variant="secondary")
clear_btn = gr.Button("Clear")
with gr.Group():
result_text = gr.Textbox(label="Detection Summary", elem_classes="result-box")
result_plot = gr.Plot(label="Confidence Meter")
analysis_md = gr.Markdown(label="Detailed Analysis")
analyze_btn.click(
analyze_phishing,
inputs=input_text,
outputs=[result_text, result_plot, analysis_md]
)
awareness_btn.click(
open_awareness_page,
inputs=None,
outputs=gr.HTML(label="Awareness Page")
)
clear_btn.click(
lambda: ("", None, ""),
inputs=None,
outputs=[input_text, result_plot, analysis_md]
)
gr.HTML("""<div class="footer">Cyber Swa Raksha</div>""")
if __name__ == "__main__":
demo.launch()